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
1e8066ca7cf9a81b09d58c41b56173b2e6c54d94
11,970
/* * Copyright 2020 threadcat * * https://github.com/threadcat/accumulating-record * * 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.threadcat.acm; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; /** * Transactional store for custom cumulative functions. * It triggers execution of related functions and stores calculated results atomically. * Functions have access to committed and draft data. * * @author threadcat */ class AcmHandler implements AcmView { private int statusOffset; private int draftOffset; private int dataOffset; private final List<AcmColumn> columnList = new ArrayList<>(); private int revisionColumn = -1; private long provisioned; protected ByteBuffer buffer; /** * Constructor defines offsets in ByteBuffer for 'empty' and 'committed' info and column data area. * * @param statusOffset - columns which were updated since last 'reset'. * @param draftOffset - draft vs committed data offsets. * @param dataOffset - start of column data area. */ public AcmHandler(int statusOffset, int draftOffset, int dataOffset) { this.statusOffset = statusOffset; this.draftOffset = draftOffset; this.dataOffset = dataOffset; } protected void setStatusOffset(int statusOffset) { this.statusOffset = statusOffset; } protected void setDraftOffset(int draftOffset) { this.draftOffset = draftOffset; } protected void setDataOffset(int dataOffset) { this.dataOffset = dataOffset; } public int addColumn(AcmDoubleAction action) { AcmColumn col = new AcmColumn(action, columnList.size()); columnList.add(col); return col.storeColumn; } public int addColumn(AcmLongAction action) { AcmColumn col = new AcmColumn(action, columnList.size()); columnList.add(col); return col.storeColumn; } public int addColumn(AcmDoubleToLongAction action) { AcmColumn col = new AcmColumn(action, columnList.size()); columnList.add(col); return col.storeColumn; } public int addColumn(AcmLongToDoubleAction action) { AcmColumn col = new AcmColumn(action, columnList.size()); columnList.add(col); return col.storeColumn; } public int addRevisionColumn() { if (revisionColumn == -1) { AcmLongAction increment = (view, storeColumn, referenceColumn, value) -> value + 1L; AcmColumn col = new AcmColumn(increment, columnList.size()); columnList.add(col); revisionColumn = col.storeColumn; } return revisionColumn; } public int addColumn(AcmDoubleAction action, int reference) { AcmColumn col = new AcmColumn(action, columnList.size()); return linkColumn(col, reference); } public int addColumn(AcmLongAction action, int reference) { AcmColumn col = new AcmColumn(action, columnList.size()); return linkColumn(col, reference); } public int addColumn(AcmDoubleToLongAction action, int reference) { AcmColumn col = new AcmColumn(action, columnList.size()); return linkColumn(col, reference); } public int addColumn(AcmLongToDoubleAction action, int reference) { AcmColumn col = new AcmColumn(action, columnList.size()); return linkColumn(col, reference); } protected int size() { return columnList.size() * 16; } public void setByteBuffer(ByteBuffer buffer) { this.buffer = buffer; // Completing eventual consistency cycle for 'status' (emptiness flags). // This is needed if process terminated at the moment between storing 'committed' and 'status'. long status = buffer.getLong(statusOffset) | buffer.getLong(draftOffset); buffer.putLong(statusOffset, status); } /** * Updates specified column draft value and triggers functions on linked columns. */ public void update(int col, long value) { AcmColumn column = columnList.get(col); switch (column.type) { case LONG: long newLong = column.longAction.apply(this, col, column.referenceColumn, value); provision(col, newLong); processLinks(column.linkedColumns, newLong); break; case LONG_TO_DOUBLE: double newDouble = column.longToDoubleAction.apply(this, col, column.referenceColumn, value); provision(col, newDouble); processLinks(column.linkedColumns, newDouble); break; default: throw new AcmException("Can not process 'long', column type is " + column.type); } } /** * Updates specified column draft value and triggers functions on linked columns. */ public void update(int col, double value) { AcmColumn column = columnList.get(col); switch (column.type) { case DOUBLE: double newDouble = column.doubleAction.apply(this, col, column.referenceColumn, value); provision(col, newDouble); processLinks(column.linkedColumns, newDouble); break; case DOUBLE_TO_LONG: long newLong = column.doubleToLongAction.apply(this, col, column.referenceColumn, value); provision(col, newLong); processLinks(column.linkedColumns, newLong); break; default: throw new AcmException("Can not process 'double', column type is " + column.type); } } @Override public boolean isEmpty(int col) { return (buffer.getLong(statusOffset) >> col & 1L) == 0L; } @Override public long getLong(int col) { int committedOffset = dataOffset(col, true); return buffer.getLong(committedOffset); } @Override public double getDouble(int col) { int committedOffset = dataOffset(col, true); return buffer.getDouble(committedOffset); } @Override public long getDraftLong(int col) { int committedOffset = dataOffset(col, false); return buffer.getLong(committedOffset); } @Override public double getDraftDouble(int col) { int committedOffset = dataOffset(col, false); return buffer.getDouble(committedOffset); } /** * Sets value not triggering any calculations e.g. initial or cascading values. * {@link #commit()} still required. */ public void setLong(int col, long value) { provision(col, value); } /** * Sets value not triggering any calculations e.g. initial or cascading values. * {@link #commit()} still required. */ public void setDouble(int col, double value) { provision(col, value); } /** * Increments 'revision' column (if present) and makes all draft values persisted. */ public void commit() { if (revisionColumn != -1) { long revision = getLong(revisionColumn); update(revisionColumn, revision); } long committed = buffer.getLong(draftOffset) ^ provisioned; buffer.putLong(draftOffset, committed); long empty = buffer.getLong(statusOffset) | provisioned; buffer.putLong(statusOffset, empty); provisioned = 0L; } /** * Increments 'revision' column (if present) and sets other columns to zero. {@link #commit()} not needed. */ public void reset() { for (int i = 0; i < columnList.size(); i++) { AcmColumn column = columnList.get(i); if (i == revisionColumn) { continue; } switch (column.type) { case DOUBLE, LONG_TO_DOUBLE -> provision(i, 0.); case LONG, DOUBLE_TO_LONG -> provision(i, 0L); } } if (revisionColumn != -1) { long revision = getLong(revisionColumn); update(revisionColumn, revision); } long committed = buffer.getLong(draftOffset) ^ provisioned; buffer.putLong(draftOffset, committed); buffer.putLong(statusOffset, 0L); provisioned = 0L; } private int linkColumn(AcmColumn col, int reference) { AcmColumn ref = columnList.get(reference); validate(col.type, ref.type); col.referenceColumn = reference; ref.linkedColumns.add(col); columnList.add(col); return col.storeColumn; } // Column input type should be the same as reference column output type. private void validate(AcmColumn.Type type, AcmColumn.Type refType) { boolean inputLong = type == AcmColumn.Type.LONG || type == AcmColumn.Type.LONG_TO_DOUBLE; boolean outputDouble = refType == AcmColumn.Type.DOUBLE || refType == AcmColumn.Type.LONG_TO_DOUBLE; if (inputLong == outputDouble) { throw new AcmException(String.format("Can not link %s column to %s column, input/output type mismatch", type, refType)); } } private void processLinks(List<AcmColumn> links, long value) { for (AcmColumn link : links) { if (link.type == AcmColumn.Type.LONG) { long newValue = link.longAction.apply(this, link.storeColumn, link.referenceColumn, value); provision(link.storeColumn, newValue); processLinks(link.linkedColumns, newValue); } else { double newValue = link.longToDoubleAction.apply(this, link.storeColumn, link.referenceColumn, value); provision(link.storeColumn, newValue); processLinks(link.linkedColumns, newValue); } } } private void processLinks(List<AcmColumn> linkedColumns, double value) { for (AcmColumn link : linkedColumns) { if (link.type == AcmColumn.Type.DOUBLE) { double newValue = link.doubleAction.apply(this, link.storeColumn, link.referenceColumn, value); provision(link.storeColumn, newValue); processLinks(link.linkedColumns, newValue); } else { long newValue = link.doubleToLongAction.apply(this, link.storeColumn, link.referenceColumn, value); provision(link.storeColumn, newValue); processLinks(link.linkedColumns, newValue); } } } private void provision(int col, long value) { int provisionalOffset = dataOffset(col, false); buffer.putLong(provisionalOffset, value); provisioned |= (1L << col); } private void provision(int col, double value) { int provisionalOffset = dataOffset(col, false); buffer.putDouble(provisionalOffset, value); provisioned |= (1L << col); } private int dataOffset(int col, boolean committed) { long savedState = buffer.getLong(draftOffset); return dataOffset + shift(col, committed, savedState); } // Calculating draft/committed cell place inside 'data' area protected int shift(int col, boolean committed, long savedState) { int shift = (int) (savedState >> col & 0x1L); if (committed) { shift ^= 0x1; // inverted } shift *= columnList.size(); return 8 * (col + shift); } }
36.163142
117
0.629825
ed7d75a57237c16a4b89fde6b93d540b0f05b6cf
402
package clickandobey.dockerized.webservice; import io.dropwizard.Configuration; import com.fasterxml.jackson.annotation.JsonProperty; public class HelloWorldConfiguration extends Configuration { private boolean debug; @JsonProperty public boolean getDebug() { return debug; } @JsonProperty public void setDebug(boolean debug) { this.debug = debug; } }
19.142857
60
0.721393
2696414c24fd6b2fba2055c0b4fb767e7eefd63d
17,783
package org.planet_sl.apimigration.benchmark.jdom.test_as_xom; import org.planet_sl.apimigration.benchmark.anno.Progress; import org.planet_sl.apimigration.benchmark.anno.Progress.Status; import org.planet_sl.apimigration.benchmark.anno.Solution; import org.planet_sl.apimigration.benchmark.anno.Solution.Strategy; import org.planet_sl.apimigration.benchmark.anno.Issue; import org.planet_sl.apimigration.benchmark.jdom.wrapped_as_xom.*; /** * <p> * Tests adding, removing, and counting children from parent nodes. * </p> * * @author Elliotte Rusty Harold * @version 1.2d1 * */ public class ParentNodeTest extends XOMTestCase { @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") public ParentNodeTest(String name) { super(name); } private Element empty; private Element notEmpty; private Text child; @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") protected void setUp() { empty = new Element("Empty"); notEmpty = new Element("NotEmpty"); child = new Text("Hello"); notEmpty.appendChild(child); } @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") public void testDetach() { Text text = new Text("This will be attached then detached"); empty.appendChild(text); assertEquals(empty, text.getParent()); text.detach(); assertNull(text.getParent()); } @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") public void testAppendChild() { Element child = new Element("test"); empty.appendChild(child); assertEquals(1, empty.getChildCount()); assertEquals(empty.getChild(0), child); child.detach(); notEmpty.appendChild(child); assertFalse(notEmpty.getChild(0).equals(child)); assertTrue(notEmpty.getChild(1).equals(child)); } @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") public void testAppendChildToItself() { Element child = new Element("test"); try { child.appendChild(child); fail("Appended node to itself"); } catch (CycleException success) { assertNotNull(success.getMessage()); } } @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") public void testCycle() { Element a = new Element("test"); Element b = new Element("test"); try { a.appendChild(b); b.appendChild(a); fail("Allowed cycle"); } catch (CycleException success) { assertNotNull(success.getMessage()); } } @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") public void testInsertChild() { Element parent = new Element("parent"); // Test insert into empty element Element child1 = new Element("child"); parent.insertChild(child1, 0); assertTrue(parent.getChildCount() > 0); assertEquals(0, parent.indexOf(child1)); // Test insert at beginning Element child2 = new Element("child2"); parent.insertChild(child2, 0); assertEquals(0, parent.indexOf(child2)); assertEquals(1, parent.indexOf(child1)); // Test insert in middle Element child3 = new Element("child3"); parent.insertChild(child3, 1); assertEquals(0, parent.indexOf(child2)); assertEquals(1, parent.indexOf(child3)); assertEquals(2, parent.indexOf(child1)); // Test insert at beginning with children Element child4 = new Element("child4"); parent.insertChild(child4, 0); assertEquals(0, parent.indexOf(child4)); assertEquals(1, parent.indexOf(child2)); assertEquals(2, parent.indexOf(child3)); assertEquals(3, parent.indexOf(child1)); // Test insert at end with children Element child5 = new Element("child5"); parent.insertChild(child5, 4); assertEquals(0, parent.indexOf(child4)); assertEquals(1, parent.indexOf(child2)); assertEquals(2, parent.indexOf(child3)); assertEquals(3, parent.indexOf(child1)); assertEquals(4, parent.indexOf(child5)); try { parent.insertChild((Element) null, 0); fail("Inserted null"); } catch (NullPointerException success) { assertNotNull(success.getMessage()); } try { parent.insertChild((Text) null, 0); fail("Inserted null"); } catch (NullPointerException success) { assertNotNull(success.getMessage()); } try { parent.insertChild((Comment) null, 0); fail("Inserted null"); } catch (NullPointerException success) { assertNotNull(success.getMessage()); } try { parent.insertChild((ProcessingInstruction) null, 0); fail("Inserted null"); } catch (NullPointerException success) { assertNotNull(success.getMessage()); } } @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") public void testAppendChild2() { try { empty.appendChild(new Document(notEmpty)); fail("appended a document to an element"); } catch (IllegalAddException success) { assertNotNull(success.getMessage()); } try { empty.appendChild(child); fail("appended a child twice"); } catch (MultipleParentException success) { assertNotNull(success.getMessage()); } } @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") public void testReplaceChild() { Element old1 = new Element("old1"); Element old2 = new Element("old2"); Element old3 = new Element("old3"); Element new1 = new Element("new1"); Element new2 = new Element("new2"); Element new3 = new Element("new3"); empty.appendChild(old1); empty.appendChild(old2); empty.appendChild(old3); empty.replaceChild(old1, new1); empty.replaceChild(old3, new3); empty.replaceChild(old2, new2); Node current1 = empty.getChild(0); Node current2 = empty.getChild(1); Node current3 = empty.getChild(2); assertEquals(new1, current1); assertEquals(new2, current2); assertEquals(new3, current3); try { empty.replaceChild(new1, null); } catch (NullPointerException success) { assertNotNull(success.getMessage()); } try { empty.replaceChild(null, old1); } catch (NullPointerException success) { assertNotNull(success.getMessage()); } Element new4 = new Element("new4"); try { empty.replaceChild(new4, new Element("test")); fail("Replaced Nonexistent element"); } catch (NoSuchChildException success) { assertNotNull(success.getMessage()); } // Test replacing node with itself empty.replaceChild(new1, new1); assertEquals(new1, empty.getChild(0)); assertEquals(empty, new1.getParent()); // Test replacing node with a sibling try { empty.replaceChild(new1, new2); fail("replaced a node with its sibling"); } catch (MultipleParentException success) { assertNotNull(success.getMessage()); } } @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") public void testIndexOf() { Element child1 = new Element("old1"); Text child2 = new Text("old2"); Comment child3 = new Comment("old3"); assertEquals(-1, empty.indexOf(child1)); empty.appendChild(child1); empty.appendChild(child2); empty.appendChild(child3); assertEquals(0, empty.indexOf(child1)); assertEquals(1, empty.indexOf(child2)); assertEquals(2, empty.indexOf(child3)); assertEquals(-1, empty.indexOf(empty)); assertEquals(-1, empty.indexOf(new Text("test"))); } @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") public void testGetChild() { Element old1 = new Element("old1"); Element old2 = new Element("old2"); Element old3 = new Element("old3"); try { empty.getChild(0); fail("No index exception"); } catch (IndexOutOfBoundsException success) { // success assertNotNull(success.getMessage()); } empty.appendChild(old1); empty.appendChild(old2); empty.appendChild(old3); assertEquals(old1, empty.getChild(0)); assertEquals(old3, empty.getChild(2)); assertEquals(old2, empty.getChild(1)); try { empty.getChild(5); fail("No index exception"); } catch (IndexOutOfBoundsException success) { // success assertNotNull(success.getMessage()); } } @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") public void testRemoveChild() { try { empty.removeChild(0); fail("Removed child from empty element"); } catch (IndexOutOfBoundsException success) { assertNotNull(success.getMessage()); } Element old1 = new Element("old1"); Element old2 = new Element("old2"); Element old3 = new Element("old3"); try { empty.removeChild(old1); fail("Removed non-existent child from empty element"); } catch (NoSuchChildException success) { assertNotNull(success.getMessage()); } empty.appendChild(old1); empty.appendChild(old2); empty.appendChild(old3); empty.removeChild(1); assertEquals(old1, empty.getChild(0)); assertEquals(old3, empty.getChild(1)); try { empty.removeChild(5); fail("No IndexOutOfBoundsException"); } catch (IndexOutOfBoundsException success) { assertNotNull(success.getMessage()); } empty.removeChild(1); empty.removeChild(0); assertNull(old2.getParent()); assertEquals(0, empty.getChildCount()); empty.appendChild(old1); empty.appendChild(old2); empty.appendChild(old3); assertEquals(3, empty.getChildCount()); empty.removeChild(old3); empty.removeChild(old1); empty.removeChild(old2); assertEquals(0, empty.getChildCount()); assertNull(old1.getParent()); } @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") public void testReplaceChildFailures() { Element old1 = new Element("old1"); Element old2 = new Element("old2"); Element old3 = new Element("old3"); Element new1 = new Element("new1"); Element new3 = new Element("new3"); empty.appendChild(old1); empty.appendChild(old2); try { empty.replaceChild(old3, new3); fail("Replaced non-existent child"); } catch (NoSuchChildException success) { assertNotNull(success.getMessage()); } try { empty.replaceChild(old1, null); fail("Replaced child with null"); } catch (NullPointerException success) { assertNotNull(success.getMessage()); } try { empty.replaceChild(null, new1); fail("Replaced null"); } catch (NullPointerException success) { assertNotNull(success.getMessage()); } } @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") public void testReplaceChildInEmptyParent() { Element test1 = new Element("test"); Element test2 = new Element("test"); try { empty.replaceChild(test1, test2); fail("Replaced element in empty parent"); } catch (NoSuchChildException success) { assertNotNull(success.getMessage()); } } // Document that this behavior is intentional // An element cannot be replaced by its sibling unless // the sibling is first detached. @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") public void testReplaceSibling() { Element parent = new Element("parent"); Element test1 = new Element("test"); Element test2 = new Element("test"); parent.appendChild(test1); parent.appendChild(test2); try { parent.replaceChild(test1, test2); fail("Replaced element without detaching first"); } catch (IllegalAddException success) { assertNotNull(success.getMessage()); } assertEquals(2, parent.getChildCount()); assertEquals(parent, test1.getParent()); assertEquals(parent, test2.getParent()); } // Similarly, this test documents the conscious decision // that you cannot insert an existing child into its own parent, // even at the same position @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") public void testCantInsertExisitngChild() { Element parent = new Element("parent"); Element test1 = new Element("test"); Element test2 = new Element("test"); parent.appendChild(test1); parent.appendChild(test2); try { parent.insertChild(test2, 0); fail("Inserted element without detaching first"); } catch (MultipleParentException success) { assertNotNull(success.getMessage()); } try { parent.insertChild(test2, 1); fail("Inserted element without detaching first"); } catch (MultipleParentException success) { assertNotNull(success.getMessage()); } assertEquals(2, parent.getChildCount()); assertEquals(parent, test1.getParent()); assertEquals(parent, test2.getParent()); } // can't remove when insertion is legal; // succeeed or fail as unit @Progress( value = Status.TODO, comment = "" ) @Solution( value = Strategy.OTHER, comment = "" ) @Issue.Pre("") @Issue.Post("") @Issue.Throws("") public void testReplaceChildAtomicity() { Element parent = new Element("parent"); Text child = new Text("child"); parent.appendChild(child); try { parent.replaceChild(child, new DocType("root")); fail("allowed doctype child of element"); } catch (IllegalAddException success) { assertEquals(parent, child.getParent()); assertEquals(1, parent.getChildCount()); } Element e = new Element("e"); Text child2 = new Text("child2"); e.appendChild(child2); try { parent.replaceChild(child, child2); fail("allowed replacement with existing parent"); } catch (MultipleParentException success) { assertEquals(e, child2.getParent()); assertEquals(parent, child.getParent()); assertEquals(1, parent.getChildCount()); assertEquals(1, e.getChildCount()); } } }
25.152758
69
0.557667
30d4c4e2f500ee83347c3ff55f5871578c7068c2
16,908
package com.upokecenter.numbers; /* Written by Peter O. Any copyright to this work is released to the Public Domain. In case this is not possible, this work is also licensed under Creative Commons Zero (CC0): https://creativecommons.org/publicdomain/zero/1.0/ */ final class BitShiftAccumulator implements IShiftAccumulator { private static final int SmallBitLength = 32; private int bitLeftmost; public final int getLastDiscardedDigit() { return this.bitLeftmost; } private int bitsAfterLeftmost; public final int getOlderDiscardedDigits() { return this.bitsAfterLeftmost; } private EInteger shiftedBigInt; private FastInteger knownBitLength; public FastInteger GetDigitLength() { this.knownBitLength = (this.knownBitLength == null) ? (this.CalcKnownBitLength()) : this.knownBitLength; return FastInteger.CopyFrozen(this.knownBitLength); } public FastInteger OverestimateDigitLength() { return this.GetDigitLength(); } private static void VerifyKnownLength() { } public void ShiftToDigits( FastInteger bits, FastInteger preShift, boolean truncate) { if (bits.signum() < 0) { throw new IllegalArgumentException("bits's sign(" + bits.signum() + ") is less than 0"); } if (preShift != null && preShift.signum() > 0) { this.knownBitLength = (this.knownBitLength == null) ? (this.CalcKnownBitLength()) : this.knownBitLength; // System.out.println("bits=" + bits + " pre=" + preShift + " known=" + // (//kbl) + " [" + this.shiftedBigInt + "]"); if (this.knownBitLength.compareTo(bits) <= 0) { // Known digit length is already small enough // NOTE: For BitShiftAccumulator, truncating and shifting // are the same, unlike in DigitShiftAccumulator this.ShiftRight(preShift); VerifyKnownLength(); return; } else { FastInteger bitDiff = this.knownBitLength.Copy() .Subtract(bits); // System.out.println("bitDiff=" + bitDiff); int cmp = bitDiff.compareTo(preShift); if (cmp <= 0) { // NOTE: For BitShiftAccumulator, truncating and shifting // are the same, unlike in DigitShiftAccumulator this.ShiftRight(preShift); VerifyKnownLength(); return; } else { // NOTE: For BitShiftAccumulator, truncating and shifting // are the same, unlike in DigitShiftAccumulator this.ShiftRight(bitDiff); VerifyKnownLength(); return; } } } if (bits.CanFitInInt32()) { this.ShiftToDigitsInt(bits.ToInt32()); VerifyKnownLength(); } else { this.knownBitLength = (this.knownBitLength == null) ? (this.CalcKnownBitLength()) : this.knownBitLength; EInteger bigintDiff = this.knownBitLength.ToEInteger(); EInteger bitsBig = bits.ToEInteger(); bigintDiff = bigintDiff.Subtract(bitsBig); if (bigintDiff.signum() > 0) { // current length is greater than the // desired bit length this.ShiftRight(FastInteger.FromBig(bigintDiff)); } VerifyKnownLength(); } } private int shiftedSmall; private boolean isSmall; public final EInteger getShiftedInt() { return this.isSmall ? (EInteger.FromInt32(this.shiftedSmall)) : this.shiftedBigInt; } public final FastInteger getShiftedIntFast() { return this.isSmall ? new FastInteger(this.shiftedSmall) : FastInteger.FromBig(this.shiftedBigInt); } public int ShiftedIntMod(int mod) { if (mod < 1) { throw new IllegalArgumentException("mod (" + mod + ") is not greater or equal to 1"); } switch (mod) { case 1: return 0; case 2: return this.isSmall ? (this.shiftedSmall & 1) : (this.shiftedBigInt.isEven() ? 0 : 1); default: return this.isSmall ? (this.shiftedSmall % mod) : this.shiftedBigInt.Mod(mod).ToInt32Checked(); } } private FastInteger discardedBitCount; public final FastInteger getDiscardedDigitCount() { return this.discardedBitCount; } public BitShiftAccumulator( EInteger bigint, int lastDiscarded, int olderDiscarded) { if (bigint.signum() < 0) { throw new IllegalArgumentException("bigint's sign(" + bigint.signum() + ") is less than 0"); } if (bigint.CanFitInInt32()) { this.isSmall = true; this.shiftedSmall = bigint.ToInt32Checked(); } else { this.shiftedBigInt = bigint; } this.discardedBitCount = new FastInteger(0); this.bitsAfterLeftmost = (olderDiscarded != 0) ? 1 : 0; this.bitLeftmost = (lastDiscarded != 0) ? 1 : 0; } public BitShiftAccumulator( int smallint, int lastDiscarded, int olderDiscarded) { this.shiftedSmall = smallint; if (this.shiftedSmall < 0) { throw new IllegalArgumentException("shiftedSmall(" + this.shiftedSmall + ") is less than 0"); } this.isSmall = true; this.discardedBitCount = new FastInteger(0); this.bitsAfterLeftmost = (olderDiscarded != 0) ? 1 : 0; this.bitLeftmost = (lastDiscarded != 0) ? 1 : 0; } public static BitShiftAccumulator FromInt32(int smallNumber) { if (smallNumber < 0) { throw new IllegalArgumentException("smallNumber(" + smallNumber + ") is less than 0"); } BitShiftAccumulator bsa = new BitShiftAccumulator(EInteger.FromInt32(0), 0, 0); bsa.shiftedSmall = smallNumber; bsa.discardedBitCount = new FastInteger(0); bsa.isSmall = true; return bsa; } public void TruncateOrShiftRight(FastInteger fastint, boolean truncate) { this.ShiftRight(fastint); } public void ShiftRight(FastInteger fastint) { if (fastint.signum() <= 0) { return; } if (fastint.CanFitInInt32()) { this.ShiftRightInt(fastint.ToInt32()); } else { EInteger bi = fastint.ToEInteger(); while (bi.signum() > 0) { int count = 1000000; if (bi.compareTo(EInteger.FromInt64(1000000)) < 0) { count = bi.ToInt32Checked(); } this.ShiftRightInt(count); bi = bi.Subtract(EInteger.FromInt32(count)); if (this.isSmall ? this.shiftedSmall == 0 : this.shiftedBigInt.isZero()) { break; } } } } private void ShiftRightBig(int bits) { if (bits <= 0) { return; } if (this.shiftedBigInt.isZero()) { this.discardedBitCount.AddInt(bits); this.bitsAfterLeftmost |= this.bitLeftmost; this.bitLeftmost = 0; this.isSmall = true; this.shiftedSmall = 0; this.knownBitLength = new FastInteger(1); return; } this.knownBitLength = (this.knownBitLength == null) ? (this.CalcKnownBitLength()) : this.knownBitLength; this.discardedBitCount.AddInt(bits); int cmp = this.knownBitLength.CompareToInt(bits); if (cmp < 0) { // too few bits this.bitsAfterLeftmost |= this.bitLeftmost; this.bitsAfterLeftmost |= this.shiftedBigInt.isZero() ? 0 : 1; this.bitLeftmost = 0; this.isSmall = true; this.shiftedSmall = 0; this.knownBitLength = new FastInteger(1); } else { // enough bits in the current value int bs = bits; this.knownBitLength.SubtractInt(bits); if (bs == 1) { boolean odd = !this.shiftedBigInt.isEven(); this.shiftedBigInt = shiftedBigInt.ShiftRight(1); this.bitsAfterLeftmost |= this.bitLeftmost; this.bitLeftmost = odd ? 1 : 0; } else { this.bitsAfterLeftmost |= this.bitLeftmost; long lowestSet = this.shiftedBigInt.GetLowBitAsInt64(); if (lowestSet == Long.MAX_VALUE) { EInteger lowestSetBit = this.shiftedBigInt.GetLowBitAsEInteger(); if (lowestSetBit.compareTo(bs - 1) < 0) { // One of the discarded bits after // the last one is set this.bitsAfterLeftmost |= 1; this.bitLeftmost = this.shiftedBigInt.GetSignedBit(bs - 1) ? 1 : 0; } else if (lowestSetBit.compareTo(bs - 1) > 0) { // Means all discarded bits are zero this.bitLeftmost = 0; } else { // Only the last discarded bit is set this.bitLeftmost = 1; } } else { if (lowestSet < bs - 1) { // One of the discarded bits after // the last one is set this.bitsAfterLeftmost |= 1; this.bitLeftmost = this.shiftedBigInt.GetSignedBit(bs - 1) ? 1 : 0; } else if (lowestSet > bs - 1) { // Means all discarded bits are zero this.bitLeftmost = 0; } else { // Only the last discarded bit is set this.bitLeftmost = 1; } } this.shiftedBigInt = shiftedBigInt.ShiftRight(bs); } if (this.knownBitLength.CompareToInt(SmallBitLength) < 0) { // Shifting to small number of bits, // convert to small integer this.isSmall = true; this.shiftedSmall = this.shiftedBigInt.ToInt32Checked(); } this.bitsAfterLeftmost = (this.bitsAfterLeftmost != 0) ? 1 : 0; } } private FastInteger CalcKnownBitLength() { if (this.isSmall) { int kb = SmallBitLength; for (int i = SmallBitLength - 1; i >= 0; --i) { if ((this.shiftedSmall & (1 << i)) != 0) { break; } --kb; } // Make sure bit length is 1 if value is 0 if (kb == 0) { ++kb; } return new FastInteger(kb); } if (this.shiftedBigInt.isZero()) { { return new FastInteger(1); } } long sbe = this.shiftedBigInt.GetSignedBitLengthAsInt64(); return (sbe < Integer.MAX_VALUE) ? new FastInteger((int)sbe) : FastInteger.FromBig(this.shiftedBigInt.GetSignedBitLengthAsEInteger()); } private void ShiftBigToBits(int bits) { // Shifts a number until it reaches the given number of bits, // gathering information on whether the last bit discarded is set and // whether the discarded bits to the right of that bit are set. Assumes // that the big integer being shifted is positive. if (this.knownBitLength != null) { if (this.knownBitLength.CompareToInt(bits) <= 0) { return; } } this.knownBitLength = (this.knownBitLength == null) ? (this.CalcKnownBitLength()) : this.knownBitLength; if (this.knownBitLength.CompareToInt(bits) <= 0) { return; } // Shift by the difference in bit length if (this.knownBitLength.CompareToInt(bits) > 0) { int bs = 0; if (this.knownBitLength.CanFitInInt32()) { bs = this.knownBitLength.ToInt32(); bs -= bits; } else { FastInteger bitShift = this.knownBitLength.Copy().SubtractInt(bits); if (!bitShift.CanFitInInt32()) { this.ShiftRight(bitShift); return; } bs = bitShift.ToInt32(); } this.knownBitLength.SetInt(bits); this.discardedBitCount.AddInt(bs); if (bs == 1) { boolean odd = !this.shiftedBigInt.isEven(); this.shiftedBigInt = shiftedBigInt.ShiftRight(1); this.bitsAfterLeftmost |= this.bitLeftmost; this.bitLeftmost = odd ? 1 : 0; } else { this.bitsAfterLeftmost |= this.bitLeftmost; long lowestSet = this.shiftedBigInt.GetLowBitAsInt64(); if (lowestSet == Long.MAX_VALUE) { EInteger lowestSetBit = this.shiftedBigInt.GetLowBitAsEInteger(); if (lowestSetBit.compareTo(bs - 1) < 0) { // One of the discarded bits after // the last one is set this.bitsAfterLeftmost |= 1; this.bitLeftmost = this.shiftedBigInt.GetSignedBit(bs - 1) ? 1 : 0; } else if (lowestSetBit.compareTo(bs - 1) > 0) { // Means all discarded bits are zero this.bitLeftmost = 0; } else { // Only the last discarded bit is set this.bitLeftmost = 1; } } else { if (lowestSet < bs - 1) { // One of the discarded bits after // the last one is set this.bitsAfterLeftmost |= 1; this.bitLeftmost = this.shiftedBigInt.GetSignedBit(bs - 1) ? 1 : 0; } else if (lowestSet > bs - 1) { // Means all discarded bits are zero this.bitLeftmost = 0; } else { // Only the last discarded bit is set this.bitLeftmost = 1; } } this.shiftedBigInt = shiftedBigInt.ShiftRight(bs); } if (bits < SmallBitLength) { // Shifting to small number of bits, // convert to small integer this.isSmall = true; this.shiftedSmall = this.shiftedBigInt.ToInt32Checked(); } this.bitsAfterLeftmost = (this.bitsAfterLeftmost != 0) ? 1 : 0; } } public void ShiftRightInt(int bits) { // <summary>Shifts a number to the right, gathering information on // whether the last bit discarded is set and whether the discarded // bits to the right of that bit are set. Assumes that the big integer // being shifted is positive.</summary> if (this.isSmall) { this.ShiftRightSmall(bits); } else { this.ShiftRightBig(bits); } } private void ShiftRightSmall(int bits) { if (bits <= 0) { return; } if (this.shiftedSmall == 0) { this.discardedBitCount.AddInt(bits); this.bitsAfterLeftmost |= this.bitLeftmost; this.bitLeftmost = 0; this.knownBitLength = new FastInteger(1); return; } int kb = SmallBitLength; for (int i = SmallBitLength - 1; i >= 0; --i) { if ((this.shiftedSmall & (1 << i)) != 0) { break; } --kb; } int shift = (int)Math.min(kb, bits); boolean shiftingMoreBits = bits > kb; kb -= shift; this.knownBitLength = new FastInteger(kb); this.discardedBitCount.AddInt(bits); this.bitsAfterLeftmost |= this.bitLeftmost; // Get the bottommost shift minus 1 bits this.bitsAfterLeftmost |= (shift > 1 && (this.shiftedSmall << (SmallBitLength - shift + 1)) != 0) ? 1 : 0; // Get the bit just above that bit this.bitLeftmost = (int)((this.shiftedSmall >> (shift - 1)) & 0x01); this.shiftedSmall >>= shift; if (shiftingMoreBits) { // Shifted more bits than the bit length this.bitsAfterLeftmost |= this.bitLeftmost; this.bitLeftmost = 0; } this.bitsAfterLeftmost = (this.bitsAfterLeftmost != 0) ? 1 : 0; } public void ShiftToDigitsInt(int bits) { if (bits < 0) { throw new IllegalArgumentException("bits(" + bits + ") is less than 0"); } if (this.isSmall) { this.ShiftSmallToBits(bits); } else { this.ShiftBigToBits(bits); } } private void ShiftSmallToBits(int bits) { if (this.knownBitLength != null) { if (this.knownBitLength.CompareToInt(bits) <= 0) { return; } } this.knownBitLength = (this.knownBitLength == null) ? (this.CalcKnownBitLength()) : this.knownBitLength; if (this.knownBitLength.CompareToInt(bits) <= 0) { return; } int kbl = this.knownBitLength.ToInt32(); // Shift by the difference in bit length if (kbl > bits) { int bitShift = kbl - (int)bits; int shift = (int)bitShift; this.knownBitLength = new FastInteger(bits); this.discardedBitCount.AddInt(bitShift); this.bitsAfterLeftmost |= this.bitLeftmost; // Get the bottommost shift minus 1 bits this.bitsAfterLeftmost |= (shift > 1 && (this.shiftedSmall << (SmallBitLength - shift + 1)) != 0) ? 1 : 0; // Get the bit just above that bit this.bitLeftmost = (int)((this.shiftedSmall >> (shift - 1)) & 0x01); this.bitsAfterLeftmost = (this.bitsAfterLeftmost != 0) ? 1 : 0; this.shiftedSmall >>= shift; } else { this.knownBitLength = new FastInteger(kbl); } } }
35.372385
112
0.57872
142852ed9b49f9d231db5683799da255b0926af5
4,291
/* * 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.kylin.cube.kv; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.List; import org.apache.kylin.common.util.DateFormat; import org.apache.kylin.common.util.LocalFileMetadataTestCase; import org.apache.kylin.cube.CubeInstance; import org.apache.kylin.cube.CubeManager; import org.apache.kylin.cube.cuboid.Cuboid; import org.apache.kylin.cube.model.CubeDesc; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; public class RowKeyDecoderTest extends LocalFileMetadataTestCase { @Before public void setUp() throws Exception { this.createTestMetadata(); } @After public void after() throws Exception { this.cleanupTestMetadata(); } @Test public void testDecodeWithoutSlr() throws Exception { CubeInstance cube = CubeManager.getInstance(getTestConfig()).getCube("TEST_KYLIN_CUBE_WITHOUT_SLR_READY"); RowKeyDecoder rowKeyDecoder = new RowKeyDecoder(cube.getFirstSegment()); byte[] key = { 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 11, 55, -13, 13, 22, 34, 121, 70, 80, 45, 71, 84, 67, 9, 9, 9, 9, 9, 9, 0, 10, 5 }; rowKeyDecoder.decode(key); List<String> values = rowKeyDecoder.getValues(); assertEquals("[" + millis("2012-12-15") + ", 11848, Health & Beauty, Fragrances, Women, FP-GTC, 0, 15]", values.toString()); } @Ignore @Test public void testDecodeWithSlr() throws Exception { CubeInstance cube = CubeManager.getInstance(getTestConfig()).getCube("TEST_KYLIN_CUBE_WITH_SLR_READY"); RowKeyDecoder rowKeyDecoder = new RowKeyDecoder(cube.getFirstSegment()); byte[] key = { 0, 0, 0, 0, 0, 0, 0, 0, 1, -1, 0, -104, -106, -128, 11, 54, -105, 50, 48, 50, 49, 51, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 13, 71, 114, 65, 66, 73, 78, 9, 9, 9, 9, 9, 9, 9, 9, 0, 10, 0 }; rowKeyDecoder.decode(key); List<String> values = rowKeyDecoder.getValues(); assertEquals("[10000000, " + millis("2012-01-02") + ", 20213, Collectibles, Postcards, US StateCities & Towns, ABIN, 0, -99]", values.toString()); } @Test public void testEncodeAndDecodeWithUtf8() throws IOException { CubeInstance cube = CubeManager.getInstance(getTestConfig()).getCube("TEST_KYLIN_CUBE_WITHOUT_SLR_READY"); CubeDesc cubeDesc = cube.getDescriptor(); String[] data = new String[8]; data[0] = "2012-12-15"; data[1] = "11848"; data[2] = "Health & Beauty"; data[3] = "Fragrances"; data[4] = "Women"; data[5] = "刊登格式测试";// UTF-8 data[6] = "0"; data[7] = "15"; long baseCuboidId = Cuboid.getBaseCuboidId(cubeDesc); Cuboid baseCuboid = Cuboid.findForMandatory(cubeDesc, baseCuboidId); RowKeyEncoder rowKeyEncoder = new RowKeyEncoder(cube.getFirstSegment(), baseCuboid); byte[] encodedKey = rowKeyEncoder.encode(data); assertEquals(22 + rowKeyEncoder.getHeaderLength(), encodedKey.length); RowKeyDecoder rowKeyDecoder = new RowKeyDecoder(cube.getFirstSegment()); rowKeyDecoder.decode(encodedKey); List<String> values = rowKeyDecoder.getValues(); assertEquals("[" + millis("2012-12-15") + ", 11848, Health & Beauty, Fragrances, Women, 刊登格式, 0, 15]", values.toString()); } private String millis(String dateStr) { return String.valueOf(DateFormat.stringToMillis(dateStr)); } }
39.366972
212
0.675134
e65b9e12d3dde0c0e3c196dbcfa593c0b6c793e6
606
package dsm.service.schedule.controller.mapper; import dsm.service.schedule.core.usecase.timetable.GetTimetablesUseCase; import dsm.service.schedule.proto.GetTimeTablesRequest; import org.springframework.stereotype.Component; @Component public class GetTimetablesInputMapper { public GetTimetablesUseCase.InputValues map(GetTimeTablesRequest request) { return new GetTimetablesUseCase.InputValues( request.getUuid(), request.getYear(), request.getMonth(), request.getDay(), request.getCount() ); } }
31.894737
79
0.691419
11a6aaea85514bc4fe038bd9fff7f9c1a4a69a02
3,501
package com.swak.flux.web.statics; import java.io.IOException; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import com.swak.Constants; import com.swak.flux.transport.HttpConst; import com.swak.flux.transport.multipart.FileProps; import com.swak.flux.transport.server.HttpServerRequest; import com.swak.flux.web.Handler; import com.swak.utils.Sets; import com.swak.utils.StringUtils; import reactor.core.publisher.Mono; /** * 静态资源处理 * * @see ResourceWebHandler * * @author lifeng */ public class StaticHandler implements Handler, InitializingBean { protected final Logger logger = LoggerFactory.getLogger(getClass()); // 目前只支持这三个目录,可以是jar或者jar外 private ResourceLoader resourceLoader; private PathResourceResolver pathResourceResolver; private final Set<String> locationsValues = Sets.newHashSet("classpath:/static/", "classpath:/files/", "classpath:/META-INF/resources/"); private final Set<Resource> locations = Sets.newHashSet(); private long HTTP_CACHE_SECONDS = 86400 * 30; // 30 day private String INDEX_PAGE = "index.html"; public StaticHandler(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } /** * index */ public void setIndexPage(String indexPage) { this.INDEX_PAGE = indexPage; } /** * cache */ public void setMaxAgeSeconds(long maxAgeSeconds) { this.HTTP_CACHE_SECONDS = maxAgeSeconds; } /** * 设置支持的资源 */ public void setLocationValues(List<String> locationValues) { this.locationsValues.clear(); this.locationsValues.addAll(locationValues); } /** * 使用 NIO 写文件 * * @param request * @return */ public Mono<Void> handle(HttpServerRequest request) { // 查找的路径 String requestPath = request.getRequestURL(); // 设置首页 if (StringUtils.isBlank(requestPath) || requestPath.equals(Constants.URL_PATH_SEPARATE)) { requestPath = INDEX_PAGE; } // 获取资源 return pathResourceResolver.resolveResource(requestPath, locations).flatMap(resource -> { // 转换资源 FileProps fileProps = null; try { fileProps = FileProps.props(resource); } catch (IOException e) { // 404 not found return Mono.error(HttpConst.NOT_FOUND_EXCEPTION); } // 304 NotModified if (HTTP_CACHE_SECONDS > 0 && request.ifModified(fileProps)) { return Mono.empty(); } // 打开 return fileProps.open(); }).flatMap(fileProps -> { // 输出头部,缓存 request.getResponse().cache(HTTP_CACHE_SECONDS, fileProps.lastModifiedTime()); // 输出内容 request.getResponse().buffer(fileProps); // 返回空就OK return Mono.empty(); }); } /** * 初始化 * * 一般会用到: classpath: 和 file: 这两种方式 * * @see DefaultResourceLoader, ResourceUtils * 1. start with /, not(2,3,4) ClassPathContextResource 从classPath 路径下获取数据,相对路径 * 2. start with classpath: ClassPathResource 从classPath 路径下获取数据,相对路径 * 3. start with file: FileUrlResource 从文件系统中获取数据,要么写绝对路径,要么写相对路径(打包之后可以用) * 4. start with jar:, war: UrlResource */ @Override public void afterPropertiesSet() throws Exception { // 资源加载 pathResourceResolver = new PathResourceResolver(); // 需要加载的资源 for (String location : this.locationsValues) { Resource resource = this.resourceLoader.getResource(location); this.locations.add(resource); } } /** * 清空缓存 */ public void close() { } }
23.979452
103
0.720651
3963aaa6a4f114fd057ae4c0b54bb902a978e09a
370
// This is a generated file. Not intended for manual editing. package org.c3lang.intellijplugin.parser.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface C3UnaryExpression extends PsiElement { @NotNull C3PostfixExpression getPostfixExpression(); @NotNull List<C3UnaryOp> getUnaryOpList(); }
21.764706
61
0.789189
ce06994045374f8c3e92773d9258c99aebaacd74
341
package com.yelp.clientlib.exception.exceptions; public class UnexpectedAPIError extends YelpAPIError { public UnexpectedAPIError(int code, String message) { this(code, message, null, null); } public UnexpectedAPIError(int code, String message, String id, String text) { super(code, message, id, text); } }
28.416667
81
0.706745
27415f5465c0f6b200d29d89eb8bce66029ee9c5
1,785
/* * Copyright 2017 Prudential Corporation Asia * * 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 hk.com.prudential.gradle.sassign; import com.symantec.ws.api.webtrust.codesigningservice.Error; import com.symantec.ws.api.webtrust.codesigningservice.Errors; public class SasSignServiceException extends Exception { private Errors errors; public SasSignServiceException(String message) { super(message); } public SasSignServiceException(String message, Errors errors) { super(message); this.errors = errors; } @Override public String toString() { String defaultMessage = super.toString(); StringBuilder sb = new StringBuilder("["); for (Error e: errors.getError()) { sb.append("{code: ") .append(e.getErrorCode()) .append(", field: \"") .append(e.getErrorField()) .append("\", message: \"") .append(e.getErrorMessage()) .append("\"},"); } if (1 == sb.length()) { sb.append("]"); } else { sb.setCharAt(sb.length()-1, ']'); } return sb.insert(0, defaultMessage+": ").toString(); } }
30.775862
75
0.615686
bb813b5c3451c7e0cd9e3dcd1b854f5cadb954b0
3,071
/******************************************************************************* * Copyright 2018 Quentin Lefèvre * * 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.github.qlefevre.tetris.qrcode.encode; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; public class MatrixToImageWriter { public static final int SPRITE_SIZE = 8; private static BufferedImage toBufferedImage(final Matrix byteMatrix) throws IOException { int size = (byteMatrix.getWidth() + 2) * SPRITE_SIZE; BufferedImage position = readImage("position.png"); Map<Integer, BufferedImage> images = new HashMap<>(); // Create image BufferedImage bi = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); g.setPaint(new Color(0xff, 0xff, 0xff)); g.fillRect(0, 0, bi.getWidth(), bi.getHeight()); for (int col = 0; col < byteMatrix.getWidth(); col++) { for (int row = 0; row < byteMatrix.getWidth(); row++) { int data = byteMatrix.get(col, row); if (data > 0) { g.drawImage(getImage(images, data), col * SPRITE_SIZE + SPRITE_SIZE, row * SPRITE_SIZE + SPRITE_SIZE, null); } } } g.drawImage(position, 3 * SPRITE_SIZE, 3 * SPRITE_SIZE, null); g.drawImage(position, (byteMatrix.getWidth() - 4) * SPRITE_SIZE, 3 * SPRITE_SIZE, null); g.drawImage(position, 3 * SPRITE_SIZE, (byteMatrix.getHeight() - 4) * SPRITE_SIZE, null); g.dispose(); return bi; } public static void writeToPath(final Matrix matrix, Path path) throws IOException { try (final FileOutputStream fileOutputStream = new FileOutputStream(path.toFile())) { BufferedImage bi = toBufferedImage(matrix); ImageIO.write(bi, "png", fileOutputStream); } } private static BufferedImage getImage(Map<Integer, BufferedImage> images, int index) throws IOException { BufferedImage image = images.get(index); if (image == null) { String file = "tetris" + index + ".png"; image = readImage(file); images.put(index, image); } return image; } private static BufferedImage readImage(String imageFile) throws IOException { BufferedImage img; try (InputStream is = MatrixToImageWriter.class.getResourceAsStream("/" + imageFile)) { img = ImageIO.read(is); } return img; } }
34.505618
106
0.682514
6c63bb4836490d2706ab0915cb6a45d3237862fc
32,004
/* * 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.solr.client.solrj.request.schema; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.request.RequestWriter; import org.apache.solr.client.solrj.response.schema.SchemaResponse; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.util.ContentStream; import org.apache.solr.common.util.ContentStreamBase; import org.apache.solr.common.util.NamedList; import org.noggit.CharArr; import org.noggit.JSONWriter; /** * <p>This class offers access to the operations exposed by the Solr Schema API.</p> * <p>Most of the operations of this class offer a very abstract interface avoiding * in this manner eventual changes due to Solr Schema API updates. On the other * hand, the creation of request parameters for creating new fields or field types * can be tedious because it is not strongly typed (the user has to build on his own * a {@link NamedList} argument containing the field/field type properties).</p> * <p>The class does not currently offer explicit support for the Schema API operations exposed * through Managed Resources, but such operations can be built with little effort manually * based on this class within the client applications.</p> * <p>This class is experimental and it is subject to change.</p> * * @see <a href="https://lucene.apache.org/solr/guide/schema-api.html">Solr Schema API</a> * @see <a href="https://lucene.apache.org/solr/guide/managed-resources.html">Solr managed resources</a> * @since solr 5.3 */ public class SchemaRequest extends AbstractSchemaRequest<SchemaResponse> { /** * Default constructor. * It can be used to retrieve the entire schema. * * @see #process(SolrClient) */ public SchemaRequest() { this(null); } public SchemaRequest(SolrParams q) { super(METHOD.GET, "/schema", q); } private static NamedList<Object> createAddFieldTypeNamedList(FieldTypeDefinition fieldTypeDefinition) { final NamedList<Object> addFieldTypeNamedList = new NamedList<>(); addFieldTypeNamedList.addAll(fieldTypeDefinition.getAttributes()); AnalyzerDefinition analyzerDefinition = fieldTypeDefinition.getAnalyzer(); if (analyzerDefinition != null) { NamedList<Object> analyzerNamedList = createAnalyzerNamedList(analyzerDefinition); addFieldTypeNamedList.add("analyzer", analyzerNamedList); } AnalyzerDefinition indexAnalyzerDefinition = fieldTypeDefinition.getIndexAnalyzer(); if (indexAnalyzerDefinition != null) { NamedList<Object> indexAnalyzerNamedList = createAnalyzerNamedList(indexAnalyzerDefinition); addFieldTypeNamedList.add("indexAnalyzer", indexAnalyzerNamedList); } AnalyzerDefinition queryAnalyzerDefinition = fieldTypeDefinition.getQueryAnalyzer(); if (queryAnalyzerDefinition != null) { NamedList<Object> queryAnalyzerNamedList = createAnalyzerNamedList(queryAnalyzerDefinition); addFieldTypeNamedList.add("queryAnalyzer", queryAnalyzerNamedList); } AnalyzerDefinition multiTermAnalyzerDefinition = fieldTypeDefinition.getMultiTermAnalyzer(); if (multiTermAnalyzerDefinition != null) { NamedList<Object> multiTermAnalyzerNamedList = createAnalyzerNamedList(multiTermAnalyzerDefinition); addFieldTypeNamedList.add("multiTermAnalyzer", multiTermAnalyzerNamedList); } Map<String, Object> similarityAttributes = fieldTypeDefinition.getSimilarity(); if (similarityAttributes != null && !similarityAttributes.isEmpty()) { addFieldTypeNamedList.add("similarity", new NamedList<>(similarityAttributes)); } return addFieldTypeNamedList; } private static NamedList<Object> createAnalyzerNamedList(AnalyzerDefinition analyzerDefinition) { NamedList<Object> analyzerNamedList = new NamedList<>(); Map<String, Object> analyzerAttributes = analyzerDefinition.getAttributes(); if (analyzerAttributes != null) analyzerNamedList.addAll(analyzerAttributes); List<Map<String, Object>> charFiltersAttributes = analyzerDefinition.getCharFilters(); if (charFiltersAttributes != null) { List<NamedList<Object>> charFiltersList = new LinkedList<>(); for (Map<String, Object> charFilterAttributes : charFiltersAttributes) charFiltersList.add(new NamedList<>(charFilterAttributes)); analyzerNamedList.add("charFilters", charFiltersList); } Map<String, Object> tokenizerAttributes = analyzerDefinition.getTokenizer(); if (tokenizerAttributes != null) { analyzerNamedList.add("tokenizer", new NamedList<>(tokenizerAttributes)); } List<Map<String, Object>> filtersAttributes = analyzerDefinition.getFilters(); if (filtersAttributes != null) { List<NamedList<Object>> filtersList = new LinkedList<>(); for (Map<String, Object> filterAttributes : filtersAttributes) filtersList.add(new NamedList<>(filterAttributes)); analyzerNamedList.add("filters", filtersList); } return analyzerNamedList; } private static NamedList<Object> createAddFieldNamedList(Map<String, Object> fieldAttributes) { final NamedList<Object> addFieldProps = new NamedList<>(); if (fieldAttributes != null) addFieldProps.addAll(fieldAttributes); return addFieldProps; } @Override protected SchemaResponse createResponse(SolrClient client) { return new SchemaResponse(); } /** * Schema API request class that can be used to retrieve the name of the schema. */ public static class SchemaName extends AbstractSchemaRequest<SchemaResponse.SchemaNameResponse> { public SchemaName() { this(null); } public SchemaName(SolrParams q) { super(METHOD.GET, "/schema/name", q); } @Override protected SchemaResponse.SchemaNameResponse createResponse(SolrClient client) { return new SchemaResponse.SchemaNameResponse(); } } /** * Schema API request that can be used to retrieve the version * of the schema for the specified collection. */ public static class SchemaVersion extends AbstractSchemaRequest<SchemaResponse.SchemaVersionResponse> { public SchemaVersion() { this(null); } public SchemaVersion(SolrParams q) { super(METHOD.GET, "/schema/version", q); } @Override protected SchemaResponse.SchemaVersionResponse createResponse(SolrClient client) { return new SchemaResponse.SchemaVersionResponse(); } } /** * Schema API request class that lists the field definitions contained in the schema. */ public static class Fields extends AbstractSchemaRequest<SchemaResponse.FieldsResponse> { public Fields() { this(null); } public Fields(SolrParams q) { super(METHOD.GET, "/schema/fields", q); } @Override protected SchemaResponse.FieldsResponse createResponse(SolrClient client) { return new SchemaResponse.FieldsResponse(); } } /** * Schema API request that lists the field definition for the specified field * contained in the schema. */ public static class Field extends AbstractSchemaRequest<SchemaResponse.FieldResponse> { /** * Creates a new instance of the request. * * @param fieldName the name of the field for which the definition is to be retrieved */ public Field(String fieldName) { this(fieldName, null); } public Field(String fieldName, SolrParams q) { super(METHOD.GET, "/schema/fields/" + fieldName, q); } @Override protected SchemaResponse.FieldResponse createResponse(SolrClient client) { return new SchemaResponse.FieldResponse(); } } /** * Schema API request that lists the dynamic field definitions contained in the schema. */ public static class DynamicFields extends AbstractSchemaRequest<SchemaResponse.DynamicFieldsResponse> { public DynamicFields() { this(null); } public DynamicFields(SolrParams q) { super(METHOD.GET, "/schema/dynamicfields", q); } @Override protected SchemaResponse.DynamicFieldsResponse createResponse(SolrClient client) { return new SchemaResponse.DynamicFieldsResponse(); } } /** * Schema API request that lists the dynamic field definition for the specified field * contained in the schema. */ public static class DynamicField extends AbstractSchemaRequest<SchemaResponse.DynamicFieldResponse> { /** * Creates a new instance of the class. * * @param dynamicFieldName the name of the dynamic field for which the definition is to be retrieved */ public DynamicField(String dynamicFieldName) { this(dynamicFieldName, null); } public DynamicField(String dynamicFieldName, SolrParams q) { super(METHOD.GET, "/schema/dynamicfields/" + dynamicFieldName); } @Override protected SchemaResponse.DynamicFieldResponse createResponse(SolrClient client) { return new SchemaResponse.DynamicFieldResponse(); } } /** * Schema API request that lists the types definitions contained * in the schema. */ public static class FieldTypes extends AbstractSchemaRequest<SchemaResponse.FieldTypesResponse> { public FieldTypes() { this(null); } public FieldTypes(SolrParams q) { super(METHOD.GET, "/schema/fieldtypes"); } @Override protected SchemaResponse.FieldTypesResponse createResponse(SolrClient client) { return new SchemaResponse.FieldTypesResponse(); } } /** * Schema API request that retrieves the type definitions for the specified field * type contained in the schema. */ public static class FieldType extends AbstractSchemaRequest<SchemaResponse.FieldTypeResponse> { /** * Creates a new instance of the request. * * @param fieldTypeName the name of the field type for which the definition is to be retrieved */ public FieldType(String fieldTypeName) { this(fieldTypeName, null); } public FieldType(String fieldTypeName, SolrParams q) { super(METHOD.GET, "/schema/fieldtypes/" + fieldTypeName, q); } @Override protected SchemaResponse.FieldTypeResponse createResponse(SolrClient client) { return new SchemaResponse.FieldTypeResponse(); } } /** * Schema API request that retrieves the source and destination of * each copy field in the schema. */ public static class CopyFields extends AbstractSchemaRequest<SchemaResponse.CopyFieldsResponse> { public CopyFields() { this(null); } public CopyFields(SolrParams q) { super(METHOD.GET, "/schema/copyfields", q); } @Override protected SchemaResponse.CopyFieldsResponse createResponse(SolrClient client) { return new SchemaResponse.CopyFieldsResponse(); } } /** * Schema API request that retrieves the field name that is defined as * the uniqueKey for the index of the specified collection. */ public static class UniqueKey extends AbstractSchemaRequest<SchemaResponse.UniqueKeyResponse> { public UniqueKey() { this(null); } public UniqueKey(SolrParams q) { super(METHOD.GET, "/schema/uniquekey", q); } @Override protected SchemaResponse.UniqueKeyResponse createResponse(SolrClient client) { return new SchemaResponse.UniqueKeyResponse(); } } /** * Retrieves the class name of the global similarity defined (if any) in the schema. */ public static class GlobalSimilarity extends AbstractSchemaRequest<SchemaResponse.GlobalSimilarityResponse> { public GlobalSimilarity() { this(null); } public GlobalSimilarity(SolrParams q) { super(METHOD.GET, "/schema/similarity", q); } @Override protected SchemaResponse.GlobalSimilarityResponse createResponse(SolrClient client) { return new SchemaResponse.GlobalSimilarityResponse(); } } /** * Adds a new field definition to the schema. * If the field already exists, the method {@link #process(SolrClient, String)} will fail. * Note that the request will be translated to json, so please use concrete values (e.g. : true, 1) * instead of their string representation (e.g. : "true", "1") for the field attributes expecting * boolean or number values. */ public static class AddField extends SingleUpdate { /** * Creates a new instance of the request. * * @param fieldAttributes field type attributes that can be used to enrich the field definition. * @see <a href="https://lucene.apache.org/solr/guide/defining-fields.html">Defining Solr fields</a> */ public AddField(Map<String, Object> fieldAttributes) { this(fieldAttributes, null); } public AddField(Map<String, Object> fieldAttributes, SolrParams q) { super(createRequestParameters(fieldAttributes), q); } private static NamedList<Object> createRequestParameters(Map<String, Object> fieldAttributes) { final NamedList<Object> addFieldParameters = createAddFieldNamedList(fieldAttributes); final NamedList<Object> requestParameters = new NamedList<>(); requestParameters.add("add-field", addFieldParameters); return requestParameters; } } /** * Replaces a field's definition. Note that the full definition for a field must be supplied - this command * will not partially modify a field's definition. If the field does not exist in the schema the method call * {@link #process(SolrClient, String)} will fail. * * @see <a href="https://lucene.apache.org/solr/guide/defining-fields.html">Defining Solr fields</a> */ public static class ReplaceField extends SingleUpdate { /** * Creates a new instance of the request. * * @param fieldAttributes field type attributes that can be used to enrich the field definition. */ public ReplaceField(Map<String, Object> fieldAttributes) { this(fieldAttributes, null); } public ReplaceField(Map<String, Object> fieldAttributes, SolrParams q) { super(createRequestParameters(fieldAttributes), q); } private static NamedList<Object> createRequestParameters(Map<String, Object> fieldAttributes) { final NamedList<Object> replaceFieldParameters = createAddFieldNamedList(fieldAttributes); final NamedList<Object> requestParameters = new NamedList<>(); requestParameters.add("replace-field", replaceFieldParameters); return requestParameters; } } /** * Removes a field definition from the schema. If the field does not exist in the schema, * or if the field is the source or destination of a copy field rule the method call * {@link #process(SolrClient, String)} will fail. */ public static class DeleteField extends SingleUpdate { /** * Creates a new instance of the request. * * @param fieldName the name of the new field to be removed */ public DeleteField(String fieldName) { this(fieldName, null); } public DeleteField(String fieldName, SolrParams q) { super(createRequestParameters(fieldName), q); } private static NamedList<Object> createRequestParameters(String fieldName) { final NamedList<Object> deleteFieldParameters = new NamedList<>(); deleteFieldParameters.add("name", fieldName); final NamedList<Object> requestParameters = new NamedList<>(); requestParameters.add("delete-field", deleteFieldParameters); return requestParameters; } } /** * Adds a new dynamic field rule to the schema of the specified collection. * * @see <a href="https://lucene.apache.org/solr/guide/defining-fields.html">Defining Solr fields</a> * @see <a href="https://lucene.apache.org/solr/guide/dynamic-fields.html">Solr dynamic fields</a> */ public static class AddDynamicField extends SingleUpdate { /** * Creates a new instance of the request. * * @param fieldAttributes field type attributes that can be used to enrich the field definition. */ public AddDynamicField(Map<String, Object> fieldAttributes) { this(fieldAttributes, null); } public AddDynamicField(Map<String, Object> fieldAttributes, SolrParams q) { super(createRequestParameters(fieldAttributes), q); } private static NamedList<Object> createRequestParameters(Map<String, Object> fieldAttributes) { final NamedList<Object> addDynamicFieldParameters = createAddFieldNamedList(fieldAttributes); final NamedList<Object> requestParameters = new NamedList<>(); requestParameters.add("add-dynamic-field", addDynamicFieldParameters); return requestParameters; } } /** * Replaces a dynamic field rule in the schema of the specified collection. * Note that the full definition for a dynamic field rule must be supplied - this command * will not partially modify a dynamic field rule's definition. * If the dynamic field rule does not exist in the schema the method call * {@link #process(SolrClient, String)} will fail. */ public static class ReplaceDynamicField extends SingleUpdate { /** * Creates a new instance of the request. * * @param dynamicFieldAttributes field type attributes that can be used to enrich the field definition. * @see <a href="https://lucene.apache.org/solr/guide/defining-fields.html">Defining Solr fields</a> * @see <a href="https://lucene.apache.org/solr/guide/dynamic-fields.html">Solr dynamic fields</a> */ public ReplaceDynamicField(Map<String, Object> dynamicFieldAttributes) { this(dynamicFieldAttributes, null); } public ReplaceDynamicField(Map<String, Object> dynamicFieldAttributes, SolrParams q) { super(createRequestParameters(dynamicFieldAttributes), q); } private static NamedList<Object> createRequestParameters( Map<String, Object> dynamicFieldAttributes) { final NamedList<Object> replaceDynamicFieldParameters = createAddFieldNamedList(dynamicFieldAttributes); final NamedList<Object> requestParameters = new NamedList<>(); requestParameters.add("replace-dynamic-field", replaceDynamicFieldParameters); return requestParameters; } } /** * Deletes a dynamic field rule from your schema. If the dynamic field rule does not exist in the schema, * or if the schema contains a copy field rule with a target or destination that matches only this * dynamic field rule the method call {@link #process(SolrClient, String)} will fail. */ public static class DeleteDynamicField extends SingleUpdate { /** * Creates a new instance of the request. * * @param dynamicFieldName the name of the dynamic field to be removed */ public DeleteDynamicField(String dynamicFieldName) { this(dynamicFieldName, null); } public DeleteDynamicField(String fieldName, SolrParams q) { super(createRequestParameters(fieldName), q); } private static NamedList<Object> createRequestParameters(String fieldName) { final NamedList<Object> deleteDynamicFieldParameters = new NamedList<>(); deleteDynamicFieldParameters.add("name", fieldName); final NamedList<Object> requestParameters = new NamedList<>(); requestParameters.add("delete-dynamic-field", deleteDynamicFieldParameters); return requestParameters; } } /** * Update request used to add a new field type to the schema. */ public static class AddFieldType extends SingleUpdate { /** * Creates a new instance of the request. * * @param fieldTypeDefinition the field type definition * @see <a href="https://lucene.apache.org/solr/guide/solr-field-types.html">Solr field types</a> */ public AddFieldType(FieldTypeDefinition fieldTypeDefinition) { this(fieldTypeDefinition, null); } public AddFieldType(FieldTypeDefinition fieldTypeDefinition, SolrParams q) { super(createRequestParameters(fieldTypeDefinition), q); } private static NamedList<Object> createRequestParameters(FieldTypeDefinition fieldTypeDefinition) { final NamedList<Object> addFieldTypeParameters = createAddFieldTypeNamedList(fieldTypeDefinition); final NamedList<Object> requestParameters = new NamedList<>(); requestParameters.add("add-field-type", addFieldTypeParameters); return requestParameters; } } /** * Replaces a field type in schema belonging to the schema of the specified collection. * Note that the full definition for a field type must be supplied- this command will not partially modify * a field type's definition. If the field type does not exist in the schema the * method call {@link #process(SolrClient, String)} will fail. */ public static class ReplaceFieldType extends SingleUpdate { /** * Creates a new instance of the request. * * @param fieldTypeDefinition the field type definition * @see <a href="https://lucene.apache.org/solr/guide/solr-field-types.html">Solr field types</a> */ public ReplaceFieldType(FieldTypeDefinition fieldTypeDefinition) { this(fieldTypeDefinition, null); } public ReplaceFieldType(FieldTypeDefinition fieldTypeDefinition, SolrParams q) { super(createRequestParameters(fieldTypeDefinition), q); } private static NamedList<Object> createRequestParameters(FieldTypeDefinition fieldTypeDefinition) { final NamedList<Object> replaceFieldTypeParameters = createAddFieldTypeNamedList(fieldTypeDefinition); final NamedList<Object> requestParameters = new NamedList<>(); requestParameters.add("replace-field-type", replaceFieldTypeParameters); return requestParameters; } } /** * Removes a field type from the schema of the specified collection. * If the field type does not exist in the schema, or if any * field or dynamic field rule in the schema uses the field type, the * method call {@link #process(SolrClient, String)} will fail. */ public static class DeleteFieldType extends SingleUpdate { /** * Creates a new instance of the request. * * @param fieldTypeName the name of the field type to be removed */ public DeleteFieldType(String fieldTypeName) { this(fieldTypeName, null); } public DeleteFieldType(String fieldTypeName, SolrParams q) { super(createRequestParameters(fieldTypeName), q); } private static NamedList<Object> createRequestParameters(String fieldTypeName) { final NamedList<Object> deleteFieldTypeParameters = new NamedList<>(); deleteFieldTypeParameters.add("name", fieldTypeName); final NamedList<Object> requestParameters = new NamedList<>(); requestParameters.add("delete-field-type", deleteFieldTypeParameters); return requestParameters; } } /** * Adds a new copy field rule to the schema of the specified collection. */ public static class AddCopyField extends SingleUpdate { /** * Creates a new instance of the request. * * @param source the source field name * @param dest the collection of the destination field names * @see <a href="https://lucene.apache.org/solr/guide/copying-fields.html">Copying fields</a> */ public AddCopyField(String source, List<String> dest) { this(source, dest, (SolrParams) null); } /** * Creates a new instance of the request. * * @param source the source field name * @param dest the collection of the destination field names * @param maxChars the number of characters to be copied from the source to the dest. Specifying * 0 as value, means that all the source characters will be copied to the dest. * @see <a href="https://lucene.apache.org/solr/guide/copying-fields.html">Copying fields</a> */ public AddCopyField(String source, List<String> dest, Integer maxChars) { this(source, dest, maxChars, null); } public AddCopyField(String source, List<String> dest, SolrParams q) { super(createRequestParameters(source, dest, null), q); } public AddCopyField(String source, List<String> dest, Integer maxChars, SolrParams q) { super(createRequestParameters(source, dest, maxChars), q); } private static NamedList<Object> createRequestParameters(String source, List<String> dest, Integer maxchars) { final NamedList<Object> addCopyFieldParameters = new NamedList<>(); addCopyFieldParameters.add("source", source); addCopyFieldParameters.add("dest", dest); if (maxchars != null) { addCopyFieldParameters.add("maxChars", maxchars); } final NamedList<Object> requestParameters = new NamedList<>(); requestParameters.add("add-copy-field", addCopyFieldParameters); return requestParameters; } } /** * Deletes a copy field rule from the schema of the specified collection. * If the copy field rule does not exist in the schema then the * method call {@link #process(SolrClient, String)} will fail. */ public static class DeleteCopyField extends SingleUpdate { /** * Creates a new instance of the request. * * @param source the source field name * @param dest the collection of the destination field names */ public DeleteCopyField(String source, List<String> dest) { this(source, dest, null); } public DeleteCopyField(String source, List<String> dest, SolrParams q) { super(createRequestParameters(source, dest), q); } private static NamedList<Object> createRequestParameters(String source, List<String> dest) { final NamedList<Object> addCopyFieldParameters = new NamedList<>(); addCopyFieldParameters.add("source", source); addCopyFieldParameters.add("dest", dest); final NamedList<Object> requestParameters = new NamedList<>(); requestParameters.add("delete-copy-field", addCopyFieldParameters); return requestParameters; } } public abstract static class Update extends AbstractSchemaRequest<SchemaResponse.UpdateResponse> { public Update() { this(null); } public Update(SolrParams q) { super(METHOD.POST, "/schema", q); } protected abstract NamedList<Object> getRequestParameters(); @Override @Deprecated public Collection<ContentStream> getContentStreams() throws IOException { CharArr json = new CharArr(); new SchemaRequestJSONWriter(json).write(getRequestParameters()); return Collections.singletonList(new ContentStreamBase.StringStream(json.toString())); } @Override public RequestWriter.ContentWriter getContentWriter(String expectedType) { return new RequestWriter.ContentWriter() { @Override public void write(OutputStream os) throws IOException { //TODO : find a way to do streaming write CharArr json = new CharArr(); new SchemaRequestJSONWriter(json).write(getRequestParameters()); os.write(json.toString().getBytes(StandardCharsets.UTF_8)); } @Override public String getContentType() { return CommonParams.JSON_MIME; } }; } @Override protected SchemaResponse.UpdateResponse createResponse(SolrClient client) { return new SchemaResponse.UpdateResponse(); } } private static abstract class SingleUpdate extends Update { private final NamedList<Object> requestParameters; public SingleUpdate(NamedList<Object> requestParameters) { this(requestParameters, null); } public SingleUpdate(NamedList<Object> requestParameters, SolrParams q) { super(q); this.requestParameters = requestParameters; } @Override protected NamedList<Object> getRequestParameters() { return requestParameters; } } /** * <p>The Schema API offers the possibility to perform one or more add requests in a single command.</p> * <p>The API is transactional and all commands in a single {@link #process(SolrClient, String)} call * either succeed or fail together.</p> */ public static class MultiUpdate extends Update { private List<Update> updateSchemaRequests = new LinkedList<>(); public MultiUpdate(List<Update> updateSchemaRequests) { this(updateSchemaRequests, null); } public MultiUpdate(List<Update> updateSchemaRequests, SolrParams q) { super(q); if (updateSchemaRequests == null) { throw new IllegalArgumentException("updateSchemaRequests must be non-null"); } for (Update updateSchemaRequest : updateSchemaRequests) { if (updateSchemaRequest == null) { throw new IllegalArgumentException("updateSchemaRequests elements must be non-null"); } this.updateSchemaRequests.add(updateSchemaRequest); } } @Override protected NamedList<Object> getRequestParameters() { NamedList<Object> multipleRequestsParameters = new NamedList<>(); for (Update updateSchemaRequest : updateSchemaRequests) { multipleRequestsParameters.addAll(updateSchemaRequest.getRequestParameters()); } return multipleRequestsParameters; } } /** * Simple extension of the noggit JSONWriter used to be write objects * of type {@link NamedList}. * Writing of objects of the type {@link NamedList} is done in very much * the same way as for a map. * <p> * This writer is particularly useful when doing multiple update requests. * In update Schema API there can be done multiple add operations of the same * type (e.g. : add-field-type), they are grouped in an associative array, even though * this can't be done normally in JSON. For such a use-case, the {@link NamedList} * objects are particularly useful because they can group key-value mappings * having the same values for the keys (unlike maps). */ private static class SchemaRequestJSONWriter extends JSONWriter { public SchemaRequestJSONWriter(CharArr out, int indentSize) { super(out, indentSize); } public SchemaRequestJSONWriter(CharArr out) { super(out); } public void write(Object o) { if (o instanceof NamedList) { write((NamedList) o); } else super.write(o); } /** * @see #write(Map) */ @SuppressWarnings("unchecked") public void write(NamedList<?> val) { this.startObject(); int sz = val.size(); boolean first = true; Iterator i$ = val.iterator(); while (i$.hasNext()) { Map.Entry<String, ?> entry = (Map.Entry<String, ?>) i$.next(); if (first) { first = false; } else { this.writeValueSeparator(); } if (sz > 1) { this.indent(); } this.writeString(entry.getKey()); this.writeNameSeparator(); this.write(entry.getValue()); } this.endObject(); } } }
37.38785
114
0.711692
3b799d54b51cc95ae5f3a00b83640dfccaaa9a88
872
package com.kclmedu.mvc.mapper; import com.kclmedu.mvc.entity.Account; import java.io.Serializable; import java.util.List; /**************************** * 帐户持久层 * CRUD操作 */ public interface IAccountDao { /********* * 插入一个帐户对象到数据库中 * @param account */ void save(Account account); /*************** * 根据帐户ID来查询帐户信息 * @param id * @return */ Account findById(Serializable id); /**************** * 查询所有帐户信息 * @return */ List<Account> findAll(); /***************** * 更新帐户 * @param account */ void update(Account account); /*************** * 删除帐户 * @param id */ void delete(Serializable id); /***************** * 根据用户ID来查询出此用户下的所有帐户信息 * @param userId * @return */ List<Account> queryUserAccounts(Serializable userId); }
16.769231
57
0.493119
48ed01dd9f90e216c416720831dc11c15c7f430b
4,169
// Copyright 2021 Databricks // // 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.finos.legend.engine.plan.execution.stores.relational.connection.driver.vendors.databricks; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.factory.Lists; import org.finos.legend.engine.plan.execution.stores.relational.connection.authentication.AuthenticationStrategy; import org.finos.legend.engine.plan.execution.stores.relational.connection.driver.DatabaseManager; import org.finos.legend.engine.plan.execution.stores.relational.connection.driver.commands.RelationalDatabaseCommands; import org.finos.legend.engine.plan.execution.stores.relational.connection.ds.specifications.DatabricksDataSourceSpecification; import org.finos.legend.engine.shared.core.operational.Assert; import org.finos.legend.engine.shared.core.operational.errorManagement.EngineException; import java.util.Properties; public class DatabricksManager extends DatabaseManager { @Override public MutableList<String> getIds() { return Lists.mutable.with("Databricks"); } @Override public String buildURL(String host, int port, String databaseName, Properties extraUserDataSourceProperties, AuthenticationStrategy authenticationStrategy) { Assert.assertTrue(extraUserDataSourceProperties.getProperty(DatabricksDataSourceSpecification.DATABRICKS_HTTP_PATH) != null, () -> DatabricksDataSourceSpecification.DATABRICKS_HTTP_PATH + " is not set"); Assert.assertTrue(extraUserDataSourceProperties.getProperty(DatabricksDataSourceSpecification.DATABRICKS_HOSTNAME) != null, () -> DatabricksDataSourceSpecification.DATABRICKS_HOSTNAME + " is not set"); Assert.assertTrue(extraUserDataSourceProperties.getProperty(DatabricksDataSourceSpecification.DATABRICKS_PORT) != null, () -> DatabricksDataSourceSpecification.DATABRICKS_PORT + " is not set"); Assert.assertTrue(extraUserDataSourceProperties.getProperty(DatabricksDataSourceSpecification.DATABRICKS_PROTOCOL) != null, () -> DatabricksDataSourceSpecification.DATABRICKS_PROTOCOL + " is not set"); String httpPath = extraUserDataSourceProperties.getProperty(DatabricksDataSourceSpecification.DATABRICKS_HTTP_PATH).trim(); String hostname = extraUserDataSourceProperties.getProperty(DatabricksDataSourceSpecification.DATABRICKS_HOSTNAME).trim(); String dbport = extraUserDataSourceProperties.getProperty(DatabricksDataSourceSpecification.DATABRICKS_PORT).trim(); String protocol = extraUserDataSourceProperties.getProperty(DatabricksDataSourceSpecification.DATABRICKS_PROTOCOL).trim(); String transportMode = "http"; int useSSL = 1; switch (protocol.toLowerCase().trim()) { case "http": useSSL = 0; break; case "https": break; default: throw new EngineException("Unsupported protocol [" + protocol + "]"); } return String.format("jdbc:spark://%s:%s/default;transportMode=%s;ssl=%s;AuthMech=3;httpPath=%s;", hostname, dbport, transportMode, useSSL, httpPath ); } @Override public String getDriver() { return "org.finos.legend.engine.plan.execution.stores.relational.connection.driver.vendors.databricks.DatabricksDriver"; } @Override public RelationalDatabaseCommands relationalDatabaseSupport() { return new DatabricksCommands(); } @Override public boolean publishMetrics() { return false; } }
47.91954
211
0.742384
b6177decaafa88523a7474cd611949b5fca2175b
751
package com.gs.api.core.exception; import com.gs.api.core.Result; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; /** * @Description TODO 全局异常捕捉处理 * @Author GuoShao * @Date 2020/9/23 19:15 * @Version 1.0 **/ @Slf4j @RestControllerAdvice public class GlobalExceptionHandler { /** * Description : 全局异常捕捉处理 */ @ExceptionHandler(RRException.class) public Result apiExceptionHandler(HttpServletRequest req, RRException ex) { log.error("ApiException 异常抛出请求地址:{}", req.getRequestURI()); Result r = new Result(); r.setMsg(ex.getMessage()); r.setCode(500); r.setData("not data"); return r; } }
22.757576
79
0.6751
51f8bfd6b9912b1be19eafa25917f6370878baf0
3,598
/* 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.flowable.eventregistry.test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import java.io.StringReader; import java.sql.Connection; import org.apache.ibatis.jdbc.ScriptRunner; import org.flowable.common.engine.impl.db.DbSqlSession; import org.flowable.common.engine.impl.interceptor.CommandExecutor; import org.flowable.eventregistry.api.ChannelDefinition; import org.flowable.eventregistry.impl.cmd.UpdateChannelDefinitionTypeAndImplementationForAllChannelDefinitionsCmd; import org.junit.jupiter.api.Test; /** * @author Filip Hrisafov */ class UpdateChannelDefinitionTypeAndImplementationForAllChannelDefinitionsCmdTest extends AbstractFlowableEventTest { @Test @EventDeploymentAnnotation(resources = { "org/flowable/eventregistry/test/repository/one.channel", "org/flowable/eventregistry/test/repository/one-outbound.channel", "org/flowable/eventregistry/test/repository/two.channel" }) void updatingChannelDefinitionTypeAndImplementationShouldWork() { assertThat(repositoryService.createChannelDefinitionQuery().list()) .extracting(ChannelDefinition::getKey, ChannelDefinition::getType, ChannelDefinition::getImplementation) .containsExactlyInAnyOrder( tuple("one", "inbound", "jms"), tuple("one-outbound", "outbound", "rabbit"), tuple("two", "inbound", "jms") ); CommandExecutor commandExecutor = eventEngineConfiguration.getCommandExecutor(); commandExecutor.execute(commandContext -> { Connection connection = commandContext.getSession(DbSqlSession.class) .getSqlSession() .getConnection(); ScriptRunner runner = new ScriptRunner(connection); runner.runScript(new StringReader("UPDATE FLW_CHANNEL_DEFINITION SET TYPE_ = null, IMPLEMENTATION_ = null;")); return null; }); assertThat(repositoryService.createChannelDefinitionQuery().list()) .extracting(ChannelDefinition::getKey, ChannelDefinition::getType, ChannelDefinition::getImplementation) .containsExactlyInAnyOrder( tuple("one", null, null), tuple("one-outbound", null, null), tuple("two", null, null) ); commandExecutor.execute(new UpdateChannelDefinitionTypeAndImplementationForAllChannelDefinitionsCmd()); assertThat(repositoryService.createChannelDefinitionQuery().list()) .extracting(ChannelDefinition::getKey, ChannelDefinition::getType, ChannelDefinition::getImplementation) .containsExactlyInAnyOrder( tuple("one", "inbound", "jms"), tuple("one-outbound", "outbound", "rabbit"), tuple("two", "inbound", "jms") ); } }
45.544304
122
0.6801
ae392fdcb2328903d64c37a51f877a602cbc4d97
515
import java.util.*; class CompareTheTriplets { static List<Integer> compareTriplets(List<Integer> a, List<Integer> b) { List<Integer> points = new ArrayList<Integer>(); points.add(0); points.add(0); for (int i = 0; i < a.size(); i++) { if (a.get(i) > b.get(i)) { points.set(0, (points.get(0) + 1)); } else if (a.get(i) < b.get(i)) { points.set(1, (points.get(1) + 1)); } } return points; } }
27.105263
73
0.47767
f8bffe568525afb671f742c291d22317c7bb1aac
3,810
/* * Copyright (C) 2012 Paul Watts (paulcwatts@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onebusaway.io.client.request; import java.net.URI; import java.util.concurrent.Callable; public final class ObaReportProblemWithStopRequest extends RequestBase implements Callable<ObaReportProblemWithStopResponse> { //private static final String TAG = "ObaReportProblemWithStopRequest"; // The stop name in OneBusAway differs from the actual stop name. public static final String NAME_WRONG = "stop_name_wrong"; // The stop number in OneBusAway differs from the actual stop number. public static final String NUMBER_WRONG = "stop_number_wrong"; // The stop location in OneBusAway differs from the action location. public static final String LOCATION_WRONG = "stop_location_wrong"; // An expected route or trip is missing from the stop. public static final String ROUTE_OR_TRIP_MISSING = "route_or_trip_missing"; // Other public static final String OTHER = "other"; protected ObaReportProblemWithStopRequest(URI uri, String postData) { super(uri, postData); } public static class Builder extends RequestBase.PostBuilderBase { public Builder(String stopId) { super(BASE_PATH + "/report-problem-with-stop.json"); mPostData.queryParam("stopId", stopId); } /** * Sets the optional problem code. * * @param code The problem code. */ public Builder setCode(String code) { mPostData.queryParam("code", code); // This is also for the old, JSON-encoded "data" format of the API. String data = String.format("{\"code\":\"%s\"}", code); mPostData.queryParam("data", data); return this; } /** * Sets the optional user comment. * * @param comment The user comment. */ public Builder setUserComment(String comment) { mPostData.queryParam("userComment", comment); return this; } /** * Sets the optional user location. * * @param lat The user's current location. * @param lon The user's current location. */ public Builder setUserLocation(double lat, double lon) { mPostData.queryParam("userLat", String.valueOf(lat)); mPostData.queryParam("userLon", String.valueOf(lon)); return this; } /** * Sets the optional user's location accuracy, in meters. * * @param meters The user's location accuracy in meters. */ public Builder setUserLocationAccuracy(int meters) { mPostData.queryParam("userLocationAccuracy", String.valueOf(meters)); return this; } public ObaReportProblemWithStopRequest build() { return new ObaReportProblemWithStopRequest(buildUri(), buildPostData()); } } @Override public ObaReportProblemWithStopResponse call() { return callPostHack(ObaReportProblemWithStopResponse.class); } @Override public String toString() { return "ObaReportProblemWithStopRequest [mUri=" + mUri + "]"; } }
34.324324
84
0.649081
6471cc93b95ca4b21bb3f1583f00cbf0d57b289f
108
package com.github.superzhc.hadoop.spark.stream; /** * 2020年10月09日 superz add */ public class JDemo1 { }
13.5
48
0.722222
29329aa5abf2ed1b51edf424f9d47f05b324fc1a
4,329
// ============================================================================ // // Copyright (C) 2006-2018 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.camel.designer.ui.bean; import java.util.Properties; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.intro.IIntroSite; import org.eclipse.ui.intro.config.IIntroAction; import org.talend.camel.core.model.camelProperties.BeanItem; import org.talend.camel.designer.i18n.Messages; import org.talend.camel.designer.util.ECamelCoreImage; import org.talend.camel.model.CamelRepositoryNodeType; import org.talend.commons.exception.SystemException; import org.talend.commons.runtime.model.repository.ERepositoryStatus; import org.talend.commons.ui.runtime.exception.MessageBoxExceptionHandler; import org.talend.commons.ui.runtime.image.ImageProvider; import org.talend.core.repository.model.ProxyRepositoryFactory; import org.talend.repository.ProjectManager; import org.talend.repository.model.IProxyRepositoryFactory; import org.talend.repository.model.RepositoryNode; /** * DOC smallet class global comment. Detailled comment <br/> * * $Id: EditProcess.java 52559 2010-12-13 04:14:06Z nrousseau $ * */ public class EditCamelBean extends AbstractBeanAction implements IIntroAction { private String EDIT_LABEL = Messages.getString("EditProcess.editBean"); //$NON-NLS-1$ // private String OPEN_LABEL = Messages.getString("EditProcess.openBean"); //$NON-NLS-1$ // private static final String DBPROJECT_LABEL = "teneo"; // private Properties params; public EditCamelBean() { super(); this.setText(EDIT_LABEL); this.setToolTipText(EDIT_LABEL); this.setImageDescriptor(ImageProvider.getImageDesc(ECamelCoreImage.BEAN_ICON)); } @Override public void init(TreeViewer viewer, IStructuredSelection selection) { super.init(viewer, selection); boolean canWork = !selection.isEmpty() && selection.size() == 1; IProxyRepositoryFactory factory = ProxyRepositoryFactory.getInstance(); if (factory.isUserReadOnlyOnCurrentProject()) { canWork = false; } RepositoryNode node = (RepositoryNode) selection.getFirstElement(); if (canWork && (node.getObjectType() != CamelRepositoryNodeType.repositoryBeansType || !ProjectManager.getInstance().isInCurrentMainProject(node) || !isLastVersion(node))) { canWork = false; } if (canWork) { canWork = factory.getStatus(node.getObject()) != ERepositoryStatus.DELETED; } setEnabled(canWork); } /* * (non-Javadoc) * * @see org.eclipse.jface.action.Action#run() */ @Override protected void doRun() { if (repositoryNode == null) { repositoryNode = (RepositoryNode) ((IStructuredSelection) getSelection()).getFirstElement(); } BeanItem beanItem = (BeanItem) repositoryNode.getObject().getProperty().getItem(); try { openBeanEditor(beanItem, false); refresh(repositoryNode); } catch (PartInitException e) { MessageBoxExceptionHandler.process(e); } catch (SystemException e) { MessageBoxExceptionHandler.process(e); } } @Override public Class<?> getClassForDoubleClick() { return BeanItem.class; } /* * (non-Jsdoc) * * @see org.eclipse.ui.intro.config.IIntroAction#run(org.eclipse.ui.intro.IIntroSite, java.util.Properties) */ @Override public void run(IIntroSite site, Properties params) { // this.params = params; PlatformUI.getWorkbench().getIntroManager().closeIntro(PlatformUI.getWorkbench().getIntroManager().getIntro()); doRun(); } }
36.378151
119
0.671056
e1f12cd83f87f92df62138bc545c691cb0369abb
2,871
/* * Copyright (c) 2018 Oracle and/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 io.helidon.microprofile.faulttolerance; import javax.enterprise.context.Dependent; import org.eclipse.microprofile.faulttolerance.Bulkhead; import org.eclipse.microprofile.faulttolerance.Fallback; /** * Class BulkheadBean. */ @Dependent public class BulkheadBean { static final int CONCURRENT_CALLS = 3; static final int WAITING_TASK_QUEUE = 3; static final int MAX_CONCURRENT_CALLS = CONCURRENT_CALLS + WAITING_TASK_QUEUE; @Bulkhead(value = CONCURRENT_CALLS, waitingTaskQueue = WAITING_TASK_QUEUE) public String execute(long sleepMillis) { FaultToleranceTest.printStatus("BulkheadBean::execute", "success"); try { Thread.sleep(sleepMillis); } catch (InterruptedException e) { // falls through } return Thread.currentThread().getName(); } @Bulkhead(value = CONCURRENT_CALLS + 1, waitingTaskQueue = WAITING_TASK_QUEUE + 1) public String executePlusOne(long sleepMillis) { FaultToleranceTest.printStatus("BulkheadBean::executePlusOne", "success"); try { Thread.sleep(sleepMillis); } catch (InterruptedException e) { // falls through } return Thread.currentThread().getName(); } @Bulkhead(value = 2, waitingTaskQueue = 1) public String executeNoQueue(long sleepMillis) { FaultToleranceTest.printStatus("BulkheadBean::executeNoQueue", "success"); try { Thread.sleep(sleepMillis); } catch (InterruptedException e) { // falls through } return Thread.currentThread().getName(); } @Fallback(fallbackMethod = "onFailure") @Bulkhead(value = 2, waitingTaskQueue = 1) public String executeNoQueueWithFallback(long sleepMillis) { FaultToleranceTest.printStatus("BulkheadBean::executeNoQueue", "success"); try { Thread.sleep(sleepMillis); } catch (InterruptedException e) { // falls through } return Thread.currentThread().getName(); } public String onFailure() { FaultToleranceTest.printStatus("BulkheadBean::onFailure()", "success"); return Thread.currentThread().getName(); } }
33.383721
86
0.679902
71b5a119a052c0d5971e2caa34d053945a751f9f
1,154
package revxrsal.commands.bukkit; import org.bukkit.plugin.Plugin; import org.jetbrains.annotations.NotNull; import revxrsal.commands.CommandHandler; import revxrsal.commands.bukkit.core.BukkitHandler; /** * Represents Bukkit's command handler implementation */ public interface BukkitCommandHandler extends CommandHandler { /** * Registers commands automatically on Minecraft's 1.13+ command system * (so that you would get the colorful command completions!) * <p> * Note that you should call this method after you've registered * all your commands. * * @return This command handler */ BukkitCommandHandler registerBrigadier(); /** * Returns the plugin this command handler was registered for. * * @return The owning plugin */ @NotNull Plugin getPlugin(); /** * Creates a new {@link BukkitCommandHandler} for the specified plugin * * @param plugin Plugin to create for * @return The newly created command handler */ static @NotNull BukkitCommandHandler create(@NotNull Plugin plugin) { return new BukkitHandler(plugin); } }
27.47619
75
0.696707
3c975623201eff59c92f47f268ff1283189f55e8
4,749
package com.sequenceiq.environment.network.v1.converter; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.springframework.stereotype.Component; import com.sequenceiq.cloudbreak.cloud.azure.AzureUtils; import com.sequenceiq.cloudbreak.cloud.model.CloudSubnet; import com.sequenceiq.cloudbreak.cloud.model.Network; import com.sequenceiq.cloudbreak.cloud.model.network.CreatedCloudNetwork; import com.sequenceiq.cloudbreak.cloud.model.network.CreatedSubnet; import com.sequenceiq.environment.CloudPlatform; import com.sequenceiq.environment.network.dao.domain.AzureNetwork; import com.sequenceiq.environment.network.dao.domain.BaseNetwork; import com.sequenceiq.environment.network.dao.domain.RegistrationType; import com.sequenceiq.environment.network.dto.AzureParams; import com.sequenceiq.environment.network.dto.NetworkDto; @Component public class AzureEnvironmentNetworkConverter extends EnvironmentBaseNetworkConverter { @Override BaseNetwork createProviderSpecificNetwork(NetworkDto network) { AzureNetwork azureNetwork = new AzureNetwork(); AzureParams azureParams = network.getAzure(); if (azureParams != null) { azureNetwork.setNetworkId(azureParams.getNetworkId()); azureNetwork.setResourceGroupName(azureParams.getResourceGroupName()); azureNetwork.setNoPublicIp(azureParams.isNoPublicIp()); azureNetwork.setNoFirewallRules(azureParams.isNoFirewallRules()); } return azureNetwork; } @Override public BaseNetwork setProviderSpecificNetwork(BaseNetwork baseNetwork, CreatedCloudNetwork createdCloudNetwork) { AzureNetwork azureNetwork = (AzureNetwork) baseNetwork; azureNetwork.setName(createdCloudNetwork.getStackName()); azureNetwork.setRegistrationType(RegistrationType.CREATE_NEW); azureNetwork.setNetworkId(createdCloudNetwork.getNetworkId()); azureNetwork.setResourceGroupName(String.valueOf(createdCloudNetwork.getProperties().get("resourceGroupName"))); azureNetwork.setSubnetMetas(createdCloudNetwork.getSubnets().stream() .collect(Collectors.toMap(CreatedSubnet::getSubnetId, subnet -> new CloudSubnet( subnet.getSubnetId(), subnet.getSubnetId(), subnet.getAvailabilityZone(), subnet.getCidr(), subnet.isPublicSubnet(), subnet.isMapPublicIpOnLaunch(), subnet.isIgwAvailable()) ) ) ); return azureNetwork; } @Override NetworkDto setProviderSpecificFields(NetworkDto.Builder builder, BaseNetwork network) { AzureNetwork azureNetwork = (AzureNetwork) network; AzureParams.AzureParamsBuilder azureParamsBuilder = AzureParams.AzureParamsBuilder.anAzureParams(); Optional.ofNullable(azureNetwork.getNetworkId()).ifPresent(azureParamsBuilder::withNetworkId); Optional.ofNullable(azureNetwork.getResourceGroupName()).ifPresent(azureParamsBuilder::withResourceGroupName); Optional.ofNullable(azureNetwork.getNoFirewallRules()).ifPresent(azureParamsBuilder::withNoFirewallRules); Optional.ofNullable(azureNetwork.getNoPublicIp()).ifPresent(azureParamsBuilder::withNoPublicIp); return builder.withAzure(azureParamsBuilder.build()).build(); } @Override void setRegistrationType(BaseNetwork result, NetworkDto networkDto) { if (isExistingNetworkSpecified(networkDto)) { result.setRegistrationType(RegistrationType.EXISTING); } else { result.setRegistrationType(RegistrationType.CREATE_NEW); } } private boolean isExistingNetworkSpecified(NetworkDto networkDto) { return networkDto.getAzure() != null && networkDto.getAzure().getNetworkId() != null; } @Override public CloudPlatform getCloudPlatform() { return CloudPlatform.AZURE; } @Override public boolean hasExistingNetwork(BaseNetwork baseNetwork) { return Optional.ofNullable((AzureNetwork) baseNetwork).map(AzureNetwork::getNetworkId).isPresent(); } @Override public Network convertToNetwork(BaseNetwork baseNetwork) { AzureNetwork azureNetwork = (AzureNetwork) baseNetwork; Map<String, Object> param = new HashMap<>(); param.put(AzureUtils.RG_NAME, azureNetwork.getResourceGroupName()); param.put(AzureUtils.NETWORK_ID, azureNetwork.getNetworkId()); return new Network(null, param); } }
45.663462
120
0.714466
3e4f6aca5b8b8b3f437e008f2c210e5ba423cb28
2,479
package me.hhs.wanandroid.fragment; import android.content.Intent; import android.view.View; import android.widget.TextView; import butterknife.BindView; import butterknife.OnClick; import me.hhs.wanandroid.R; import me.hhs.wanandroid.ui.LoginActivity; import me.hhs.wanandroid.ui.SystemActivity; import me.hhs.wanandroid.utils.SPUtils; /** * Created by KevinSong on 2019/7/18 */ public class MeFragment extends BaseFragment { @BindView(R.id.user_name) TextView tvUserName; @BindView(R.id.user_id) TextView tvUserID; @Override public int getLayoutResId() { return R.layout.fragment_me; } @Override protected void initData() { super.initData(); tvUserName.setText((String) SPUtils.get(getContext(), "username", getString(R.string.go_login))); tvUserID.setText((String) SPUtils.get(getContext(), "userid", "id: ")); } @OnClick({R.id.user_name, R.id.ll_user_collect, R.id.ll_system_setting}) public void onClick(View view) { switch (view.getId()) { case R.id.user_name: if (tvUserName.getText().equals(getString(R.string.go_login))) startActivityForResult(new Intent(getContext(), LoginActivity.class), 100); break; case R.id.ll_user_collect: if (SPUtils.get(getContext(), "username", getString(R.string.go_login)).equals(getString(R.string.go_login))) { startActivityForResult(new Intent(getContext(), LoginActivity.class), 101); } else { Intent collcetIntent = new Intent(getActivity(), SystemActivity.class); collcetIntent.putExtra("from", "collect"); startActivity(collcetIntent); } break; case R.id.ll_system_setting: Intent sysIntent = new Intent(getActivity(), SystemActivity.class); sysIntent.putExtra("from", "system"); startActivityForResult(sysIntent, 101); break; default: break; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); tvUserName.setText((String) SPUtils.get(getContext(), "username", getString(R.string.go_login))); tvUserID.setText((String) SPUtils.get(getContext(), "userid", "id: ")); } }
35.927536
127
0.629286
548a2d05dc4455e851aa6fcb5ecc9bcc9bab107f
4,909
package me.bscal.healthy.common.mixin; import me.bscal.healthy.Healthy; import me.bscal.healthy.IBurnableCampfireBlockEntity; import me.bscal.healthy.common.mixin_accessors.CampfireBlockEntityAccessor; import net.minecraft.block.BlockState; import net.minecraft.block.CampfireBlock; import net.minecraft.block.entity.BlockEntity; import net.minecraft.block.entity.BlockEntityType; import net.minecraft.block.entity.CampfireBlockEntity; import net.minecraft.item.Item; import net.minecraft.nbt.NbtCompound; import net.minecraft.state.property.Properties; import net.minecraft.util.ActionResult; import net.minecraft.util.Clearable; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.Objects; @Mixin(CampfireBlockEntity.class) public abstract class CampfireBlockEntityMixin extends BlockEntity implements Clearable, IBurnableCampfireBlockEntity, CampfireBlockEntityAccessor { /** * Amount of ticks the fire should be lit */ @Unique private int m_fireLitTicks; public CampfireBlockEntityMixin(BlockEntityType<?> type, BlockPos pos, BlockState state) { super(type, pos, state); } /** * Injections */ @Inject(method = "litServerTick", at = @At(value = "HEAD")) private static void OnLitServerTick(World world, BlockPos pos, BlockState state, CampfireBlockEntity campfire, CallbackInfo ci) { CampfireBlockEntityAccessor campfireAccessor = (CampfireBlockEntityAccessor)campfire; if (!world.isClient()) { int ticks = campfireAccessor.GetTicks() - 1; campfireAccessor.SetTicks(ticks--); if (ticks < 0) { world.setBlockState(campfire.getPos(), state.with(Properties.LIT, false), 11); } } } @Inject(method = "unlitServerTick", at = @At(value = "HEAD")) private static void OnUnlitServerTick(World world, BlockPos pos, BlockState state, CampfireBlockEntity campfire, CallbackInfo ci) { CampfireBlockEntityAccessor campfireAccessor = (CampfireBlockEntityAccessor)campfire; if (!world.isClient() && campfireAccessor.GetTicks() > 0) { campfireAccessor.SetTicks(0); } } // SNAPSHOT BROKE THIS // @Inject(method = "tick", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/entity/CampfireBlockEntity;updateItemsBeingCooked()V")) // public void tick(CallbackInfo cb) // { // CampfireBlockEntity blockEntity = (CampfireBlockEntity) (Object) this; // if (!Objects.requireNonNull(blockEntity.getWorld()).isClient) // { // BlockState state = blockEntity.getCachedState(); // if (state.get(Properties.LIT)) // { // m_fireLitTicks--; // if (m_fireLitTicks < 0) // { // blockEntity.getWorld().setBlockState(blockEntity.getPos(), state.with(Properties.LIT, false), 11); // } // } // else if (m_fireLitTicks > 0) // m_fireLitTicks = 0; // } // } @Inject(method = "readNbt", at = @At(value = "RETURN")) public void fromTag(NbtCompound tag, CallbackInfo cb) { m_fireLitTicks = tag.getInt("FireLitTicks"); } @Inject(method="writeNbt", at = @At(value = "TAIL")) public void toTag(NbtCompound tag, CallbackInfoReturnable<NbtCompound> cb) { tag.putInt("FireLitTicks", m_fireLitTicks); } /** * Override custom interface methods. */ @Override public boolean isLit() { return CampfireBlock.isLitCampfire(((CampfireBlockEntity) ((Object) this)).getCachedState()); } @Override public ActionResult addFireTicks(Item item, int ticks) { CampfireBlockEntity blockEntity = (CampfireBlockEntity) (Object) this; if (!Objects.requireNonNull(blockEntity.getWorld()).isClient) { BlockState state = blockEntity.getCachedState(); boolean lit = CampfireBlock.isLitCampfire(state); if (!state.get(Properties.WATERLOGGED) && lit) { m_fireLitTicks += ticks; return ActionResult.SUCCESS; } } return ActionResult.FAIL; } @Override public ActionResult tryFireIgnite(Item item, int ticks, float chance) { CampfireBlockEntity blockEntity = (CampfireBlockEntity) (Object) this; if (!Objects.requireNonNull(blockEntity.getWorld()).isClient) { BlockState state = blockEntity.getCachedState(); boolean lit = CampfireBlock.isLitCampfire(state); if (!state.get(Properties.WATERLOGGED) && !lit && Healthy.RAND.nextFloat() > chance) { blockEntity.getWorld().setBlockState(blockEntity.getPos(), state.with(Properties.LIT, true), 11); m_fireLitTicks += ticks; return ActionResult.SUCCESS; } } return ActionResult.FAIL; } @Unique @Override public int GetTicks() { return m_fireLitTicks; } @Unique @Override public void SetTicks(int i) { m_fireLitTicks = i; } }
29.572289
141
0.742921
8ec15129bc3ad3b1b0d6e9bee9d207848b7ee881
4,402
package com.gempukku.swccgo.cards.set8.light; import com.gempukku.swccgo.cards.AbstractNormalEffect; import com.gempukku.swccgo.cards.GameConditions; import com.gempukku.swccgo.cards.conditions.FiredWeaponsInBattleCondition; import com.gempukku.swccgo.cards.effects.CancelForceRetrievalEffect; import com.gempukku.swccgo.common.*; import com.gempukku.swccgo.filters.Filters; import com.gempukku.swccgo.game.PhysicalCard; import com.gempukku.swccgo.game.SwccgGame; import com.gempukku.swccgo.logic.TriggerConditions; import com.gempukku.swccgo.logic.actions.RequiredGameTextTriggerAction; import com.gempukku.swccgo.logic.decisions.YesNoDecision; import com.gempukku.swccgo.logic.effects.PlayoutDecisionEffect; import com.gempukku.swccgo.logic.effects.UseForceEffect; import com.gempukku.swccgo.logic.modifiers.Modifier; import com.gempukku.swccgo.logic.modifiers.TotalPowerModifier; import com.gempukku.swccgo.logic.timing.EffectResult; import com.gempukku.swccgo.logic.timing.GuiUtils; import com.gempukku.swccgo.logic.timing.results.AboutToRetrieveForceResult; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * Set: Endor * Type: Effect * Title: Aim High */ public class Card8_034 extends AbstractNormalEffect { public Card8_034() { super(Side.LIGHT, 3, PlayCardZoneOption.YOUR_SIDE_OF_TABLE, Title.Aim_High, Uniqueness.UNIQUE); setLore("The destruction of a command vehicle negatively impacts Imperial battle efficiency."); setGameText("Deploy on table. When you fire two weapons (except lightsabers) in a battle, your total power is +5. Also, whenever opponent retrieves X cards, opponent must first use X Force or that retrieval is canceled. (Immune to Alter.)"); addIcons(Icon.ENDOR); addImmuneToCardTitle(Title.Alter); } @Override protected List<Modifier> getGameTextWhileActiveInPlayModifiers(SwccgGame game, final PhysicalCard self) { String player = self.getOwner(); List<Modifier> modifiers = new LinkedList<Modifier>(); modifiers.add(new TotalPowerModifier(self, Filters.battleLocation, new FiredWeaponsInBattleCondition(player, 2, Filters.except(Filters.lightsaber)), 5, player)); return modifiers; } @Override protected List<RequiredGameTextTriggerAction> getGameTextRequiredAfterTriggers(SwccgGame game, EffectResult effectResult, final PhysicalCard self, int gameTextSourceCardId) { final String opponent = game.getOpponent(self.getOwner()); // Check condition(s) if (TriggerConditions.isAboutToRetrieveForce(game, effectResult, opponent)) { final float amountOfForce = ((AboutToRetrieveForceResult) effectResult).getAmountOfForceToRetrieve(); final RequiredGameTextTriggerAction action = new RequiredGameTextTriggerAction(self, gameTextSourceCardId); action.setText("Use Force or cancel retrieval"); action.setActionMsg("Make " + opponent + " use " + GuiUtils.formatAsString(amountOfForce) + " Force or Force retrieval is canceled"); if (GameConditions.canUseForce(game, opponent, amountOfForce)) { // Ask player to Use Force or retrieval is canceled action.appendEffect( new PlayoutDecisionEffect(action, opponent, new YesNoDecision("Do you want to use " + GuiUtils.formatAsString(amountOfForce) + " Force to proceed with Force retrieval?") { @Override protected void yes() { action.appendEffect( new UseForceEffect(action, opponent, amountOfForce)); } @Override protected void no() { action.appendEffect( new CancelForceRetrievalEffect(action)); } } ) ); } else { action.appendEffect( new CancelForceRetrievalEffect(action)); } return Collections.singletonList(action); } return null; } }
50.022727
249
0.659246
9623038f880748ac20255e61c589b2a7e5ed6df0
312
package com.mab.model; import lombok.Getter; import lombok.Setter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @Getter @Setter @JsonInclude(Include.NON_NULL) public class UrbanModel extends SubDistrictModel { private String urban; }
18.352941
60
0.810897
559e164b481b6bef6baf074555d4530641086257
2,957
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.config; import com.intellij.openapi.compiler.CompilerManager; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.EditorNotificationPanel; import com.intellij.ui.EditorNotifications; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.GroovyFileType; import org.jetbrains.plugins.groovy.annotator.GroovyFrameworkConfigNotification; /** * @author Maxim.Medvedev */ public final class ConfigureGroovyLibraryNotificationProvider extends EditorNotifications.Provider<EditorNotificationPanel> { private static final Key<EditorNotificationPanel> KEY = Key.create("configure.groovy.library"); @NotNull @Override public Key<EditorNotificationPanel> getKey() { return KEY; } @Override public EditorNotificationPanel createNotificationPanel(@NotNull VirtualFile file, @NotNull FileEditor fileEditor, @NotNull Project project) { try { if (!file.getFileType().equals(GroovyFileType.GROOVY_FILE_TYPE)) return null; // do not show the panel for Gradle build scripts // expecting groovy library to always be available at the gradle distribution if (StringUtil.endsWith(file.getName(), ".gradle")) return null; if (CompilerManager.getInstance(project).isExcludedFromCompilation(file)) return null; final Module module = ModuleUtilCore.findModuleForFile(file, project); if (module == null) return null; if (isMavenModule(module)) return null; for (GroovyFrameworkConfigNotification configNotification : GroovyFrameworkConfigNotification.EP_NAME.getExtensions()) { if (configNotification.hasFrameworkStructure(module)) { if (!configNotification.hasFrameworkLibrary(module)) { return (EditorNotificationPanel)configNotification.createConfigureNotificationPanel(module); } return null; } } } catch (ProcessCanceledException | IndexNotReadyException ignored) { } return null; } private static boolean isMavenModule(@NotNull Module module) { for (VirtualFile root : ModuleRootManager.getInstance(module).getContentRoots()) { if (root.findChild("pom.xml") != null) return true; } return false; } }
39.959459
140
0.739601
911d9c51e58d4d1754865bba855c7aaa031714a6
306
package com.zscat.mallplus.build.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.zscat.mallplus.build.entity.BuildingRoom; /** * <p> * 小区 Mapper 接口 * </p> * * @author zscat * @since 2019-11-27 */ public interface BuildingRoomMapper extends BaseMapper<BuildingRoom> { }
18
70
0.735294
e4ca59fe86a3c48d7ec66a280f32cbf763c66016
4,600
package com.conquestia.mobs; import com.gmail.filoghost.holograms.api.Hologram; import com.gmail.filoghost.holograms.api.HolographicDisplaysAPI; import java.text.DecimalFormat; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; /** * Provides a set of tools for creating holograms. * */ public class HoloUtils { Plugin plugin; public HoloUtils(Plugin plugin) { this.plugin = plugin; } /** * Creates a hologram that is displayed for everyone within * the default show distance from the hologram. * * @param deathLoc where the hologram will be (typically use location of eyes or hologram shows up in ground). * @param exp the exp amount to show. * @param money the money amount to show (if this is 0 will omit this line). * @param time how long to leave the hologram up(in seconds). */ public void sendDeathHologram(Location deathLoc, double exp, double money, long time) { DecimalFormat df = new DecimalFormat("#.##"); final Hologram createHologram; if (money != 0) { createHologram = HolographicDisplaysAPI.createHologram(plugin, deathLoc, ChatColor.WHITE + "+" + df.format(exp) + ChatColor.BLUE + " exp", ChatColor.GREEN + "+" + df.format(money) + ChatColor.WHITE + " Edens"); } else { createHologram = HolographicDisplaysAPI.createHologram(plugin, deathLoc, ChatColor.WHITE + "+" + df.format(exp) + ChatColor.BLUE + " exp"); } Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { public void run() { createHologram.delete(); } }, time * 20); } /** * Creates a hologram that is displayed only to a * specific player. * * @param deathLoc Where to display the hologram. * @param eyes Which player should see this hologram. * @param exp how much xp the player is receiving. * @param money how much money the player is receiving (if 0 omits line). * @param time how long to show the hologram. */ public Hologram sendSoloHologram(Location deathLoc, Player eyes, double exp, double money, long time) { DecimalFormat df = new DecimalFormat("#.##"); final Hologram createHologram; deathLoc.setY(deathLoc.getY()+2); if (money != 0) { createHologram = HolographicDisplaysAPI.createIndividualHologram(plugin, deathLoc, eyes, ChatColor.WHITE + "+" + df.format(exp) + ChatColor.BLUE + " exp", ChatColor.GREEN + "+" + df.format(money) + ChatColor.WHITE + " Edens"); } else { createHologram = HolographicDisplaysAPI.createIndividualHologram(plugin, deathLoc, eyes, ChatColor.WHITE + "+" + df.format(exp) + ChatColor.BLUE + " exp"); } Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { @Override public void run() { createHologram.delete(); } }, time * 20); return createHologram; } /** * Creates a hologram that is displayed to an * entire hero party. * * @param deathLoc Where to display the hologram. * @param party the list of which players should see the party. * @param exp how much xp the player is receiving. * @param money how much money the player is receiving (if 0 omits line). * @param time how long to show the hologram. */ public Hologram sendPartyHologram(Location deathLoc, List<Player> party, double exp, double money, long time) { DecimalFormat df = new DecimalFormat("#.##"); final Hologram createHologram; deathLoc.setY(deathLoc.getY()+2); if (money != 0) { createHologram = HolographicDisplaysAPI.createIndividualHologram(plugin, deathLoc, party , ChatColor.WHITE + "+" + df.format(exp) + ChatColor.BLUE + " exp", ChatColor.GREEN + "+" + df.format(money) + ChatColor.WHITE + " Edens"); } else { createHologram = HolographicDisplaysAPI.createIndividualHologram(plugin, deathLoc, party, ChatColor.WHITE + "+" + df.format(exp) + ChatColor.BLUE + " exp"); } Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { @Override public void run() { createHologram.delete(); } }, time * 20); return createHologram; } }
38.016529
240
0.622174
2ec08ddbb848f5fab28614473a73778c36f2f0b6
1,405
package com.ja.smarkdown.processing.plugins; import com.ja.smarkdown.model.ResourceInfo; import com.ja.smarkdown.processing.AbstractContentDataProcessor; import com.ja.smarkdown.processing.LineContext; import com.ja.smarkdown.processing.MetaData; /** * Adds a list of duplicate locations to the beginning of the document. * * @author Thomas Scheuchzer * */ public class CheckDuplicatesContentDataProcessor extends AbstractContentDataProcessor { private boolean addDuplicateInfo; @Override public void processLine(String line, LineContext ctx) { final MetaData metaData = getMetaData(); if (addDuplicateInfo) { final StringBuilder buf = new StringBuilder(); buf.append("<div class='alert alert-info'>"); buf.append("Document found in multiple locations!"); buf.append("<ul>"); buf.append("<li>") .append(metaData.getResource().getLocation().getUrl()) .append("</li>"); for (final ResourceInfo ri : metaData.getResource().getOverridden()) { buf.append("<li>").append(ri.getLocation().getUrl()) .append(ri.getPath()).append("</li>"); } buf.append("</ul>"); buf.append("</div>\n"); ctx.insertBefore(buf.toString()); addDuplicateInfo = false; } } public void start(MetaData metaData, StringBuilder out) { super.start(metaData, out); if (!metaData.getResource().getOverridden().isEmpty()) { addDuplicateInfo = true; } } }
28.1
73
0.71032
44399e1dc42f56a28bff1d84228e2e7a70f45db5
1,116
package eu.operando.interfaces.oapi.factories; import eu.operando.Utils; import eu.operando.interfaces.oapi.Config; import eu.operando.interfaces.oapi.ReportsService; import eu.operando.interfaces.oapi.impl.ReportsServiceImpl; import eu.operando.moduleclients.ClientReportGenerator; @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2016-07-12T14:06:26.001Z") public class ReportsServiceFactory { // Properties file property names. private static final String PROPERTY_NAME_ORIGIN_REPORT_GENERATOR = "originReportGenerator"; private static ReportsService service = null; public static ReportsService getReportsService() { if (service == null) { service = configureService(); } return service; } private static ReportsService configureService() { String originReportGenerator = Utils.loadPropertyString(Config.PROPERTIES_FILE_OAPI, PROPERTY_NAME_ORIGIN_REPORT_GENERATOR); ClientReportGenerator clientReportGenerator = new ClientReportGenerator(originReportGenerator); return new ReportsServiceImpl(clientReportGenerator); } }
32.823529
132
0.815412
883e52ff57c2ba5041422d083b1e5eb1e34e7cce
1,102
package com.celestiala.apipotion.jersey.config; import com.celestiala.apipotion.jersey.async.AsyncRunner; import com.celestiala.apipotion.jersey.cache.CacheInterceptorService; import com.celestiala.apipotion.jersey.cache.JerseyMemCacheRepository; import com.celestiala.apipotion.jersey.cache.CacheAsyncRunner; import org.glassfish.hk2.api.InterceptionService; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.spi.ContainerLifecycleListener; import javax.inject.Singleton; import java.util.Properties; public class MobileUtilBinder extends AbstractBinder { @Override protected void configure() { bindFactory(PropertyFactory.class).to(Properties.class).in(Singleton.class); bind(AsyncRunner.class).to(ContainerLifecycleListener.class).in(Singleton.class); bind(CacheAsyncRunner.class).to(ContainerLifecycleListener.class).in(Singleton.class); bind(CacheInterceptorService.class).to(InterceptionService.class).in(Singleton.class); bindAsContract(JerseyMemCacheRepository.class).in(Singleton.class); } }
42.384615
94
0.809437
fa57cf0720dc6e13c1cfe50e97820c62ed67da39
4,692
/* * Copyright 2014 Avanza Bank AB * * 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.avanza.astrix.modules; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Stack; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import com.avanza.astrix.modules.ObjectCache.ObjectFactory; /** * * @author Elias Lindholm (elilin) * */ class ModuleInjector { private final ObjectCache objectCache = new ObjectCache(); private final ConcurrentMap<Class<?>, Class<?>> beanBindings = new ConcurrentHashMap<>(); private final Set<Class<?>> imports = new HashSet<>(); private final Set<Class<?>> exports = new HashSet<>(); private final String moduleName; private final ModuleInstancePostProcessors postProcessors = new ModuleInstancePostProcessors(); public ModuleInjector(String moduleName) { this.moduleName = moduleName; } public void registerBeanPostProcessor(ModuleInstancePostProcessor beanPostProcessor) { this.postProcessors.add(beanPostProcessor); } public <T> void bind(Class<T> type, Class<? extends T> providerType) { this.beanBindings.put(type, providerType); } public <T> void bind(Class<T> type, final T provider) { beanBindings.put(type, provider.getClass()); objectCache.create(provider.getClass(), provider); } public <T> T getBean(Class<T> type, ImportedDependencies importedDependencies) { if (!exports.contains(type)) { throw new IllegalArgumentException("Non exported bean: " + type); } return new CircularDependenciesAwareCreation(importedDependencies).create(type); } private class CircularDependenciesAwareCreation { private final Stack<Class<?>> constructionStack = new Stack<>(); private final ImportedDependencies importedDependencies; public CircularDependenciesAwareCreation(ImportedDependencies importedDependencies) { this.importedDependencies = importedDependencies; } public <T> T create(Class<T> type) { final Class<T> resolvedType = resolveBean(type); return objectCache.getInstance(resolvedType, new ObjectFactory<T>() { @Override public T create() throws Exception { return doCreate(resolvedType); } }); } public <T> Class<T> resolveBean(Class<T> type) { Class<?> boundType = beanBindings.get(type); if (boundType != null) { @SuppressWarnings("unchecked") var castedBoundType = (Class<T>) boundType; return castedBoundType; } if (Modifier.isAbstract(type.getModifiers()) || type.isInterface()) { throw new MissingBeanBinding(moduleName, type, constructionStack); } return type; } private <T> T doCreate(final Class<T> type) { try { if (constructionStack.contains(type)) { throw new CircularDependency(); } constructionStack.add(type); final ClassConstructorFactory<T> factory = new ClassConstructorFactory<T>(type); T result = factory.create(new Dependencies() { @Override public <E> Collection<E> getAll(Class<E> type) { List<E> result = new ArrayList<>(); if (ModuleInjector.this.imports.contains(type)) { result.addAll(importedDependencies.getAll(type)); } if (ModuleInjector.this.beanBindings.containsKey(type)) { result.add(create(type)); } return result; } @Override public <E> E get(Class<E> type) { if (ModuleInjector.this.imports.contains(type)) { return importedDependencies.get(type); } return create(type); } }); postProcessors.postProcess(result); constructionStack.pop(); return result; } catch (ModulesConfigurationException configurationException) { configurationException.addToDependencyTrace(type, moduleName); throw configurationException; } } } public void destroy() { this.objectCache.destroy(); } public void addExport(Class<?> exportedBean) { this.exports.add(exportedBean); } public void addImport(Class<?> importedBean) { this.imports.add(importedBean); } public Set<Class<?>> getExports() { return this.exports; } }
30.666667
96
0.719309
24e3689797b4d8832853b1c8f41f928f0831897f
29,241
/** * Copyright 2013 multibit.org * * Licensed under the MIT license (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.php * * 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.multibit.viewsystem.swing.view.walletlist; import com.google.bitcoin.core.Wallet.BalanceType; import org.bitcoinj.wallet.Protos.Wallet.EncryptionType; import org.joda.money.Money; import org.multibit.controller.Controller; import org.multibit.controller.bitcoin.BitcoinController; import org.multibit.exchange.CurrencyConverter; import org.multibit.message.Message; import org.multibit.model.bitcoin.WalletBusyListener; import org.multibit.model.bitcoin.WalletData; import org.multibit.network.MultiBitDownloadListener; import org.multibit.network.ReplayManager; import org.multibit.network.ReplayTask; import org.multibit.utils.ImageLoader; import org.multibit.viewsystem.swing.ColorAndFontConstants; import org.multibit.viewsystem.swing.MultiBitFrame; import org.multibit.viewsystem.swing.action.HelpContextAction; import org.multibit.viewsystem.swing.view.components.BlinkLabel; import org.multibit.viewsystem.swing.view.components.FontSizer; import org.multibit.viewsystem.swing.view.components.MultiBitTextField; import org.multibit.viewsystem.swing.view.components.MultiBitTitledPanel; import org.multibit.viewsystem.swing.view.panels.HelpContentsPanel; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.*; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; public class SingleWalletPanel extends JPanel implements ActionListener, FocusListener, WalletBusyListener { private static final int WIDTH_OF_TEXT_FIELD = 12; private static final long serialVersionUID = -7110340338285836548L; private static final Dimension ABOVE_BASELINE_LEADING_CORNER_PADDING = new Dimension(5, 5); private static final Dimension BELOW_BASELINE_TRAILING_CORNER_PADDING = new Dimension(5, 5); private WalletData perWalletModelData; private static final int COLOR_DELTA = 24; private static final int HEIGHT_DELTA = 26; private static final int WIDTH_DELTA = 4; private static final int MIN_WIDTH_SCROLLBAR_DELTA = 20; private static final double MINIMUM_WIDTH_SCALE_FACTOR = 0.5; private static Color inactiveBackGroundColor; private MultiBitTextField walletDescriptionTextField; private Border walletDescriptionTextFieldBorder; private BlinkLabel amountLabelBTC; private BlinkLabel amountLabelFiat; private final Controller controller; private final BitcoinController bitcoinController; private MultiBitFrame mainFrame; private int normalHeight; private int normalWidth; private RoundedPanel myRoundedPanel; public static int DESCRIPTION_HEIGHT_DELTA = 4; private boolean selected = false; private static final int WALLET_TYPE_LEFT_BORDER = 6; private static final int WALLET_TYPE_TOP_BORDER = 3; private static final int TWISTY_LEFT_OR_RIGHT_BORDER = 1; private static final int TWISTY_TOP_BORDER = 1; private JPanel twistyStent; private String unencryptedTooltip = ""; private String encryptedTooltip = ""; private JButton walletTypeButton; private JLabel hourglassLabel; private FontMetrics fontMetrics; private double lastSyncPercent; public SingleWalletPanel(WalletData perWalletModelData, final BitcoinController bitcoinController, MultiBitFrame mainFrame, final WalletListPanel walletListPanel) { this.perWalletModelData = perWalletModelData; this.bitcoinController = bitcoinController; this.controller = this.bitcoinController; this.mainFrame = mainFrame; perWalletModelData.setSingleWalletDownloadListener(new SingleWalletPanelDownloadListener(this.bitcoinController, this)); Font font = FontSizer.INSTANCE.getAdjustedDefaultFont(); fontMetrics = getFontMetrics(font); // By default not selected. selected = false; unencryptedTooltip = HelpContentsPanel.createMultilineTooltipText(new String[]{controller.getLocaliser().getString("singleWalletPanel.unencrypted.tooltip"), " ", controller.getLocaliser().getString("multiBitFrame.helpMenuTooltip")}); encryptedTooltip = HelpContentsPanel.createMultilineTooltipText(new String[]{controller.getLocaliser().getString("singleWalletPanel.encrypted.tooltip"), " ", controller.getLocaliser().getString("multiBitFrame.helpMenuTooltip")}); int NUMBER_OF_ROWS_IN_SUMMARY_PANEL = 2; int AMOUNT_HEIGHT_DELTA = 4; normalHeight = NUMBER_OF_ROWS_IN_SUMMARY_PANEL * fontMetrics.getHeight() + DESCRIPTION_HEIGHT_DELTA + AMOUNT_HEIGHT_DELTA + HEIGHT_DELTA; normalWidth = calculateNormalWidth(this); // Add contents to myRoundedPanel. myRoundedPanel = new RoundedPanel(controller.getLocaliser().getLocale()); myRoundedPanel.setLayout(new GridBagLayout()); myRoundedPanel.setOpaque(true); myRoundedPanel.setPreferredSize(new Dimension(normalWidth, normalHeight)); if (ComponentOrientation.LEFT_TO_RIGHT == ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())) { myRoundedPanel.setMinimumSize(new Dimension(calculateMinimumWidth(normalWidth), normalHeight)); } else { myRoundedPanel.setMinimumSize(new Dimension(normalWidth, normalHeight)); } myRoundedPanel.setMaximumSize(new Dimension(normalWidth * 2, normalHeight)); setOpaque(true); setFocusable(true); setBackground(ColorAndFontConstants.VERY_LIGHT_BACKGROUND_COLOR); if (ColorAndFontConstants.isInverse()) { inactiveBackGroundColor = new Color(Math.min(255, ColorAndFontConstants.BACKGROUND_COLOR.getRed() + 2 * COLOR_DELTA), Math.min(255, ColorAndFontConstants.BACKGROUND_COLOR.getBlue() + 2 * COLOR_DELTA), Math.min(255, ColorAndFontConstants.BACKGROUND_COLOR.getGreen() + 2 * COLOR_DELTA)); } else { inactiveBackGroundColor = new Color(Math.max(0, ColorAndFontConstants.BACKGROUND_COLOR.getRed() - COLOR_DELTA), Math.max(0, ColorAndFontConstants.BACKGROUND_COLOR.getBlue() - COLOR_DELTA), Math.max(0, ColorAndFontConstants.BACKGROUND_COLOR.getGreen() - COLOR_DELTA)); } GridBagConstraints constraints = new GridBagConstraints(); JLabel filler1 = new JLabel(); filler1.setMinimumSize(ABOVE_BASELINE_LEADING_CORNER_PADDING); filler1.setPreferredSize(ABOVE_BASELINE_LEADING_CORNER_PADDING); filler1.setMaximumSize(ABOVE_BASELINE_LEADING_CORNER_PADDING); filler1.setOpaque(false); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 0; constraints.gridy = 0; constraints.weightx = 0.04; constraints.weighty = 0.04; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.ABOVE_BASELINE_LEADING; myRoundedPanel.add(filler1, constraints); walletDescriptionTextField = new MultiBitTextField(perWalletModelData.getWalletDescription(), WIDTH_OF_TEXT_FIELD, controller); walletDescriptionTextField.setFocusable(true); walletDescriptionTextField.addActionListener(this); walletDescriptionTextField.addFocusListener(this); walletDescriptionTextField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (walletListPanel != null) { walletListPanel.selectAdjacentWallet(e, "SingleWalletPanel#WalletDescriptionTextField"); } super.keyTyped(e); } }); walletDescriptionTextFieldBorder = walletDescriptionTextField.getBorder(); walletDescriptionTextField.setOpaque(false); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 1; constraints.gridy = 1; constraints.weightx = 100; constraints.weighty = 8; constraints.gridwidth = 8; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_START; myRoundedPanel.add(walletDescriptionTextField, constraints); JLabel filler2 = new JLabel(); filler2.setMinimumSize(ABOVE_BASELINE_LEADING_CORNER_PADDING); filler2.setPreferredSize(ABOVE_BASELINE_LEADING_CORNER_PADDING); filler2.setMaximumSize(ABOVE_BASELINE_LEADING_CORNER_PADDING); filler2.setOpaque(false); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 7; constraints.gridy = 0; constraints.weightx = 0.04; constraints.weighty = 0.04; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.ABOVE_BASELINE_TRAILING; myRoundedPanel.add(filler2, constraints); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 1; constraints.gridy = 2; constraints.weightx = 0.1; constraints.weighty = 0.1; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_END; myRoundedPanel.add(MultiBitTitledPanel.createStent(2, 2), constraints); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 1; constraints.gridy = 3; constraints.weightx = 0.1; constraints.weighty = 0.1; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_END; JPanel iconRowStent = MultiBitTitledPanel.createStent((int) (walletDescriptionTextFieldBorder.getBorderInsets(this).left * 0.5)); myRoundedPanel.add(iconRowStent, constraints); // Wallet type icon. walletTypeButton = new JButton(); walletTypeButton.setOpaque(false); walletTypeButton.setVisible(true); walletTypeButton.setHorizontalAlignment(SwingConstants.CENTER); walletTypeButton.setVerticalAlignment(SwingConstants.CENTER); walletTypeButton.setBorder(BorderFactory.createEmptyBorder(WALLET_TYPE_TOP_BORDER, WALLET_TYPE_LEFT_BORDER, 0, WALLET_TYPE_LEFT_BORDER)); if (perWalletModelData.getWallet() != null) { setIconForWalletType(perWalletModelData.getWallet().getEncryptionType(), walletTypeButton); } constraints.fill = GridBagConstraints.NONE; constraints.gridx = 2; constraints.gridy = 3; constraints.weightx = 0.1; constraints.weighty = 0.1; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.CENTER; myRoundedPanel.add(walletTypeButton, constraints); // Hourglass icon. hourglassLabel = new JLabel(ImageLoader.createImageIcon(ImageLoader.HOURGLASS_ICON_FILE)); hourglassLabel.setOpaque(false); hourglassLabel.setVisible(perWalletModelData.isBusy()); hourglassLabel.setBorder(BorderFactory.createEmptyBorder(WALLET_TYPE_TOP_BORDER, WALLET_TYPE_LEFT_BORDER, 0, 0)); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 3; constraints.gridy = 3; constraints.weightx = 0.1; constraints.weighty = 0.1; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_START; myRoundedPanel.add(hourglassLabel, constraints); twistyStent = MultiBitTitledPanel.createStent(1, 1); twistyStent.setBorder(BorderFactory.createEmptyBorder(TWISTY_TOP_BORDER, TWISTY_LEFT_OR_RIGHT_BORDER, 0, TWISTY_LEFT_OR_RIGHT_BORDER)); twistyStent.setOpaque(false); myRoundedPanel.add(twistyStent, constraints); amountLabelBTC = new BlinkLabel(controller, false); amountLabelBTC.setBackground(ColorAndFontConstants.BACKGROUND_COLOR); amountLabelBTC.setBorder(BorderFactory.createEmptyBorder(0, 3, 0, 3)); amountLabelBTC.setBlinkEnabled(true); amountLabelBTC.setHorizontalAlignment(JLabel.TRAILING); amountLabelFiat = new BlinkLabel(controller, false); amountLabelFiat.setBackground(ColorAndFontConstants.BACKGROUND_COLOR); amountLabelFiat.setBorder(BorderFactory.createEmptyBorder(0, 3, 0, 3)); amountLabelFiat.setBlinkEnabled(true); amountLabelFiat.setHorizontalAlignment(JLabel.TRAILING); JPanel stent = new JPanel(); stent.setOpaque(false); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 5; constraints.gridy = 3; constraints.weightx = 10000; constraints.weighty = 0.1; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.LINE_END; myRoundedPanel.add(stent, constraints); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 6; constraints.gridy = 3; constraints.weightx = 0.1; constraints.weighty = 0.1; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_END; myRoundedPanel.add(amountLabelBTC, constraints); constraints.fill = GridBagConstraints.VERTICAL; constraints.gridx = 8; constraints.gridy = 3; constraints.weightx = 0.1; constraints.weighty = 0.1; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.LINE_END; myRoundedPanel.add(amountLabelFiat, constraints); JPanel filler5 = new JPanel(); filler5.setMinimumSize(BELOW_BASELINE_TRAILING_CORNER_PADDING); filler5.setPreferredSize(BELOW_BASELINE_TRAILING_CORNER_PADDING); filler5.setMaximumSize(BELOW_BASELINE_TRAILING_CORNER_PADDING); filler5.setOpaque(false); constraints.fill = GridBagConstraints.NONE; constraints.gridx = 9; constraints.gridy = 5; constraints.weightx = 0.02; constraints.weighty = 0.02; constraints.gridwidth = 1; constraints.anchor = GridBagConstraints.BELOW_BASELINE_TRAILING; myRoundedPanel.add(filler5, constraints); // Add myRoundedPanel to myself. setLayout(new GridBagLayout()); GridBagConstraints constraints2 = new GridBagConstraints(); constraints2.fill = GridBagConstraints.HORIZONTAL; constraints2.gridx = 0; constraints2.gridy = 0; constraints2.weightx = 1; constraints2.weighty = 1; constraints2.gridwidth = 1; constraints2.gridheight = 1; constraints2.anchor = GridBagConstraints.CENTER; add(myRoundedPanel, constraints2); // Add bottom filler. JPanel filler = new JPanel(); filler.setOpaque(false); constraints2.fill = GridBagConstraints.BOTH; constraints2.gridx = 0; constraints2.gridy = 2; constraints2.weightx = 1.0; constraints2.weighty = 1000; constraints2.gridwidth = 1; constraints2.gridheight = 1; constraints2.anchor = GridBagConstraints.CENTER; add(filler, constraints2); applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); setSelected(false); updateFromModel(false, true); addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent arg0) { if (walletListPanel != null) { walletListPanel.selectAdjacentWallet(arg0, "SingleWalletPanel"); } super.keyTyped(arg0); } }); // See if there is a waiting ReplayTask for this SingleWalletPanel and set up UI accordingly. ReplayTask replayTask = ReplayManager.INSTANCE.getWaitingReplayTask(perWalletModelData); if (replayTask != null) { String waitingText = controller.getLocaliser().getString("singleWalletPanel.waiting.verb"); // When busy occasionally the localiser fails to localise. if (!(waitingText.indexOf("singleWalletPanel.waiting.verb") > -1)) { setSyncMessage(waitingText, Message.NOT_RELEVANT_PERCENTAGE_COMPLETE); } } } private void setIconForWalletType(EncryptionType walletType, JButton button) { button.setHorizontalAlignment(SwingConstants.CENTER); button.setContentAreaFilled(false); if (selected) { button.setOpaque(true); button.setBackground(ColorAndFontConstants.VERY_LIGHT_BACKGROUND_COLOR); button.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(1, 1, 1, 1, ColorAndFontConstants.SELECTION_BACKGROUND_COLOR.darker()), BorderFactory.createMatteBorder(2, 2, 2, 2, ColorAndFontConstants.VERY_LIGHT_BACKGROUND_COLOR))); button.setBorderPainted(true); } else { button.setOpaque(false); button.setBackground(inactiveBackGroundColor); button.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); button.setBorderPainted(false); } if (walletType == EncryptionType.ENCRYPTED_SCRYPT_AES) { Action helpAction = new HelpContextAction(controller, ImageLoader.LOCK_ICON_FILE, "multiBitFrame.helpMenuText", "multiBitFrame.helpMenuTooltip", "multiBitFrame.helpMenuText", HelpContentsPanel.HELP_WALLET_TYPES_URL); button.setAction(helpAction); button.setText(""); button.setToolTipText(encryptedTooltip); } else { Action helpAction = new HelpContextAction(controller, ImageLoader.SINGLE_WALLET_ICON_FILE, "multiBitFrame.helpMenuText", "multiBitFrame.helpMenuTooltip", "multiBitFrame.helpMenuText", HelpContentsPanel.HELP_WALLET_TYPES_URL); button.setAction(helpAction); button.setText(""); button.setToolTipText(unencryptedTooltip); } } public static int calculateNormalWidth(JComponent component) { Font font = FontSizer.INSTANCE.getAdjustedDefaultFont(); FontMetrics fontMetrics = component.getFontMetrics(font); return (int) (fontMetrics.stringWidth(MultiBitFrame.EXAMPLE_MEDIUM_FIELD_TEXT) + WIDTH_DELTA); } private int calculateMinimumWidth(int normalWidth) { if (ComponentOrientation.LEFT_TO_RIGHT == ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())) { return (int) Math.max(0, normalWidth * MINIMUM_WIDTH_SCALE_FACTOR - MIN_WIDTH_SCROLLBAR_DELTA); } else { return normalWidth; } } @Override public void addMouseListener(MouseListener mouseListener) { super.addMouseListener(mouseListener); walletDescriptionTextField.addMouseListener(mouseListener); amountLabelBTC.addMouseListener(mouseListener); amountLabelFiat.addMouseListener(mouseListener); myRoundedPanel.addMouseListener(mouseListener); if (hourglassLabel != null) { hourglassLabel.addMouseListener(mouseListener); } } public void setBusyIconStatus(boolean isBusy) { hourglassLabel.setVisible(isBusy); // Update the tooltip. if (this.bitcoinController.getModel().getActivePerWalletModelData().isBusy()) { // Wallet is busy with another operation that may change the private keys - Action is disabled. if (perWalletModelData != null) { String toolTipText = HelpContentsPanel.createTooltipText(controller.getLocaliser().getString("multiBitSubmitAction.walletIsBusy", new Object[]{controller.getLocaliser().getString(perWalletModelData.getBusyTaskKey())})); hourglassLabel.setToolTipText(toolTipText); } else { hourglassLabel.setToolTipText(null); } } else { hourglassLabel.setToolTipText(null); } } public void setSelected(boolean selected) { this.selected = selected; myRoundedPanel.setSelected(selected); if (!perWalletModelData.isFilesHaveBeenChangedByAnotherProcess()) { setPreferredSize(new Dimension(normalWidth, normalHeight)); if (ComponentOrientation.LEFT_TO_RIGHT == ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())) { setMinimumSize(new Dimension(calculateMinimumWidth(normalWidth), normalHeight)); } else { setMinimumSize(new Dimension(normalWidth, normalHeight)); } setMaximumSize(new Dimension(normalWidth * 2, normalHeight)); if (selected) { walletDescriptionTextField.setForeground(ColorAndFontConstants.TEXT_COLOR); if (!walletDescriptionTextField.isEditable()) { walletDescriptionTextField.setEditable(true); } requestFocusInWindow(); walletDescriptionTextField.setBorder(walletDescriptionTextFieldBorder); walletDescriptionTextField.setBackground(ColorAndFontConstants.BACKGROUND_COLOR); myRoundedPanel.setBackground(ColorAndFontConstants.BACKGROUND_COLOR); walletTypeButton.setOpaque(true); walletTypeButton.setBackground(ColorAndFontConstants.VERY_LIGHT_BACKGROUND_COLOR); Color selectionBackGroundColor = ColorAndFontConstants.SELECTION_BACKGROUND_COLOR; selectionBackGroundColor = ColorAndFontConstants.isInverse() ? selectionBackGroundColor.brighter() : selectionBackGroundColor.darker(); walletTypeButton.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, selectionBackGroundColor), BorderFactory.createMatteBorder(2, 2, 2, 2, ColorAndFontConstants.VERY_LIGHT_BACKGROUND_COLOR))); walletTypeButton.setBorderPainted(true); myRoundedPanel.repaint(); twistyStent.setVisible(true); } else { walletDescriptionTextField.setForeground(ColorAndFontConstants.TEXT_COLOR); walletDescriptionTextField.setEditable(false); Insets insets = walletDescriptionTextFieldBorder.getBorderInsets(this); Border border = BorderFactory.createEmptyBorder(insets.top, insets.left, insets.bottom, insets.right); walletDescriptionTextField.setBorder(border); walletDescriptionTextField.setBackground(inactiveBackGroundColor); myRoundedPanel.setBackground(inactiveBackGroundColor); walletTypeButton.setOpaque(false); walletTypeButton.setBackground(inactiveBackGroundColor); walletTypeButton.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3)); walletTypeButton.setBorderPainted(false); myRoundedPanel.repaint(); twistyStent.setVisible(true); } } } @Override public void actionPerformed(ActionEvent evt) { saveChanges(); if (!perWalletModelData.isFilesHaveBeenChangedByAnotherProcess()) { walletDescriptionTextField.setBackground(ColorAndFontConstants.BACKGROUND_COLOR); } requestFocusInWindow(); } public WalletData getPerWalletModelData() { return perWalletModelData; } @Override public void focusGained(FocusEvent arg0) { if (!perWalletModelData.isFilesHaveBeenChangedByAnotherProcess()) { walletDescriptionTextField.setSelectedTextColor(ColorAndFontConstants.SELECTION_FOREGROUND_COLOR); walletDescriptionTextField.setSelectionColor(ColorAndFontConstants.SELECTION_BACKGROUND_COLOR); String text = walletDescriptionTextField.getText(); walletDescriptionTextField.setCaretPosition(text == null ? 0 : text.length()); perWalletModelData.setWalletDescription(text); if (!(arg0.getSource() instanceof JTextField)) { // Panel selection. requestFocusInWindow(); } } } @Override public void focusLost(FocusEvent arg0) { saveChanges(); } private void saveChanges() { if (!perWalletModelData.isFilesHaveBeenChangedByAnotherProcess()) { walletDescriptionTextField.setForeground(ColorAndFontConstants.TEXT_COLOR); walletDescriptionTextField.select(0, 0); String text = walletDescriptionTextField.getText(); perWalletModelData.setWalletDescription(text); String titleText = controller.getLocaliser().getString("multiBitFrame.title"); if (this.bitcoinController.getModel().getActiveWallet() != null) { titleText = titleText + MultiBitFrame.SEPARATOR + this.bitcoinController.getModel().getActivePerWalletModelData().getWalletDescription() + MultiBitFrame.SEPARATOR + this.bitcoinController.getModel().getActivePerWalletModelData().getWalletFilename(); } mainFrame.setTitle(titleText); } } /** * Update any UI elements from the model (hint that data has changed). */ public void updateFromModel(boolean blinkEnabled, boolean useBusyStatus) { if (ColorAndFontConstants.isInverse()) { inactiveBackGroundColor = new Color(Math.min(255, ColorAndFontConstants.BACKGROUND_COLOR.getRed() + 2 * COLOR_DELTA), Math.min(255, ColorAndFontConstants.BACKGROUND_COLOR.getBlue() + 2 * COLOR_DELTA), Math.min(255, ColorAndFontConstants.BACKGROUND_COLOR.getGreen() + 2 * COLOR_DELTA)); } else { inactiveBackGroundColor = new Color(Math.max(0, ColorAndFontConstants.BACKGROUND_COLOR.getRed() - COLOR_DELTA), Math.max(0, ColorAndFontConstants.BACKGROUND_COLOR.getBlue() - COLOR_DELTA), Math.max(0, ColorAndFontConstants.BACKGROUND_COLOR.getGreen() - COLOR_DELTA)); } BigInteger estimatedBalance = perWalletModelData.getWallet().getBalance(BalanceType.ESTIMATED); String balanceTextToShowBTC = controller.getLocaliser().bitcoinValueToString(estimatedBalance, true, false); String balanceTextToShowFiat = ""; if (CurrencyConverter.INSTANCE.getRate() != null && CurrencyConverter.INSTANCE.isShowingFiat()) { Money fiat = CurrencyConverter.INSTANCE.convertFromBTCToFiat(estimatedBalance); balanceTextToShowFiat = "(" + CurrencyConverter.INSTANCE.getFiatAsLocalisedString(fiat) + ")"; } if (useBusyStatus && perWalletModelData.isBusy()) { if (lastSyncPercent > 0) { setSyncMessage(controller.getLocaliser().getString(perWalletModelData.getBusyTaskVerbKey()), lastSyncPercent); } else { setSyncMessage(controller.getLocaliser().getString(perWalletModelData.getBusyTaskVerbKey()), Message.NOT_RELEVANT_PERCENTAGE_COMPLETE); } } else { if (amountLabelBTC != null && amountLabelBTC.getText() != null && !"".equals(amountLabelBTC.getText()) && !balanceTextToShowBTC.equals(amountLabelBTC.getText()) && blinkEnabled) { amountLabelBTC.blink(balanceTextToShowBTC); amountLabelFiat.blink(balanceTextToShowFiat); } else { amountLabelBTC.setText(balanceTextToShowBTC); amountLabelFiat.setText(balanceTextToShowFiat); } } if (perWalletModelData.getWallet() != null) { setIconForWalletType(perWalletModelData.getWallet().getEncryptionType(), walletTypeButton); } if (perWalletModelData.isFilesHaveBeenChangedByAnotherProcess()) { myRoundedPanel.setOpaque(true); myRoundedPanel.setBackground(ColorAndFontConstants.VERY_LIGHT_BACKGROUND_COLOR); walletDescriptionTextField.setBackground(ColorAndFontConstants.VERY_LIGHT_BACKGROUND_COLOR); walletDescriptionTextField.setText(controller.getLocaliser().getString("singleWalletPanel.dataHasChanged.text")); walletDescriptionTextField.setForeground(ColorAndFontConstants.DATA_HAS_CHANGED_TEXT_COLOR); walletDescriptionTextField.setDisabledTextColor(ColorAndFontConstants.DATA_HAS_CHANGED_TEXT_COLOR); mainFrame.setUpdatesStoppedTooltip(walletDescriptionTextField); walletDescriptionTextField.setEnabled(false); walletDescriptionTextField.setEditable(false); amountLabelBTC.setText(""); amountLabelBTC.setEnabled(false); amountLabelFiat.setText(""); amountLabelFiat.setEnabled(false); walletTypeButton.setEnabled(false); } invalidate(); revalidate(); repaint(); } public void setSyncMessage(String message, double syncPercent) { if (message == null) { return; } lastSyncPercent = syncPercent; if (syncPercent > MultiBitDownloadListener.DONE_FOR_DOUBLES) { updateFromModel(false, false); } else { if (perWalletModelData.isBusy()) { // It shoud always be whilst a download is occurring. setBusyIconStatus(true); } String percentText = " "; if (syncPercent > Message.NOT_RELEVANT_PERCENTAGE_COMPLETE) { percentText = "(" + (int) syncPercent + "%)"; } amountLabelBTC.setBlinkEnabled(false); amountLabelFiat.setBlinkEnabled(false); amountLabelBTC.setText(message); amountLabelFiat.setText(percentText); amountLabelBTC.setBlinkEnabled(true); amountLabelFiat.setBlinkEnabled(true); if (perWalletModelData.getWalletFilename().equals(this.bitcoinController.getModel().getActiveWalletFilename())) { mainFrame.updateHeader(message, syncPercent); } } } public int getFiatLabelWidth() { return fontMetrics.stringWidth(amountLabelFiat.getText()); } public void setFiatLabelWidth(int fiatLabelMinimumWidth) { amountLabelFiat.setMinimumSize(new Dimension(fiatLabelMinimumWidth, amountLabelFiat.getMinimumSize().height)); amountLabelFiat.setPreferredSize(new Dimension(fiatLabelMinimumWidth, amountLabelFiat.getPreferredSize().height)); amountLabelFiat.setMaximumSize(new Dimension(fiatLabelMinimumWidth, amountLabelFiat.getMaximumSize().height)); } public boolean isSelectedInternal() { return selected; } @Override public void walletBusyChange(boolean newWalletIsBusy) { if (perWalletModelData.isBusy()) { setSyncMessage(controller.getLocaliser().getString(perWalletModelData.getBusyTaskVerbKey()), Message.NOT_RELEVANT_PERCENTAGE_COMPLETE); } } }
42.134006
167
0.753907
73b3464afd3234f8eb2954522376ef1fe70ca956
2,914
// --- // Copyright 2020 ClusterVAS Team // All rights reserved // --- package org.opentoolset.clustervas.utils; import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.helpers.MessageFormatter; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.net.SyslogAppender; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.Appender; public class CVLogger { private static ch.qos.logback.classic.Logger logger; static { Logger genericLogger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); if (genericLogger instanceof ch.qos.logback.classic.Logger) { logger = (ch.qos.logback.classic.Logger) genericLogger; logger.setLevel(Level.INFO); boolean addSyslogAppender = true; Iterator<Appender<ILoggingEvent>> appenders = logger.iteratorForAppenders(); while (appenders.hasNext()) { Appender<ILoggingEvent> appender = appenders.next(); // if (appender instanceof ConsoleAppender) { // logger.detachAppender(appender); // } if (appender instanceof SyslogAppender) { addSyslogAppender = false; } } if (addSyslogAppender) { SyslogAppender appender = new SyslogAppender(); logger.addAppender(appender); } } else { throw new IllegalStateException(String.format("ch.qos.logback.classic.Logger is required. Current one is: %s", logger)); } } public static void debug(String format, Object... args) { logger.debug(format, args); } public static void info(String format, Object... args) { logger.info(format, args); } public static void warn(String format, Object... args) { logger.warn(format, args); } public static void error(String format, Object... args) { logger.error(format, args); } public static void debug(Throwable e, String format, Object... args) { String msg = MessageFormatter.format(format, args).getMessage(); logger.debug(msg, e); } public static void warn(Throwable e, String format, Object... args) { String msg = MessageFormatter.format(format, args).getMessage(); logger.warn(msg, e); } public static void error(Throwable e, String format, Object... args) { String msg = MessageFormatter.format(format, args).getMessage(); logger.error(msg, e); } public static void warn(Throwable e) { logger.warn("", e); } public static void error(Throwable e) { logger.error("", e); } public static void entering() { StackTraceElement element = getCallingMethod(); logger.info("entering {}.{}", element.getClassName(), element.getMethodName()); } public static void exiting() { StackTraceElement element = getCallingMethod(); logger.info("exiting {}.{}", element.getClassName(), element.getMethodName()); } // --- private static StackTraceElement getCallingMethod() { StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[3]; return stackTraceElement; } }
27.490566
123
0.721002
04d1e48e5b12dfe9617d735f8afecb0a602ae49a
3,398
package net.techreadiness.ui.util; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.when; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.google.common.collect.Maps; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; @RunWith(MockitoJUnitRunner.class) public class ConversationScopeInterceptorTest { ConversationScopeInterceptor interceptor; @Mock ActionInvocation invocation; @Mock ActionContext context; Map<String, Object> session; ExampleActionClass action; public static class BaseExcampleAction { @ConversationScoped private Object baseObject; public Object getBaseObject() { return baseObject; } } public static class ExampleActionClass extends BaseExcampleAction implements ConversationAware { @ConversationScoped private Object object; @ConversationScoped("otherObject") private Object myObject; private Conversation conversation; public void setObject(Object object) { this.object = object; } public Object getObject() { return object; } public void setMyObject(Object myObject) { this.myObject = myObject; } public Object getMyObject() { return myObject; } @Override public void setConversation(Conversation conversation) { this.conversation = conversation; } public Conversation getConversation() { return conversation; } } @Before public void setup() { interceptor = new ConversationScopeInterceptor(); session = Maps.newHashMap(); action = new ExampleActionClass(); when(invocation.getAction()).thenReturn(action); when(invocation.getInvocationContext()).thenReturn(context); when(context.getSession()).thenReturn(session); } @Test public void testIntercept() throws Exception { interceptor.intercept(invocation); assertNotNull("the action's object should be created", action.getObject()); assertSame("the action's object should be stored in the session", action.getObject(), getConversation().get(Object.class, "object")); } @Test public void testConversationLookup() throws Exception { Object object = new Object(); getConversation().put("object", object); interceptor.intercept(invocation); assertSame("the object previously stored in the conversation should be set on the action", object, action.getObject()); } @Test public void testAnnotationName() throws Exception { Object expected = new Object(); getConversation().put("otherObject", expected); interceptor.intercept(invocation); assertSame("the object should have been injected based on the value of the annotation", expected, action.getMyObject()); } @Test public void testConversationAware() throws Exception { interceptor.intercept(invocation); assertNotNull(action.getConversation()); } @Test public void testInjectionOnBaseProperties() throws Exception { Object expected = new Object(); getConversation().put("baseObject", expected); interceptor.intercept(invocation); assertSame("The object should be injected on the base class", expected, action.getBaseObject()); } private Conversation getConversation() { return interceptor.getDefaultConversation(action, session); } }
24.623188
100
0.762802
f3d9480039eba6188a0ab8c2c8096c35b3495c1d
3,405
/* */ package org.apache.xpath.axes; /* */ /* */ import javax.xml.transform.TransformerException; /* */ import org.apache.xml.dtm.DTMAxisTraverser; /* */ import org.apache.xml.dtm.DTMIterator; /* */ import org.apache.xpath.compiler.Compiler; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class ChildTestIterator /* */ extends BasicTestIterator /* */ { /* */ protected transient DTMAxisTraverser m_traverser; /* */ /* */ ChildTestIterator(Compiler compiler, int opPos, int analysis) throws TransformerException { /* 54 */ super(compiler, opPos, analysis); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public ChildTestIterator(DTMAxisTraverser traverser) { /* 67 */ super(null); /* */ /* 69 */ this.m_traverser = traverser; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ protected int getNextNode() { /* 80 */ this.m_lastFetched = (-1 == this.m_lastFetched) ? this.m_traverser.first(this.m_context) : this.m_traverser.next(this.m_context, this.m_lastFetched); /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* 92 */ return this.m_lastFetched; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public DTMIterator cloneWithReset() throws CloneNotSupportedException { /* 107 */ ChildTestIterator clone = (ChildTestIterator)super.cloneWithReset(); /* 108 */ clone.m_traverser = this.m_traverser; /* */ /* 110 */ return clone; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public void setRoot(int context, Object environment) { /* 123 */ super.setRoot(context, environment); /* 124 */ this.m_traverser = this.m_cdtm.getAxisTraverser(3); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public int getAxis() { /* 154 */ return 3; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public void detach() { /* 166 */ if (this.m_allowDetach) { /* */ /* 168 */ this.m_traverser = null; /* */ /* */ /* 171 */ super.detach(); /* */ } /* */ } /* */ } /* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/xpath/axes/ChildTestIterator.class * Java compiler version: 1 (45.3) * JD-Core Version: 1.1.3 */
18.916667
163
0.331865
6b8e5c9e14365c9956fc27ff12de2c0bc7cb408b
648
package de.lmu.ifi.dbs.utilities; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * @author graf */ public class Math2Test { @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Test public void testDiv(){ double div = Math2.div(1, 2, 3); assertEquals(0.5, div, 0.001); div = Math2.div(0, 2, 3); assertEquals(0, div, 0.001); div = Math2.div(1, 0, 3); assertEquals(3, div, 0.001); } }
19.058824
57
0.595679
cc5a98b3560d092bff6942e7d5fe98e0cdc5064f
2,567
/* * Copyright 2021 Shulie Technology, Co.Ltd * Email: shulie@shulie.io * 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, * See the License for the specific language governing permissions and * limitations under the License. */ package io.shulie.tro.web.common.future; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * @Description * @Author xiaobin.zfb * @mail xiaobin@shulie.io * @Date 2020/8/14 2:50 下午 */ public class ResponseFuture<T> { private final long timeoutMillis; private final long startInMillis = System.currentTimeMillis(); private final CountDownLatch countDownLatch = new CountDownLatch(1); private volatile T response; private volatile Throwable cause; private volatile boolean success; private volatile boolean isDone; public ResponseFuture(long timeoutMillis) { this.timeoutMillis = timeoutMillis; } public boolean isTimeout() { return System.currentTimeMillis() - this.startInMillis >= this.timeoutMillis; } public boolean isTimeout(long timeoutMillis) { return System.currentTimeMillis() - this.startInMillis >= timeoutMillis; } public T waitFor() throws InterruptedException { this.countDownLatch.await(timeoutMillis, TimeUnit.MILLISECONDS); return this.response; } public void success(final T response) { this.response = response; this.success = true; this.isDone = true; this.countDownLatch.countDown(); } public void failure(Throwable throwable) { this.cause = throwable; this.success = false; this.isDone = true; this.countDownLatch.countDown(); } public T getResponse() { return response; } public Throwable getCause() { return cause; } public boolean isSuccess() { return success; } public boolean isDone() { return isDone; } public long getStartInMillis() { return startInMillis; } public long getTimeoutMillis() { return timeoutMillis; } @Override public String toString() { return "ReplyFuture [response=" + response + ", cause=" + cause + "]"; } }
26.463918
85
0.671212
6b71ab6510a0f47a125d0b5bf92b8e86f4dac831
1,196
package com.vaadin.tests.components.customlayout; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import com.vaadin.tests.components.TestBase; import com.vaadin.ui.Button; import com.vaadin.ui.CustomLayout; import com.vaadin.v7.ui.TextField; public class CustomLayoutPrimaryStyleName extends TestBase { @Override protected void setup() { InputStream is = new ByteArrayInputStream( "<div location='loc1'>".getBytes()); try { final CustomLayout cl = new CustomLayout(is); cl.addComponent(new TextField("Hello world"), "loc1"); cl.setPrimaryStyleName("my-customlayout"); addComponent(cl); addComponent(new Button("Set primary stylename", event -> cl.setPrimaryStyleName("my-second-customlayout"))); } catch (IOException e) { e.printStackTrace(); } } @Override protected String getDescription() { return "CustomLayout should support primary stylenames both initially and dynamically"; } @Override protected Integer getTicketNumber() { return 9902; } }
26.577778
95
0.657191
3413385a60fa0a61755a1658b9ba864e720a6bd9
763
package com.vm.test.spring; import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.stereotype.Component; /** * 类名以两个大写字母开始的默认beanName为类名beanName举例 例如:ITestClass 那BeanName 为 ITestClass * 以一个大写字母开始的默认BeanName举例:例如: TestClass 那BeanName 为 testClass * @author huaihai.guan * @since 2021/11/19 9:46 */ @Component public class IMergedBeanDefinitionPostProcessor implements MergedBeanDefinitionPostProcessor { @Override public void postProcessMergedBeanDefinition(RootBeanDefinition rootBeanDefinition, Class<?> beanClass, String beanName) { } @Override public void resetBeanDefinition(String beanName) { } }
27.25
125
0.806029
11a25e5adb96fc2f47fea5660846e8bdd344ae62
495
package perococco.command; import com.google.common.collect.ImmutableMap; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; import perobobbot.command.CommandParsing; @RequiredArgsConstructor public class PeroCommandParsing implements CommandParsing { @Getter private final @NonNull String fullName; @Getter private final @NonNull String fullParameters; @Getter private final @NonNull ImmutableMap<String,String> parameterValues; }
22.5
71
0.8
b24eca10f9b928e66ee424a229930e02c18b2f95
3,814
package org.treeops.compare; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.stream.Stream; import org.junit.Test; import org.treeops.DataNode; import org.treeops.ParseData; import org.treeops.utils.Utils; public class ComparerTest { @Test public void test() { DataNode r1 = new DataNode("root"); DataNode r2 = new DataNode("root"); ComparisonSettings settings = new ComparisonSettings(new ArrayList<>()); ComparisonResult res = Compararer.compare(r1, r2, settings); assertTrue(res.getData().isSameNodeAndChildren()); assertFalse(res.getData().isIgnored()); assertTrue(res.getData().getN1() == r1); assertTrue(res.getData().getN2() == r2); } @Test public void testDiff() { DataNode r1 = new DataNode("root1"); DataNode r2 = new DataNode("root2"); ComparisonSettings settings = new ComparisonSettings(new ArrayList<>()); ComparisonResult res = Compararer.compare(r1, r2, settings); assertFalse(res.getData().isNodeSame()); assertFalse(res.getData().isIgnored()); assertTrue(res.getData().getN1() == r1); assertTrue(res.getData().getN2() == r2); } @Test public void testNullLeft() { DataNode r1 = new DataNode("root1"); ComparisonSettings settings = new ComparisonSettings(new ArrayList<>()); ComparisonResult res = Compararer.compare(r1, null, settings); assertFalse(res.getData().isNodeSame()); assertFalse(res.getData().isIgnored()); assertTrue(res.getData().getN1() == r1); assertTrue(res.getData().getN2() == null); } @Test public void testNullRight() { DataNode r2 = new DataNode("root2"); ComparisonSettings settings = new ComparisonSettings(new ArrayList<>()); ComparisonResult res = Compararer.compare(null, r2, settings); assertFalse(res.getData().isNodeSame()); assertFalse(res.getData().isIgnored()); assertTrue(res.getData().getN1() == null); assertTrue(res.getData().getN2() == r2); } @Test public void testChildCompare() { assertTrue(Compararer.compare(node("a"), node("a"), new ComparisonSettings(new ArrayList<>())).getData().isSameNodeAndChildren()); assertFalse(Compararer.compare(node("a"), node("b"), new ComparisonSettings(new ArrayList<>())).getData().isAllChildrenSame()); assertFalse(Compararer.compare(node("a"), node("a", "b"), new ComparisonSettings(new ArrayList<>())).getData().isAllChildrenSame()); assertTrue(Compararer.compare(node("a", "b"), node("a", "b"), new ComparisonSettings(new ArrayList<>())).getData().isAllChildrenSame()); assertTrue(Compararer.compare(node("b", "a"), node("a", "b"), new ComparisonSettings(new ArrayList<>())).getData().isAllChildrenSame()); assertTrue(Compararer.compare(node("a", "a"), node("a", "a"), new ComparisonSettings(new ArrayList<>())).getData().isAllChildrenSame()); assertFalse(Compararer.compare(node("a", "a", "a"), node("a", "a"), new ComparisonSettings(new ArrayList<>())).getData().isAllChildrenSame()); assertFalse(Compararer.compare(node("a", "a"), node("a", "a", "a"), new ComparisonSettings(new ArrayList<>())).getData().isAllChildrenSame()); } @Test public void testChildNames() { assertEquals(Compararer.childNames(node("a"), node("a")), Utils.list("a")); assertEquals(Compararer.childNames(node("a", "b"), node("a")), Utils.list("a", "b")); assertEquals(Compararer.childNames(node("a", "b"), node("a", "c")), Utils.list("a", "b", "c")); assertEquals(Compararer.childNames(node("a"), node("c", "a")), Utils.list("a", "c")); } private DataNode node(String... childs) { DataNode n = new DataNode("root"); Stream.of(childs).forEach(c -> new DataNode(n, c, new ParseData())); return n; } }
41.456522
145
0.684059
ad0d2595502bde4547173b4c67cedc7d8f97945b
292
package pl.codeset.aesfiletype; import java.nio.charset.StandardCharsets; class AesConstraints { static final byte[] AES_HEADER = "AES".getBytes(StandardCharsets.UTF_8); static final int BLOCK_SIZE = 16; static final int KEY_SIZE = 32; private AesConstraints() { } }
19.466667
76
0.719178
0f291da98d5d8f5a13fc4f7e5776e5054db7634e
2,731
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The contents of this file are subject to the terms of either the Universal Permissive License * v 1.0 as shown at http://oss.oracle.com/licenses/upl * * or the following license: * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided with * the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.openjdk.jmc.common.util; import java.text.Format; /** * Thread local implementation to use prototypes of {@link Format} subclasses that are not thread * safe by themselves. Use {@link ThreadLocal#get()} on an instance of this class to get a thread * local formatter instance. * * @param <T> * the type of formatter to provide */ public class FormatThreadLocal<T extends Format> extends ThreadLocal<T> { private final T prototype; /** * Create a new thread local formatter generator. * * @param prototype * prototype to use when getting a formatter */ @SuppressWarnings("unchecked") public FormatThreadLocal(T prototype) { // Clone now to ensure no one can manipulate our prototype. this.prototype = (T) prototype.clone(); } @SuppressWarnings("unchecked") @Override protected T initialValue() { return (T) prototype.clone(); } }
41.378788
100
0.749542
358e15a0298c60dc80fd1efc2c35d711f0cad317
4,012
package com.vinpos.pos; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author vinson */ public class Msg extends javax.swing.JDialog { /** * Creates new form MessageDialog */ public Msg(String text) { super(new java.awt.Frame(), true); initComponents(); this.setText(text); this.setLocationRelativeTo(null); this.setAlwaysOnTop(true); this.setVisible(true); } public void setText(String s){ jTextPane1.setText(s); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jInternalFrame1 = new javax.swing.JInternalFrame(); jPanel2 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jTextPane1 = new javax.swing.JTextPane(); jInternalFrame1.setVisible(true); org.jdesktop.layout.GroupLayout jInternalFrame1Layout = new org.jdesktop.layout.GroupLayout(jInternalFrame1.getContentPane()); jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout); jInternalFrame1Layout.setHorizontalGroup( jInternalFrame1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 708, Short.MAX_VALUE) ); jInternalFrame1Layout.setVerticalGroup( jInternalFrame1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(0, 160, Short.MAX_VALUE) ); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel2.setBackground(new java.awt.Color(255, 255, 255)); jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jButton1.setFont(new java.awt.Font("Lucida Grande", 1, 48)); // NOI18N jButton1.setText("OK"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel2.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(550, 30, 130, 100)); jScrollPane2.setBorder(null); jScrollPane2.setOpaque(false); jTextPane1.setBackground(new java.awt.Color(153, 255, 255)); jTextPane1.setBorder(null); jTextPane1.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N jTextPane1.setDisabledTextColor(new java.awt.Color(0, 255, 51)); jTextPane1.setOpaque(false); jScrollPane2.setViewportView(jTextPane1); jPanel2.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(34, 30, 490, 100)); getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 700, 160)); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed setVisible(false); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JInternalFrame jInternalFrame1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTextPane jTextPane1; // End of variables declaration//GEN-END:variables }
38.209524
135
0.663011
01df67ef0b243e2e5e66469f2a6004685f5e369e
617
package info.nemhauser.turmoil.response; import info.nemhauser.turmoil.engine.domain.Person; import java.util.Set; public class FriendlyUnitResponse extends EnemyUnitResponse { private Set<String> polygonsInRange; private String gender; public FriendlyUnitResponse(Person person, Set<String> polygonsInRange) { super(person); this.gender = person.getGender().toString().toLowerCase(); this.polygonsInRange = polygonsInRange; } public String[] getPolygonsInRange() { return polygonsInRange.toArray(new String[0]); } public String getGender() { return gender; } }
21.275862
73
0.734198
1f359e2332d81921eeaaeac241d05e20e539cc0c
10,231
package com.mlnlp.algorithms; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import com.mlnlp.utilities.SentimentLabel; import com.mlnlp.utilities.TweetUtils; public class NaiveBayes { private TweetUtils tweetUtil; private SentimentLabel label; //sentiment class private Hashtable<SentimentLabel, Integer> labelCounter = new Hashtable<SentimentLabel, Integer>(); private Hashtable<String, Integer> posCounter = new Hashtable<String, Integer >(); private Hashtable<String, Integer> negCounter = new Hashtable<String, Integer >(); private Hashtable<String, Integer> netCounter = new Hashtable<String, Integer >(); private List<String> vocabulary = new ArrayList<String>(); private int vocabSize; private double posPrior; private double negPrior; private double netPrior; private int totalPosCounter; private int totalNegCounter; private int totalNetCounter; public NaiveBayes() throws IOException{ posPrior = 1.0/3.0; negPrior = 1.0/3.0; netPrior = 1.0/3.0; totalPosCounter = 0; totalNegCounter = 0; totalNetCounter = 0; vocabSize = 0; tweetUtil = new TweetUtils(true, true, true); } public void getLabel(){ switch (label) { case NEGATIVE: System.out.println("class=-1"); break; case NETURAL: System.out.println("class=0"); break; case POSITIVE: System.out.println("class=+1"); break; default: System.out.println("No WAY!!!"); break; } } public void trainClassifier(String trainingFile) throws IOException{ extractFeatures(trainingFile); cleanCounterMaps(); printCounterMaps(10); printLabelMaps(); computePriors(); computeTotalCounters(); } /* * Read the training file */ public void extractFeatures(String trainingFile) throws IOException{ BufferedReader in = new BufferedReader(new FileReader(trainingFile)); String line; int no = 0; int cnt = 0; int validLines = 0; int obamaCnt = 0; int romneyCnt = 0; String [] words = null; while ((line = in.readLine()) != null) { if((cnt % 2) == 0){ String cleanTweet = tweetUtil.cleanTweet(line); words = cleanTweet.split(" "); if(cleanTweet.contains("obama")){ obamaCnt++; }else if(cleanTweet.contains("romney")){ romneyCnt++; } //System.out.println(cleanTweet); }else{ String label = line; //System.out.println(label); if(label.contains("obama=+1,romney=na") || label.contains("obama=na,romney=+1")){ validLines++; //positive for obama/romney for(String word:words){ if(!word.isEmpty()){ vocabulary.add(word); vocabSize += 1; if(posCounter.containsKey(word)){ int value = posCounter.get(word); posCounter.put(word, value + 1); }else{ posCounter.put(word, 1); } } } //let's add a counter to labelCounter if(labelCounter.containsKey(SentimentLabel.POSITIVE)){ int posCnt = labelCounter.get(SentimentLabel.POSITIVE); labelCounter.put(SentimentLabel.POSITIVE, posCnt + 1); }else{ labelCounter.put(SentimentLabel.POSITIVE, 1); } }else if(label.contains("obama=-1,romney=na") || label.contains("obama=na,romney=-1")){ validLines++; //negative for obama/romney for(String word:words){ if(!word.isEmpty()){ vocabulary.add(word); vocabSize += 1; if(negCounter.containsKey(word)){ int value = negCounter.get(word); negCounter.put(word, value + 1); }else{ negCounter.put(word, 1); } } } //let's add a counter to labelCounter if(labelCounter.containsKey(SentimentLabel.NEGATIVE)){ int negCnt = labelCounter.get(SentimentLabel.NEGATIVE); labelCounter.put(SentimentLabel.NEGATIVE, negCnt + 1); }else{ labelCounter.put(SentimentLabel.NEGATIVE, 1); } }else if(label.contains("obama=0,romney=na") || label.contains("obama=na,romney=0") || label.contains("obama=0,romney=0")){ validLines++; //neutral for obama/romney for(String word:words){ if(!word.isEmpty()){ vocabulary.add(word); vocabSize += 1; if(netCounter.containsKey(word)){ int value = netCounter.get(word); netCounter.put(word, value + 1); }else{ netCounter.put(word, 1); } } } //let's add a counter to labelCounter if(labelCounter.containsKey(SentimentLabel.NETURAL)){ int netCnt = labelCounter.get(SentimentLabel.NETURAL); labelCounter.put(SentimentLabel.NETURAL, netCnt + 1); }else{ labelCounter.put(SentimentLabel.NETURAL, 1); } } } cnt++; no++; } System.out.println("vocabulary size=" + vocabSize); System.out.println("no of tweets=" + no/2); System.out.println("no of tweets mentioned obama=" + obamaCnt); System.out.println("no of tweets mentioned romney=" + romneyCnt); System.out.println("valid lines=" + validLines); in.close(); } private void computePriors(){ int posCnt = labelCounter.get(SentimentLabel.POSITIVE); int negCnt = labelCounter.get(SentimentLabel.NEGATIVE); int netCnt = labelCounter.get(SentimentLabel.NETURAL); int sum = posCnt + negCnt + netCnt; posPrior = (double)posCnt/(double)sum; negPrior = (double)negCnt/(double)sum; netPrior = (double)netCnt/(double)sum; System.out.println("pos prior=" + posPrior + ", neg prior=" + negPrior + ", net prior=" + netPrior); } private void computeTotalCounters(){ for (int counter : posCounter.values()) { totalPosCounter += counter; } for (int counter : negCounter.values()) { totalNegCounter += counter; } for (int counter : netCounter.values()) { totalNetCounter += counter; } System.out.println("tot pos counter=" + totalPosCounter + ", tot neg counter=" + totalNegCounter + ", tot net counter=" + totalNetCounter); } public SentimentLabel classify(String text){ String cleanTweet = tweetUtil.cleanTweet(text); String [] words = cleanTweet.split(" "); double posProb = posPrior; double negProb = negPrior; double netProb = netPrior; double logPosProb = Math.log(posPrior); double logNegProb = Math.log(negPrior); double logNetProb = Math.log(netPrior); for(String word: words){ if(!word.isEmpty()){ //System.out.println("word = " + word); if(!posCounter.containsKey(word) && !negCounter.containsKey(word) && !netCounter.containsKey(word)){ continue; } int posCnt = 0, negCnt = 0, netCnt = 0; if(posCounter.containsKey(word)){ //System.out.println("found word " + word + " in pos counter=" + (double)posCounter.get(word)); posCnt = posCounter.get(word); } posProb *= (double)(posCnt + 1)/(double)(totalPosCounter + vocabSize); logPosProb += Math.log((double)(posCnt + 1)/(double)(totalPosCounter + vocabSize)); if(negCounter.containsKey(word)){ //System.out.println("found word " + word + " in neg counter=" + (double)negCounter.get(word)); negCnt = negCounter.get(word); } negProb *= (double)(negCnt + 1)/(double)(totalNegCounter + vocabSize); logNegProb += Math.log((double)(negCnt + 1)/(double)(totalNegCounter + vocabSize)); if(netCounter.containsKey(word)){ //System.out.println("found word " + word + " in net counter=" + (double)netCounter.get(word)); netCnt = netCounter.get(word); } netProb *= (double)(netCnt + 1)/(double)(totalNetCounter + vocabSize); logNetProb += Math.log((double)(netCnt + 1)/(double)(totalNetCounter + vocabSize)); //System.out.println("pos=" + posProb + ", neg=" + negProb + ", net=" + netProb); //System.out.println("log pos=" + logPosProb + ", log neg=" + logNegProb + ", log net=" + logNetProb); } } //System.out.println("pos=" + posProb + ", neg=" + negProb + ", net=" + netProb); //System.out.println("log pos=" + logPosProb + ", log neg=" + logNegProb + ", log net=" + logNetProb); if(logPosProb > logNegProb && logPosProb > logNetProb){ return SentimentLabel.POSITIVE; } else if(logNegProb > logPosProb && logNegProb > logNetProb){ return SentimentLabel.NEGATIVE; } return SentimentLabel.NETURAL; } /* * remove forbidden words */ private int cleanCounterMaps(){ String[] forbiddenWords = {"obama", "romney", "m", "mitt", "barack", "re"}; for(String word: forbiddenWords){ posCounter.remove(word); negCounter.remove(word); netCounter.remove(word); } return 0; } private void printCounterMaps(int threshold){ System.out.println("positive words:"); for (Map.Entry<String, Integer> entry : posCounter.entrySet()) { String word = entry.getKey(); Integer counter = entry.getValue(); if(counter > threshold){ System.out.println("word=" + word + ",counter=" + counter ); } } System.out.println("negative words:"); for (Map.Entry<String, Integer> entry : negCounter.entrySet()) { String word = entry.getKey(); Integer counter = entry.getValue(); if(counter > threshold){ System.out.println("word=" + word + ",counter=" + counter ); } } System.out.println("neutral words:"); for (Map.Entry<String, Integer> entry : netCounter.entrySet()) { String word = entry.getKey(); Integer counter = entry.getValue(); if(counter > threshold){ System.out.println("word=" + word + ",counter=" + counter ); } } } private void printLabelMaps(){ for(Map.Entry<SentimentLabel, Integer> entry : labelCounter.entrySet()){ if(entry.getKey() == SentimentLabel.POSITIVE){ System.out.println("postive count=" + entry.getValue()); } else if(entry.getKey() == SentimentLabel.NEGATIVE){ System.out.println("negative count=" + entry.getValue()); } else if(entry.getKey() == SentimentLabel.NETURAL){ System.out.println("neutral count=" + entry.getValue()); } } } }
31.872274
141
0.639234
ff1452a79ab6e40dfdbe520c2f1d4c818e3a63e3
4,499
package com.github.nohum.localezenmode; import android.os.Bundle; import android.service.notification.NotificationListenerService; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.RadioButton; import com.github.nohum.localezenmode.util.BlurbHelper; import com.github.nohum.localezenmode.util.BundleHelper; import com.github.nohum.localezenmode.util.ServiceHelper; import com.twofortyfouram.locale.sdk.client.ui.activity.AbstractLocalePluginActivity; /** * Entry point activity for Locale plugins */ public class EditSettingActivity extends AbstractLocalePluginActivity implements CompoundButton.OnCheckedChangeListener, View.OnClickListener { private static final String TAG = "EditSettingActivity"; private static final String STATE_SELECTED_SETTING = "selected_setting"; private int selectedSetting = 0; private RadioButton modeAll; private RadioButton modePriority; private RadioButton modeNone; private Button btnFinished; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit); modeAll = (RadioButton) findViewById(R.id.mode_all); modePriority = (RadioButton) findViewById(R.id.mode_priority); modeNone = (RadioButton) findViewById(R.id.mode_none); btnFinished = (Button) findViewById(R.id.btn_finished); modeAll.setOnCheckedChangeListener(this); modePriority.setOnCheckedChangeListener(this); modeNone.setOnCheckedChangeListener(this); btnFinished.setOnClickListener(this); } private void updateUi() { switch (selectedSetting) { case NotificationListenerService.INTERRUPTION_FILTER_PRIORITY: modePriority.setChecked(true); break; case NotificationListenerService.INTERRUPTION_FILTER_NONE: modeNone.setChecked(true); break; case NotificationListenerService.INTERRUPTION_FILTER_ALL: modeAll.setChecked(true); break; } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); selectedSetting = savedInstanceState.getInt(STATE_SELECTED_SETTING, 0); updateUi(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_SELECTED_SETTING, selectedSetting); } @Override protected void onResume() { super.onResume(); ServiceHelper.showServiceEnableDialogIfNecessary(this); } @Override public boolean isBundleValid(@NonNull Bundle bundle) { return BundleHelper.isValid(bundle); } @Override public void onPostCreateWithPreviousResult(@NonNull Bundle bundle, @NonNull String previousBlurb) { selectedSetting = BundleHelper.getRequestedZenMode(bundle); updateUi(); } @Nullable @Override public Bundle getResultBundle() { // 0 = unknown return selectedSetting > 0 ? BundleHelper.create(selectedSetting) : null; } @NonNull @Override public String getResultBlurb(@NonNull Bundle bundle) { int mode = BundleHelper.getRequestedZenMode(bundle); String blurb = getString(R.string.locale_blurb_update_zen_mode, BlurbHelper.modeToString(this, mode)); Log.i(TAG, "result blurb = " + blurb); return blurb; } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (!isChecked) { return; } if (buttonView.equals(modeAll)) { selectedSetting = NotificationListenerService.INTERRUPTION_FILTER_ALL; } else if (buttonView.equals(modePriority)) { selectedSetting = NotificationListenerService.INTERRUPTION_FILTER_PRIORITY; } else if (buttonView.equals(modeNone)) { selectedSetting = NotificationListenerService.INTERRUPTION_FILTER_NONE; } Log.i(TAG, "selected interruptions mode set to = " + selectedSetting); } @Override public void onClick(View v) { if (v.equals(btnFinished)) { finish(); } } }
31.683099
110
0.701489
f7e7af6fea3f40b0418850fe25d04b3ca015a01f
2,183
package lambda; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.function.Function; public class GZCompletableFutureTestMain<T> { private static class GZExchangeImpl<T> { public GZExchangeImpl() { System.out.println("Constructor GZExchangeImpl"); } public CompletableFuture<GZExchangeImpl<T>> sendHeadersAsync() { return CompletableFuture.supplyAsync(() -> { return new GZExchangeImpl<>(); }); } } private static class GZResponse { public GZResponse() { System.out.println("Constructor GZResponse"); } } public CompletableFuture<GZResponse> checkFor407(GZExchangeImpl<T> ex, Throwable t, Function<GZExchangeImpl<T>, CompletableFuture<GZResponse>> andThen) { return( (CompletableFuture)andThen.apply(ex)).thenCompose(Function.identity()); } // public Object checkFor407(GZExchangeImpl<T> ex, Throwable t, Function<GZExchangeImpl<T>, CompletableFuture<GZResponse>> andThen) { // return andThen.apply(ex); // } public CompletableFuture<GZExchangeImpl<T>> sendHeadersAsync() { // https://colobu.com/2016/02/29/Java-CompletableFuture/ return CompletableFuture.supplyAsync(() -> { return new GZExchangeImpl<T>(); }); } private CompletableFuture<GZResponse> sendRequestBody(Object ex) { return CompletableFuture.<GZResponse>supplyAsync(() -> { return new GZResponse(); }); } public void test() { Function after407Check = this::sendRequestBody; Function<GZExchangeImpl<T>, CompletableFuture<GZResponse>> afterExch407Check = (ex) -> { return ex.sendHeadersAsync().handle((r, t) -> { return this.checkFor407(r, t, after407Check); }).thenCompose(t -> t); }; } public static void main(String[] args) { GZCompletableFutureTestMain gz = new GZCompletableFutureTestMain(); gz.test(); } }
33.584615
136
0.614292
34a1d72fdbe0d5cd1f28c31d1aa282c712742533
768
package me.parzibyte.sistemaventasspringboot; public class ProductoParaVender extends Producto { private Float cantidad; public ProductoParaVender(String nombre, String codigo, Float precio, Float existencia, Integer id, Float cantidad) { super(nombre, codigo, precio, existencia, id); this.cantidad = cantidad; } public ProductoParaVender(String nombre, String codigo, Float precio, Float existencia, Float cantidad) { super(nombre, codigo, precio, existencia); this.cantidad = cantidad; } public void aumentarCantidad() { this.cantidad++; } public Float getCantidad() { return cantidad; } public Float getTotal() { return this.getPrecio() * this.cantidad; } }
27.428571
121
0.677083
479931a99616acbdbee7d8a5952927b5ead005b7
7,510
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.shaman.sve.filters; import java.util.Objects; import javax.swing.undo.AbstractUndoableEdit; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import org.openide.util.lookup.ServiceProvider; import org.shaman.sve.model.Resource; import org.shaman.sve.model.ResourceTimelineObject; import org.shaman.sve.model.TimelineObject; import org.shaman.sve.player.Player; import org.shaman.sve.player.PlayerAudioControl; import org.simpleframework.xml.Element; /** * * @author Sebastian Weiss */ public class GainAudioFilter extends TimelineObject implements CloneableFilter { @Element private float startGain; public static final String PROP_START_GAIN = "startGain"; @Element private float endGain; public static final String PROP_END_GAIN = "endGain"; @Element private boolean applyOverBorders; public static final String PROP_APPLY_OVER_BORDERS = "applyOverBorders"; public GainAudioFilter() { } public GainAudioFilter(TimelineObject parent) { setParent(parent); } public GainAudioFilter(TimelineObject parent, float startGain, float endGain, boolean applyOverBorders) { this(parent); this.startGain = startGain; this.endGain = endGain; this.applyOverBorders = applyOverBorders; } /** * Get the value of startGain * * @return the value of startGain */ public float getStartGain() { return startGain; } /** * Set the value of startGain * * @param newStartGain new value of startGain */ public void setStartGain(final float newStartGain) { final float oldStartGain = this.startGain; this.startGain = newStartGain; propertyChangeSupport.firePropertyChange(PROP_START_GAIN, oldStartGain, newStartGain); if (!Objects.equals(oldStartGain, newStartGain) && undoSupport != null) { undoSupport.postEdit(new AbstractUndoableEdit() { @Override public void undo() throws CannotUndoException { super.undo(); startGain = oldStartGain; propertyChangeSupport.firePropertyChange(PROP_START_GAIN, newStartGain, oldStartGain); } @Override public void redo() throws CannotRedoException { super.redo(); startGain = newStartGain; propertyChangeSupport.firePropertyChange(PROP_START_GAIN, oldStartGain, newStartGain); } }); } } /** * Get the value of endGain * * @return the value of endGain */ public float getEndGain() { return endGain; } /** * Set the value of endGain * * @param newEndGain new value of endGain */ public void setEndGain(final float newEndGain) { final float oldEndGain = this.endGain; this.endGain = newEndGain; propertyChangeSupport.firePropertyChange(PROP_END_GAIN, oldEndGain, newEndGain); if (!Objects.equals(oldEndGain, newEndGain) && undoSupport != null) { undoSupport.postEdit(new AbstractUndoableEdit() { @Override public void undo() throws CannotUndoException { super.undo(); endGain = oldEndGain; propertyChangeSupport.firePropertyChange(PROP_END_GAIN, newEndGain, oldEndGain); } @Override public void redo() throws CannotRedoException { super.redo(); endGain = newEndGain; propertyChangeSupport.firePropertyChange(PROP_END_GAIN, oldEndGain, newEndGain); } }); } } /** * Get the value of applyOverBorders * * @return the value of applyOverBorders */ public boolean isApplyOverBorders() { return applyOverBorders; } /** * Set the value of applyOverBorders * * @param newApplyOverBorders new value of applyOverBorders */ public void setApplyOverBorders(final boolean newApplyOverBorders) { final boolean oldApplyOverBorders = this.applyOverBorders; this.applyOverBorders = newApplyOverBorders; propertyChangeSupport.firePropertyChange(PROP_APPLY_OVER_BORDERS, oldApplyOverBorders, newApplyOverBorders); if (!Objects.equals(oldApplyOverBorders, newApplyOverBorders) && undoSupport != null) { undoSupport.postEdit(new AbstractUndoableEdit() { @Override public void undo() throws CannotUndoException { super.undo(); applyOverBorders = oldApplyOverBorders; propertyChangeSupport.firePropertyChange(PROP_APPLY_OVER_BORDERS, newApplyOverBorders, oldApplyOverBorders); } @Override public void redo() throws CannotRedoException { super.redo(); applyOverBorders = newApplyOverBorders; propertyChangeSupport.firePropertyChange(PROP_APPLY_OVER_BORDERS, oldApplyOverBorders, newApplyOverBorders); } }); } } /** * Called by {@link PlayerAudioControl} to compute the gain * @param gain the old gain * @param millis the current global time * @return the new gain */ public float getGain(float gain, int millis) { if (!isEnabled()) { return gain; } int localTime = parent.getLocalTime(millis); float alpha; if (localTime < start) { if (applyOverBorders) { alpha = startGain; } else { return gain; } } else if (localTime > start + duration) { if (applyOverBorders) { alpha = endGain; } else { return gain; } } else { alpha = startGain + ((localTime - start) / (float)duration) * (endGain - startGain); } return gain * alpha; } @Override public TimelineObject cloneForParent(TimelineObject parent) { GainAudioFilter f = new GainAudioFilter(parent, startGain, endGain, applyOverBorders); f.setStart(start); f.setDuration(duration); f.setName(name); return f; } @ServiceProvider(service = FilterFactory.class) public static class SilenceFilterFactory implements FilterFactory { @Override public String getName() { return "Audio/Silence"; } @Override public boolean isApplicable(ResourceTimelineObject<Resource> obj) { return obj.playerProperties.containsKey(Player.AUDIO_CONTROL); } @Override public TimelineObject createFilter(ResourceTimelineObject<Resource> obj) { GainAudioFilter f = new GainAudioFilter(obj, 0.0f, 0.0f, false); f.setDuration(obj.getDuration()); f.setName("Silence"); return f; } } @ServiceProvider(service = FilterFactory.class) public static class FadeInFilterFactory implements FilterFactory { @Override public String getName() { return "Audio/Fade In"; } @Override public boolean isApplicable(ResourceTimelineObject<Resource> obj) { return obj.playerProperties.containsKey(Player.AUDIO_CONTROL); } @Override public TimelineObject createFilter(ResourceTimelineObject<Resource> obj) { GainAudioFilter f = new GainAudioFilter(obj, 0.0f, 1.0f, false); int duration = Math.min(obj.getDuration(), 1000); f.setDuration(duration); f.setName("Fade in"); return f; } } @ServiceProvider(service = FilterFactory.class) public static class FadeOutFilterFactory implements FilterFactory { @Override public String getName() { return "Audio/Fade Out"; } @Override public boolean isApplicable(ResourceTimelineObject<Resource> obj) { return obj.playerProperties.containsKey(Player.AUDIO_CONTROL); } @Override public TimelineObject createFilter(ResourceTimelineObject<Resource> obj) { GainAudioFilter f = new GainAudioFilter(obj, 1.0f, 0.0f, false); int duration = Math.min(obj.getDuration(), 1000); f.setDuration(duration); f.setStart(obj.getDuration() - duration); f.setName("Fade out"); return f; } } }
26.821429
113
0.731824
22463a8a43d95aeb480bcae15a840664772a91ae
2,090
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.siyeh.ig.memory; import com.intellij.codeInspection.CommonQuickFixBundle; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.InspectionGadgetsFix; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; /** * @author Konstantin Bulenkov */ public class ReplaceEmptyArrayToConstantFix extends InspectionGadgetsFix { private final String myText; private final String myName; public ReplaceEmptyArrayToConstantFix(PsiClass aClass, PsiField field) { myText = aClass.getQualifiedName() + "." + field.getName(); myName = CommonQuickFixBundle.message("fix.replace.with.x", aClass.getName() + "." + field.getName()); } @Nls @NotNull @Override public String getName() { return myName; } @Nls @NotNull @Override public String getFamilyName() { return InspectionGadgetsBundle.message("constant.for.zero.length.array.quickfix.family"); } @Override protected void doFix(Project project, ProblemDescriptor descriptor) { PsiExpression newExp = JavaPsiFacade.getInstance(project).getElementFactory().createExpressionFromText(myText, descriptor.getPsiElement()); PsiElement element = descriptor.getPsiElement().replace(newExp); JavaCodeStyleManager.getInstance(project).shortenClassReferences(element); } }
34.262295
143
0.768421
b79c70b952c34304955f07148f53c433c7ad2bf0
792
package com.ninjatech.kodivideoorganizercli.settings.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class TheMovieDB { private static final String API = "api"; private static final String LANGUAGE = "language"; @JsonProperty(TheMovieDB.API) private final String api; @JsonProperty(TheMovieDB.LANGUAGE) private final String language; @JsonCreator public TheMovieDB(@JsonProperty(TheMovieDB.API) String api, @JsonProperty(TheMovieDB.LANGUAGE) String language) { this.api = api; this.language = language; } public String getApi() { return this.api; } public String getLanguage() { return this.language; } }
24.75
75
0.689394
e02d1779afe3d66f3703ab43e30d4c64937ae45c
189
package net.froztigaming.fantasycraft.items; import net.minecraft.item.Item; public class StoneRod extends Item { public StoneRod(Settings settings){ super(settings); } }
18.9
44
0.730159
fade44b2facdc6e52526b4edfd74ede32eb0924d
260
package ml.pkom.solomonsrod.fabric; import ml.pkom.solomonsrod.SolomonsRod; import net.fabricmc.api.ModInitializer; public class SolomonsRodFabric implements ModInitializer { @Override public void onInitialize() { SolomonsRod.init(); } }
21.666667
58
0.75
9b4a421f121fb6f384d51a9227117df4bea6cd62
652
/* 1、第一步的作用是把最高位1右移移位,并与原数据按位取或。那么这就使得最高位和它的下一位是连续两个1。 2、第二步的作用是把刚刚移位得到连续两个1继续右移两位并与原数据按位取或。那么这就使得最高两位和它的下两个连续位组成四个连续的1。 3、 以此类推,最终得到的i是从开始的最高位到结束全是1。并减去i不带符号的右移一位,即可得到一个int数据的最高位的值。 4、上述情况是针对于i不为零和负数的情况,如果i为零,那么得到的结果始终为零。如果i位负数,那么得到的结果始终是-2147483648。即等于Integer.MIN_VALUE。(原因在于负数的最高位始终为1,即是负数的符号位) publicstaticinthighestOneBit(int i) { // HD, Figure 3-1 i |= (i >> 1); i |= (i >> 2); i |= (i >> 4); i |= (i >> 8); i |= (i >> 16); return i - (i >>> 1); } */ public class Solution { public int findComplement(int num) { return ~num & ((Integer.highestOneBit(num) << 1) - 1); } }
29.636364
117
0.636503
f7698e050dfaa51fcf041804e1036d8586f739ac
1,040
/* * Copyright (c) 2021. Alibaba Group Holding Limited */ package com.alibaba.hologres.client; import java.util.concurrent.atomic.AtomicInteger; /** * 用于debug性能追踪. */ public class Trace { long[] values = new long[20]; String[] text = new String[20]; AtomicInteger index = new AtomicInteger(1); public void begin() { values[0] = System.nanoTime(); text[0] = "start"; } public void step(String name) { long current = System.nanoTime(); int index = this.index.getAndIncrement(); if (index < values.length - 1) { values[index] = current; text[index] = name; } } public long getCost() { int index = this.index.get(); return (values[index - 1] - values[0]) / 1000L; } @Override public String toString() { StringBuilder sb = new StringBuilder(); int index = this.index.get(); for (int i = 1; i < index; ++i) { sb.append(text[i]).append(":").append((values[i] - values[i - 1]) / 1000L).append(" us -> "); } sb.append("total:").append(getCost()).append(" us"); return sb.toString(); } }
21.22449
96
0.632692
cc2da2392ccbef9e7d018229512b9c627abfd4f5
1,664
package dev.teamtesseract.molang; public class MolangResult { public static MolangResult ZERO = ofFloat(0.0F); private final float floatValue; private final boolean booleanValue; private final String stringValue; private MolangResult(float f, boolean b, String s) { this.floatValue = f; this.booleanValue = b; this.stringValue = s; } public static MolangResult ofFloat(float f) { return new MolangResult(f, false, null); } public static MolangResult ofFloat(double f) { return new MolangResult((float)f, false, null); } public static MolangResult ofBoolean(boolean b) { return new MolangResult(Float.NaN, b, null); } public static MolangResult ofString(String s) { return new MolangResult(Float.NaN, false, s); } public boolean hasFloat() { return !Float.isNaN(floatValue); } public boolean hasBoolean() { return !hasFloat() && !hasString(); } public boolean hasString() { return stringValue != null; } public float getFloat() { if(hasFloat()) return floatValue; else return booleanValue ? 1.0F : 0.0F; } public boolean getBoolean() { if(hasFloat()) return floatValue > 0.0F; else return booleanValue; } public String getString() { if(hasString()) return stringValue; else return ""; } @Override public String toString() { return String.format("R{ F: %.2f | B: %s | S: \"%s\" }", getFloat(), getBoolean(), getString()); } }
23.43662
105
0.588341
1cc6f0650b14e88f9d600db6034f708deaecb355
11,758
/* * 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.stanbol.rules.web.resources; import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static org.apache.stanbol.commons.web.base.CorsHelper.addCORSOrigin; import static org.apache.stanbol.commons.web.base.CorsHelper.enableCORS; import java.io.InputStream; import javax.servlet.ServletContext; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.OPTIONS; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import org.apache.stanbol.commons.web.base.ContextHelper; import org.apache.stanbol.commons.web.base.format.KRFormat; import org.apache.stanbol.commons.web.base.resource.BaseStanbolResource; import org.apache.stanbol.commons.web.base.utils.MediaTypeUtil; import org.apache.stanbol.rules.base.api.NoSuchRecipeException; import org.apache.stanbol.rules.base.api.Recipe; import org.apache.stanbol.rules.base.api.util.RuleList; import org.apache.stanbol.rules.manager.KB; import org.apache.stanbol.rules.manager.changes.RecipeImpl; import org.apache.stanbol.rules.manager.parse.RuleParserImpl; import org.apache.stanbol.rules.refactor.api.Refactorer; import org.apache.stanbol.rules.refactor.api.RefactoringException; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.jersey.api.view.ImplicitProduces; import com.sun.jersey.multipart.FormDataParam; /** * * @author andrea.nuzzolese * */ @Path("/refactor") @ImplicitProduces(MediaType.TEXT_HTML + ";qs=2") public class RefactorResource extends BaseStanbolResource { private Logger log = LoggerFactory.getLogger(getClass()); protected Refactorer refactorer; public RefactorResource(@Context ServletContext servletContext) { refactorer = (Refactorer) ContextHelper.getServiceFromContext(Refactorer.class, servletContext); if (refactorer == null) { throw new IllegalStateException("SemionRefactorer missing in ServletContext"); } } /** * The apply mode allows the client to compose a recipe, by mean of string containg the rules, and apply * it "on the fly" to the graph in input. * * @param recipe * String * @param input * InputStream * @return a Response containing the transformed graph */ @POST @Path("/apply") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(value = {KRFormat.TURTLE, KRFormat.FUNCTIONAL_OWL, KRFormat.MANCHESTER_OWL, KRFormat.RDF_XML, KRFormat.OWL_XML, KRFormat.RDF_JSON}) public Response applyRefactoring(@FormDataParam("recipe") String recipe, @FormDataParam("input") InputStream input, @Context HttpHeaders headers) { OWLOntology output = null; try { output = doRefactoring(input, RuleParserImpl.parse(recipe)); } catch (OWLOntologyCreationException e1) { throw new WebApplicationException(e1, INTERNAL_SERVER_ERROR); } catch (RefactoringException e1) { throw new WebApplicationException(e1, INTERNAL_SERVER_ERROR); } if (output == null){ ResponseBuilder rb = Response.status(NOT_FOUND); rb.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN + "; charset=utf-8"); addCORSOrigin(servletContext, rb, headers); return rb.build(); } ResponseBuilder rb = Response.ok(output); rb.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN + "; charset=utf-8"); addCORSOrigin(servletContext, rb, headers); return rb.build(); } /** * The apply mode allows the client to compose a recipe, by mean of string containg the rules, and apply * it "on the fly" to the graph in input. * * @param recipe * String * @param input * InputStream * @return a Response containing the transformed graph */ @POST @Path("/applyfile") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(value = {KRFormat.TURTLE, KRFormat.FUNCTIONAL_OWL, KRFormat.MANCHESTER_OWL, KRFormat.RDF_XML, KRFormat.OWL_XML, KRFormat.RDF_JSON}) public Response applyRefactoringFromRuleFile(@FormDataParam("recipe") InputStream recipeStream, @FormDataParam("input") InputStream input, @Context HttpHeaders headers) { OWLOntology output = null; try { output = doRefactoring(input, RuleParserImpl.parse(recipeStream)); } catch (OWLOntologyCreationException e1) { throw new WebApplicationException(e1, INTERNAL_SERVER_ERROR); } catch (RefactoringException e1) { throw new WebApplicationException(e1, INTERNAL_SERVER_ERROR); } if (output == null){ ResponseBuilder rb = Response.status(NOT_FOUND); rb.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN + "; charset=utf-8"); addCORSOrigin(servletContext, rb, headers); return rb.build(); } ResponseBuilder rb = Response.ok(output); rb.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN + "; charset=utf-8"); addCORSOrigin(servletContext, rb, headers); return rb.build(); } /** * Utility method that groups all calls to the refactorer. * * @param input * @param recipe * @return * @throws OWLOntologyCreationException * @throws RefactoringException */ private OWLOntology doRefactoring(InputStream input, KB kb) throws OWLOntologyCreationException, RefactoringException { if (kb == null) return null; RuleList ruleList = kb.getkReSRuleList(); if (ruleList == null) return null; Recipe actualRecipe = new RecipeImpl(null, null, ruleList); // Parse the input ontology OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); OWLOntology inputOntology = manager.loadOntologyFromOntologyDocument(input); // Refactor return refactorer.ontologyRefactoring(inputOntology, actualRecipe); } @POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(value = {KRFormat.TURTLE, KRFormat.FUNCTIONAL_OWL, KRFormat.MANCHESTER_OWL, KRFormat.RDF_XML, KRFormat.OWL_XML, KRFormat.RDF_JSON}) public Response performRefactoring(@FormDataParam("recipe") String recipe, @FormDataParam("input") InputStream input, @Context HttpHeaders headers) { // Refactorer semionRefactorer = semionManager.getRegisteredRefactorer(); IRI recipeIRI = IRI.create(recipe); OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); OWLOntology inputOntology; try { inputOntology = manager.loadOntologyFromOntologyDocument(input); OWLOntology outputOntology; try { outputOntology = refactorer.ontologyRefactoring(inputOntology, recipeIRI); } catch (RefactoringException e) { // refactoring exceptions are re-thrown throw new WebApplicationException(e, INTERNAL_SERVER_ERROR); } catch (NoSuchRecipeException e) { // missing recipes result in a status 404 ResponseBuilder rb = Response.status(Status.NOT_FOUND); MediaType mediaType = MediaTypeUtil.getAcceptableMediaType(headers, null); if (mediaType != null) rb.header(HttpHeaders.CONTENT_TYPE, mediaType); addCORSOrigin(servletContext, rb, headers); return rb.build(); } ResponseBuilder rb = Response.ok(outputOntology); MediaType mediaType = MediaTypeUtil.getAcceptableMediaType(headers, null); if (mediaType != null) rb.header(HttpHeaders.CONTENT_TYPE, mediaType); addCORSOrigin(servletContext, rb, headers); return rb.build(); } catch (OWLOntologyCreationException e) { throw new WebApplicationException(e, INTERNAL_SERVER_ERROR); } } @GET public Response performRefactoringLazyCreateGraph(@QueryParam("recipe") String recipe, @QueryParam("input-graph") String inputGraph, @QueryParam("output-graph") String outputGraph, @Context HttpHeaders headers) { log.info("recipe: {}", recipe); log.info("input-graph: {}", inputGraph); log.info("output-graph: {}", outputGraph); IRI recipeIRI = IRI.create(recipe); IRI inputGraphIRI = IRI.create(inputGraph); IRI outputGraphIRI = IRI.create(outputGraph); // Refactorer semionRefactorer = semionManager.getRegisteredRefactorer(); try { refactorer.ontologyRefactoring(outputGraphIRI, inputGraphIRI, recipeIRI); ResponseBuilder rb = Response.ok(); MediaType mediaType = MediaTypeUtil.getAcceptableMediaType(headers, null); if (mediaType != null) rb.header(HttpHeaders.CONTENT_TYPE, mediaType); addCORSOrigin(servletContext, rb, headers); return rb.build(); } catch (RefactoringException e) { // refactoring exceptions are re-thrown throw new WebApplicationException(e, INTERNAL_SERVER_ERROR); } catch (NoSuchRecipeException e) { // missing recipes result in a status 404 ResponseBuilder rb = Response.status(NOT_FOUND); MediaType mediaType = MediaTypeUtil.getAcceptableMediaType(headers, null); if (mediaType != null) rb.header(HttpHeaders.CONTENT_TYPE, mediaType); addCORSOrigin(servletContext, rb, headers); return rb.build(); } } @OPTIONS public Response handleCorsPreflight(@Context HttpHeaders headers) { ResponseBuilder rb = Response.ok(); enableCORS(servletContext, rb, headers); return rb.build(); } }
42.447653
108
0.665589
4f3bcb1998ce80b957a258af458bb6d97eb5ee41
3,686
/* * This software is in the public domain under CC0 1.0 Universal plus a * Grant of Patent License. * * To the extent possible under law, the author(s) have dedicated all * copyright and related and neighboring rights to this software to the * public domain worldwide. This software is distributed without any * warranty. * * You should have received a copy of the CC0 Public Domain Dedication * along with this software (see the LICENSE.md file). If not, see * <http://creativecommons.org/publicdomain/zero/1.0/>. */ package org.moqui.service; import java.util.Map; @SuppressWarnings("unused") public interface ServiceCallSchedule extends ServiceCall { /** Name of the service to run. The combined service name, like: "${path}.${verb}${noun}". To explicitly separate * the verb and noun put a hash (#) between them, like: "${path}.${verb}#${noun}" (this is useful for calling the * implicit entity CrUD services where verb is create, update, or delete and noun is the name of the entity). */ ServiceCallSchedule name(String serviceName); ServiceCallSchedule name(String verb, String noun); ServiceCallSchedule name(String path, String verb, String noun); /** Map of name, value pairs that make up the context (in parameters) passed to the service. */ ServiceCallSchedule parameters(Map<String, ?> context); /** Single name, value pairs to put in the context (in parameters) passed to the service. */ ServiceCallSchedule parameter(String name, Object value); /** Name of the job. If specified repeated schedules with the same jobName will use the same underlying job. * @return Reference to this for convenience. */ ServiceCallSchedule jobName(String jobName); /* * Name of the service pool to send to (optional). * @return Reference to this for convenience. */ /* leaving this out for now, not easily supported by Quartz Scheduler: ServiceCallSchedule poolName(String poolName); */ /** Time to first run this service (in milliseconds from epoch). * @return Reference to this for convenience. */ ServiceCallSchedule startTime(long startTime); /** Number of times to repeat. * @return Reference to this for convenience. */ ServiceCallSchedule count(int count); /** Time that this service schedule should expire (in milliseconds from epoch). * @return Reference to this for convenience. */ ServiceCallSchedule endTime(long endTime); /** A time interval specifying how often to run this service. * * @param interval Number of units that make up the interval. * @param intervalUnit One of ServiceCall.IntervalUnit { SECONDS, MINUTES, HOURS, DAYS, WEEKS, MONTHS, YEARS } * @return Reference to this for convenience. */ ServiceCallSchedule interval(int interval, TimeUnit intervalUnit); /** A string in the same format used by cron to define a recurrence. * * dailyAtHourAndMinute(int hour, int minute): String.format("0 %d %d ? * *", minute, hour) * weeklyOnDayAndHourAndMinute(int dayOfWeek, int hour, int minute): String.format("0 %d %d ? * %d", minute, hour, dayOfWeek) * monthlyOnDayAndHourAndMinute(int dayOfMonth, int hour, int minute): String.format("0 %d %d %d * ?", minute, hour, dayOfMonth) * * @return Reference to this for convenience. */ ServiceCallSchedule cron(String cronString); /** Maximum number of times to retry running this service. * @return Reference to this for convenience. */ ServiceCallSchedule maxRetry(int maxRetry); /** Schedule the service call. */ void call() throws ServiceException; }
41.886364
132
0.703201
8046eb84cf4f651cfd92a6a6bf15d388db1f5117
16,088
/* * Copyright (c) 2021. Jeffrey Vroom. All Rights Reserved. */ package sc.bind; import sc.dyn.DynUtil; import sc.type.IBeanMapper; public class AssignmentBinding extends DestinationListener { VariableBinding lhsBinding; IBinding rhsBinding; volatile boolean valid = false; Object srcObj; Object boundValue; // The last value we assigned from rhsBinding Object lastTriggeredValue; // For reverse only bindings, the last value which triggered the binding to fire. This let's us know when to refire via refreshBinding public AssignmentBinding(Object srcObject, VariableBinding lhsBinding, IBinding rhsBinding) { srcObj = srcObject; this.lhsBinding = lhsBinding; this.rhsBinding = rhsBinding; } public AssignmentBinding(Object srcObject, VariableBinding lhsBinding, Object rhsValue) { srcObj = srcObject; this.lhsBinding = lhsBinding; this.rhsBinding = rhsValue instanceof IBinding ? (IBinding) rhsValue : new ConstantBinding(rhsValue); } public AssignmentBinding(Object dstObject, IBinding dstProperty, Object srcObject, VariableBinding lhsBinding, IBinding rhsBinding, BindingDirection bindingDirection, int flags, BindOptions opts) { this(srcObject, lhsBinding, rhsBinding); dstObj = dstObject; dstProp = dstProperty; direction = bindingDirection; initFlags(flags, opts); } public AssignmentBinding(Object dstObject, IBinding dstProperty, Object srcObject, VariableBinding lhsBinding, Object rhsValue, BindingDirection bindingDirection, int flags, BindOptions opts) { this(srcObject, lhsBinding, rhsValue); dstObj = dstObject; dstProp = dstProperty; direction = bindingDirection; initFlags(flags, opts); } @Override public boolean isValid() { // Right now, the only non DestinationListener for the RHS is a constant if (rhsBinding.isConstant()) return true; return ((DestinationListener) rhsBinding).isValid(); } public Object getPropertyValue(Object parent, boolean getField, boolean pendingChild) { return rhsBinding.getPropertyValue(parent, getField, pendingChild); } public void addBindingListener(Object eventObject, IListener listener, int event) { if (dstObj == dstProp && isValidObject(eventObject)) { rhsBinding.addBindingListener(eventObject, this, event); } } public void removeBindingListener(Object eventObject, IListener listener, int event) { if (dstObj == dstProp && isValidObject(eventObject)) { rhsBinding.removeBindingListener(eventObject, this, event); } } // Should only be used with ON_DEMAND sync'ing which only works when dstObj is IBindable private void invalidate(boolean sendEvent, int event) { if (dstObj == dstProp || dstProp instanceof IBinding) ((IBinding)dstProp).invalidateBinding(dstObj, sendEvent, event, false); else Bind.sendEvent(event, dstObj, dstProp); valid = false; } public void invalidateBinding(Object object, boolean sendEvent, int event, boolean includeParams) { invalidate(sendEvent, event); } public boolean applyBinding(Object obj, Object value, IBinding src, boolean refresh, boolean pendingChild) { if (!DynUtil.equalObjects(boundValue, value)) { boundValue = value; applyBinding(); return true; } return false; } void applyBinding() { // Get this before marking it valid Object newValue = getBoundValue(); if (activated) valid = true; if (dstObj != dstProp) { // Don't set the top-level property with the sentinel, do pass it up to nested bindings though // so they know their value is UNSET rather than null. if (newValue == UNSET_VALUE_SENTINEL) newValue = null; //if (trace) // System.out.println(toString("<=")); } if (dstProp == dstObj || dstProp instanceof IBinding) ((IBinding) dstProp).applyBinding(dstObj == dstProp ? null : dstObj, newValue, this, false, false); else if (newValue != PENDING_VALUE_SENTINEL) PBindUtil.setPropertyValue(dstObj, dstProp, newValue); } public void applyReverseBinding(Object obj, Object value, Object src) { // This is the =: case which is different. if (direction.doReverse() && !direction.doForward()) doAssignment(); else { rhsBinding.applyReverseBinding(obj, value, src); doAssignment(); } } protected void applyReverseBinding() { doAssignment(); // Any other cases here that need to be propagated? if (rhsBinding instanceof AssignmentBinding) ((AssignmentBinding) rhsBinding).applyReverseBinding(); } /** Called by the parent when this is a hierarchical binding - i.e. one expression in another */ public void setBindingParent(IBinding parent, BindingDirection dir) { dstProp = parent; dstObj = parent; direction = dir; initBinding(); addListeners(); } public boolean isConstant() { return false; } /** Called to initialize and retrieve the value of a top-level binding */ public Object initializeBinding() { assert dstObj != dstProp; initBinding(); addListeners(); if (direction.doForward()) { Object result = getBoundValue(); //if (trace) { // System.out.println("Init: " + this); //} if (!isValidObject(result)) result = null; return result; } else return null; } protected Object getBoundValue() { if (direction.doForward()) return boundValue; else // reverse bindings are not cached - no listeners so we eval them each time return rhsBinding.getPropertyValue(srcObj, false, false); } protected void initBinding() { lhsBinding.isAssignment = true; lhsBinding.setBindingParent(this, direction); rhsBinding.setBindingParent(this, direction); if (direction.doForward()) { boundValue = rhsBinding.getPropertyValue(srcObj, false, false); doAssignment(); } else if (direction.doReverse() && dstProp != dstObj) { // Only fire after this value has changed lastTriggeredValue = PBindUtil.getPropertyValue(dstObj, dstProp, false, false); } if (activated) valid = true; } protected void reactivate(Object obj) { if (direction.doForward()) { Object bindingParent = srcObj; if (isValidObject(bindingParent)) { boundValue = rhsBinding.getPropertyValue(bindingParent, false, false); doAssignment(); } } valid = true; } private void doAssignment() { Object bv = getBoundValue(); if (bv != UNSET_VALUE_SENTINEL && bv != PENDING_VALUE_SENTINEL) { // Sets the value for lhsBinding's property to the boundValue specified. lhsBinding.applyReverseBinding(srcObj, bv, this); } } private void addListeners() { if (sync == SyncType.ON_DEMAND) { if (direction.doForward()) { Bind.addListener(dstObj, dstProp, this, VALUE_REQUESTED); } } // We always add the forward listeners so that we do not have to re-evaluate everything on demand if (srcObj != null) { if (direction.doForward()) { rhsBinding.addBindingListener(srcObj, this, VALUE_CHANGED_MASK); if (srcObj instanceof IChangeable) { Bind.addListener(srcObj, null, this, VALUE_CHANGED_MASK); } // If the value wants to be notified of individual events, always listen on it if (boundValue instanceof IChangeable) { Bind.addListener(boundValue, null, this, VALUE_CHANGED_MASK); } } } if (direction.doReverse() && dstObj != dstProp) { Bind.addListener(dstObj, dstProp, this, VALUE_CHANGED_MASK); } } public void removeListener() { if (sync == SyncType.ON_DEMAND) { if (direction.doForward()) Bind.removeListener(dstObj, dstProp, this, VALUE_REQUESTED); } if (direction.doForward()) { if (srcObj != null) { rhsBinding.removeBindingListener(srcObj, this, VALUE_CHANGED_MASK); if (srcObj instanceof IChangeable) { Bind.removeListener(srcObj, null, this, VALUE_CHANGED_MASK); } } if (boundValue instanceof IChangeable) { Bind.removeListener(boundValue, null, this, VALUE_CHANGED_MASK); } rhsBinding.removeListener(); } if (direction.doReverse() && dstProp != dstObj) { Bind.removeListener(dstObj, dstProp, this, VALUE_CHANGED_MASK); } } public void valueRequested(Object obj, IBeanMapper prop) { if (sync == SyncType.ON_DEMAND) { // If the binding is out of date and the value requested is the right one. if (!valid) { synchronized (this) { if (!valid) { if (obj == dstObj && prop == dstProp && direction.doForward()) { applyBinding(); } } } } } } public boolean valueValidated(Object srcObject, Object srcProp, Object eventDetail, boolean apply) { if (dstObj == srcObject && PBindUtil.equalProps(dstProp, srcProp)) { if (direction.doReverse()) { if (sync != SyncType.ON_DEMAND) { if (apply) { applyReverseBinding(); lastTriggeredValue = eventDetail; // TODO: is this always the new value? It is only used for an equals check so I guess it is ok... } } } return true; } boolean changed = false; int i; if (direction.doForward()) { // An event occurred on the value itself for IChangeable objects // In this case, we need to mark all dstObj bindings as changed since the physical object may not have changed // instead, the value of the internal object changed. equalObjs will return true. We need valid=false for // all parent bindings. if (srcProp == null) { if (apply) applyBinding(); return true; } Object newValue = rhsBinding.getPropertyValue(srcObj, false, false); if (!DynUtil.equalObjects(newValue, boundValue)) { changed = true; if (apply) applyBinding(); } } return changed; } public boolean valueInvalidated(Object srcObject, Object srcProp, Object eventDetail, boolean apply) { if (dstObj == srcObject && PBindUtil.equalProps(dstProp, srcProp)) { if (direction.doReverse()) { if (sync == SyncType.ON_DEMAND) { invalidate(true, VALUE_INVALIDATED); } } return true; } boolean changed = false; int i; if (direction.doForward()) { // An event occurred on the value itself for IChangeable objects // In this case, we need to mark all dstObj bindings as changed since the physical object may not have changed // instead, the value of the internal object changed. equalObjs will return true. We need valid=false for // all parent bindings. if (srcProp == null) { // If we are applying (and thus not already invalidating) first invalidate the parent binding if (apply) invalidateBinding(null, false, 0, false); // Then apply it bindingInvalidated(apply); return true; } Object newValue = rhsBinding.getPropertyValue(srcObj, false, false); if (!DynUtil.equalObjects(newValue, boundValue)) bindingInvalidated(apply); } return changed; } protected void bindingInvalidated(boolean apply) { if (sync == SyncType.ON_DEMAND) { invalidate(true, VALUE_INVALIDATED); } else { invalidateBinding(null, true, VALUE_INVALIDATED, false); } } public String toString(String operation, boolean displayValue) { StringBuilder sb = new StringBuilder(); if (dstObj != dstProp && operation != null) { sb.append(operation); sb.append(" "); } sb.append(super.toString(operation, displayValue)); if (displayValue) { if (dstObj != dstProp) { sb.append(toBindingString()); sb.append(" "); } if (direction != null && direction.doForward()) { if (dstObj != dstProp) { sb.append("= "); } if (boundValue != null) sb.append(DynUtil.getInstanceName(boundValue)); } } else { sb.append(toBindingString()); } return sb.toString(); } private StringBuilder toBindingString() { StringBuilder sb = new StringBuilder(); if (lhsBinding == null || rhsBinding == null) sb.append("<not initialized>"); else { // Indicate that these bindings are not on properties from the "this" object. // they could have come from any object reference or a parent of this... not sure // how we get from the instance back to its type name (if any) if (srcObj != dstObj) { sb.append(DynUtil.getInstanceName(srcObj)); sb.append("."); } sb.append(lhsBinding.toString()); sb.append(" = "); sb.append(rhsBinding.toString()); } return sb; } public void activate(boolean state, Object obj, boolean chained) { if (state == activated) return; super.activate(state, obj, chained); lhsBinding.activate(state, obj, true); rhsBinding.activate(state, obj, true); if (state) { if (!valid) reactivate(obj); } else // TODO: required because bindings when deactivated do not always deliver events. Could be fixed if they invalidate the parent during the re-activation process when their value is changed. The goal being that if you switch back and forth you do not have to recache the world. See SelectorBinding as well valid = false; } public int refreshBinding() { if (direction.doReverse() && !direction.doForward() && dstObj != dstProp) { Object newValue = PBindUtil.getPropertyValue(dstObj, dstProp, false, false); if (!DynUtil.equalObjects(newValue, lastTriggeredValue)) { lastTriggeredValue = newValue; doAssignment(); return 1; } return 0; } else System.err.println("*** not refreshing assignment binding"); return 0; } public void accessBinding() { super.accessBinding(); if (dstObj != null) accessObj(dstObj); lhsBinding.accessBinding(); if (rhsBinding instanceof DestinationListener) ((DestinationListener)rhsBinding).accessBinding(); } public boolean isReversible() { return false; } // Called when our expression's value has a result from a remote method. This will happen when a previous apply binding call // was skipped due to a pending value. protected void applyPendingChildValue(Object val, IBinding src) { boundValue = val; lhsBinding.applyReverseBinding(srcObj, val, this); } protected Object getBoundValueForChild(IBinding child) { return UNSET_VALUE_SENTINEL; } protected void initFlagsOnChildren(int flags) { super.initFlagsOnChildren(flags); if (lhsBinding != null) lhsBinding.initFlagsOnChildren(flags); if (rhsBinding instanceof DestinationListener) ((DestinationListener)rhsBinding).initFlagsOnChildren(flags); } }
34.822511
317
0.62096
cca8ab78896ace0905568e61f799cc98885ee455
10,578
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.monitor.query; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceClient; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.SimpleResponse; import com.azure.core.util.Context; import com.azure.monitor.query.log.implementation.AzureLogAnalyticsImpl; import com.azure.monitor.query.log.implementation.models.BatchRequest; import com.azure.monitor.query.log.implementation.models.BatchResponse; import com.azure.monitor.query.log.implementation.models.ErrorDetails; import com.azure.monitor.query.log.implementation.models.LogQueryRequest; import com.azure.monitor.query.log.implementation.models.LogQueryResponse; import com.azure.monitor.query.log.implementation.models.QueryBody; import com.azure.monitor.query.log.implementation.models.QueryResults; import com.azure.monitor.query.log.implementation.models.Table; import com.azure.monitor.query.models.ColumnDataType; import com.azure.monitor.query.models.LogsQueryBatch; import com.azure.monitor.query.models.LogsQueryBatchResult; import com.azure.monitor.query.models.LogsQueryBatchResultCollection; import com.azure.monitor.query.models.LogsQueryErrorDetails; import com.azure.monitor.query.models.LogsQueryOptions; import com.azure.monitor.query.models.LogsQueryResult; import com.azure.monitor.query.models.LogsTable; import com.azure.monitor.query.models.LogsTableCell; import com.azure.monitor.query.models.LogsTableColumn; import com.azure.monitor.query.models.LogsTableRow; import com.azure.monitor.query.models.QueryTimeSpan; import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import static com.azure.core.util.FluxUtil.withContext; /** * The asynchronous client for querying Azure Monitor logs. */ @ServiceClient(builder = LogsClientBuilder.class, isAsync = true) public final class LogsAsyncClient { private final AzureLogAnalyticsImpl innerClient; /** * Constructor that has the inner generated client to make the service call. * @param innerClient The inner generated client. */ LogsAsyncClient(AzureLogAnalyticsImpl innerClient) { this.innerClient = innerClient; } /** * Returns all the Azure Monitor logs matching the given query in the specified workspaceId. * @param workspaceId The workspaceId where the query should be executed. * @param query The Kusto query to fetch the logs. * @param timeSpan The time period for which the logs should be looked up. * @return The logs matching the query. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LogsQueryResult> queryLogs(String workspaceId, String query, QueryTimeSpan timeSpan) { return queryLogsWithResponse(new LogsQueryOptions(workspaceId, query, timeSpan)) .map(Response::getValue); } /** * Returns all the Azure Monitor logs matching the given query in the specified workspaceId. * @param options The query options. * @return The logs matching the query. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<LogsQueryResult>> queryLogsWithResponse(LogsQueryOptions options) { return withContext(context -> queryLogsWithResponse(options, context)); } /** * Returns all the Azure Monitor logs matching the given batch of queries in the specified workspaceId. * @param workspaceId The workspaceId where the batch of queries should be executed. * @param queries A batch of Kusto queries. * @param timeSpan The time period for which the logs should be looked up. * @return A collection of query results corresponding to the input batch of queries. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<LogsQueryBatchResultCollection> queryLogsBatch(String workspaceId, List<String> queries, QueryTimeSpan timeSpan) { LogsQueryBatch logsQueryBatch = new LogsQueryBatch(); queries.forEach(query -> logsQueryBatch.addQuery(workspaceId, query, timeSpan)); return queryLogsBatchWithResponse(logsQueryBatch).map(Response::getValue); } /** * Returns all the Azure Monitor logs matching the given batch of queries. * @param logsQueryBatch {@link LogsQueryBatch} containing a batch of queries. * @return A collection of query results corresponding to the input batch of queries.@return */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<LogsQueryBatchResultCollection>> queryLogsBatchWithResponse(LogsQueryBatch logsQueryBatch) { return queryLogsBatchWithResponse(logsQueryBatch, Context.NONE); } Mono<Response<LogsQueryBatchResultCollection>> queryLogsBatchWithResponse(LogsQueryBatch logsQueryBatch, Context context) { BatchRequest batchRequest = new BatchRequest(); AtomicInteger id = new AtomicInteger(); List<LogQueryRequest> requests = logsQueryBatch.getQueries() .stream() .map(query -> { QueryBody body = new QueryBody(query.getQuery()) .setWorkspaces(query.getWorkspaceNames()) .setAzureResourceIds(query.getAzureResourceIds()) .setQualifiedNames(query.getQualifiedWorkspaceNames()) .setWorkspaceIds(query.getWorkspaceIds()); return new LogQueryRequest() .setId(String.valueOf(id.incrementAndGet())) .setBody(body) .setWorkspace(query.getWorkspaceId()) .setPath("/query") .setMethod("POST"); }) .collect(Collectors.toList()); batchRequest.setRequests(requests); return innerClient.getQueries().batchWithResponseAsync(batchRequest, context) .map(this::convertToLogQueryBatchResult); } private Response<LogsQueryBatchResultCollection> convertToLogQueryBatchResult(Response<BatchResponse> response) { List<LogsQueryBatchResult> batchResults = new ArrayList<>(); LogsQueryBatchResultCollection logsQueryBatchResultCollection = new LogsQueryBatchResultCollection(batchResults); BatchResponse batchResponse = response.getValue(); for (LogQueryResponse singleQueryResponse : batchResponse.getResponses()) { LogsQueryBatchResult logsQueryBatchResult = new LogsQueryBatchResult(singleQueryResponse.getId(), singleQueryResponse.getStatus(), getLogsQueryResult(singleQueryResponse.getBody()), mapLogsQueryBatchError(singleQueryResponse.getBody().getErrors())); batchResults.add(logsQueryBatchResult); } batchResults.sort(Comparator.comparingInt(o -> Integer.parseInt(o.getId()))); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), logsQueryBatchResultCollection); } private LogsQueryErrorDetails mapLogsQueryBatchError(ErrorDetails errors) { if (errors != null) { return new LogsQueryErrorDetails(errors.getMessage(), errors.getCode(), errors.getTarget()); } return null; } Mono<Response<LogsQueryResult>> queryLogsWithResponse(LogsQueryOptions options, Context context) { StringBuilder sb = new StringBuilder(); if (options.isIncludeRendering()) { sb.append("include-render=true"); } if (options.isIncludeStatistics()) { if (sb.length() > 0) { sb.append(";"); } sb.append("include-statistics=true"); } if (options.getServerTimeout() != null) { if (sb.length() > 0) { sb.append(";"); } sb.append("wait="); sb.append(options.getServerTimeout().getSeconds()); } String preferHeader = sb.toString().isEmpty() ? null : sb.toString(); QueryBody queryBody = new QueryBody(options.getQuery()); if (options.getTimeSpan() != null) { queryBody.setTimespan(options.getTimeSpan().toString()); } return innerClient .getQueries() .executeWithResponseAsync(options.getWorkspaceId(), queryBody, preferHeader, context) .map(this::convertToLogQueryResult); } private Response<LogsQueryResult> convertToLogQueryResult(Response<QueryResults> response) { QueryResults queryResults = response.getValue(); LogsQueryResult logsQueryResult = getLogsQueryResult(queryResults); return new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), logsQueryResult); } private LogsQueryResult getLogsQueryResult(QueryResults queryResults) { List<LogsTable> tables = new ArrayList<>(); LogsQueryResult logsQueryResult = new LogsQueryResult(tables); if (queryResults.getTables() == null) { return null; } for (Table table : queryResults.getTables()) { List<LogsTableCell> tableCells = new ArrayList<>(); List<LogsTableRow> tableRows = new ArrayList<>(); List<LogsTableColumn> tableColumns = new ArrayList<>(); LogsTable logsTable = new LogsTable(tableCells, tableRows, tableColumns); tables.add(logsTable); List<List<String>> rows = table.getRows(); for (int i = 0; i < rows.size(); i++) { List<String> row = rows.get(i); LogsTableRow tableRow = new LogsTableRow(i, new ArrayList<>()); tableRows.add(tableRow); for (int j = 0; j < row.size(); j++) { LogsTableCell cell = new LogsTableCell(table.getColumns().get(j).getName(), ColumnDataType.fromString(table.getColumns().get(j).getType()), j, i, row.get(j)); tableCells.add(cell); tableRow.getTableRow().add(cell); } } } return logsQueryResult; } }
46.19214
140
0.67508
80d86df85a8fb928ffbdbcdd8b3c980061b5ca5e
830
package shuaicj.hobby.great.free.will.protocol.socks.type; import lombok.Getter; /** * SOCKS5 connection address type. * * o IP V4 address: X'01' * o DOMAIN NAME: X'03' * o IP V6 address: X'04' * * @see <a href="https://www.ietf.org/rfc/rfc1928.txt">RFC1928</a> * * @author shuaicj 2017/09/27 */ @Getter public enum ConnectionAddrType { IP_V4 (0x01), DOMAIN_NAME(0x03), IP_V6 (0x04); private final short value; ConnectionAddrType(int value) { this.value = (short) value; } public static ConnectionAddrType valueOf(int value) { for (ConnectionAddrType m : ConnectionAddrType.values()) { if (m.value == value) { return m; } } throw new IllegalArgumentException("illegal value: " + value); } }
21.842105
70
0.598795
32f76fd82b8f0fc20045591de35c598f41cff9b7
689
package info.macias.kaconf.test; import info.macias.kaconf.Property; public class WithBooleans { @Property("prop.true") public boolean trueProperty; @Property("prop.yes") public Boolean yesProperty; @Property("prop.1") public Boolean oneProperty; @Property("prop.false") public boolean falseProperty; @Property("prop.no") public Boolean noProperty; @Property("prop.0") public boolean zeroProperty; @Property("nonPresentProperty") public boolean hasToBeFalse; @Property("otherNonPresentProperty") public Boolean hasToBeNull; @Property("prop.anyOtherProperty") public final Boolean anyOtherProperty = null; }
20.878788
49
0.706821
eefaf818346ac887a5dd955f1a0d3865170c1807
1,248
package br.com.guimsmendes.dnasimians.configuration; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Regions; import com.amazonaws.services.sqs.AmazonSQSAsync; import com.amazonaws.services.sqs.AmazonSQSAsyncClientBuilder; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import io.awspring.cloud.messaging.core.QueueMessagingTemplate; @Configuration public class SQSConfig { @Value("${cloud.aws.region.static}") private String region; @Value("${cloud.aws.credentials.access-key}") private String awsAccessKey; @Value("${cloud.aws.credentials.secret-key}") private String awsSecretKey; @Bean public QueueMessagingTemplate queueMessagingTemplate() { return new QueueMessagingTemplate(amazonSQSAsync()); } public AmazonSQSAsync amazonSQSAsync() { return AmazonSQSAsyncClientBuilder.standard().withRegion(Regions.US_EAST_2) .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(awsAccessKey, awsSecretKey))) .build(); } }
32
119
0.772436
c1b976252fadad32d8d41d6d3ebf80318ef6ef9c
66
package com.tngtech.archunit.example; public class SomeClass { }
13.2
37
0.787879
df875ca580ccf6638e5aeccf02f8a136281a1efc
3,314
package com.awslabs.iot.client.commands.greengrass.groups; import com.awslabs.iot.client.commands.greengrass.GreengrassCommandHandler; import com.awslabs.iot.client.helpers.progressbar.ProgressBarHelper; import com.awslabs.iot.client.parameters.interfaces.ParameterExtractor; import com.awslabs.iot.client.streams.interfaces.UsesStream; import com.awslabs.iot.helpers.interfaces.GreengrassV1Helper; import com.awslabs.iot.helpers.interfaces.IotHelper; import com.awslabs.lambda.helpers.interfaces.LambdaHelper; import io.vavr.collection.List; import io.vavr.collection.Stream; import io.vavr.control.Try; import software.amazon.awssdk.services.greengrass.model.GroupInformation; import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest; import software.amazon.awssdk.services.lambda.model.FunctionConfiguration; import javax.inject.Inject; public class DeleteAllGreengrassLambdaFunctionsCommandHandler implements GreengrassCommandHandler, UsesStream<FunctionConfiguration> { private static final String DELETE_ALL_LAMBDA_FUNCTIONS = "delete-all-lambda-functions"; @Inject GreengrassV1Helper greengrassV1Helper; @Inject IotHelper iotHelper; @Inject ParameterExtractor parameterExtractor; @Inject LambdaClient lambdaClient; @Inject LambdaHelper lambdaHelper; @Inject ProgressBarHelper progressBarHelper; @Inject public DeleteAllGreengrassLambdaFunctionsCommandHandler() { } @Override public void innerHandle(String input) { Try.withResources(() -> progressBarHelper.start("Delete all Greengrass Lambda functions", this)) .of(progressBar -> run()); } private Void run() { getStream() .peek(certificate -> progressBarHelper.next()) // Extract just the name .map(FunctionConfiguration::functionName) // Delete each group's Lambda functions and rethrow all exceptions .forEach(this::deleteFunction); return null; } private void deleteFunction(String functionName) { DeleteFunctionRequest deleteFunctionRequest = DeleteFunctionRequest.builder() .functionName(functionName) .build(); lambdaClient.deleteFunction(deleteFunctionRequest); } @Override public String getCommandString() { return DELETE_ALL_LAMBDA_FUNCTIONS; } @Override public String getHelp() { return "Deletes all Lambda functions associated with any Greengrass groups."; } @Override public int requiredParameters() { return 0; } public ParameterExtractor getParameterExtractor() { return this.parameterExtractor; } @Override public Stream<FunctionConfiguration> getStream() { List<String> nonImmutableGroupNameList = greengrassV1Helper.getNonImmutableGroups() .map(GroupInformation::name) .toList(); return lambdaHelper.getAllFunctionConfigurations() // Only get functions that start with the group name .filter(functionConfiguration -> nonImmutableGroupNameList.filter(functionConfiguration.functionName()::startsWith).nonEmpty()); } }
34.884211
144
0.725407
3b207cd7733b6b05848bf0927c554dd3f17cfcac
6,918
package com.lihaodong.appupdate; import android.os.Handler; import android.os.Looper; import android.os.Message; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; import java.text.DecimalFormat; /** * Created by lihaodong on 2017/6/7. */ public class UpdateDownloadRequest implements Runnable{ private String downloadUrl; private String localFilePath; private UpdateDownloadListener downloadListener; private boolean isDownloading=false; private long currentLength; private DownloadResponseHandler downloadResponseHandler; public UpdateDownloadRequest(String downloadUrl,String localFilePath,UpdateDownloadListener downloadListener) { this.downloadListener=downloadListener; this.downloadUrl=downloadUrl; this.localFilePath=localFilePath; this.isDownloading=true; this.downloadResponseHandler=new DownloadResponseHandler(); } //真正的去建立连接的方法 private void makeRequest()throws IOException,InterruptedException{ if(!Thread.currentThread().isInterrupted()){ try { URL url=new URL(downloadUrl); HttpURLConnection connection= (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(50000); connection.setRequestProperty("Connection","Keep-Alive"); connection.connect();//放到子线程 currentLength=connection.getContentLength(); if(!Thread.currentThread().isInterrupted()){ downloadResponseHandler.sendResponseMessage(connection.getInputStream()); } }catch (IOException e){ throw e; } } } @Override public void run() { try { makeRequest(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } //格式化数据 private String getTowPointFloatStr(float value){ DecimalFormat fnum=new DecimalFormat("0.00"); return fnum.format(value); } //包含了下载过程所有可能出现的异常情况 public enum FailureCode{ UnknownHost,Socket,SocketTimeout,ConnectTimeout,IO,HttpResponse,JSON,Interrupted } public class DownloadResponseHandler{ protected static final int SUCCESS_MESSAGE=0; protected static final int FAILURE_MESSAGE=1; protected static final int START_MESSAGE=2; protected static final int FINISH_MESSAGE=3; protected static final int NETWORK_OFF=4; protected static final int PROGRESS_CHANGED=5; private int mCompleteSize=0; private int progress=0; private Handler handler; public DownloadResponseHandler(){ handler=new Handler(Looper.getMainLooper()){ @Override public void handleMessage(Message msg) { handleSelfMessage(msg); } }; } protected void sendFinishMessage(){ sendMessage(obtainMessage(FINISH_MESSAGE,null)); } private void sendProgressChangedMessage(int progress){ sendMessage(obtainMessage(PROGRESS_CHANGED,new Object[]{progress})); } protected void sendFailureMessage(FailureCode failureCode){ sendMessage(obtainMessage(FAILURE_MESSAGE,new Object[]{failureCode})); } protected Message obtainMessage(int responseMessage,Object response) { Message msg=null; if(handler!=null){ msg=handler.obtainMessage(responseMessage,response); }else{ msg=Message.obtain(); msg.what=responseMessage; msg.obj=response; } return msg; } protected void sendMessage(Message msg) { if(handler!=null){ handler.sendMessage(msg); }else{ handleSelfMessage(msg); } } protected void handleSelfMessage(Message msg) { Object[] response; switch (msg.what){ case FAILURE_MESSAGE: response= (Object[]) msg.obj; handleFailureMessage((FailureCode)response[0]); break; case PROGRESS_CHANGED: response= (Object[]) msg.obj; handleProgressChangedMessage(((Integer)response[0]).intValue()); break; case FINISH_MESSAGE: onFinish(); break; } } protected void handleFailureMessage(FailureCode failureCode) { onFailure(failureCode); } protected void handleProgressChangedMessage(int progress) { downloadListener.onProgressChanged(progress,""); } //接口的回调 public void onFailure(FailureCode failureCode) { downloadListener.onFailure(); } public void onFinish(){ downloadListener.onFinished(mCompleteSize,""); } //文件下载方法 会发送时间 void sendResponseMessage(InputStream is){ RandomAccessFile randomAccessFile=null; mCompleteSize=0; try{ byte[] buffer=new byte[1024]; int length=-1; int limit=0; randomAccessFile=new RandomAccessFile(localFilePath,"rwd"); while ((length=is.read(buffer))!=-1){ if(isDownloading){ randomAccessFile.write(buffer,0,length); mCompleteSize+=length; if(mCompleteSize<currentLength){ progress=(int)Float.parseFloat(getTowPointFloatStr(mCompleteSize*100/currentLength)); if(limit/30==0||progress<=100){ //限制notification的更新频率 sendProgressChangedMessage(progress); } limit++; } } } sendFinishMessage(); }catch (IOException e){ e.printStackTrace(); sendFailureMessage(FailureCode.IO); }finally { try{ if(is!=null){ is.close(); } if(randomAccessFile!=null){ randomAccessFile.close(); } }catch (IOException e){ e.printStackTrace(); sendFailureMessage(FailureCode.IO); } } } } }
35.295918
115
0.560856
203d0aefc4f934511d45171a780f89bd404b0f07
1,009
package edu.pdx.cs410j.parth2; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void launchreadme(View view) { Intent intent = new Intent(this, readmeactivity.class); startActivity(intent); } public void launchaddflight(View view) { Intent intent = new Intent(this, AddFlightActivity.class); startActivity(intent); } public void launchsearch(View view) { Intent intent = new Intent(this, LaunchSearchActivity.class); startActivity(intent); } public void launchdelete(View view) { Intent intent = new Intent(this, DeleteActivity.class); startActivity(intent); } }
27.27027
69
0.703667
5f118dadae6379201bb3f989a277fddccb4818be
2,007
package org.jmisb.api.klv.st0903.algorithm; import static org.testng.Assert.*; import org.testng.annotations.Test; /** Unit tests for AlgorithmMetadataKey. */ public class AlgorithmMetadataKeyTest { @Test public void Enum0Test() { AlgorithmMetadataKey key = AlgorithmMetadataKey.getKey(0); assertEquals(key, AlgorithmMetadataKey.Undefined); assertEquals(key.getTag(), 0); assertEquals(key.getIdentifier(), 0); } @Test public void EnumUnknownTest() { AlgorithmMetadataKey key = AlgorithmMetadataKey.getKey(999); assertEquals(key, AlgorithmMetadataKey.Undefined); assertEquals(key.getTag(), 0); assertEquals(key.getIdentifier(), 0); } @Test public void Enum1Test() { AlgorithmMetadataKey key = AlgorithmMetadataKey.getKey(1); assertEquals(key, AlgorithmMetadataKey.id); assertEquals(key.getTag(), 1); assertEquals(key.getIdentifier(), 1); } @Test public void Enum2Test() { AlgorithmMetadataKey key = AlgorithmMetadataKey.getKey(2); assertEquals(key, AlgorithmMetadataKey.name); assertEquals(key.getTag(), 2); assertEquals(key.getIdentifier(), 2); } @Test public void Enum3Test() { AlgorithmMetadataKey key = AlgorithmMetadataKey.getKey(3); assertEquals(key, AlgorithmMetadataKey.version); assertEquals(key.getTag(), 3); assertEquals(key.getIdentifier(), 3); } @Test public void Enum4Test() { AlgorithmMetadataKey key = AlgorithmMetadataKey.getKey(4); assertEquals(key, AlgorithmMetadataKey.algorithmClass); assertEquals(key.getTag(), 4); assertEquals(key.getIdentifier(), 4); } @Test public void Enum5Test() { AlgorithmMetadataKey key = AlgorithmMetadataKey.getKey(5); assertEquals(key, AlgorithmMetadataKey.nFrames); assertEquals(key.getTag(), 5); assertEquals(key.getIdentifier(), 5); } }
30.409091
68
0.664175
575e7a1765723d10d599699493d14585c93cc5c5
4,575
package hhtat.game.ois.ois3d; import hhtat.game.ois.math.Vector3; import hhtat.game.ois.math.Vector4; import hhtat.game.ois.util.OiSU; public class Viewport { private double xScale; private double yScale; private double zScale; private double xOffset; private double yOffset; private double zOffset; private Clipper clipper; private Rasterizer rasterizer; private Vector4 tmpA = new Vector4(); private Vector4 tmpB = new Vector4(); private Vector4 tmpC = new Vector4(); private Vector3 tmpAColor = new Vector3(); private Vector3 tmpBColor = new Vector3(); private Vector3 tmpCColor = new Vector3(); public Viewport( double width, double height, Clipper clipper, Rasterizer rasterizer ) { this.clipper = clipper; this.rasterizer = rasterizer; this.setViewport( 0.0, 0.0, width, height ); this.setDepthRange( 0.0, 1.0 ); } public void setViewport( double x, double y, double width, double height ) { double halfWidth = 0.5 * width; double halfHeight = 0.5 * height; this.xScale = halfWidth; this.yScale = halfHeight; this.xOffset = x + halfWidth; this.yOffset = y + halfHeight; } public void setDepthRange( double near, double far ) { this.zScale = 0.5 * ( far - near ); this.zOffset = 0.5 * ( near + far ); } public void drawPoint( Vector4 a, Vector3 aColor ) { double ax = a.x(); double ay = a.y(); double az = a.z(); double aw = a.w(); double awAbs = OiSU.abs( aw ); if ( ( -awAbs <= ax ) && ( ax <= awAbs ) && ( -awAbs <= ay ) && ( ay <= awAbs ) && ( -awAbs <= az ) && ( az <= awAbs ) ) { a = this.tmpA.set( ax, ay, az, aw ); // TODO when we start working with color (lighting, etc) // aColor = this.tmpAColor.set( aColor ); a.divide( a.w() ); // @formatter:off this.rasterizer.rasterizePoint( ( this.xScale * a.x() ) + this.xOffset, ( this.yScale * a.y() ) + this.yOffset, ( this.zScale * a.z() ) + this.zOffset, aColor.x(), aColor.y(), aColor.z() ); // @formatter:on } } public void drawLine( Vector4 a, Vector3 aColor, Vector4 b, Vector3 bColor ) { a = this.tmpA.set( a ); b = this.tmpB.set( b ); aColor = this.tmpAColor.set( aColor ); bColor = this.tmpBColor.set( bColor ); if ( this.clipper.clipLine( a, aColor, b, bColor ) ) { a.divide( a.w() ); b.divide( b.w() ); // @formatter:off this.rasterizer.rasterizeLine( ( this.xScale * a.x() ) + this.xOffset, ( this.yScale * a.y() ) + this.yOffset, ( this.zScale * a.z() ) + this.zOffset, aColor.x(), aColor.y(), aColor.z(), ( this.xScale * b.x() ) + this.xOffset, ( this.yScale * b.y() ) + this.yOffset, ( this.zScale * b.z() ) + this.zOffset, bColor.x(), bColor.y(), bColor.z() ); // @formatter:on } } public void drawTriangle( Vector4 a, Vector3 aColor, Vector4 b, Vector3 bColor, Vector4 c, Vector3 cColor ) { a = this.tmpA.set( a ); b = this.tmpB.set( b ); c = this.tmpC.set( c ); aColor = this.tmpAColor.set( aColor ); bColor = this.tmpBColor.set( bColor ); cColor = this.tmpCColor.set( cColor ); // TODO clip a.divide( a.w() ); b.divide( b.w() ); c.divide( c.w() ); // @formatter:off this.rasterizer.rasterizeTriangle( ( this.xScale * a.x() ) + this.xOffset, ( this.yScale * a.y() ) + this.yOffset, ( this.zScale * a.z() ) + this.zOffset, aColor.x(), aColor.y(), aColor.z(), ( this.xScale * b.x() ) + this.xOffset, ( this.yScale * b.y() ) + this.yOffset, ( this.zScale * b.z() ) + this.zOffset, bColor.x(), bColor.y(), bColor.z(), ( this.xScale * c.x() ) + this.xOffset, ( this.yScale * c.y() ) + this.yOffset, ( this.zScale * c.z() ) + this.zOffset, cColor.x(), cColor.y(), cColor.z() ); // @formatter:on } }
34.923664
126
0.498798
8f835634688baeb770c07e85aec9facbb879ed8a
961
/* * Copyright (c) 2018. paascloud.net All Rights Reserved. * 项目名称:附近有好吃的 * 类名称:OrderDetailDto.java * 创建人:兰龙斌 * 联系方式:llb7891@163.com * 开源地址: https://github.com/NewlyLan/nearbyEat.git * * */ package com.paascloud.provider.model.dto; import lombok.Data; import java.io.Serializable; import java.math.BigDecimal; /** * The class Order detail dto. * * @author paascloud.net@gmail.com */ @Data public class OrderDetailDto implements Serializable { private static final long serialVersionUID = 4423448618530228839L; private Long id; /** * 订单明细序列号 */ private String detailNo; private Long userId; private String orderNo; private Long productId; /** * 商品名称 */ private String productName; /** * 商品图片地址 */ private String productImage; /** * 生成订单时的商品单价, 单位是元,保留两位小数 */ private BigDecimal currentUnitPrice; /** * 商品数量 */ private Integer quantity; /** * 商品总价,单位是元,保留两位小数 */ private BigDecimal totalPrice; }
14.784615
67
0.695109
14adbb2dd1070e3c66d8fdcf4178e12497280235
1,316
/* * Copyright 2010 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.runtime.pipeline.impl; import org.drools.runtime.pipeline.Callable; import org.drools.runtime.pipeline.PipelineContext; public class CallableImpl<E> extends BaseEmitter implements Callable { public static final String key = "__CallableReturnValue__"; public CallableImpl() { super(); } public Object call(Object object, PipelineContext context) { emit( object, context ); return context.getProperties().remove( key ); } public void receive(Object object, PipelineContext context) { context.getProperties().put( key, object ); } }
28.608696
75
0.662614
b181899a15d19e96f34b150c5ee867e0660105e6
1,455
package com.packt.springsecurity.backend.security; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import com.google.common.collect.Lists; import com.packt.springsecurity.backend.model.Account; import com.packt.springsecurity.backend.model.Permission; import com.packt.springsecurity.backend.model.Role; import com.packt.springsecurity.backend.persistence.service.IAccountService; @Component public class SecUserService implements UserDetailsService { @Autowired private IAccountService accountService; public SecUserService() { super(); } // API public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { final Account foundByUsername = accountService.findByName(username); final Set<Role> roles = foundByUsername.getRoles(); final List<Permission> permissions = Lists.newArrayList(); for (final Role role : roles) { permissions.addAll(role.getPermissions()); } return new org.springframework.security.core.userdetails.User(username, foundByUsername.getPassword(), permissions); } }
34.642857
124
0.780069
56dddd1f20e570f27c07d67d0dc3bf24bb95483b
1,600
/** * Copyright 2013 Jonathan Cobb * Copyright 2014 TangoMe Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tango.BucketSyncer.KeyListers; import com.tango.BucketSyncer.MirrorContext; import com.tango.BucketSyncer.ObjectSummaries.ObjectSummary; import lombok.extern.slf4j.Slf4j; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; @Slf4j public abstract class KeyLister implements Runnable { protected MirrorContext context; protected Integer maxQueueCapacity; protected String bucket; protected String prefix; protected final AtomicBoolean done = new AtomicBoolean(false); public boolean isDone() { return done.get(); } public KeyLister(String bucket, String prefix, MirrorContext context, Integer maxQueueCapacity) { this.bucket = bucket; this.prefix = prefix; this.context = context; this.maxQueueCapacity = maxQueueCapacity; } public abstract List<ObjectSummary> getNextBatch(); }
31.372549
76
0.7075
b099d655b6187e202d65828e439319c9419347e5
1,894
package com.zoho.crm.api; import java.util.HashMap; import com.zoho.crm.api.exception.SDKException; import com.zoho.crm.api.util.Constants; import com.zoho.crm.api.util.DataTypeConverter; /** * This class represents the HTTP parameter name and value. */ public class ParameterMap { private HashMap<String, String> parameterMap = new HashMap<String, String>(); /** * This is a getter method to get parameter map. * @return A HashMap&lt;String, String&gt; representing the API request parameters. */ public HashMap<String, String> getParameterMap() { return parameterMap; } /** * This method to add parameter name and value. * @param <T> A T containing the specified data type. * @param param A Param&lt;T&gt; class instance. * @param value A T containing the parameter value. * @throws SDKException */ public <T> void add(Param<T> param, T value) throws SDKException { if(param == null) { throw new SDKException(Constants.PARAMETER_NULL_ERROR, Constants.PARAM_INSTANCE_NULL_ERROR); } String paramName = param.getName(); if(paramName == null) { throw new SDKException(Constants.PARAM_NAME_NULL_ERROR, Constants.PARAM_NAME_NULL_ERROR_MESSAGE); } if(value == null) { throw new SDKException(Constants.PARAMETER_NULL_ERROR, paramName + Constants.NULL_VALUE_ERROR_MESSAGE); } String paramValue = null; try { paramValue = DataTypeConverter.postConvert(value, value.getClass().getName()).toString(); } catch (Exception e) { paramValue = value.toString(); } if(parameterMap.containsKey(paramName) && !parameterMap.get(paramName).isEmpty()) { String existingParamValue = parameterMap.get(paramName); existingParamValue = existingParamValue + "," + paramValue; parameterMap.put(paramName, existingParamValue); } else { parameterMap.put(paramName, paramValue); } } }
25.253333
106
0.714361
91f3301ba6ddb46aaa730b74ae3d2332d759cef0
1,613
package com.zy18703.podcastplayer; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class AddPodcastActivity extends AppCompatActivity { // Activity for user to enter custom podcast URL @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog_add_podcast); } public void buttonAction(View view) { int id = view.getId(); if (id == R.id.button_cancel) { // User clicks CANCEL or moves focus out of the view setResult(RESULT_CANCELED); finish(); } else if (id == R.id.button_add) { // User click ADD EditText editText = findViewById(R.id.edit_add_url); Uri uri = Uri.parse(editText.getText().toString().trim()); // Examine whether it is an HTTP/HTTPS URL if (uri != null && uri.getScheme() != null && (uri.getScheme().toLowerCase().equals("http") || uri.getScheme().toLowerCase().equals("https"))) { Intent result = new Intent(this, MainActivity.class); result.setData(uri); setResult(RESULT_OK, result); finish(); } else Toast.makeText(this, R.string.toast_invalid_url, Toast.LENGTH_SHORT).show(); } } }
36.659091
93
0.590825
7ba2378b53265e53e6cc0444329ff073e787495d
2,226
/* Copyright 2004 The Apache Software Foundation * * 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.codehaus.jam; /** * <p>Represents an exposed field on a Java class.</p> * * @author Patrick Calahan &lt;email: pcal-at-bea-dot-com&gt; */ public interface JField extends JMember { /** * Returns the type of this field. */ public JClass getType(); /** * Return true if this field is final. */ public boolean isFinal(); /** * Return true if this field is static. */ public boolean isStatic(); /** * Return true if this field is volatile. */ public boolean isVolatile(); /** * Return true if this field is transient. */ public boolean isTransient(); /** * <p>Returns a qualied name for this method as specified by * <code>java.lang.reflect.Field.toString()</code>:</p> * * <p><i>Returns a string describing this Field. The format is the access * modifiers for the field, if any, followed by the field type, followed * by a space, followed by the fully-qualified name of the class declaring * the field, followed by a period, followed by the name of the field. * For example:</i></p> * * <p><i>public static final int java.lang.Thread.MIN_PRIORITY</i></p> * <p><i>private int java.io.FileDescriptor.fd</i></p> * * <p><i>The modifiers are placed in canonical order as specified by "The * Java Language Specification". This is public, protected or private * first, and then other modifiers in the following order: static, final, * transient, volatile.</i></p> */ public String getQualifiedName(); }
30.493151
78
0.655885
f63df848e1ed0c30431f12f58e5eb54e36842c95
8,905
package db.repository.mariadb; import db.ConnectionPool; import db.model.guildWarLeaderboard.GuildWarLeaderboard; import db.model.guildWarLeaderboard.GuildWarLeaderboardId; import db.repository.base.GuildWarLeaderboardRepository; import log.Logger; import org.jetbrains.annotations.NotNull; import javax.annotation.Nullable; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; public class MariaGuildWarLeaderboardRepository extends MariaRepository<GuildWarLeaderboard> implements GuildWarLeaderboardRepository { private static final DateFormat dbFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); MariaGuildWarLeaderboardRepository(ConnectionPool db, Logger logger) { super(db, logger); } @Override protected GuildWarLeaderboard bind(@NotNull ResultSet res) throws SQLException { return new GuildWarLeaderboard( res.getString(1), res.getInt(2), res.getInt(3), res.getMetaData().getColumnCount() > 3 ? res.getBigDecimal(4) : null ); } @Override public <S extends GuildWarLeaderboard> boolean create(@NotNull S entity) { return this.execute( "INSERT INTO `guild_war_leaderboard` (guild_name, total_war, success_war) VALUES (?, ?, ?)", entity.getGuildName(), entity.getTotalWar(), entity.getSuccessWar() ); } @Override public boolean exists(@NotNull GuildWarLeaderboardId guildWarLeaderboardId) { ResultSet res = this.executeQuery( "SELECT COUNT(*) FROM `guild_war_leaderboard` WHERE `guild_name` = ?", guildWarLeaderboardId.getGuildName() ); if (res == null) { return false; } try { if (res.next()) return res.getInt(1) > 0; } catch (SQLException e) { this.logResponseException(e); } return false; } @Override public long count() { ResultSet res = this.executeQuery( "SELECT COUNT(*) FROM `guild_war_leaderboard`" ); if (res == null) { return -1; } try { if (res.next()) return res.getInt(1); } catch (SQLException e) { this.logResponseException(e); } return -1; } @Nullable @Override public GuildWarLeaderboard findOne(@NotNull GuildWarLeaderboardId guildWarLeaderboardId) { ResultSet res = this.executeQuery( "SELECT * FROM `guild_war_leaderboard` WHERE `guild_name` = ?", guildWarLeaderboardId.getGuildName() ); if (res == null) { return null; } try { if (res.next()) return bind(res); } catch (SQLException e) { this.logResponseException(e); } return null; } @Nullable @Override public List<GuildWarLeaderboard> findAll() { ResultSet res = this.executeQuery( "SELECT * FROM `guild_war_leaderboard`" ); if (res == null) { return null; } try { return bindAll(res); } catch (SQLException e) { this.logResponseException(e); return null; } } @Nullable @Override public List<GuildWarLeaderboard> getByTotalWarDescending(int limit, int offset) { ResultSet res = this.executeQuery( "SELECT * FROM `guild_war_leaderboard` ORDER BY `total_war` DESC, `guild_name` DESC LIMIT " + limit + " OFFSET " + offset ); if (res == null) { return null; } try { return bindAll(res); } catch (SQLException e) { this.logResponseException(e); return null; } } @Nullable @Override public List<GuildWarLeaderboard> getBySuccessWarDescending(int limit, int offset) { ResultSet res = this.executeQuery( "SELECT * FROM `guild_war_leaderboard` ORDER BY `success_war` DESC, `guild_name` DESC LIMIT " + limit + " OFFSET " + offset ); if (res == null) { return null; } try { return bindAll(res); } catch (SQLException e) { this.logResponseException(e); return null; } } private int getFirstWarLogIdAfter(@NotNull Date date) { ResultSet res = this.executeQuery( "SELECT first_war_log_id_after(?)", dbFormat.format(date) ); if (res == null) { return -1; } try { if (res.next()) return res.getInt(1); } catch (SQLException e) { this.logResponseException(e); } return -1; } @Override public int getGuildsInRange(@NotNull Date start, @NotNull Date end) { int first = getFirstWarLogIdAfter(start); int last = getFirstWarLogIdAfter(end); if (first == -1 || last == -1) { return -1; } ResultSet res = this.executeQuery( "SELECT COUNT(*) FROM (" + "SELECT guild_name FROM `guild_war_log` " + "WHERE `guild_total_wars_between`(guild_name, ?, ?) > 0 " + "GROUP BY `guild_name`" + ") AS t", first, last ); if (res == null) { return -1; } try { if (res.next()) return res.getInt(1); } catch (SQLException e) { this.logResponseException(e); } return -1; } @Nullable @Override public List<GuildWarLeaderboard> getByTotalWarDescending(int limit, int offset, @NotNull Date start, @NotNull Date end) { int first = getFirstWarLogIdAfter(start); int last = getFirstWarLogIdAfter(end); if (first == -1 || last == -1) { return null; } ResultSet res = this.executeQuery( "SELECT * FROM (SELECT guild_name, " + "guild_total_wars_between(guild_name, ?, ?) AS total_wars, " + "guild_success_wars_between(guild_name, ?, ?) AS success_wars " + "FROM `guild_war_log` " + "WHERE `guild_total_wars_between`(guild_name, ?, ?) > 0 " + "GROUP BY `guild_name` " + "ORDER BY total_wars DESC, guild_name DESC) AS t LIMIT " + limit + " OFFSET " + offset, first, last, first, last, first, last ); if (res == null) { return null; } try { return bindAll(res); } catch (SQLException e) { this.logResponseException(e); return null; } } @Nullable @Override public List<GuildWarLeaderboard> getBySuccessWarDescending(int limit, int offset, @NotNull Date start, @NotNull Date end) { int first = getFirstWarLogIdAfter(start); int last = getFirstWarLogIdAfter(end); if (first == -1 || last == -1) { return null; } ResultSet res = this.executeQuery( "SELECT * FROM (SELECT guild_name, " + "guild_total_wars_between(guild_name, ?, ?) AS total_wars, " + "guild_success_wars_between(guild_name, ?, ?) AS success_wars " + "FROM `guild_war_log` " + "WHERE `guild_total_wars_between`(guild_name, ?, ?) > 0 " + "GROUP BY `guild_name` " + "ORDER BY success_wars DESC, guild_name DESC) AS t LIMIT " + limit + " OFFSET " + offset, first, last, first, last, first, last ); if (res == null) { return null; } try { return bindAll(res); } catch (SQLException e) { this.logResponseException(e); return null; } } @Override public boolean update(@NotNull GuildWarLeaderboard entity) { return this.execute( "UPDATE `guild_war_leaderboard` SET `total_war` = ?, `success_war` = ? WHERE `guild_name` = ?", entity.getTotalWar(), entity.getSuccessWar(), entity.getGuildName() ); } @Override public boolean delete(@NotNull GuildWarLeaderboardId guildWarLeaderboardId) { return this.execute( "DELETE FROM `guild_war_leaderboard` WHERE `guild_name` = ?", guildWarLeaderboardId.getGuildName() ); } }
30.186441
139
0.541943
46f2a5334ddd9396115b17c2715d813fc98442b9
101,748
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: SignatureVerificationResult.proto package Diadoc.Api.Proto; public final class SignatureVerificationResultProtos { private SignatureVerificationResultProtos() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface SignatureVerificationResultOrBuilder extends // @@protoc_insertion_point(interface_extends:Diadoc.Api.Proto.SignatureVerificationResult) com.google.protobuf.MessageOrBuilder { /** * <code>required bool IsValid = 1;</code> */ boolean hasIsValid(); /** * <code>required bool IsValid = 1;</code> */ boolean getIsValid(); /** * <code>optional .Diadoc.Api.Proto.CertificateVerificationResult CertificateStatus = 2;</code> */ boolean hasCertificateStatus(); /** * <code>optional .Diadoc.Api.Proto.CertificateVerificationResult CertificateStatus = 2;</code> */ Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult getCertificateStatus(); /** * <code>optional .Diadoc.Api.Proto.CertificateVerificationResult CertificateStatus = 2;</code> */ Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResultOrBuilder getCertificateStatusOrBuilder(); /** * <code>optional .Diadoc.Api.Proto.Timestamp SignatureTimestamp = 3;</code> */ boolean hasSignatureTimestamp(); /** * <code>optional .Diadoc.Api.Proto.Timestamp SignatureTimestamp = 3;</code> */ Diadoc.Api.Proto.TimestampProtos.Timestamp getSignatureTimestamp(); /** * <code>optional .Diadoc.Api.Proto.Timestamp SignatureTimestamp = 3;</code> */ Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getSignatureTimestampOrBuilder(); } /** * Protobuf type {@code Diadoc.Api.Proto.SignatureVerificationResult} */ public static final class SignatureVerificationResult extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:Diadoc.Api.Proto.SignatureVerificationResult) SignatureVerificationResultOrBuilder { // Use SignatureVerificationResult.newBuilder() to construct. private SignatureVerificationResult(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private SignatureVerificationResult(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final SignatureVerificationResult defaultInstance; public static SignatureVerificationResult getDefaultInstance() { return defaultInstance; } public SignatureVerificationResult getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private SignatureVerificationResult( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; isValid_ = input.readBool(); break; } case 18: { Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.Builder subBuilder = null; if (((bitField0_ & 0x00000002) == 0x00000002)) { subBuilder = certificateStatus_.toBuilder(); } certificateStatus_ = input.readMessage(Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(certificateStatus_); certificateStatus_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000002; break; } case 26: { Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder subBuilder = null; if (((bitField0_ & 0x00000004) == 0x00000004)) { subBuilder = signatureTimestamp_.toBuilder(); } signatureTimestamp_ = input.readMessage(Diadoc.Api.Proto.TimestampProtos.Timestamp.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(signatureTimestamp_); signatureTimestamp_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000004; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.internal_static_Diadoc_Api_Proto_SignatureVerificationResult_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.internal_static_Diadoc_Api_Proto_SignatureVerificationResult_fieldAccessorTable .ensureFieldAccessorsInitialized( Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult.class, Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult.Builder.class); } public static com.google.protobuf.Parser<SignatureVerificationResult> PARSER = new com.google.protobuf.AbstractParser<SignatureVerificationResult>() { public SignatureVerificationResult parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new SignatureVerificationResult(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<SignatureVerificationResult> getParserForType() { return PARSER; } private int bitField0_; public static final int ISVALID_FIELD_NUMBER = 1; private boolean isValid_; /** * <code>required bool IsValid = 1;</code> */ public boolean hasIsValid() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required bool IsValid = 1;</code> */ public boolean getIsValid() { return isValid_; } public static final int CERTIFICATESTATUS_FIELD_NUMBER = 2; private Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult certificateStatus_; /** * <code>optional .Diadoc.Api.Proto.CertificateVerificationResult CertificateStatus = 2;</code> */ public boolean hasCertificateStatus() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional .Diadoc.Api.Proto.CertificateVerificationResult CertificateStatus = 2;</code> */ public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult getCertificateStatus() { return certificateStatus_; } /** * <code>optional .Diadoc.Api.Proto.CertificateVerificationResult CertificateStatus = 2;</code> */ public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResultOrBuilder getCertificateStatusOrBuilder() { return certificateStatus_; } public static final int SIGNATURETIMESTAMP_FIELD_NUMBER = 3; private Diadoc.Api.Proto.TimestampProtos.Timestamp signatureTimestamp_; /** * <code>optional .Diadoc.Api.Proto.Timestamp SignatureTimestamp = 3;</code> */ public boolean hasSignatureTimestamp() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional .Diadoc.Api.Proto.Timestamp SignatureTimestamp = 3;</code> */ public Diadoc.Api.Proto.TimestampProtos.Timestamp getSignatureTimestamp() { return signatureTimestamp_; } /** * <code>optional .Diadoc.Api.Proto.Timestamp SignatureTimestamp = 3;</code> */ public Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getSignatureTimestampOrBuilder() { return signatureTimestamp_; } private void initFields() { isValid_ = false; certificateStatus_ = Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.getDefaultInstance(); signatureTimestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; if (!hasIsValid()) { memoizedIsInitialized = 0; return false; } if (hasCertificateStatus()) { if (!getCertificateStatus().isInitialized()) { memoizedIsInitialized = 0; return false; } } if (hasSignatureTimestamp()) { if (!getSignatureTimestamp().isInitialized()) { memoizedIsInitialized = 0; return false; } } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBool(1, isValid_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeMessage(2, certificateStatus_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeMessage(3, signatureTimestamp_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(1, isValid_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, certificateStatus_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, signatureTimestamp_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code Diadoc.Api.Proto.SignatureVerificationResult} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:Diadoc.Api.Proto.SignatureVerificationResult) Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResultOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.internal_static_Diadoc_Api_Proto_SignatureVerificationResult_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.internal_static_Diadoc_Api_Proto_SignatureVerificationResult_fieldAccessorTable .ensureFieldAccessorsInitialized( Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult.class, Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult.Builder.class); } // Construct using Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getCertificateStatusFieldBuilder(); getSignatureTimestampFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); isValid_ = false; bitField0_ = (bitField0_ & ~0x00000001); if (certificateStatusBuilder_ == null) { certificateStatus_ = Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.getDefaultInstance(); } else { certificateStatusBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); if (signatureTimestampBuilder_ == null) { signatureTimestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance(); } else { signatureTimestampBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000004); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.internal_static_Diadoc_Api_Proto_SignatureVerificationResult_descriptor; } public Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult getDefaultInstanceForType() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult.getDefaultInstance(); } public Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult build() { Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult buildPartial() { Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult result = new Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.isValid_ = isValid_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } if (certificateStatusBuilder_ == null) { result.certificateStatus_ = certificateStatus_; } else { result.certificateStatus_ = certificateStatusBuilder_.build(); } if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } if (signatureTimestampBuilder_ == null) { result.signatureTimestamp_ = signatureTimestamp_; } else { result.signatureTimestamp_ = signatureTimestampBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult) { return mergeFrom((Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult other) { if (other == Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult.getDefaultInstance()) return this; if (other.hasIsValid()) { setIsValid(other.getIsValid()); } if (other.hasCertificateStatus()) { mergeCertificateStatus(other.getCertificateStatus()); } if (other.hasSignatureTimestamp()) { mergeSignatureTimestamp(other.getSignatureTimestamp()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasIsValid()) { return false; } if (hasCertificateStatus()) { if (!getCertificateStatus().isInitialized()) { return false; } } if (hasSignatureTimestamp()) { if (!getSignatureTimestamp().isInitialized()) { return false; } } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (Diadoc.Api.Proto.SignatureVerificationResultProtos.SignatureVerificationResult) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private boolean isValid_ ; /** * <code>required bool IsValid = 1;</code> */ public boolean hasIsValid() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required bool IsValid = 1;</code> */ public boolean getIsValid() { return isValid_; } /** * <code>required bool IsValid = 1;</code> */ public Builder setIsValid(boolean value) { bitField0_ |= 0x00000001; isValid_ = value; onChanged(); return this; } /** * <code>required bool IsValid = 1;</code> */ public Builder clearIsValid() { bitField0_ = (bitField0_ & ~0x00000001); isValid_ = false; onChanged(); return this; } private Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult certificateStatus_ = Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.Builder, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResultOrBuilder> certificateStatusBuilder_; /** * <code>optional .Diadoc.Api.Proto.CertificateVerificationResult CertificateStatus = 2;</code> */ public boolean hasCertificateStatus() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional .Diadoc.Api.Proto.CertificateVerificationResult CertificateStatus = 2;</code> */ public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult getCertificateStatus() { if (certificateStatusBuilder_ == null) { return certificateStatus_; } else { return certificateStatusBuilder_.getMessage(); } } /** * <code>optional .Diadoc.Api.Proto.CertificateVerificationResult CertificateStatus = 2;</code> */ public Builder setCertificateStatus(Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult value) { if (certificateStatusBuilder_ == null) { if (value == null) { throw new NullPointerException(); } certificateStatus_ = value; onChanged(); } else { certificateStatusBuilder_.setMessage(value); } bitField0_ |= 0x00000002; return this; } /** * <code>optional .Diadoc.Api.Proto.CertificateVerificationResult CertificateStatus = 2;</code> */ public Builder setCertificateStatus( Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.Builder builderForValue) { if (certificateStatusBuilder_ == null) { certificateStatus_ = builderForValue.build(); onChanged(); } else { certificateStatusBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; return this; } /** * <code>optional .Diadoc.Api.Proto.CertificateVerificationResult CertificateStatus = 2;</code> */ public Builder mergeCertificateStatus(Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult value) { if (certificateStatusBuilder_ == null) { if (((bitField0_ & 0x00000002) == 0x00000002) && certificateStatus_ != Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.getDefaultInstance()) { certificateStatus_ = Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.newBuilder(certificateStatus_).mergeFrom(value).buildPartial(); } else { certificateStatus_ = value; } onChanged(); } else { certificateStatusBuilder_.mergeFrom(value); } bitField0_ |= 0x00000002; return this; } /** * <code>optional .Diadoc.Api.Proto.CertificateVerificationResult CertificateStatus = 2;</code> */ public Builder clearCertificateStatus() { if (certificateStatusBuilder_ == null) { certificateStatus_ = Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.getDefaultInstance(); onChanged(); } else { certificateStatusBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } /** * <code>optional .Diadoc.Api.Proto.CertificateVerificationResult CertificateStatus = 2;</code> */ public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.Builder getCertificateStatusBuilder() { bitField0_ |= 0x00000002; onChanged(); return getCertificateStatusFieldBuilder().getBuilder(); } /** * <code>optional .Diadoc.Api.Proto.CertificateVerificationResult CertificateStatus = 2;</code> */ public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResultOrBuilder getCertificateStatusOrBuilder() { if (certificateStatusBuilder_ != null) { return certificateStatusBuilder_.getMessageOrBuilder(); } else { return certificateStatus_; } } /** * <code>optional .Diadoc.Api.Proto.CertificateVerificationResult CertificateStatus = 2;</code> */ private com.google.protobuf.SingleFieldBuilder< Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.Builder, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResultOrBuilder> getCertificateStatusFieldBuilder() { if (certificateStatusBuilder_ == null) { certificateStatusBuilder_ = new com.google.protobuf.SingleFieldBuilder< Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.Builder, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResultOrBuilder>( getCertificateStatus(), getParentForChildren(), isClean()); certificateStatus_ = null; } return certificateStatusBuilder_; } private Diadoc.Api.Proto.TimestampProtos.Timestamp signatureTimestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder> signatureTimestampBuilder_; /** * <code>optional .Diadoc.Api.Proto.Timestamp SignatureTimestamp = 3;</code> */ public boolean hasSignatureTimestamp() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional .Diadoc.Api.Proto.Timestamp SignatureTimestamp = 3;</code> */ public Diadoc.Api.Proto.TimestampProtos.Timestamp getSignatureTimestamp() { if (signatureTimestampBuilder_ == null) { return signatureTimestamp_; } else { return signatureTimestampBuilder_.getMessage(); } } /** * <code>optional .Diadoc.Api.Proto.Timestamp SignatureTimestamp = 3;</code> */ public Builder setSignatureTimestamp(Diadoc.Api.Proto.TimestampProtos.Timestamp value) { if (signatureTimestampBuilder_ == null) { if (value == null) { throw new NullPointerException(); } signatureTimestamp_ = value; onChanged(); } else { signatureTimestampBuilder_.setMessage(value); } bitField0_ |= 0x00000004; return this; } /** * <code>optional .Diadoc.Api.Proto.Timestamp SignatureTimestamp = 3;</code> */ public Builder setSignatureTimestamp( Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder builderForValue) { if (signatureTimestampBuilder_ == null) { signatureTimestamp_ = builderForValue.build(); onChanged(); } else { signatureTimestampBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; return this; } /** * <code>optional .Diadoc.Api.Proto.Timestamp SignatureTimestamp = 3;</code> */ public Builder mergeSignatureTimestamp(Diadoc.Api.Proto.TimestampProtos.Timestamp value) { if (signatureTimestampBuilder_ == null) { if (((bitField0_ & 0x00000004) == 0x00000004) && signatureTimestamp_ != Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance()) { signatureTimestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.newBuilder(signatureTimestamp_).mergeFrom(value).buildPartial(); } else { signatureTimestamp_ = value; } onChanged(); } else { signatureTimestampBuilder_.mergeFrom(value); } bitField0_ |= 0x00000004; return this; } /** * <code>optional .Diadoc.Api.Proto.Timestamp SignatureTimestamp = 3;</code> */ public Builder clearSignatureTimestamp() { if (signatureTimestampBuilder_ == null) { signatureTimestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance(); onChanged(); } else { signatureTimestampBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000004); return this; } /** * <code>optional .Diadoc.Api.Proto.Timestamp SignatureTimestamp = 3;</code> */ public Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder getSignatureTimestampBuilder() { bitField0_ |= 0x00000004; onChanged(); return getSignatureTimestampFieldBuilder().getBuilder(); } /** * <code>optional .Diadoc.Api.Proto.Timestamp SignatureTimestamp = 3;</code> */ public Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getSignatureTimestampOrBuilder() { if (signatureTimestampBuilder_ != null) { return signatureTimestampBuilder_.getMessageOrBuilder(); } else { return signatureTimestamp_; } } /** * <code>optional .Diadoc.Api.Proto.Timestamp SignatureTimestamp = 3;</code> */ private com.google.protobuf.SingleFieldBuilder< Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder> getSignatureTimestampFieldBuilder() { if (signatureTimestampBuilder_ == null) { signatureTimestampBuilder_ = new com.google.protobuf.SingleFieldBuilder< Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder>( getSignatureTimestamp(), getParentForChildren(), isClean()); signatureTimestamp_ = null; } return signatureTimestampBuilder_; } // @@protoc_insertion_point(builder_scope:Diadoc.Api.Proto.SignatureVerificationResult) } static { defaultInstance = new SignatureVerificationResult(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:Diadoc.Api.Proto.SignatureVerificationResult) } public interface CertificateVerificationResultOrBuilder extends // @@protoc_insertion_point(interface_extends:Diadoc.Api.Proto.CertificateVerificationResult) com.google.protobuf.MessageOrBuilder { /** * <code>required bool IsValid = 2;</code> */ boolean hasIsValid(); /** * <code>required bool IsValid = 2;</code> */ boolean getIsValid(); /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ java.util.List<Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement> getCertificateChainList(); /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement getCertificateChain(int index); /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ int getCertificateChainCount(); /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ java.util.List<? extends Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElementOrBuilder> getCertificateChainOrBuilderList(); /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElementOrBuilder getCertificateChainOrBuilder( int index); /** * <code>required .Diadoc.Api.Proto.Timestamp VerificationTime = 4;</code> */ boolean hasVerificationTime(); /** * <code>required .Diadoc.Api.Proto.Timestamp VerificationTime = 4;</code> */ Diadoc.Api.Proto.TimestampProtos.Timestamp getVerificationTime(); /** * <code>required .Diadoc.Api.Proto.Timestamp VerificationTime = 4;</code> */ Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getVerificationTimeOrBuilder(); } /** * Protobuf type {@code Diadoc.Api.Proto.CertificateVerificationResult} */ public static final class CertificateVerificationResult extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:Diadoc.Api.Proto.CertificateVerificationResult) CertificateVerificationResultOrBuilder { // Use CertificateVerificationResult.newBuilder() to construct. private CertificateVerificationResult(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private CertificateVerificationResult(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final CertificateVerificationResult defaultInstance; public static CertificateVerificationResult getDefaultInstance() { return defaultInstance; } public CertificateVerificationResult getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private CertificateVerificationResult( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 16: { bitField0_ |= 0x00000001; isValid_ = input.readBool(); break; } case 26: { if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { certificateChain_ = new java.util.ArrayList<Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement>(); mutable_bitField0_ |= 0x00000002; } certificateChain_.add(input.readMessage(Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.PARSER, extensionRegistry)); break; } case 34: { Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder subBuilder = null; if (((bitField0_ & 0x00000002) == 0x00000002)) { subBuilder = verificationTime_.toBuilder(); } verificationTime_ = input.readMessage(Diadoc.Api.Proto.TimestampProtos.Timestamp.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(verificationTime_); verificationTime_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000002; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { certificateChain_ = java.util.Collections.unmodifiableList(certificateChain_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.internal_static_Diadoc_Api_Proto_CertificateVerificationResult_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.internal_static_Diadoc_Api_Proto_CertificateVerificationResult_fieldAccessorTable .ensureFieldAccessorsInitialized( Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.class, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.Builder.class); } public static com.google.protobuf.Parser<CertificateVerificationResult> PARSER = new com.google.protobuf.AbstractParser<CertificateVerificationResult>() { public CertificateVerificationResult parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new CertificateVerificationResult(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<CertificateVerificationResult> getParserForType() { return PARSER; } private int bitField0_; public static final int ISVALID_FIELD_NUMBER = 2; private boolean isValid_; /** * <code>required bool IsValid = 2;</code> */ public boolean hasIsValid() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required bool IsValid = 2;</code> */ public boolean getIsValid() { return isValid_; } public static final int CERTIFICATECHAIN_FIELD_NUMBER = 3; private java.util.List<Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement> certificateChain_; /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public java.util.List<Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement> getCertificateChainList() { return certificateChain_; } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public java.util.List<? extends Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElementOrBuilder> getCertificateChainOrBuilderList() { return certificateChain_; } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public int getCertificateChainCount() { return certificateChain_.size(); } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement getCertificateChain(int index) { return certificateChain_.get(index); } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElementOrBuilder getCertificateChainOrBuilder( int index) { return certificateChain_.get(index); } public static final int VERIFICATIONTIME_FIELD_NUMBER = 4; private Diadoc.Api.Proto.TimestampProtos.Timestamp verificationTime_; /** * <code>required .Diadoc.Api.Proto.Timestamp VerificationTime = 4;</code> */ public boolean hasVerificationTime() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required .Diadoc.Api.Proto.Timestamp VerificationTime = 4;</code> */ public Diadoc.Api.Proto.TimestampProtos.Timestamp getVerificationTime() { return verificationTime_; } /** * <code>required .Diadoc.Api.Proto.Timestamp VerificationTime = 4;</code> */ public Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getVerificationTimeOrBuilder() { return verificationTime_; } private void initFields() { isValid_ = false; certificateChain_ = java.util.Collections.emptyList(); verificationTime_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; if (!hasIsValid()) { memoizedIsInitialized = 0; return false; } if (!hasVerificationTime()) { memoizedIsInitialized = 0; return false; } for (int i = 0; i < getCertificateChainCount(); i++) { if (!getCertificateChain(i).isInitialized()) { memoizedIsInitialized = 0; return false; } } if (!getVerificationTime().isInitialized()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBool(2, isValid_); } for (int i = 0; i < certificateChain_.size(); i++) { output.writeMessage(3, certificateChain_.get(i)); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeMessage(4, verificationTime_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(2, isValid_); } for (int i = 0; i < certificateChain_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, certificateChain_.get(i)); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(4, verificationTime_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code Diadoc.Api.Proto.CertificateVerificationResult} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:Diadoc.Api.Proto.CertificateVerificationResult) Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResultOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.internal_static_Diadoc_Api_Proto_CertificateVerificationResult_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.internal_static_Diadoc_Api_Proto_CertificateVerificationResult_fieldAccessorTable .ensureFieldAccessorsInitialized( Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.class, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.Builder.class); } // Construct using Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getCertificateChainFieldBuilder(); getVerificationTimeFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); isValid_ = false; bitField0_ = (bitField0_ & ~0x00000001); if (certificateChainBuilder_ == null) { certificateChain_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); } else { certificateChainBuilder_.clear(); } if (verificationTimeBuilder_ == null) { verificationTime_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance(); } else { verificationTimeBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000004); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.internal_static_Diadoc_Api_Proto_CertificateVerificationResult_descriptor; } public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult getDefaultInstanceForType() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.getDefaultInstance(); } public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult build() { Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult buildPartial() { Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult result = new Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.isValid_ = isValid_; if (certificateChainBuilder_ == null) { if (((bitField0_ & 0x00000002) == 0x00000002)) { certificateChain_ = java.util.Collections.unmodifiableList(certificateChain_); bitField0_ = (bitField0_ & ~0x00000002); } result.certificateChain_ = certificateChain_; } else { result.certificateChain_ = certificateChainBuilder_.build(); } if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000002; } if (verificationTimeBuilder_ == null) { result.verificationTime_ = verificationTime_; } else { result.verificationTime_ = verificationTimeBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult) { return mergeFrom((Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult other) { if (other == Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult.getDefaultInstance()) return this; if (other.hasIsValid()) { setIsValid(other.getIsValid()); } if (certificateChainBuilder_ == null) { if (!other.certificateChain_.isEmpty()) { if (certificateChain_.isEmpty()) { certificateChain_ = other.certificateChain_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureCertificateChainIsMutable(); certificateChain_.addAll(other.certificateChain_); } onChanged(); } } else { if (!other.certificateChain_.isEmpty()) { if (certificateChainBuilder_.isEmpty()) { certificateChainBuilder_.dispose(); certificateChainBuilder_ = null; certificateChain_ = other.certificateChain_; bitField0_ = (bitField0_ & ~0x00000002); certificateChainBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getCertificateChainFieldBuilder() : null; } else { certificateChainBuilder_.addAllMessages(other.certificateChain_); } } } if (other.hasVerificationTime()) { mergeVerificationTime(other.getVerificationTime()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasIsValid()) { return false; } if (!hasVerificationTime()) { return false; } for (int i = 0; i < getCertificateChainCount(); i++) { if (!getCertificateChain(i).isInitialized()) { return false; } } if (!getVerificationTime().isInitialized()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateVerificationResult) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private boolean isValid_ ; /** * <code>required bool IsValid = 2;</code> */ public boolean hasIsValid() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required bool IsValid = 2;</code> */ public boolean getIsValid() { return isValid_; } /** * <code>required bool IsValid = 2;</code> */ public Builder setIsValid(boolean value) { bitField0_ |= 0x00000001; isValid_ = value; onChanged(); return this; } /** * <code>required bool IsValid = 2;</code> */ public Builder clearIsValid() { bitField0_ = (bitField0_ & ~0x00000001); isValid_ = false; onChanged(); return this; } private java.util.List<Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement> certificateChain_ = java.util.Collections.emptyList(); private void ensureCertificateChainIsMutable() { if (!((bitField0_ & 0x00000002) == 0x00000002)) { certificateChain_ = new java.util.ArrayList<Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement>(certificateChain_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilder< Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.Builder, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElementOrBuilder> certificateChainBuilder_; /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public java.util.List<Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement> getCertificateChainList() { if (certificateChainBuilder_ == null) { return java.util.Collections.unmodifiableList(certificateChain_); } else { return certificateChainBuilder_.getMessageList(); } } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public int getCertificateChainCount() { if (certificateChainBuilder_ == null) { return certificateChain_.size(); } else { return certificateChainBuilder_.getCount(); } } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement getCertificateChain(int index) { if (certificateChainBuilder_ == null) { return certificateChain_.get(index); } else { return certificateChainBuilder_.getMessage(index); } } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public Builder setCertificateChain( int index, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement value) { if (certificateChainBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCertificateChainIsMutable(); certificateChain_.set(index, value); onChanged(); } else { certificateChainBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public Builder setCertificateChain( int index, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.Builder builderForValue) { if (certificateChainBuilder_ == null) { ensureCertificateChainIsMutable(); certificateChain_.set(index, builderForValue.build()); onChanged(); } else { certificateChainBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public Builder addCertificateChain(Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement value) { if (certificateChainBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCertificateChainIsMutable(); certificateChain_.add(value); onChanged(); } else { certificateChainBuilder_.addMessage(value); } return this; } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public Builder addCertificateChain( int index, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement value) { if (certificateChainBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCertificateChainIsMutable(); certificateChain_.add(index, value); onChanged(); } else { certificateChainBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public Builder addCertificateChain( Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.Builder builderForValue) { if (certificateChainBuilder_ == null) { ensureCertificateChainIsMutable(); certificateChain_.add(builderForValue.build()); onChanged(); } else { certificateChainBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public Builder addCertificateChain( int index, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.Builder builderForValue) { if (certificateChainBuilder_ == null) { ensureCertificateChainIsMutable(); certificateChain_.add(index, builderForValue.build()); onChanged(); } else { certificateChainBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public Builder addAllCertificateChain( java.lang.Iterable<? extends Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement> values) { if (certificateChainBuilder_ == null) { ensureCertificateChainIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, certificateChain_); onChanged(); } else { certificateChainBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public Builder clearCertificateChain() { if (certificateChainBuilder_ == null) { certificateChain_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { certificateChainBuilder_.clear(); } return this; } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public Builder removeCertificateChain(int index) { if (certificateChainBuilder_ == null) { ensureCertificateChainIsMutable(); certificateChain_.remove(index); onChanged(); } else { certificateChainBuilder_.remove(index); } return this; } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.Builder getCertificateChainBuilder( int index) { return getCertificateChainFieldBuilder().getBuilder(index); } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElementOrBuilder getCertificateChainOrBuilder( int index) { if (certificateChainBuilder_ == null) { return certificateChain_.get(index); } else { return certificateChainBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public java.util.List<? extends Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElementOrBuilder> getCertificateChainOrBuilderList() { if (certificateChainBuilder_ != null) { return certificateChainBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(certificateChain_); } } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.Builder addCertificateChainBuilder() { return getCertificateChainFieldBuilder().addBuilder( Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.getDefaultInstance()); } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.Builder addCertificateChainBuilder( int index) { return getCertificateChainFieldBuilder().addBuilder( index, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.getDefaultInstance()); } /** * <code>repeated .Diadoc.Api.Proto.CertificateChainElement CertificateChain = 3;</code> * * <pre> * first element corresponds to signer certificate * </pre> */ public java.util.List<Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.Builder> getCertificateChainBuilderList() { return getCertificateChainFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.Builder, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElementOrBuilder> getCertificateChainFieldBuilder() { if (certificateChainBuilder_ == null) { certificateChainBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.Builder, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElementOrBuilder>( certificateChain_, ((bitField0_ & 0x00000002) == 0x00000002), getParentForChildren(), isClean()); certificateChain_ = null; } return certificateChainBuilder_; } private Diadoc.Api.Proto.TimestampProtos.Timestamp verificationTime_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder> verificationTimeBuilder_; /** * <code>required .Diadoc.Api.Proto.Timestamp VerificationTime = 4;</code> */ public boolean hasVerificationTime() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>required .Diadoc.Api.Proto.Timestamp VerificationTime = 4;</code> */ public Diadoc.Api.Proto.TimestampProtos.Timestamp getVerificationTime() { if (verificationTimeBuilder_ == null) { return verificationTime_; } else { return verificationTimeBuilder_.getMessage(); } } /** * <code>required .Diadoc.Api.Proto.Timestamp VerificationTime = 4;</code> */ public Builder setVerificationTime(Diadoc.Api.Proto.TimestampProtos.Timestamp value) { if (verificationTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } verificationTime_ = value; onChanged(); } else { verificationTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000004; return this; } /** * <code>required .Diadoc.Api.Proto.Timestamp VerificationTime = 4;</code> */ public Builder setVerificationTime( Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder builderForValue) { if (verificationTimeBuilder_ == null) { verificationTime_ = builderForValue.build(); onChanged(); } else { verificationTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; return this; } /** * <code>required .Diadoc.Api.Proto.Timestamp VerificationTime = 4;</code> */ public Builder mergeVerificationTime(Diadoc.Api.Proto.TimestampProtos.Timestamp value) { if (verificationTimeBuilder_ == null) { if (((bitField0_ & 0x00000004) == 0x00000004) && verificationTime_ != Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance()) { verificationTime_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.newBuilder(verificationTime_).mergeFrom(value).buildPartial(); } else { verificationTime_ = value; } onChanged(); } else { verificationTimeBuilder_.mergeFrom(value); } bitField0_ |= 0x00000004; return this; } /** * <code>required .Diadoc.Api.Proto.Timestamp VerificationTime = 4;</code> */ public Builder clearVerificationTime() { if (verificationTimeBuilder_ == null) { verificationTime_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance(); onChanged(); } else { verificationTimeBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000004); return this; } /** * <code>required .Diadoc.Api.Proto.Timestamp VerificationTime = 4;</code> */ public Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder getVerificationTimeBuilder() { bitField0_ |= 0x00000004; onChanged(); return getVerificationTimeFieldBuilder().getBuilder(); } /** * <code>required .Diadoc.Api.Proto.Timestamp VerificationTime = 4;</code> */ public Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getVerificationTimeOrBuilder() { if (verificationTimeBuilder_ != null) { return verificationTimeBuilder_.getMessageOrBuilder(); } else { return verificationTime_; } } /** * <code>required .Diadoc.Api.Proto.Timestamp VerificationTime = 4;</code> */ private com.google.protobuf.SingleFieldBuilder< Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder> getVerificationTimeFieldBuilder() { if (verificationTimeBuilder_ == null) { verificationTimeBuilder_ = new com.google.protobuf.SingleFieldBuilder< Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder>( getVerificationTime(), getParentForChildren(), isClean()); verificationTime_ = null; } return verificationTimeBuilder_; } // @@protoc_insertion_point(builder_scope:Diadoc.Api.Proto.CertificateVerificationResult) } static { defaultInstance = new CertificateVerificationResult(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:Diadoc.Api.Proto.CertificateVerificationResult) } public interface CertificateChainElementOrBuilder extends // @@protoc_insertion_point(interface_extends:Diadoc.Api.Proto.CertificateChainElement) com.google.protobuf.MessageOrBuilder { /** * <code>required int32 CertificateChainStatusFlags = 1;</code> * * <pre> * X509ChainStatusFlags value * </pre> */ boolean hasCertificateChainStatusFlags(); /** * <code>required int32 CertificateChainStatusFlags = 1;</code> * * <pre> * X509ChainStatusFlags value * </pre> */ int getCertificateChainStatusFlags(); /** * <code>required bytes DerCertificate = 2;</code> */ boolean hasDerCertificate(); /** * <code>required bytes DerCertificate = 2;</code> */ com.google.protobuf.ByteString getDerCertificate(); } /** * Protobuf type {@code Diadoc.Api.Proto.CertificateChainElement} */ public static final class CertificateChainElement extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:Diadoc.Api.Proto.CertificateChainElement) CertificateChainElementOrBuilder { // Use CertificateChainElement.newBuilder() to construct. private CertificateChainElement(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private CertificateChainElement(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final CertificateChainElement defaultInstance; public static CertificateChainElement getDefaultInstance() { return defaultInstance; } public CertificateChainElement getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private CertificateChainElement( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; certificateChainStatusFlags_ = input.readInt32(); break; } case 18: { bitField0_ |= 0x00000002; derCertificate_ = input.readBytes(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.internal_static_Diadoc_Api_Proto_CertificateChainElement_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.internal_static_Diadoc_Api_Proto_CertificateChainElement_fieldAccessorTable .ensureFieldAccessorsInitialized( Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.class, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.Builder.class); } public static com.google.protobuf.Parser<CertificateChainElement> PARSER = new com.google.protobuf.AbstractParser<CertificateChainElement>() { public CertificateChainElement parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new CertificateChainElement(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<CertificateChainElement> getParserForType() { return PARSER; } private int bitField0_; public static final int CERTIFICATECHAINSTATUSFLAGS_FIELD_NUMBER = 1; private int certificateChainStatusFlags_; /** * <code>required int32 CertificateChainStatusFlags = 1;</code> * * <pre> * X509ChainStatusFlags value * </pre> */ public boolean hasCertificateChainStatusFlags() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required int32 CertificateChainStatusFlags = 1;</code> * * <pre> * X509ChainStatusFlags value * </pre> */ public int getCertificateChainStatusFlags() { return certificateChainStatusFlags_; } public static final int DERCERTIFICATE_FIELD_NUMBER = 2; private com.google.protobuf.ByteString derCertificate_; /** * <code>required bytes DerCertificate = 2;</code> */ public boolean hasDerCertificate() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required bytes DerCertificate = 2;</code> */ public com.google.protobuf.ByteString getDerCertificate() { return derCertificate_; } private void initFields() { certificateChainStatusFlags_ = 0; derCertificate_ = com.google.protobuf.ByteString.EMPTY; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; if (!hasCertificateChainStatusFlags()) { memoizedIsInitialized = 0; return false; } if (!hasDerCertificate()) { memoizedIsInitialized = 0; return false; } memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeInt32(1, certificateChainStatusFlags_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, derCertificate_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeInt32Size(1, certificateChainStatusFlags_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, derCertificate_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code Diadoc.Api.Proto.CertificateChainElement} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:Diadoc.Api.Proto.CertificateChainElement) Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElementOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.internal_static_Diadoc_Api_Proto_CertificateChainElement_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.internal_static_Diadoc_Api_Proto_CertificateChainElement_fieldAccessorTable .ensureFieldAccessorsInitialized( Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.class, Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.Builder.class); } // Construct using Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); certificateChainStatusFlags_ = 0; bitField0_ = (bitField0_ & ~0x00000001); derCertificate_ = com.google.protobuf.ByteString.EMPTY; bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.internal_static_Diadoc_Api_Proto_CertificateChainElement_descriptor; } public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement getDefaultInstanceForType() { return Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.getDefaultInstance(); } public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement build() { Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement buildPartial() { Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement result = new Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.certificateChainStatusFlags_ = certificateChainStatusFlags_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.derCertificate_ = derCertificate_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement) { return mergeFrom((Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement other) { if (other == Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement.getDefaultInstance()) return this; if (other.hasCertificateChainStatusFlags()) { setCertificateChainStatusFlags(other.getCertificateChainStatusFlags()); } if (other.hasDerCertificate()) { setDerCertificate(other.getDerCertificate()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasCertificateChainStatusFlags()) { return false; } if (!hasDerCertificate()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (Diadoc.Api.Proto.SignatureVerificationResultProtos.CertificateChainElement) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private int certificateChainStatusFlags_ ; /** * <code>required int32 CertificateChainStatusFlags = 1;</code> * * <pre> * X509ChainStatusFlags value * </pre> */ public boolean hasCertificateChainStatusFlags() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required int32 CertificateChainStatusFlags = 1;</code> * * <pre> * X509ChainStatusFlags value * </pre> */ public int getCertificateChainStatusFlags() { return certificateChainStatusFlags_; } /** * <code>required int32 CertificateChainStatusFlags = 1;</code> * * <pre> * X509ChainStatusFlags value * </pre> */ public Builder setCertificateChainStatusFlags(int value) { bitField0_ |= 0x00000001; certificateChainStatusFlags_ = value; onChanged(); return this; } /** * <code>required int32 CertificateChainStatusFlags = 1;</code> * * <pre> * X509ChainStatusFlags value * </pre> */ public Builder clearCertificateChainStatusFlags() { bitField0_ = (bitField0_ & ~0x00000001); certificateChainStatusFlags_ = 0; onChanged(); return this; } private com.google.protobuf.ByteString derCertificate_ = com.google.protobuf.ByteString.EMPTY; /** * <code>required bytes DerCertificate = 2;</code> */ public boolean hasDerCertificate() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>required bytes DerCertificate = 2;</code> */ public com.google.protobuf.ByteString getDerCertificate() { return derCertificate_; } /** * <code>required bytes DerCertificate = 2;</code> */ public Builder setDerCertificate(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; derCertificate_ = value; onChanged(); return this; } /** * <code>required bytes DerCertificate = 2;</code> */ public Builder clearDerCertificate() { bitField0_ = (bitField0_ & ~0x00000002); derCertificate_ = getDefaultInstance().getDerCertificate(); onChanged(); return this; } // @@protoc_insertion_point(builder_scope:Diadoc.Api.Proto.CertificateChainElement) } static { defaultInstance = new CertificateChainElement(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:Diadoc.Api.Proto.CertificateChainElement) } private static final com.google.protobuf.Descriptors.Descriptor internal_static_Diadoc_Api_Proto_SignatureVerificationResult_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_Diadoc_Api_Proto_SignatureVerificationResult_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_Diadoc_Api_Proto_CertificateVerificationResult_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_Diadoc_Api_Proto_CertificateVerificationResult_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_Diadoc_Api_Proto_CertificateChainElement_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_Diadoc_Api_Proto_CertificateChainElement_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n!SignatureVerificationResult.proto\022\020Dia" + "doc.Api.Proto\032\017Timestamp.proto\"\263\001\n\033Signa" + "tureVerificationResult\022\017\n\007IsValid\030\001 \002(\010\022" + "J\n\021CertificateStatus\030\002 \001(\0132/.Diadoc.Api." + "Proto.CertificateVerificationResult\0227\n\022S" + "ignatureTimestamp\030\003 \001(\0132\033.Diadoc.Api.Pro" + "to.Timestamp\"\254\001\n\035CertificateVerification" + "Result\022\017\n\007IsValid\030\002 \002(\010\022C\n\020CertificateCh" + "ain\030\003 \003(\0132).Diadoc.Api.Proto.Certificate" + "ChainElement\0225\n\020VerificationTime\030\004 \002(\0132\033", ".Diadoc.Api.Proto.Timestamp\"V\n\027Certifica" + "teChainElement\022#\n\033CertificateChainStatus" + "Flags\030\001 \002(\005\022\026\n\016DerCertificate\030\002 \002(\014B#B!S" + "ignatureVerificationResultProtos" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { Diadoc.Api.Proto.TimestampProtos.getDescriptor(), }, assigner); internal_static_Diadoc_Api_Proto_SignatureVerificationResult_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_Diadoc_Api_Proto_SignatureVerificationResult_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_Diadoc_Api_Proto_SignatureVerificationResult_descriptor, new java.lang.String[] { "IsValid", "CertificateStatus", "SignatureTimestamp", }); internal_static_Diadoc_Api_Proto_CertificateVerificationResult_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_Diadoc_Api_Proto_CertificateVerificationResult_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_Diadoc_Api_Proto_CertificateVerificationResult_descriptor, new java.lang.String[] { "IsValid", "CertificateChain", "VerificationTime", }); internal_static_Diadoc_Api_Proto_CertificateChainElement_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_Diadoc_Api_Proto_CertificateChainElement_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_Diadoc_Api_Proto_CertificateChainElement_descriptor, new java.lang.String[] { "CertificateChainStatusFlags", "DerCertificate", }); Diadoc.Api.Proto.TimestampProtos.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
40.488659
299
0.67619
8333658c6779df4ec674af1ed33a8f2f29267d65
248
package com.homebrew.service.timer; import com.homebrew.exception.BaseException; import com.homebrew.rest.type.ResponseType; public interface ITimerScheduleOnce { ResponseType process(Integer minutes) throws BaseException; }
22.545455
44
0.770161
7e82da8e80df5b9e9b89066120d8095ae194a45b
356
/** * Author: Bob Chen */ package com.jcommerce.core.dao; import java.util.List; import com.jcommerce.core.model.BonusType; public interface BonusTypeDAO extends DAO { public List<BonusType> getBonusTypeList(); public BonusType getBonusType(Long id); public void saveBonusType(BonusType obj); public void removeBonusType(Long id); }
17.8
46
0.741573
f9c12cb121bb33436e13fec14965e35bcb9764c1
602
package io.core9.firewall.rules; import io.core9.core.plugin.Core9Plugin; import io.core9.plugin.server.VirtualHost; import io.core9.proxy.ProxyRequest; import io.core9.rules.RuleException; import io.core9.rules.RuleSet; import io.core9.rules.RulesEngine; import io.core9.rules.Status; import java.util.List; import java.util.Map; public interface FirewallRequestRulesEngine extends RulesEngine<ProxyRequest, Status>, Core9Plugin { Status handle(List<String> ruleSets, ProxyRequest context) throws RuleException; Map<String, RuleSet> getRuleSets(); void setVirtualHost(VirtualHost vhost); }
26.173913
100
0.810631
195a829bcc7c829451ad2f7399995b1d213d627e
6,184
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package com.google.android.gms.base; public final class R { public static final class attr { public static final int buttonSize = 0x7f040017; public static final int circleCrop = 0x7f040018; public static final int colorScheme = 0x7f040026; public static final int imageAspectRatio = 0x7f040050; public static final int imageAspectRatioAdjust = 0x7f040051; public static final int scopeUris = 0x7f0400c1; } public static final class color { public static final int common_google_signin_btn_text_dark = 0x7f060014; public static final int common_google_signin_btn_text_dark_default = 0x7f060015; public static final int common_google_signin_btn_text_dark_disabled = 0x7f060016; public static final int common_google_signin_btn_text_dark_focused = 0x7f060017; public static final int common_google_signin_btn_text_dark_pressed = 0x7f060018; public static final int common_google_signin_btn_text_light = 0x7f060019; public static final int common_google_signin_btn_text_light_default = 0x7f06001a; public static final int common_google_signin_btn_text_light_disabled = 0x7f06001b; public static final int common_google_signin_btn_text_light_focused = 0x7f06001c; public static final int common_google_signin_btn_text_light_pressed = 0x7f06001d; public static final int common_google_signin_btn_tint = 0x7f06001e; } public static final class drawable { public static final int common_full_open_on_phone = 0x7f08000a; public static final int common_google_signin_btn_icon_dark = 0x7f08000b; public static final int common_google_signin_btn_icon_dark_focused = 0x7f08000c; public static final int common_google_signin_btn_icon_dark_normal = 0x7f08000d; public static final int common_google_signin_btn_icon_dark_normal_background = 0x7f08000e; public static final int common_google_signin_btn_icon_disabled = 0x7f08000f; public static final int common_google_signin_btn_icon_light = 0x7f080010; public static final int common_google_signin_btn_icon_light_focused = 0x7f080011; public static final int common_google_signin_btn_icon_light_normal = 0x7f080012; public static final int common_google_signin_btn_icon_light_normal_background = 0x7f080013; public static final int common_google_signin_btn_text_dark = 0x7f080014; public static final int common_google_signin_btn_text_dark_focused = 0x7f080015; public static final int common_google_signin_btn_text_dark_normal = 0x7f080016; public static final int common_google_signin_btn_text_dark_normal_background = 0x7f080017; public static final int common_google_signin_btn_text_disabled = 0x7f080018; public static final int common_google_signin_btn_text_light = 0x7f080019; public static final int common_google_signin_btn_text_light_focused = 0x7f08001a; public static final int common_google_signin_btn_text_light_normal = 0x7f08001b; public static final int common_google_signin_btn_text_light_normal_background = 0x7f08001c; public static final int googleg_disabled_color_18 = 0x7f080021; public static final int googleg_standard_color_18 = 0x7f080022; } public static final class id { public static final int adjust_height = 0x7f0a0006; public static final int adjust_width = 0x7f0a0007; public static final int auto = 0x7f0a000c; public static final int dark = 0x7f0a001e; public static final int icon_only = 0x7f0a002d; public static final int light = 0x7f0a0033; public static final int none = 0x7f0a003e; public static final int standard = 0x7f0a0053; public static final int wide = 0x7f0a0073; } public static final class string { public static final int common_google_play_services_enable_button = 0x7f110020; public static final int common_google_play_services_enable_text = 0x7f110021; public static final int common_google_play_services_enable_title = 0x7f110022; public static final int common_google_play_services_install_button = 0x7f110023; public static final int common_google_play_services_install_text = 0x7f110024; public static final int common_google_play_services_install_title = 0x7f110025; public static final int common_google_play_services_notification_channel_name = 0x7f110026; public static final int common_google_play_services_notification_ticker = 0x7f110027; public static final int common_google_play_services_unsupported_text = 0x7f110029; public static final int common_google_play_services_update_button = 0x7f11002a; public static final int common_google_play_services_update_text = 0x7f11002b; public static final int common_google_play_services_update_title = 0x7f11002c; public static final int common_google_play_services_updating_text = 0x7f11002d; public static final int common_google_play_services_wear_update_text = 0x7f11002e; public static final int common_open_on_phone = 0x7f11002f; public static final int common_signin_button_text = 0x7f110030; public static final int common_signin_button_text_long = 0x7f110031; } public static final class styleable { public static final int[] LoadingImageView = { 0x7f040018, 0x7f040050, 0x7f040051 }; public static final int LoadingImageView_circleCrop = 0; public static final int LoadingImageView_imageAspectRatio = 1; public static final int LoadingImageView_imageAspectRatioAdjust = 2; public static final int[] SignInButton = { 0x7f040017, 0x7f040026, 0x7f0400c1 }; public static final int SignInButton_buttonSize = 0; public static final int SignInButton_colorScheme = 1; public static final int SignInButton_scopeUris = 2; } }
65.094737
99
0.771345
f7e47d72fa4d599e8c520ce596130130f7b19a9a
11,373
/* * Copyright (c) 2010-2016 William Bittle http://www.dyn4j.org/ * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of dyn4j nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.dyn4j.collision; import java.util.Iterator; import java.util.List; import java.util.UUID; import org.dyn4j.DataContainer; import org.dyn4j.geometry.AABB; import org.dyn4j.geometry.Convex; import org.dyn4j.geometry.Shape; import org.dyn4j.geometry.Shiftable; import org.dyn4j.geometry.Transform; import org.dyn4j.geometry.Transformable; import org.dyn4j.geometry.Vector2; /** * Represents an object that can collide with other objects. * @author William Bittle * @version 3.2.0 * @since 1.0.0 * @param <T> the {@link Fixture} type * @see AbstractCollidable */ public interface Collidable<T extends Fixture> extends Transformable, Shiftable, DataContainer { /** Number of fixtures typically attached to a {@link Collidable} */ public static final int TYPICAL_FIXTURE_COUNT = 1; /** * Returns a unique identifier for this {@link Collidable}. * <p> * This identifier is constant for the life of this {@link Collidable}. * @return UUID the unique id * @since 3.0.0 */ public abstract UUID getId(); /** * Creates an {@link AABB} from this {@link Collidable}'s attached {@link Fixture}s. * <p> * If there are no fixtures attached, a degenerate AABB, (0.0, 0.0) to (0.0, 0.0), is returned. * @return {@link AABB} * @since 3.0.0 */ public abstract AABB createAABB(); /** * Creates an {@link AABB} from this {@link Collidable}'s attached {@link Fixture}s using the given * world space {@link Transform}. * <p> * If there are no fixtures attached, a degenerate AABB, (0.0, 0.0) to (0.0, 0.0), is returned. * @param transform the world space {@link Transform} * @return {@link AABB} * @throws NullPointerException if the given transform is null * @since 3.2.0 */ public abstract AABB createAABB(Transform transform); /** * Adds the given {@link Fixture} to this {@link Collidable}. * @param fixture the {@link Fixture} to add * @return {@link Collidable} this collidable * @since 3.2.0 * @throws NullPointerException if fixture is null */ public abstract Collidable<T> addFixture(T fixture); /** * Creates a {@link Fixture} for the given {@link Convex} {@link Shape}, * adds it to this {@link Collidable}, and returns it. * @param convex the {@link Convex} {@link Shape} to add * @return T the fixture created * @since 3.2.0 * @throws NullPointerException if convex is null */ public abstract T addFixture(Convex convex); /** * Returns the {@link Fixture} at the given index. * @param index the index of the {@link Fixture} * @return T the fixture * @throws IndexOutOfBoundsException if index is out of bounds * @since 2.0.0 */ public abstract T getFixture(int index); /** * Returns true if this {@link Collidable} contains the given {@link Fixture}. * @param fixture the fixture * @return boolean * @since 3.2.0 */ public abstract boolean containsFixture(T fixture); /** * Returns the first {@link Fixture} in this {@link Collidable}, determined by the order in * which they were added, that contains the given point. * <p> * Returns null if the point is not contained in any fixture in this {@link Collidable}. * @param point a world space point * @return T the fixture or null * @throws NullPointerException if point is null * @since 3.2.0 */ public abstract T getFixture(Vector2 point); /** * Returns all the {@link Fixture}s in this {@link Collidable} that contain the given point. * <p> * Returns an empty list if the point is not contained in any fixture in this {@link Collidable}. * @param point a world space point * @return List&lt;T&gt; * @throws NullPointerException if point is null * @since 3.2.0 */ public abstract List<T> getFixtures(Vector2 point); /** * Removes the given {@link Fixture} from this {@link Collidable}. * @param fixture the {@link Fixture} * @return boolean true if the {@link Fixture} was removed from this {@link Collidable} * @since 3.2.0 */ public abstract boolean removeFixture(T fixture); /** * Removes the {@link Fixture} at the given index. * @param index the index * @return T the fixture removed * @throws IndexOutOfBoundsException if index is out of bounds * @since 3.2.0 */ public abstract T removeFixture(int index); /** * Removes all fixtures from this {@link Collidable} and returns them. * @return List&lt;T&gt; * @since 3.2.0 */ public abstract List<T> removeAllFixtures(); /** * Removes the first {@link Fixture} in this {@link Collidable}, determined by the order in * which they were added, that contains the given point and returns it. * <p> * Returns null if the point is not contained in any {@link Fixture} in this {@link Collidable}. * @param point a world space point * @return T the fixture or null * @throws NullPointerException if point is null * @since 3.2.0 */ public abstract T removeFixture(Vector2 point); /** * Removes all the {@link Fixture}s in this {@link Collidable} that contain the given point and * returns them. * <p> * Returns an empty list if the point is not contained in any {@link Fixture} in this {@link Collidable}. * @param point a world space point * @return List&lt;T&gt; * @throws NullPointerException if point is null * @since 3.2.0 */ public abstract List<T> removeFixtures(Vector2 point); /** * Returns the number of {@link Fixture}s attached * to this {@link Collidable} object. * @return int * @since 2.0.0 */ public abstract int getFixtureCount(); /** * Returns an unmodifiable list containing the {@link Fixture}s attached to this {@link Collidable}. * <p> * The returned list is backed by the internal list, therefore adding or removing fixtures while * iterating through the returned list is not permitted. Use the {@link #getFixtureIterator()} * method instead. * @return List&lt;T&gt; * @since 3.1.5 * @see #getFixtureIterator() */ public abstract List<T> getFixtures(); /** * Returns an iterator for this collidable's fixtures. * <p> * The returned iterator supports the <code>remove</code> method. * @return Iterator&lt;T&gt; * @since 3.2.0 */ public abstract Iterator<T> getFixtureIterator(); /** * Returns true if the given world space point is contained in this {@link Collidable}. * <p> * The point is contained in this {@link Collidable} if and only if the point is contained * in one of this {@link Collidable}'s {@link Fixture}s. * @param point the world space test point * @return boolean * @throws NullPointerException if point is null * @since 3.2.0 */ public abstract boolean contains(Vector2 point); /** * Returns the center for this {@link Collidable} in local coordinates. * @return {@link Vector2} the center in local coordinates * @since 3.2.0 */ public abstract Vector2 getLocalCenter(); /** * Returns the center for this {@link Collidable} in world coordinates. * @return {@link Vector2} the center in world coordinates * @since 3.2.0 */ public abstract Vector2 getWorldCenter(); /** * Returns a new point in local coordinates of this {@link Collidable} given * a point in world coordinates. * @param worldPoint a world space point * @return {@link Vector2} local space point * @throws NullPointerException if the given point is null * @since 3.2.0 */ public abstract Vector2 getLocalPoint(Vector2 worldPoint); /** * Returns a new point in world coordinates given a point in the * local coordinates of this {@link Collidable}. * @param localPoint a point in the local coordinates of this {@link Collidable} * @return {@link Vector2} world space point * @throws NullPointerException if the given point is null * @since 3.2.0 */ public abstract Vector2 getWorldPoint(Vector2 localPoint); /** * Returns a new vector in local coordinates of this {@link Collidable} given * a vector in world coordinates. * @param worldVector a world space vector * @return {@link Vector2} local space vector * @throws NullPointerException if the given vector is null * @since 3.2.0 */ public abstract Vector2 getLocalVector(Vector2 worldVector); /** * Returns a new vector in world coordinates given a vector in the * local coordinates of this {@link Collidable}. * @param localVector a vector in the local coordinates of this {@link Collidable} * @return {@link Vector2} world space vector * @throws NullPointerException if the given vector is null * @since 3.2.0 */ public abstract Vector2 getWorldVector(Vector2 localVector); /** * Returns the maximum radius of the disk that the * {@link Collidable} creates if rotated 360 degrees about its center. * @return double the maximum radius of the rotation disk */ public abstract double getRotationDiscRadius(); /** * Returns the local to world space {@link Transform} of this {@link Collidable}. * @return {@link Transform} */ public abstract Transform getTransform(); /** * Sets this {@link Collidable}'s local to world space {@link Transform}. * <p> * If the given transform is null, this method returns immediately. * @param transform the transform * @since 3.2.0 */ public abstract void setTransform(Transform transform); /** * Rotates the {@link Collidable} about its center. * @param theta the angle of rotation in radians */ public abstract void rotateAboutCenter(double theta); /** * Translates the center of the {@link Collidable} to the world space origin (0,0). * <p> * This method is useful if bodies have a number of fixtures and the center * is not at the origin. This method will reposition this {@link Collidable} so * that the center is at the origin. * @since 3.2.0 */ public abstract void translateToOrigin(); }
35.319876
106
0.708256
e2b0afa734872417a1f296a6b95429a305a06621
1,828
package com.chothuesach.resource; import com.chothuesach.jsonview.TheLoaiView; import com.chothuesach.model.TheLoai; import com.chothuesach.service.TheLoaiService; import com.fasterxml.jackson.annotation.JsonView; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("api/theloai") public class TheLoaiResource { @Autowired private TheLoaiService theLoaiService; @GetMapping @JsonView(TheLoaiView.Overview.class) public List<TheLoai> getAllTheLoai(@RequestParam(required = false, defaultValue = "") String tenTheLoai, @PageableDefault(page = 0, size = 20, sort = {"maTheLoai"}, direction = Sort.Direction.ASC)Pageable pageable) { return theLoaiService.getDanhSachTheLoai(tenTheLoai, pageable); } @GetMapping("/{slug}") @JsonView(TheLoaiView.Detailed.class) public TheLoai getTheLoaiBySlug(@PathVariable String slug) { return theLoaiService.getTheLoaiBySlug(slug); } @PostMapping public ResponseEntity addNewTheLoai(@RequestParam String tenTheLoai) { theLoaiService.addNewTheLoai(tenTheLoai); return new ResponseEntity(HttpStatus.OK); } @PutMapping("/{slug}") public TheLoai updateTenTheLoai(@PathVariable String slug, @RequestParam String newTenTheLoai) { return theLoaiService.changeTenTheLoai(slug, newTenTheLoai); } @DeleteMapping("/{slug}") public void deleteTheLoai(@PathVariable String slug) { theLoaiService.deleteTheLoai(slug); } }
34.490566
220
0.763676
99938a469be2885b145f738b8175ba8dfd176723
2,120
/* * Copyright (c) 2015 Christian Chevalley * This file is part of Project Ethercis * * 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.ethercis.transform.rawjson; import com.ethercis.ehr.encode.EncodeUtil; import com.ethercis.ehr.keyvalues.EcisFlattener; import com.ethercis.ehr.util.MapInspector; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.InputStreamReader; import org.junit.Assert; import org.junit.Test; import java.io.FileReader; import java.util.Deque; import java.util.Map; import java.util.TreeMap; /** * Created by christian on 8/30/2016. */ public class RawJsonParserTest { @Test public void testParseRawJson() throws Exception { // RawJsonParser rawJsonParser = new RawJsonParser(); //FileReader fileReader = new FileReader("/Development/Dropbox/eCIS_Development/samples/ehr_status_raw.json"); final InputStreamReader inputStreamReader = new InputStreamReader( getClass().getClassLoader().getResourceAsStream("ehr_status_raw.json")); String serialized = RawJsonParser.dbEncode(inputStreamReader); Assert.assertNotNull(serialized); System.out.println(serialized); GsonBuilder gsonBuilder = EncodeUtil.getGsonBuilderInstance(); Gson gson = gsonBuilder.setPrettyPrinting().create(); Map<String, Object> retmap = gson.fromJson(serialized, TreeMap.class); Map<String, String> flatten = new EcisFlattener().generateEcisFlat(retmap); Assert.assertNotNull(flatten); System.out.println(gson.toJson(flatten, TreeMap.class)); } }
36.551724
118
0.740094
18ea05b80058c540b63ed643ff689c9b379eee34
400
package com.xkcoding.springbootdemoproperties.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Data @ConfigurationProperties(prefix = "application.author") @Component public class AuthorConfig { private String name; private String website; private String qq; private String phoneNumber; }
25
75
0.8325
04ea5fec4c27a357f3ff0f092c284640b872a764
278
package io.imast.work4j.model.iterate; /** * The status of iteration * * @author davitp */ public enum IterationStatus { /** * The job iteration is successful */ SUCCESS, /** * The job iteration is not successful */ FAILURE }
13.9
42
0.57554
8555e6d29965e10d8b7aa50329f478cdfbeb1954
978
package com.wch.gulimall.warehouse.dao; import com.wch.gulimall.warehouse.entity.WareSkuEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 商品库存 * * @author wch * @email 2879924329@qq.com * @date 2022-02-20 22:27:21 */ @Mapper public interface WareSkuDao extends BaseMapper<WareSkuEntity> { /** * 入库 * @param skuId sku id * @param wareId wareId * @param skuNum number */ void addStock(@Param("skuId") Long skuId,@Param("wareId") Long wareId, @Param("skuNum") Integer skuNum); Long getSkuStock(@Param("skuId") Long skuId); List<Long> listWareIdHasStock(@Param("skuId") Long skuId); Long lockSkuStock(@Param("skuId") Long skuId, @Param("wareId") Long id, @Param("num") Integer num); void unLockStock(@Param("skuId") Long skuId,@Param("wareId") Long wareId, @Param("num") Integer num); }
27.942857
108
0.698364
3e5495aa825273cc2f486d059cc55bfa0cd9ae0a
2,794
/* * * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * */ package com.caseystella.stellar.common.shell.specials; import com.caseystella.stellar.common.shell.DefaultStellarShellExecutor; import com.caseystella.stellar.common.shell.StellarResult; import com.caseystella.stellar.dsl.functions.StringFunctions; import com.caseystella.stellar.dsl.functions.resolver.SimpleFunctionResolver; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Optional; import java.util.Properties; import static org.junit.jupiter.api.Assertions.assertTrue; public class DocCommandTest { DocCommand command; DefaultStellarShellExecutor executor; @BeforeEach public void setup() throws Exception { // setup the command command = new DocCommand(); // setup a function resolver - only 3 functions have been defined SimpleFunctionResolver functionResolver = new SimpleFunctionResolver().withClass(StringFunctions.ToString.class) .withClass(StringFunctions.ToLower.class).withClass(StringFunctions.ToUpper.class); // setup the executor Properties props = new Properties(); executor = new DefaultStellarShellExecutor(functionResolver, props, Optional.empty()); executor.init(); } @Test public void testWithFunction() { StellarResult result = command.execute("?TO_STRING", executor); // validate the result assertTrue(result.isSuccess()); assertTrue(result.getValue().isPresent()); // validate that we have some sort of doc string assertTrue(result.getValue().toString().length() > 0); } @Test public void testFunctionNotDefined() { StellarResult result = command.execute("?INVALID", executor); // validate the result assertTrue(result.isError()); assertTrue(result.getException().isPresent()); } @Test public void testNoFunction() { StellarResult result = command.execute("?", executor); // validate the result assertTrue(result.isError()); assertTrue(result.getException().isPresent()); } }
33.662651
100
0.748747
c6876e13508ef3a8e822145acf20ff51f391cbaf
990
package com.tcservices.clientapi; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class User { public Integer id; public Integer company_id; public String name; public String email; public String created_at; public String updated_at; @JsonCreator public User( @JsonProperty("id") Integer id, @JsonProperty("company_id") Integer company_id, @JsonProperty("name") String name, @JsonProperty("email") String email, @JsonProperty("created_at") String created_at, @JsonProperty("updated_at") String updated_at ) { this.id = id; this.company_id = company_id; this.name = name; this.email = email; this.created_at = created_at; this.updated_at = updated_at; } }
30
61
0.669697
e4db0f8cec11f7b8c58a0de229709e2dac00ce72
546
package serversystem.events; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerRespawnEvent; import serversystem.handler.WorldGroupHandler; public class PlayerRespawnListener implements Listener { @EventHandler public void onPlayerRespawn(PlayerRespawnEvent event) { if (WorldGroupHandler.isEnabled()) { event.setRespawnLocation(WorldGroupHandler.playerdeaths.get(event.getPlayer()).getSpawnLocation()); WorldGroupHandler.playerdeaths.remove(event.getPlayer()); } } }
27.3
102
0.811355
2c4d11d9922dbbb49b0005b5328cb8abc21412d9
409
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.language.invoke; /** * Partial implementation of {@link TypeConverter}. */ public abstract class AbstractTypeConverter implements TypeConverter { @Override public String getTypeConverterKey() { return getClass().getSimpleName(); } }
20.45
86
0.731051
3b4e274a05db924b9c6c158a627b69fc172cf12d
20,254
package org.sagebionetworks.web.unitclient.widget.discussion; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sagebionetworks.web.client.widget.discussion.DiscussionThreadListWidget.DEFAULT_ASCENDING; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.runners.MockitoJUnitRunner; import org.sagebionetworks.repo.model.discussion.DiscussionFilter; import org.sagebionetworks.repo.model.discussion.DiscussionThreadBundle; import org.sagebionetworks.repo.model.discussion.DiscussionThreadOrder; import org.sagebionetworks.web.client.PortalGinInjector; import org.sagebionetworks.web.client.SynapseJSNIUtils; import org.sagebionetworks.web.client.SynapseJavascriptClient; import org.sagebionetworks.web.client.utils.Callback; import org.sagebionetworks.web.client.utils.CallbackP; import org.sagebionetworks.web.client.widget.LoadMoreWidgetContainer; import org.sagebionetworks.web.client.widget.discussion.DiscussionThreadListItemWidget; import org.sagebionetworks.web.client.widget.discussion.DiscussionThreadListWidget; import org.sagebionetworks.web.client.widget.discussion.DiscussionThreadListWidgetView; import org.sagebionetworks.web.client.widget.entity.controller.SynapseAlert; import org.sagebionetworks.web.client.widget.refresh.DiscussionThreadCountAlert; import org.sagebionetworks.web.test.helper.AsyncMockStubber; import com.google.gwt.dev.util.collect.HashSet; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Widget; @RunWith(MockitoJUnitRunner.class) public class DiscussionThreadListWidgetTest { @Mock DiscussionThreadListWidgetView mockView; @Mock PortalGinInjector mockGinInjector; @Mock DiscussionThreadListItemWidget mockDiscussionThreadWidget; @Mock SynapseAlert mockSynAlert; @Mock CallbackP<Boolean> mockEmptyListCallback; @Mock CallbackP<DiscussionThreadBundle> mockThreadIdClickedCallback; @Mock DiscussionThreadCountAlert mockDiscussionThreadCountAlert; @Mock SynapseJSNIUtils mockSynapseJSNIUtils; @Mock DiscussionThreadBundle mockDiscussionThreadBundle; @Mock LoadMoreWidgetContainer mockThreadsContainer; @Mock SynapseJavascriptClient mockSynapseJavascriptClient; List<DiscussionThreadBundle> discussionThreadBundleList = new ArrayList<DiscussionThreadBundle>(); DiscussionThreadListWidget discussionThreadListWidget; Set<String> moderatorIds; @Before public void before() { MockitoAnnotations.initMocks(this); when(mockGinInjector.createThreadListItemWidget()).thenReturn(mockDiscussionThreadWidget); when(mockGinInjector.getDiscussionThreadCountAlert()).thenReturn(mockDiscussionThreadCountAlert); discussionThreadListWidget = new DiscussionThreadListWidget(mockView, mockGinInjector, mockSynAlert, mockThreadsContainer, mockSynapseJSNIUtils, mockSynapseJavascriptClient); moderatorIds = new HashSet<String>(); } @Test public void testConstructor() { verify(mockView).setPresenter(discussionThreadListWidget); verify(mockView).setAlert(any(Widget.class)); } @SuppressWarnings("unchecked") @Test public void testConfigureWithEntity() { String entityId = "123"; discussionThreadListWidget.configure(entityId, null, null); verify(mockThreadsContainer).clear(); verify(mockSynAlert).clear(); verify(mockSynapseJavascriptClient).getThreadsForEntity(eq(entityId), anyLong(), anyLong(), eq(DiscussionThreadOrder.PINNED_AND_LAST_ACTIVITY), eq(false), any(DiscussionFilter.class), any(AsyncCallback.class)); ArgumentCaptor<Callback> captor = ArgumentCaptor.forClass(Callback.class); verify(mockThreadsContainer).configure(captor.capture()); captor.getValue().invoke(); verify(mockSynapseJavascriptClient, times(2)).getThreadsForEntity(eq(entityId), anyLong(), anyLong(), any(DiscussionThreadOrder.class), anyBoolean(), any(DiscussionFilter.class), any(AsyncCallback.class)); verify(mockView).clearSort(); verify(mockView, never()).setSorted(any(DiscussionThreadOrder.class), anyBoolean()); // sort by number of replies, verify call, sort again, verify ascending is toggled. discussionThreadListWidget.sortBy(DiscussionThreadOrder.NUMBER_OF_REPLIES); verify(mockSynapseJavascriptClient).getThreadsForEntity(eq(entityId), anyLong(), anyLong(), eq(DiscussionThreadOrder.NUMBER_OF_REPLIES), eq(false), any(DiscussionFilter.class), any(AsyncCallback.class)); verify(mockView).setSorted(DiscussionThreadOrder.NUMBER_OF_REPLIES, false); discussionThreadListWidget.sortBy(DiscussionThreadOrder.NUMBER_OF_REPLIES); verify(mockSynapseJavascriptClient).getThreadsForEntity(eq(entityId), anyLong(), anyLong(), eq(DiscussionThreadOrder.NUMBER_OF_REPLIES), eq(true), any(DiscussionFilter.class), any(AsyncCallback.class)); verify(mockView).setSorted(DiscussionThreadOrder.NUMBER_OF_REPLIES, true); } @SuppressWarnings("unchecked") @Test public void testConfigure() { boolean canModerate = false; String forumId = "123"; discussionThreadListWidget.configure(forumId, canModerate, moderatorIds, mockEmptyListCallback, DiscussionFilter.EXCLUDE_DELETED); verify(mockThreadsContainer).clear(); verify(mockSynAlert).clear(); verify(mockSynapseJavascriptClient).getThreadsForForum(eq(forumId), anyLong(), anyLong(), eq(DiscussionThreadOrder.PINNED_AND_LAST_ACTIVITY), eq(false), any(DiscussionFilter.class), any(AsyncCallback.class)); ArgumentCaptor<Callback> captor = ArgumentCaptor.forClass(Callback.class); verify(mockThreadsContainer).configure(captor.capture()); captor.getValue().invoke(); verify(mockSynapseJavascriptClient, times(2)).getThreadsForForum(eq(forumId), anyLong(), anyLong(), any(DiscussionThreadOrder.class), anyBoolean(), any(DiscussionFilter.class), any(AsyncCallback.class)); verify(mockView).clearSort(); verify(mockView, never()).setSorted(any(DiscussionThreadOrder.class), anyBoolean()); // sort by number of replies, verify call, sort again, verify ascending is toggled. discussionThreadListWidget.sortBy(DiscussionThreadOrder.NUMBER_OF_VIEWS); verify(mockSynapseJavascriptClient).getThreadsForForum(eq(forumId), anyLong(), anyLong(), eq(DiscussionThreadOrder.NUMBER_OF_VIEWS), eq(false), any(DiscussionFilter.class), any(AsyncCallback.class)); verify(mockView).setSorted(DiscussionThreadOrder.NUMBER_OF_VIEWS, false); discussionThreadListWidget.sortBy(DiscussionThreadOrder.NUMBER_OF_VIEWS); verify(mockSynapseJavascriptClient).getThreadsForForum(eq(forumId), anyLong(), anyLong(), eq(DiscussionThreadOrder.NUMBER_OF_VIEWS), eq(true), any(DiscussionFilter.class), any(AsyncCallback.class)); verify(mockView).setSorted(DiscussionThreadOrder.NUMBER_OF_VIEWS, true); } @SuppressWarnings("unchecked") @Test public void testConfigureWithModerator() { boolean canModerate = true; AsyncMockStubber.callSuccessWith(discussionThreadBundleList).when(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), any(DiscussionThreadOrder.class), anyBoolean(), any(DiscussionFilter.class), any(AsyncCallback.class)); DiscussionThreadBundle threadBundle = new DiscussionThreadBundle(); String threadId = "987654"; threadBundle.setId(threadId); discussionThreadBundleList.add(threadBundle); discussionThreadListWidget.setThreadIdClickedCallback(mockThreadIdClickedCallback); discussionThreadListWidget.configure("123", canModerate, moderatorIds, mockEmptyListCallback, DiscussionFilter.EXCLUDE_DELETED); verify(mockThreadsContainer).clear(); verify(mockSynAlert).clear(); verify(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), any(DiscussionThreadOrder.class), anyBoolean(), any(DiscussionFilter.class), any(AsyncCallback.class)); verify(mockDiscussionThreadWidget).configure(any(DiscussionThreadBundle.class)); verify(mockDiscussionThreadWidget).setThreadIdClickedCallback(mockThreadIdClickedCallback); // test scroll to thread AsyncMockStubber.callSuccessWith(mockDiscussionThreadBundle).when(mockSynapseJavascriptClient).getThread(anyString(), any(AsyncCallback.class)); discussionThreadListWidget.scrollToThread("invalidid"); verify(mockView, never()).scrollIntoView(any(Widget.class)); discussionThreadListWidget.scrollToThread(threadId); verify(mockView).scrollIntoView(any(Widget.class)); verify(mockSynapseJavascriptClient).getThread(anyString(), any(AsyncCallback.class)); verify(mockDiscussionThreadWidget).configure(mockDiscussionThreadBundle); } @Test public void asWidgetTest() { discussionThreadListWidget.asWidget(); verify(mockView).asWidget(); } @SuppressWarnings("unchecked") @Test public void testLoadMoreSuccess() { boolean canModerate = false; AsyncMockStubber.callSuccessWith(discussionThreadBundleList).when(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), any(DiscussionThreadOrder.class), anyBoolean(), any(DiscussionFilter.class), any(AsyncCallback.class)); DiscussionThreadBundle threadBundle = new DiscussionThreadBundle(); String threadId = "987654"; threadBundle.setId(threadId); discussionThreadBundleList.add(threadBundle); discussionThreadListWidget.configure("123", canModerate, moderatorIds, mockEmptyListCallback, DiscussionFilter.EXCLUDE_DELETED); verify(mockThreadsContainer).clear(); verify(mockSynAlert).clear(); verify(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), any(DiscussionThreadOrder.class), anyBoolean(), any(DiscussionFilter.class), any(AsyncCallback.class)); verify(mockThreadsContainer).add(any(Widget.class)); verify(mockGinInjector).createThreadListItemWidget(); verify(mockDiscussionThreadWidget).configure(any(DiscussionThreadBundle.class)); verify(mockEmptyListCallback).invoke(anyBoolean()); verify(mockView).setThreadHeaderVisible(true); verify(mockView).setNoThreadsFoundVisible(false); verify(mockThreadsContainer).setIsMore(false); // test scroll to thread, rpc failure String error = "unable to refresh thread data"; AsyncMockStubber.callFailureWith(new Exception(error)).when(mockSynapseJavascriptClient).getThread(anyString(), any(AsyncCallback.class)); discussionThreadListWidget.scrollToThread(threadId); verify(mockView).scrollIntoView(any(Widget.class)); verify(mockSynapseJavascriptClient).getThread(anyString(), any(AsyncCallback.class)); verify(mockDiscussionThreadWidget, never()).configure(mockDiscussionThreadBundle); verify(mockSynapseJSNIUtils).consoleError(error); } @Test public void testLoadMoreVisible() { boolean canModerate = false; AsyncMockStubber.callSuccessWith(discussionThreadBundleList).when(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), any(DiscussionThreadOrder.class), anyBoolean(), any(DiscussionFilter.class), any(AsyncCallback.class)); for (int i = 0; i < DiscussionThreadListWidget.LIMIT; i++) { DiscussionThreadBundle threadBundle = new DiscussionThreadBundle(); threadBundle.setId("thread_" + i); discussionThreadBundleList.add(threadBundle); } discussionThreadListWidget.configure("123", canModerate, moderatorIds, mockEmptyListCallback, DiscussionFilter.EXCLUDE_DELETED); verify(mockThreadsContainer).setIsMore(true); } @SuppressWarnings("unchecked") @Test public void testLoadMoreZeroThreads() { boolean canModerate = false; AsyncMockStubber.callSuccessWith(discussionThreadBundleList).when(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), any(DiscussionThreadOrder.class), anyBoolean(), any(DiscussionFilter.class), any(AsyncCallback.class)); discussionThreadListWidget.configure("123", canModerate, moderatorIds, mockEmptyListCallback, DiscussionFilter.EXCLUDE_DELETED); verify(mockThreadsContainer).clear(); verify(mockSynAlert).clear(); verify(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), any(DiscussionThreadOrder.class), anyBoolean(), any(DiscussionFilter.class), any(AsyncCallback.class)); verify(mockThreadsContainer, never()).add(any(Widget.class)); verify(mockGinInjector, never()).createThreadListItemWidget(); verify(mockDiscussionThreadWidget, never()).configure(any(DiscussionThreadBundle.class)); verify(mockEmptyListCallback).invoke(anyBoolean()); verify(mockView).setThreadHeaderVisible(false); verify(mockView).setNoThreadsFoundVisible(true); } @SuppressWarnings("unchecked") @Test public void testLoadmoreSuccessDisplayLoadmore() { boolean canModerate = false; AsyncMockStubber.callSuccessWith(discussionThreadBundleList).when(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), any(DiscussionThreadOrder.class), anyBoolean(), any(DiscussionFilter.class), any(AsyncCallback.class)); discussionThreadBundleList.add(new DiscussionThreadBundle()); discussionThreadListWidget.configure("123", canModerate, moderatorIds, mockEmptyListCallback, DiscussionFilter.EXCLUDE_DELETED); verify(mockThreadsContainer).clear(); verify(mockSynAlert).clear(); verify(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), any(DiscussionThreadOrder.class), anyBoolean(), any(DiscussionFilter.class), any(AsyncCallback.class)); verify(mockThreadsContainer).add(any(Widget.class)); verify(mockGinInjector).createThreadListItemWidget(); verify(mockDiscussionThreadWidget).configure(any(DiscussionThreadBundle.class)); verify(mockEmptyListCallback).invoke(anyBoolean()); } @SuppressWarnings("unchecked") @Test public void testLoadmoreFailure() { boolean canModerate = false; AsyncMockStubber.callFailureWith(new Exception()).when(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), any(DiscussionThreadOrder.class), anyBoolean(), any(DiscussionFilter.class), any(AsyncCallback.class)); discussionThreadListWidget.configure("123", canModerate, moderatorIds, mockEmptyListCallback, DiscussionFilter.EXCLUDE_DELETED); verify(mockThreadsContainer).clear(); verify(mockThreadsContainer, never()).add(any(Widget.class)); verify(mockGinInjector, never()).createThreadListItemWidget(); verify(mockSynAlert).clear(); verify(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), any(DiscussionThreadOrder.class), anyBoolean(), any(DiscussionFilter.class), any(AsyncCallback.class)); verify(mockSynAlert).handleException(any(Throwable.class)); } @SuppressWarnings("unchecked") @Test public void testSortByRepliesRepeated() { boolean canModerate = false; discussionThreadListWidget.configure("123", canModerate, moderatorIds, mockEmptyListCallback, DiscussionFilter.EXCLUDE_DELETED); discussionThreadListWidget.sortBy(DiscussionThreadOrder.NUMBER_OF_REPLIES); verify(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), eq(DiscussionThreadOrder.NUMBER_OF_REPLIES), eq(DEFAULT_ASCENDING), any(DiscussionFilter.class), any(AsyncCallback.class)); discussionThreadListWidget.sortBy(DiscussionThreadOrder.NUMBER_OF_REPLIES); verify(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), eq(DiscussionThreadOrder.NUMBER_OF_REPLIES), eq(!DEFAULT_ASCENDING), any(DiscussionFilter.class), any(AsyncCallback.class)); discussionThreadListWidget.sortBy(DiscussionThreadOrder.NUMBER_OF_REPLIES); verify(mockSynapseJavascriptClient, times(2)).getThreadsForForum(anyString(), anyLong(), anyLong(), eq(DiscussionThreadOrder.NUMBER_OF_REPLIES), eq(DEFAULT_ASCENDING), any(DiscussionFilter.class), any(AsyncCallback.class)); } @SuppressWarnings("unchecked") @Test public void testSortByViewsRepeated() { boolean canModerate = false; discussionThreadListWidget.configure("123", canModerate, moderatorIds, mockEmptyListCallback, DiscussionFilter.EXCLUDE_DELETED); discussionThreadListWidget.sortBy(DiscussionThreadOrder.NUMBER_OF_VIEWS); verify(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), eq(DiscussionThreadOrder.NUMBER_OF_VIEWS), eq(DEFAULT_ASCENDING), any(DiscussionFilter.class), any(AsyncCallback.class)); discussionThreadListWidget.sortBy(DiscussionThreadOrder.NUMBER_OF_VIEWS); verify(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), eq(DiscussionThreadOrder.NUMBER_OF_VIEWS), eq(!DEFAULT_ASCENDING), any(DiscussionFilter.class), any(AsyncCallback.class)); discussionThreadListWidget.sortBy(DiscussionThreadOrder.NUMBER_OF_VIEWS); verify(mockSynapseJavascriptClient, times(2)).getThreadsForForum(anyString(), anyLong(), anyLong(), eq(DiscussionThreadOrder.NUMBER_OF_VIEWS), eq(DEFAULT_ASCENDING), any(DiscussionFilter.class), any(AsyncCallback.class)); } @SuppressWarnings("unchecked") @Test public void testSortByLastActivityRepeated() { boolean canModerate = false; discussionThreadListWidget.configure("123", canModerate, moderatorIds, mockEmptyListCallback, DiscussionFilter.EXCLUDE_DELETED); discussionThreadListWidget.sortBy(DiscussionThreadOrder.PINNED_AND_LAST_ACTIVITY); verify(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), eq(DiscussionThreadOrder.PINNED_AND_LAST_ACTIVITY), eq(!DEFAULT_ASCENDING), any(DiscussionFilter.class), any(AsyncCallback.class)); discussionThreadListWidget.sortBy(DiscussionThreadOrder.PINNED_AND_LAST_ACTIVITY); verify(mockSynapseJavascriptClient, times(2)).getThreadsForForum(anyString(), anyLong(), anyLong(), eq(DiscussionThreadOrder.PINNED_AND_LAST_ACTIVITY), eq(DEFAULT_ASCENDING), any(DiscussionFilter.class), any(AsyncCallback.class)); } @SuppressWarnings("unchecked") @Test public void testSortByTitleRepeated() { boolean canModerate = false; discussionThreadListWidget.configure("123", canModerate, moderatorIds, mockEmptyListCallback, DiscussionFilter.EXCLUDE_DELETED); discussionThreadListWidget.sortBy(DiscussionThreadOrder.THREAD_TITLE); verify(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), eq(DiscussionThreadOrder.THREAD_TITLE), eq(DEFAULT_ASCENDING), any(DiscussionFilter.class), any(AsyncCallback.class)); discussionThreadListWidget.sortBy(DiscussionThreadOrder.THREAD_TITLE); verify(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), eq(DiscussionThreadOrder.THREAD_TITLE), eq(!DEFAULT_ASCENDING), any(DiscussionFilter.class), any(AsyncCallback.class)); discussionThreadListWidget.sortBy(DiscussionThreadOrder.THREAD_TITLE); verify(mockSynapseJavascriptClient, times(2)).getThreadsForForum(anyString(), anyLong(), anyLong(), eq(DiscussionThreadOrder.THREAD_TITLE), eq(DEFAULT_ASCENDING), any(DiscussionFilter.class), any(AsyncCallback.class)); } @SuppressWarnings("unchecked") @Test public void testSort() { boolean canModerate = false; discussionThreadListWidget.configure("123", canModerate, moderatorIds, mockEmptyListCallback, DiscussionFilter.EXCLUDE_DELETED); discussionThreadListWidget.sortBy(DiscussionThreadOrder.NUMBER_OF_REPLIES); verify(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), eq(DiscussionThreadOrder.NUMBER_OF_REPLIES), eq(DEFAULT_ASCENDING), any(DiscussionFilter.class), any(AsyncCallback.class)); discussionThreadListWidget.sortBy(DiscussionThreadOrder.NUMBER_OF_VIEWS); verify(mockSynapseJavascriptClient).getThreadsForForum(anyString(), anyLong(), anyLong(), eq(DiscussionThreadOrder.NUMBER_OF_VIEWS), eq(DEFAULT_ASCENDING), any(DiscussionFilter.class), any(AsyncCallback.class)); discussionThreadListWidget.sortBy(DiscussionThreadOrder.NUMBER_OF_REPLIES); verify(mockSynapseJavascriptClient, times(2)).getThreadsForForum(anyString(), anyLong(), anyLong(), eq(DiscussionThreadOrder.NUMBER_OF_REPLIES), eq(DEFAULT_ASCENDING), any(DiscussionFilter.class), any(AsyncCallback.class)); } }
61.56231
254
0.822504
65d09a185dbf29812be81bba563c7cb338f6334b
6,062
/* * Copyright (C) 2014 Indeed Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.indeed.imhotep.local; import com.indeed.flamdex.api.FlamdexReader; import com.indeed.flamdex.datastruct.FastBitSet; import com.indeed.imhotep.BitTree; import com.indeed.imhotep.api.FTGSIterator; import com.indeed.util.core.Pair; import com.indeed.util.core.reference.SharedReference; import org.apache.log4j.Logger; /** * @author jplaisance */ public abstract class AbstractFlamdexFTGSIterator implements FTGSIterator { private static final Logger log = Logger.getLogger(AbstractFlamdexFTGSIterator.class); /** * */ protected final ImhotepLocalSession session; protected final int[] groupsSeen; protected final BitTree bitTree; protected final long[][] termGrpStats; protected boolean currentFieldIsIntType; protected SharedReference<FlamdexReader> flamdexReader; long intTermsTime = 0; long stringTermsTime = 0; long docsTime = 0; long lookupsTime = 0; long timingErrorTime = 0; protected String currentField; private int groupPointer; private int groupsSeenCount; protected boolean resetGroupStats = false; protected FastBitSet fieldZeroDocBitset; protected int termIndex; public AbstractFlamdexFTGSIterator(ImhotepLocalSession imhotepLocalSession, SharedReference<FlamdexReader> flamdexReader) { this.session = imhotepLocalSession; this.termGrpStats = new long[session.numStats][session.docIdToGroup.getNumGroups()]; this.groupsSeen = new int[session.docIdToGroup.getNumGroups()]; this.bitTree = new BitTree(session.docIdToGroup.getNumGroups()); this.flamdexReader = flamdexReader; } @Override public abstract boolean nextField(); @Override public abstract void close(); @Override public final String fieldName() { return currentField; } @Override public final boolean fieldIsIntType() { return currentFieldIsIntType; } @Override public abstract boolean nextTerm(); @Override public abstract long termDocFreq(); @Override public abstract long termIntVal(); @Override public abstract String termStringVal(); @Override public final boolean nextGroup() { if (!resetGroupStats) { if (groupPointer >= groupsSeenCount) return false; groupPointer++; return groupPointer < groupsSeenCount; } return calculateTermGroupStats(); } private boolean calculateTermGroupStats() { // clear out ram from previous iterations if necessary for (final long[] x : termGrpStats) ImhotepLocalSession.clear(x, groupsSeen, groupsSeenCount); groupsSeenCount = 0; if (fieldZeroDocBitset != null) { if (termIndex == fieldZeroDocBitset.size()) expandFieldNonZeroDocBitset(); final boolean skip = fieldZeroDocBitset.get(termIndex); termIndex++; if (skip) return false; } // this is the critical loop of all of imhotep, making this loop faster is very good.... synchronized (session) { while (true) { if (ImhotepLocalSession.logTiming) docsTime -= System.nanoTime(); final int n = fillDocIdBuffer(); if (ImhotepLocalSession.logTiming) { docsTime += System.nanoTime(); lookupsTime -= System.nanoTime(); } session.docIdToGroup.nextGroupCallback(n, termGrpStats, bitTree); if (ImhotepLocalSession.logTiming) { lookupsTime += System.nanoTime(); timingErrorTime -= System.nanoTime(); timingErrorTime += System.nanoTime(); } if (n < ImhotepLocalSession.BUFFER_SIZE) break; } } groupsSeenCount = bitTree.dump(groupsSeen); if (fieldZeroDocBitset != null && groupsSeenCount == 0) { fieldZeroDocBitset.set(termIndex - 1); } groupPointer = 0; resetGroupStats = false; return groupsSeenCount > 0; } protected abstract int fillDocIdBuffer(); private void expandFieldNonZeroDocBitset() { synchronized (session) { if (fieldZeroDocBitset == null) return; if(session.memory.claimMemory(FastBitSet.calculateMemoryUsage(fieldZeroDocBitset.size() * 2))) { final FastBitSet tmpBitset = new FastBitSet(fieldZeroDocBitset.size() * 2); tmpBitset.or(fieldZeroDocBitset); final long oldSize = fieldZeroDocBitset.memoryUsage(); fieldZeroDocBitset = tmpBitset; session.fieldZeroDocBitsets.put(Pair.of(currentField, currentFieldIsIntType), fieldZeroDocBitset); session.memory.releaseMemory(oldSize); } else { ImhotepLocalSession.log.warn("Insufficient expansion memory, disabling ftgs zero group bitset optimization"); session.clearZeroDocBitsets(); fieldZeroDocBitset = null; session.fieldZeroDocBitsets = null; } } } @Override public final int group() { return groupsSeen[groupPointer]; } @Override public final void groupStats(long[] stats) { final int group = group(); for (int i = 0; i < session.numStats; i++) { stats[i] = termGrpStats[i][group]; } } }
34.05618
127
0.651435
dcfe0db62a432a3829cc49bb63b47328c55cd161
1,707
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.identity.application.authentication.handler.session; /** * Constants used by the Session Handler. */ public abstract class ActiveSessionsLimitHandlerConstants { public static final String HANDLER_NAME = "SessionExecutor"; public static final String HANDLER_FRIENDLY_NAME = "active-sessions-limit-handler"; public static final String TERMINATE_SESSIONS_ACTION = "terminateActiveSessionsAction"; public static final String ACTIVE_SESSIONS_LIMIT_ACTION = "ActiveSessionsLimitAction"; public static final String DENY_LOGIN_ACTION = "denyLimitActiveSessionsAction"; public static final String REFRESH_ACTION = "refreshActiveSessionsAction"; public static final String MAX_SESSION_COUNT = "MaxSessionCount"; public static final String SESSIONS_TO_TERMINATE = "sessionsToTerminate"; public static final String SESSIONS = "sessions"; public static final String SESSION_DATA_KEY = "sessionDataKey"; private ActiveSessionsLimitHandlerConstants() { } }
41.634146
91
0.760984
362999c85a0f4a5840b39f54a14f4cdfc0c6afe2
211
package comalat.Application.Exception; /** * * @author SyleSakis */ public class ConflictException extends RuntimeException{ public ConflictException(String message) { super(message); } }
16.230769
56
0.701422