id
int64
file_name
string
file_path
string
content
string
size
int64
language
string
extension
string
total_lines
int64
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
repo_name
string
repo_stars
int64
repo_forks
int64
repo_open_issues
int64
repo_license
string
repo_extraction_date
string
exact_duplicates_redpajama
bool
near_duplicates_redpajama
bool
exact_duplicates_githubcode
bool
exact_duplicates_stackv2
bool
exact_duplicates_stackv1
bool
near_duplicates_githubcode
bool
near_duplicates_stackv1
bool
near_duplicates_stackv2
bool
length
int64
1,861,372
ClassRef.java
hydraxman_ApkEditor/src/main/java/com/bryansharp/tools/parseapk/entity/refs/ClassRef.java
package com.bryansharp.tools.parseapk.entity.refs; /** * Created by bsp on 17/3/18. */ public class ClassRef { public static final int SIZE = 32; public int classIdx; public int accessFlags; public int superclassIdx; public int interfacesOff; public int sourceFileIdx; public int annotationsOff; public int classDataOff; public int staticValuesOff; @Override public String toString() { return "\nClassRef{" + "classIdx=" + classIdx + ", accessFlags=" + accessFlags + ", superclassIdx=" + superclassIdx + ", interfacesOff=" + interfacesOff + ", sourceFileIdx=" + sourceFileIdx + ", annotationsOff=" + annotationsOff + ", classDataOff=" + classDataOff + ", staticValuesOff=" + staticValuesOff + '}'; } }
906
Java
.java
28
24.071429
56
0.592466
hydraxman/ApkEditor
16
3
0
GPL-3.0
9/4/2024, 8:21:15 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
906
3,466,429
OptionElementCollection.java
mehah_jRender/src/com/jrender/jscript/dom/elements/OptionElementCollection.java
package com.jrender.jscript.dom.elements; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.jrender.jscript.DOM; import com.jrender.jscript.DOMHandle; import com.jrender.jscript.dom.Node; import com.jrender.jscript.dom.Window; public final class OptionElementCollection<T> extends DOM implements Iterable<OptionElement<T>>{ private final Class<T> typeValue; OptionElementCollection(Window window, Class<T> typeValue) { super(window); this.typeValue = typeValue; } List<OptionElement<T>> list; private OptionIterator iterator; public Iterator<OptionElement<T>> iterator() { if(iterator == null) iterator = new OptionIterator(); else iterator.reset(); return iterator; } public OptionElement<T> namedItem(String nameOrId) { String res; for (OptionElement<T> o : list) { if((res = o.getAttribute("name")) != null && res.equals(nameOrId) || (res = o.getAttribute("id")) != null && res.equals(nameOrId)) return o; } return null; } public OptionElement<T> item(int index) { OptionElement<T> e = list.get(index); if(e == null) DOMHandle.registerReturnByCommand((Node)(e = new OptionElement<T>(this.window, typeValue)), this, "item", index); return e; } public Integer length() { if(list == null) { list = new ArrayList<OptionElement<T>>(); final Integer size = DOMHandle.getVariableValueByProperty(this, "length", Integer.class, "length"); for (int i = -1; ++i < size;) list.add(null); } return list.size(); } public void add(OptionElement<T> option) { add(option, null); } public void add(OptionElement<T> option, Integer index) { if(index == null) { list.add(option); DOMHandle.execCommand(this, "add", option); }else { list.add(index, option); DOMHandle.execCommand(this, "add", option, index); } } public OptionElement<T> remove(int index) { OptionElement<T> e = list.remove(index); DOMHandle.execCommand(this, "remove", index); return e; } private class OptionIterator implements Iterator<OptionElement<T>> { private int currentIndex = 0; public void reset() { currentIndex = 0; }; public boolean hasNext() { return currentIndex < list.size(); } public OptionElement<T> next() { return item(currentIndex++); } public void remove() {} } }
2,334
Java
.java
72
29.208333
133
0.722122
mehah/jRender
3
0
0
GPL-3.0
9/4/2024, 11:29:27 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
2,334
2,087,442
ClipPlaneUboDataProvider.java
KilnGraphics_Rosella/src/test/java/graphics/kiln/rosella/example/fboWater/ubo/ClipPlaneUboDataProvider.java
package graphics.kiln.rosella.example.fboWater.ubo; import graphics.kiln.rosella.scene.object.RenderObject; import graphics.kiln.rosella.ubo.UboDataProvider; import org.joml.Vector4f; import java.nio.ByteBuffer; public class ClipPlaneUboDataProvider extends UboDataProvider<RenderObject> { public final Vector4f clippingPlane; public ClipPlaneUboDataProvider(Vector4f clippingPlane) { this.clippingPlane = clippingPlane; } @Override public void update(ByteBuffer data, RenderObject renderObject) { reset(); super.writeMatrix4f(renderObject.modelMatrix, data); super.writeMatrix4f(renderObject.viewMatrix, data); super.writeMatrix4f(renderObject.projectionMatrix, data); super.writeVector4f(clippingPlane, data); } @Override public int getSize() { return (16 * Float.BYTES) + // Model Matrix (16 * Float.BYTES) + // View Matrix (16 * Float.BYTES) + // Projection Matrix (4 * Float.BYTES); // Clipping Plane } }
1,057
Java
.java
26
34
77
0.711914
KilnGraphics/Rosella
10
3
2
LGPL-3.0
9/4/2024, 8:28:58 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,057
4,609,415
ClusterOperator.java
pbousquets_beast-mcmc-flipflop/src/dr/evomodel/antigenic/phyloClustering/misc/obsolete/ClusterOperator.java
package dr.evomodel.antigenic.phyloClustering.misc.obsolete; import dr.evomodel.antigenic.NPAntigenicLikelihood; import dr.inference.model.Bounds; import dr.inference.model.CompoundParameter; import dr.inference.model.Likelihood; import dr.inference.model.MatrixParameter; import dr.inference.model.Parameter; import dr.inference.operators.GibbsOperator; import dr.inference.operators.MCMCOperator; import dr.inference.operators.OperatorFailedException; import dr.inference.operators.SimpleMCMCOperator; import dr.inference.operators.RandomWalkOperator.BoundaryCondition; import dr.math.MathUtils; import dr.xml.*; public class ClusterOperator extends SimpleMCMCOperator { public final static String CLUSTER_OPERATOR = "clusterOperator"; public static final String WINDOW_SIZE = "windowSize"; public NPAntigenicLikelihood modelLikelihood; private Parameter assignments = null; private Parameter links = null; private MatrixParameter virusLocations = null; private double windowSize = 1; public ClusterOperator(Parameter assignments, MatrixParameter virusLocations, double weight, double windowSize, NPAntigenicLikelihood Likelihood, Parameter links) { //System.out.println("Constructor"); this.links = links; this.assignments = assignments; this.virusLocations = virusLocations; this.windowSize = windowSize; this.modelLikelihood = Likelihood; setWeight(weight); //load in the virusLocations System.out.println((int)assignments.getParameterValue(0)); Parameter vLoc = virusLocations.getParameter(0); //double d0= vLoc.getParameterValue(0); //double d1= vLoc.getParameterValue(1); //System.out.println( d0 + "," + d1); //System.exit(0); } //assume no boundary /** * change the parameter and return the hastings ratio. */ public final double doOperation() { double moveWholeClusterOrChangeOnePoint = MathUtils.nextDouble(); //double moveWholeClusterProb = 0.2; double moveWholeClusterProb = 0.5; int numSamples = assignments.getDimension(); // if(moveWholeClusterOrChangeOnePoint <moveWholeClusterProb){ // System.out.print("Group changes: "); //System.out.println("Move a group of points in a cluster together"); int target = MathUtils.nextInt(numSamples); int targetCluster = (int) assignments.getParameterValue(target); //for(int i=0; i < numSamples; i++){ //Parameter vLoc = virusLocations.getParameter(i); //double d0= vLoc.getParameterValue(0); //double d1= vLoc.getParameterValue(1); //System.out.println( d0 + "," + d1); //} // a random dimension to perturb int ranDim= MathUtils.nextInt(virusLocations.getParameter(0).getDimension()); // a random point around old value within windowSize * 2 double draw = (2.0 * MathUtils.nextDouble() - 1.0) * windowSize; for(int i=0; i < numSamples; i++){ if((int) assignments.getParameterValue(i)== targetCluster ){ //System.out.print("update "+ i +" from "); Parameter vLoc = virusLocations.getParameter(i); //System.out.print(vLoc.getParameterValue(index)); double newValue = vLoc.getParameterValue(ranDim) + draw; vLoc.setParameterValue(ranDim, newValue); //System.out.println(" to " + vLoc.getParameterValue(index)); } } // } /* //change cluster assignment! else{ System.out.print("Cluster assignment & Group move:"); //System.out.println("Change a single point to another cluster"); //moving the point without coupling the point is useless! //randomly pick a point to change cluster assignment //move the point and couple it with change in cluster: int index = MathUtils.nextInt(numSamples); int oldGroup = (int)assignments.getParameterValue(index); // Set index customer link to index and all connected to it to a new assignment (min value empty) int minEmp = minEmpty(modelLikelihood.getLogLikelihoodsVector()); links.setParameterValue(index, index); int[] visited = connected(index, links); int ii = 0; while (visited[ii]!=0){ assignments.setParameterValue(visited[ii]-1, minEmp); ii++; } //Adjust likvector for group separated modelLikelihood.setLogLikelihoodsVector(oldGroup,modelLikelihood.getLogLikGroup(oldGroup) ); modelLikelihood.setLogLikelihoodsVector(minEmp,modelLikelihood.getLogLikGroup(minEmp) ); int maxFull = maxFull( modelLikelihood.getLogLikelihoodsVector()); //pick new link int k = MathUtils.nextInt(numSamples); //wonder if there is a way to make this more efficient at choosing good moves links.setParameterValue(index, k); int newGroup = (int)assignments.getParameterValue(k); int countNumChanged = 0; ii = 0; while (visited[ii]!=0){ assignments.setParameterValue(visited[ii]-1, newGroup); ii++; countNumChanged++; } System.out.print("changed="+countNumChanged+ " "); int targetCluster = (int) assignments.getParameterValue(k); // updating conditional likelihood vector modelLikelihood.setLogLikelihoodsVector(newGroup, modelLikelihood.getLogLikGroup(newGroup)); if (newGroup!=minEmp){ modelLikelihood.setLogLikelihoodsVector(minEmp, 0); } //change the location // a random dimension to perturb int ranDim= MathUtils.nextInt(virusLocations.getParameter(0).getDimension()); // a random point around old value within windowSize * 2 double draw = (2.0 * MathUtils.nextDouble() - 1.0) * windowSize; int countNumLocChanged = 0; for(int i=0; i < numSamples; i++){ if((int) assignments.getParameterValue(i)== targetCluster ){ //System.out.print("update "+ i +" from "); Parameter vLoc = virusLocations.getParameter(i); //System.out.print(vLoc.getParameterValue(index)); double newValue = vLoc.getParameterValue(ranDim) + draw; vLoc.setParameterValue(ranDim, newValue); //System.out.println(" to " + vLoc.getParameterValue(index)); countNumLocChanged++; } } System.out.print("loc changed="+countNumLocChanged+ " "); // sampleMeans(maxFull); // I decide not to resample the means here. } //Want to check that virusLocations WON't get updated if rejected // System.out.println(target); // System.out.println(targetCluster); //for(int i=0; i < assignments.getDimension();) */ return 0.0; } /* * find min Empty */ public int minEmpty(double[] logLikVector){ int isEmpty=0; int i =0; while (isEmpty==0){ if(logLikVector[i]==0){ isEmpty=1;} else { if(i==logLikVector.length-1){isEmpty=1;} i++;} } return i; } /* * find max Full */ public int maxFull(double[] logLikVector){ int isEmpty=1; int i =logLikVector.length-1; while (isEmpty==1){ if(logLikVector[i]!=0){ isEmpty=0;} else {i--;} } return i; } /* * find customers connected to i */ public int[] connected(int i, Parameter clusteringParameter){ int n = clusteringParameter.getDimension(); int[] visited = new int[n+1]; visited[0]=i+1; int tv=1; for(int j=0;j<n;j++){ if(visited[j]!=0){ int curr = visited[j]-1; /*look forward */ int forward = (int) clusteringParameter.getParameterValue(curr); visited[tv] = forward+1; tv++; // Check to see if is isn't already on the list for(int ii=0; ii<tv-1; ii++){ if(visited[ii]==forward+1){ tv--; visited[tv]=0; } } /*look back */ for (int jj=0; jj<n;jj++){ if((int)clusteringParameter.getParameterValue(jj)==curr){ visited[tv]= jj+1; tv++; for(int ii=0; ii<tv-1; ii++){ if(visited[ii]==jj+1){ tv--; visited[tv]=0; } } } } }} return visited; } public void accept(double deviation) { super.accept(deviation); // System.out.println("Accepted!"); } public void reject(){ super.reject(); // System.out.println("Rejected"); } //MCMCOperator INTERFACE public final String getOperatorName() { return CLUSTER_OPERATOR; } public final void optimize(double targetProb) { throw new RuntimeException("This operator cannot be optimized!"); } public boolean isOptimizing() { return false; } public void setOptimizing(boolean opt) { throw new RuntimeException("This operator cannot be optimized!"); } public double getMinimumAcceptanceLevel() { return 0.1; } public double getMaximumAcceptanceLevel() { return 0.4; } public double getMinimumGoodAcceptanceLevel() { return 0.20; } public double getMaximumGoodAcceptanceLevel() { return 0.30; } public String getPerformanceSuggestion() { if (Utils.getAcceptanceProbability(this) < getMinimumAcceptanceLevel()) { return ""; } else if (Utils.getAcceptanceProbability(this) > getMaximumAcceptanceLevel()) { return ""; } else { return ""; } } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public final static String ASSIGNMENTS = "assignments"; public final static String VIRUS_LOCATIONS = "virusLocations"; public final static String LIKELIHOOD = "likelihood"; public final static String LINKS = "links"; public String getParserName() { return CLUSTER_OPERATOR; } /* (non-Javadoc) * @see dr.xml.AbstractXMLObjectParser#parseXMLObject(dr.xml.XMLObject) */ public Object parseXMLObject(XMLObject xo) throws XMLParseException { double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT); // double windowSize = xo.getDoubleAttribute(WINDOW_SIZE); XMLObject cxo = xo.getChild(ASSIGNMENTS); Parameter assignments = (Parameter) cxo.getChild(Parameter.class); MatrixParameter virusLocationsParameter = null; if (xo.hasChildNamed(VIRUS_LOCATIONS)) { virusLocationsParameter = (MatrixParameter) xo.getElementFirstChild(VIRUS_LOCATIONS); } cxo = xo.getChild(LINKS); Parameter links = (Parameter) cxo.getChild(Parameter.class); cxo = xo.getChild(LIKELIHOOD); NPAntigenicLikelihood likelihood = (NPAntigenicLikelihood)cxo.getChild(NPAntigenicLikelihood.class); //set window size to be 1 return new ClusterOperator(assignments, virusLocationsParameter, weight, 1.0, likelihood, links); // public ClusterOperator(Parameter assignments, MatrixParameter virusLocations, double weight, double windowSize, NPAntigenicLikelihood Likelihood, Parameter links) { } //************************************************************************ // AbstractXMLObjectParser implementation //************************************************************************ public String getParserDescription() { return "An operator that picks a new allocation of an item to a cluster under the Dirichlet process."; } public Class getReturnType() { return ClusterOperator.class; } public XMLSyntaxRule[] getSyntaxRules() { return rules; } private final XMLSyntaxRule[] rules = { AttributeRule.newDoubleRule(MCMCOperator.WEIGHT), // AttributeRule.newDoubleRule(WINDOW_SIZE), new ElementRule(ASSIGNMENTS, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), new ElementRule(VIRUS_LOCATIONS, MatrixParameter.class, "Parameter of locations of all virus"), new ElementRule(LINKS, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}), new ElementRule(LIKELIHOOD, new XMLSyntaxRule[] { new ElementRule(Likelihood.class),}, true), }; }; public int getStepCount() { return 1; } }
17,228
Java
.java
307
33.325733
186
0.509726
pbousquets/beast-mcmc-flipflop
2
0
8
LGPL-2.1
9/5/2024, 12:19:08 AM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
17,228
4,788,373
BasicPermission2Test.java
mateor_PDroidHistory/libcore/luni/src/test/java/org/apache/harmony/security/tests/java/security/BasicPermission2Test.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.security.tests.java.security; import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargets; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetNew; import java.security.BasicPermission; import java.security.PermissionCollection; @TestTargetClass(BasicPermission.class) public class BasicPermission2Test extends junit.framework.TestCase { public static class BasicPermissionSubclass extends BasicPermission { public BasicPermissionSubclass(String name) { super(name); } public BasicPermissionSubclass(String name, String actions) { super(name, actions); } } BasicPermission bp = new BasicPermissionSubclass("aName"); BasicPermission bp2 = new BasicPermissionSubclass("aName", "anAction"); BasicPermission bp3 = new BasicPermissionSubclass("*"); BasicPermission bp4 = new BasicPermissionSubclass("this.that"); BasicPermission bp5 = new BasicPermissionSubclass("this.*"); /** * @tests java.security.BasicPermission#BasicPermission(java.lang.String) */ @TestTargetNew( level = TestLevel.PARTIAL, notes = "Test cases, where parameter name is null (expect NullPointerException) and parameter name is empty (expect IllegalArgumentException) are absent", method = "BasicPermission", args = {java.lang.String.class} ) public void test_ConstructorLjava_lang_String() { // Test for method java.security.BasicPermission(java.lang.String) assertEquals("Incorrect name returned", "aName", bp.getName()); } /** * @tests java.security.BasicPermission#BasicPermission(java.lang.String, * java.lang.String) */ @TestTargetNew( level = TestLevel.PARTIAL, notes = "Test cases, where parameter name is null (expect NullPointerException) and parameter name is empty (expect IllegalArgumentException) are absent", method = "BasicPermission", args = {java.lang.String.class, java.lang.String.class} ) public void test_ConstructorLjava_lang_StringLjava_lang_String() { // Test for method java.security.BasicPermission(java.lang.String, // java.lang.String) assertEquals("Incorrect name returned", "aName", bp2.getName()); } /** * @tests java.security.BasicPermission#equals(java.lang.Object) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "equals", args = {java.lang.Object.class} ) public void test_equalsLjava_lang_Object() { // Test for method boolean // java.security.BasicPermission.equals(java.lang.Object) assertTrue("a) Equal objects returned non-equal", bp.equals(bp2)); assertTrue("b) Equal objects returned non-equal", bp2.equals(bp)); assertTrue("a) Unequal objects returned equal", !bp.equals(bp3)); assertTrue("b) Unequal objects returned equal", !bp4.equals(bp5)); } /** * @tests java.security.BasicPermission#getActions() */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "getActions", args = {} ) public void test_getActions() { // Test for method java.lang.String // java.security.BasicPermission.getActions() assertTrue("a) Incorrect actions returned, wanted the empty String", bp .getActions().equals("")); assertTrue("b) Incorrect actions returned, wanted the empty String", bp2.getActions().equals("")); } /** * @tests java.security.BasicPermission#hashCode() */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "hashCode", args = {} ) public void test_hashCode() { // Test for method int java.security.BasicPermission.hashCode() assertTrue("Equal objects should return same hash", bp.hashCode() == bp2.hashCode()); } /** * @tests java.security.BasicPermission#implies(java.security.Permission) */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "implies", args = {java.security.Permission.class} ) public void test_impliesLjava_security_Permission() { // Test for method boolean // java.security.BasicPermission.implies(java.security.Permission) assertTrue("Equal objects should imply each other", bp.implies(bp2)); assertTrue("a) should not imply", !bp.implies(bp3)); assertTrue("b) should not imply", !bp4.implies(bp5)); assertTrue("a) should imply", bp3.implies(bp5)); assertTrue("b) should imply", bp5.implies(bp4)); } /** * @tests java.security.BasicPermission#newPermissionCollection() */ @TestTargetNew( level = TestLevel.COMPLETE, notes = "", method = "newPermissionCollection", args = {} ) public void test_newPermissionCollection() { // Test for method java.security.PermissionCollection // java.security.BasicPermission.newPermissionCollection() PermissionCollection bpc = bp.newPermissionCollection(); bpc.add(bp5); bpc.add(bp); assertTrue("Should imply", bpc.implies(bp4)); assertTrue("Should not imply", !bpc.implies(bp3)); } }
6,222
Java
.java
151
34.562914
162
0.680324
mateor/PDroidHistory
1
2
0
GPL-3.0
9/5/2024, 12:31:53 AM (Europe/Amsterdam)
true
true
true
false
true
true
true
false
6,222
905,079
JigsawStructureDataPacket.java
MemoriesOfTime_Nukkit-MOT/src/main/java/cn/nukkit/network/protocol/JigsawStructureDataPacket.java
package cn.nukkit.network.protocol; import cn.nukkit.nbt.tag.CompoundTag; import lombok.ToString; /** * @author glorydark */ @ToString public class JigsawStructureDataPacket extends DataPacket { public static final int NETWORK_ID = ProtocolInfo.JIGSAW_STRUCTURE_DATA_PACKET; public CompoundTag nbt; @Override public int packetId() { return NETWORK_ID; } @Override public byte pid() { throw new UnsupportedOperationException("Not supported."); } @Override public void decode() { this.nbt = this.getTag(); } @Override public void encode() { this.putNbtTag(this.nbt); } }
667
Java
.java
27
20.074074
83
0.693038
MemoriesOfTime/Nukkit-MOT
64
35
21
LGPL-3.0
9/4/2024, 7:09:48 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
667
3,731,776
PreloadingNetworkStoreClient.java
powsybl_powsybl-network-store/network-store-client/src/main/java/com/powsybl/network/store/client/PreloadingNetworkStoreClient.java
/** * Copyright (c) 2019, RTE (http://www.rte-france.com) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.powsybl.network.store.client; import com.google.common.base.Stopwatch; import com.powsybl.network.store.client.util.ExecutorUtil; import com.powsybl.network.store.iidm.impl.AbstractForwardingNetworkStoreClient; import com.powsybl.network.store.iidm.impl.CachedNetworkStoreClient; import com.powsybl.network.store.iidm.impl.NetworkCollectionIndex; import com.powsybl.network.store.iidm.impl.NetworkStoreClient; import com.powsybl.network.store.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * Per collection preloading. * @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com> * @author Etienne Homer <etienne.homer at rte-france.com> */ public class PreloadingNetworkStoreClient extends AbstractForwardingNetworkStoreClient implements NetworkStoreClient { private static final Logger LOGGER = LoggerFactory.getLogger(PreloadingNetworkStoreClient.class); static final Set<ResourceType> RESOURCE_TYPES_NEEDED_FOR_BUS_VIEW = Set.of( ResourceType.SUBSTATION, ResourceType.VOLTAGE_LEVEL, ResourceType.LOAD, ResourceType.GENERATOR, ResourceType.BATTERY, ResourceType.SHUNT_COMPENSATOR, ResourceType.VSC_CONVERTER_STATION, ResourceType.LCC_CONVERTER_STATION, ResourceType.STATIC_VAR_COMPENSATOR, ResourceType.BUSBAR_SECTION, // FIXME this should not be in the list but as connectable visitor also visit busbar sections we need to keep it ResourceType.GROUND, ResourceType.TWO_WINDINGS_TRANSFORMER, ResourceType.THREE_WINDINGS_TRANSFORMER, ResourceType.LINE, ResourceType.HVDC_LINE, ResourceType.DANGLING_LINE, ResourceType.TIE_LINE ); private final boolean allCollectionsNeededForBusView; private final ExecutorService executorService; private final NetworkCollectionIndex<Set<ResourceType>> cachedResourceTypes = new NetworkCollectionIndex<>(() -> EnumSet.noneOf(ResourceType.class)); public PreloadingNetworkStoreClient(CachedNetworkStoreClient delegate, boolean allCollectionsNeededForBusView, ExecutorService executorService) { super(delegate); this.allCollectionsNeededForBusView = allCollectionsNeededForBusView; this.executorService = Objects.requireNonNull(executorService); } private void loadToCache(ResourceType resourceType, UUID networkUuid, int variantNum) { switch (resourceType) { case SUBSTATION -> delegate.getSubstations(networkUuid, variantNum); case VOLTAGE_LEVEL -> delegate.getVoltageLevels(networkUuid, variantNum); case LOAD -> delegate.getLoads(networkUuid, variantNum); case GENERATOR -> delegate.getGenerators(networkUuid, variantNum); case BATTERY -> delegate.getBatteries(networkUuid, variantNum); case SHUNT_COMPENSATOR -> delegate.getShuntCompensators(networkUuid, variantNum); case VSC_CONVERTER_STATION -> delegate.getVscConverterStations(networkUuid, variantNum); case LCC_CONVERTER_STATION -> delegate.getLccConverterStations(networkUuid, variantNum); case STATIC_VAR_COMPENSATOR -> delegate.getStaticVarCompensators(networkUuid, variantNum); case BUSBAR_SECTION -> delegate.getBusbarSections(networkUuid, variantNum); case SWITCH -> delegate.getSwitches(networkUuid, variantNum); case GROUND -> delegate.getGrounds(networkUuid, variantNum); case TWO_WINDINGS_TRANSFORMER -> delegate.getTwoWindingsTransformers(networkUuid, variantNum); case THREE_WINDINGS_TRANSFORMER -> delegate.getThreeWindingsTransformers(networkUuid, variantNum); case LINE -> delegate.getLines(networkUuid, variantNum); case HVDC_LINE -> delegate.getHvdcLines(networkUuid, variantNum); case DANGLING_LINE -> delegate.getDanglingLines(networkUuid, variantNum); case CONFIGURED_BUS -> delegate.getConfiguredBuses(networkUuid, variantNum); case TIE_LINE -> delegate.getTieLines(networkUuid, variantNum); default -> { // Do nothing } } } private void loadAllCollectionsNeededForBusView(UUID networkUuid, int variantNum, Set<ResourceType> resourceTypes) { // directly load all collections Stopwatch stopwatch = Stopwatch.createStarted(); List<Future<?>> futures = new ArrayList<>(RESOURCE_TYPES_NEEDED_FOR_BUS_VIEW.size()); for (ResourceType resourceType : RESOURCE_TYPES_NEEDED_FOR_BUS_VIEW) { futures.add(executorService.submit(() -> loadToCache(resourceType, networkUuid, variantNum))); } ExecutorUtil.waitAllFutures(futures); resourceTypes.addAll(RESOURCE_TYPES_NEEDED_FOR_BUS_VIEW); stopwatch.stop(); LOGGER.info("All collections needed for bus view loaded in {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS)); } boolean isResourceTypeCached(UUID networkUuid, int variantNum, ResourceType resourceType) { Set<ResourceType> resourceTypes = cachedResourceTypes.getCollection(networkUuid, variantNum); Objects.requireNonNull(resourceType); return resourceTypes.contains(resourceType); } private void ensureCached(ResourceType resourceType, UUID networkUuid, int variantNum) { Objects.requireNonNull(resourceType); Objects.requireNonNull(networkUuid); Set<ResourceType> resourceTypes = cachedResourceTypes.getCollection(networkUuid, variantNum); if (!resourceTypes.contains(resourceType)) { if (allCollectionsNeededForBusView && RESOURCE_TYPES_NEEDED_FOR_BUS_VIEW.contains(resourceType)) { loadAllCollectionsNeededForBusView(networkUuid, variantNum, resourceTypes); } else { loadToCache(resourceType, networkUuid, variantNum); resourceTypes.add(resourceType); } } } @Override public void deleteNetwork(UUID networkUuid) { delegate.deleteNetwork(networkUuid); cachedResourceTypes.removeCollection(networkUuid); } @Override public void deleteNetwork(UUID networkUuid, int variantNum) { delegate.deleteNetwork(networkUuid, variantNum); cachedResourceTypes.removeCollection(networkUuid, variantNum); } @Override public void createSubstations(UUID networkUuid, List<Resource<SubstationAttributes>> substationResources) { for (Resource<SubstationAttributes> substationResource : substationResources) { ensureCached(ResourceType.SUBSTATION, networkUuid, substationResource.getVariantNum()); } delegate.createSubstations(networkUuid, substationResources); } @Override public List<Resource<SubstationAttributes>> getSubstations(UUID networkUuid, int variantNum) { ensureCached(ResourceType.SUBSTATION, networkUuid, variantNum); return delegate.getSubstations(networkUuid, variantNum); } @Override public Optional<Resource<SubstationAttributes>> getSubstation(UUID networkUuid, int variantNum, String substationId) { ensureCached(ResourceType.SUBSTATION, networkUuid, variantNum); return delegate.getSubstation(networkUuid, variantNum, substationId); } @Override public void removeSubstations(UUID networkUuid, int variantNum, List<String> substationsId) { ensureCached(ResourceType.SUBSTATION, networkUuid, variantNum); delegate.removeSubstations(networkUuid, variantNum, substationsId); } @Override public void updateSubstations(UUID networkUuid, List<Resource<SubstationAttributes>> substationResources, AttributeFilter attributeFilter) { for (Resource<SubstationAttributes> substationResource : substationResources) { ensureCached(ResourceType.SUBSTATION, networkUuid, substationResource.getVariantNum()); } delegate.updateSubstations(networkUuid, substationResources, attributeFilter); } @Override public void createVoltageLevels(UUID networkUuid, List<Resource<VoltageLevelAttributes>> voltageLevelResources) { for (Resource<VoltageLevelAttributes> voltageLevelResource : voltageLevelResources) { ensureCached(ResourceType.VOLTAGE_LEVEL, networkUuid, voltageLevelResource.getVariantNum()); } delegate.createVoltageLevels(networkUuid, voltageLevelResources); } @Override public Optional<Resource<VoltageLevelAttributes>> getVoltageLevel(UUID networkUuid, int variantNum, String voltageLevelId) { ensureCached(ResourceType.VOLTAGE_LEVEL, networkUuid, variantNum); return delegate.getVoltageLevel(networkUuid, variantNum, voltageLevelId); } @Override public List<Resource<VoltageLevelAttributes>> getVoltageLevels(UUID networkUuid, int variantNum) { ensureCached(ResourceType.VOLTAGE_LEVEL, networkUuid, variantNum); return delegate.getVoltageLevels(networkUuid, variantNum); } @Override public List<Resource<VoltageLevelAttributes>> getVoltageLevelsInSubstation(UUID networkUuid, int variantNum, String substationId) { ensureCached(ResourceType.VOLTAGE_LEVEL, networkUuid, variantNum); return delegate.getVoltageLevelsInSubstation(networkUuid, variantNum, substationId); } @Override public void removeVoltageLevels(UUID networkUuid, int variantNum, List<String> voltageLevelsId) { ensureCached(ResourceType.VOLTAGE_LEVEL, networkUuid, variantNum); delegate.removeVoltageLevels(networkUuid, variantNum, voltageLevelsId); } @Override public List<Resource<BusbarSectionAttributes>> getVoltageLevelBusbarSections(UUID networkUuid, int variantNum, String voltageLevelId) { ensureCached(ResourceType.BUSBAR_SECTION, networkUuid, variantNum); return delegate.getVoltageLevelBusbarSections(networkUuid, variantNum, voltageLevelId); } @Override public void removeBusBarSections(UUID networkUuid, int variantNum, List<String> busBarSectionsId) { ensureCached(ResourceType.BUSBAR_SECTION, networkUuid, variantNum); delegate.removeBusBarSections(networkUuid, variantNum, busBarSectionsId); } @Override public List<Resource<SwitchAttributes>> getVoltageLevelSwitches(UUID networkUuid, int variantNum, String voltageLevelId) { ensureCached(ResourceType.SWITCH, networkUuid, variantNum); return delegate.getVoltageLevelSwitches(networkUuid, variantNum, voltageLevelId); } @Override public List<Resource<GeneratorAttributes>> getVoltageLevelGenerators(UUID networkUuid, int variantNum, String voltageLevelId) { ensureCached(ResourceType.GENERATOR, networkUuid, variantNum); return delegate.getVoltageLevelGenerators(networkUuid, variantNum, voltageLevelId); } @Override public void removeGenerators(UUID networkUuid, int variantNum, List<String> generatorsId) { ensureCached(ResourceType.GENERATOR, networkUuid, variantNum); delegate.removeGenerators(networkUuid, variantNum, generatorsId); } @Override public List<Resource<BatteryAttributes>> getVoltageLevelBatteries(UUID networkUuid, int variantNum, String voltageLevelId) { ensureCached(ResourceType.BATTERY, networkUuid, variantNum); return delegate.getVoltageLevelBatteries(networkUuid, variantNum, voltageLevelId); } @Override public void removeBatteries(UUID networkUuid, int variantNum, List<String> batteriesId) { ensureCached(ResourceType.BATTERY, networkUuid, variantNum); delegate.removeBatteries(networkUuid, variantNum, batteriesId); } @Override public List<Resource<LoadAttributes>> getVoltageLevelLoads(UUID networkUuid, int variantNum, String voltageLevelId) { ensureCached(ResourceType.LOAD, networkUuid, variantNum); return delegate.getVoltageLevelLoads(networkUuid, variantNum, voltageLevelId); } @Override public void removeLoads(UUID networkUuid, int variantNum, List<String> loadsId) { ensureCached(ResourceType.LOAD, networkUuid, variantNum); delegate.removeLoads(networkUuid, variantNum, loadsId); } @Override public List<Resource<ShuntCompensatorAttributes>> getVoltageLevelShuntCompensators(UUID networkUuid, int variantNum, String voltageLevelId) { ensureCached(ResourceType.SHUNT_COMPENSATOR, networkUuid, variantNum); return delegate.getVoltageLevelShuntCompensators(networkUuid, variantNum, voltageLevelId); } @Override public void removeShuntCompensators(UUID networkUuid, int variantNum, List<String> shuntCompensatorsId) { ensureCached(ResourceType.SHUNT_COMPENSATOR, networkUuid, variantNum); delegate.removeShuntCompensators(networkUuid, variantNum, shuntCompensatorsId); } @Override public List<Resource<StaticVarCompensatorAttributes>> getVoltageLevelStaticVarCompensators(UUID networkUuid, int variantNum, String voltageLevelId) { ensureCached(ResourceType.STATIC_VAR_COMPENSATOR, networkUuid, variantNum); return delegate.getVoltageLevelStaticVarCompensators(networkUuid, variantNum, voltageLevelId); } @Override public void removeStaticVarCompensators(UUID networkUuid, int variantNum, List<String> staticVarCompensatorsId) { ensureCached(ResourceType.STATIC_VAR_COMPENSATOR, networkUuid, variantNum); delegate.removeStaticVarCompensators(networkUuid, variantNum, staticVarCompensatorsId); } @Override public List<Resource<VscConverterStationAttributes>> getVoltageLevelVscConverterStations(UUID networkUuid, int variantNum, String voltageLevelId) { ensureCached(ResourceType.VSC_CONVERTER_STATION, networkUuid, variantNum); return delegate.getVoltageLevelVscConverterStations(networkUuid, variantNum, voltageLevelId); } @Override public void removeVscConverterStations(UUID networkUuid, int variantNum, List<String> vscConverterStationsId) { ensureCached(ResourceType.VSC_CONVERTER_STATION, networkUuid, variantNum); delegate.removeVscConverterStations(networkUuid, variantNum, vscConverterStationsId); } @Override public List<Resource<LccConverterStationAttributes>> getVoltageLevelLccConverterStations(UUID networkUuid, int variantNum, String voltageLevelId) { ensureCached(ResourceType.LCC_CONVERTER_STATION, networkUuid, variantNum); return delegate.getVoltageLevelLccConverterStations(networkUuid, variantNum, voltageLevelId); } @Override public void removeLccConverterStations(UUID networkUuid, int variantNum, List<String> lccConverterStationsId) { ensureCached(ResourceType.LCC_CONVERTER_STATION, networkUuid, variantNum); delegate.removeLccConverterStations(networkUuid, variantNum, lccConverterStationsId); } @Override public List<Resource<GroundAttributes>> getVoltageLevelGrounds(UUID networkUuid, int variantNum, String voltageLevelId) { ensureCached(ResourceType.GROUND, networkUuid, variantNum); return delegate.getVoltageLevelGrounds(networkUuid, variantNum, voltageLevelId); } @Override public void removeGrounds(UUID networkUuid, int variantNum, List<String> groundsId) { ensureCached(ResourceType.GROUND, networkUuid, variantNum); delegate.removeGrounds(networkUuid, variantNum, groundsId); } @Override public List<Resource<TwoWindingsTransformerAttributes>> getVoltageLevelTwoWindingsTransformers(UUID networkUuid, int variantNum, String voltageLevelId) { ensureCached(ResourceType.TWO_WINDINGS_TRANSFORMER, networkUuid, variantNum); return delegate.getVoltageLevelTwoWindingsTransformers(networkUuid, variantNum, voltageLevelId); } @Override public void removeTwoWindingsTransformers(UUID networkUuid, int variantNum, List<String> twoWindingsTransformersId) { ensureCached(ResourceType.TWO_WINDINGS_TRANSFORMER, networkUuid, variantNum); delegate.removeTwoWindingsTransformers(networkUuid, variantNum, twoWindingsTransformersId); } @Override public List<Resource<ThreeWindingsTransformerAttributes>> getVoltageLevelThreeWindingsTransformers(UUID networkUuid, int variantNum, String voltageLevelId) { ensureCached(ResourceType.THREE_WINDINGS_TRANSFORMER, networkUuid, variantNum); return delegate.getVoltageLevelThreeWindingsTransformers(networkUuid, variantNum, voltageLevelId); } @Override public void removeThreeWindingsTransformers(UUID networkUuid, int variantNum, List<String> threeWindingsTransformersId) { ensureCached(ResourceType.THREE_WINDINGS_TRANSFORMER, networkUuid, variantNum); delegate.removeThreeWindingsTransformers(networkUuid, variantNum, threeWindingsTransformersId); } @Override public List<Resource<LineAttributes>> getVoltageLevelLines(UUID networkUuid, int variantNum, String voltageLevelId) { ensureCached(ResourceType.LINE, networkUuid, variantNum); return delegate.getVoltageLevelLines(networkUuid, variantNum, voltageLevelId); } @Override public void removeLines(UUID networkUuid, int variantNum, List<String> linesId) { ensureCached(ResourceType.LINE, networkUuid, variantNum); delegate.removeLines(networkUuid, variantNum, linesId); } @Override public List<Resource<DanglingLineAttributes>> getVoltageLevelDanglingLines(UUID networkUuid, int variantNum, String voltageLevelId) { ensureCached(ResourceType.DANGLING_LINE, networkUuid, variantNum); return delegate.getVoltageLevelDanglingLines(networkUuid, variantNum, voltageLevelId); } @Override public void createSwitches(UUID networkUuid, List<Resource<SwitchAttributes>> switchResources) { for (Resource<SwitchAttributes> switchResource : switchResources) { ensureCached(ResourceType.SWITCH, networkUuid, switchResource.getVariantNum()); } delegate.createSwitches(networkUuid, switchResources); } @Override public List<Resource<SwitchAttributes>> getSwitches(UUID networkUuid, int variantNum) { ensureCached(ResourceType.SWITCH, networkUuid, variantNum); return delegate.getSwitches(networkUuid, variantNum); } @Override public Optional<Resource<SwitchAttributes>> getSwitch(UUID networkUuid, int variantNum, String switchId) { ensureCached(ResourceType.SWITCH, networkUuid, variantNum); return delegate.getSwitch(networkUuid, variantNum, switchId); } @Override public void updateSwitches(UUID networkUuid, List<Resource<SwitchAttributes>> switchResources, AttributeFilter attributeFilter) { for (Resource<SwitchAttributes> switchResource : switchResources) { ensureCached(ResourceType.SWITCH, networkUuid, switchResource.getVariantNum()); } delegate.updateSwitches(networkUuid, switchResources, attributeFilter); } @Override public void removeSwitches(UUID networkUuid, int variantNum, List<String> switchesId) { ensureCached(ResourceType.SWITCH, networkUuid, variantNum); delegate.removeSwitches(networkUuid, variantNum, switchesId); } @Override public void createBusbarSections(UUID networkUuid, List<Resource<BusbarSectionAttributes>> busbarSectionResources) { for (Resource<BusbarSectionAttributes> busbarSectionResource : busbarSectionResources) { ensureCached(ResourceType.BUSBAR_SECTION, networkUuid, busbarSectionResource.getVariantNum()); } delegate.createBusbarSections(networkUuid, busbarSectionResources); } @Override public List<Resource<BusbarSectionAttributes>> getBusbarSections(UUID networkUuid, int variantNum) { ensureCached(ResourceType.BUSBAR_SECTION, networkUuid, variantNum); return delegate.getBusbarSections(networkUuid, variantNum); } @Override public Optional<Resource<BusbarSectionAttributes>> getBusbarSection(UUID networkUuid, int variantNum, String busbarSectionId) { ensureCached(ResourceType.BUSBAR_SECTION, networkUuid, variantNum); return delegate.getBusbarSection(networkUuid, variantNum, busbarSectionId); } @Override public void updateBusbarSections(UUID networkUuid, List<Resource<BusbarSectionAttributes>> busbarSectionResources, AttributeFilter attributeFilter) { for (Resource<BusbarSectionAttributes> busbarSectionResource : busbarSectionResources) { ensureCached(ResourceType.BUSBAR_SECTION, networkUuid, busbarSectionResource.getVariantNum()); } delegate.updateBusbarSections(networkUuid, busbarSectionResources, attributeFilter); } @Override public void createLoads(UUID networkUuid, List<Resource<LoadAttributes>> loadResources) { for (Resource<LoadAttributes> loadResource : loadResources) { ensureCached(ResourceType.LOAD, networkUuid, loadResource.getVariantNum()); } delegate.createLoads(networkUuid, loadResources); } @Override public List<Resource<LoadAttributes>> getLoads(UUID networkUuid, int variantNum) { ensureCached(ResourceType.LOAD, networkUuid, variantNum); return delegate.getLoads(networkUuid, variantNum); } @Override public Optional<Resource<LoadAttributes>> getLoad(UUID networkUuid, int variantNum, String loadId) { ensureCached(ResourceType.LOAD, networkUuid, variantNum); return delegate.getLoad(networkUuid, variantNum, loadId); } @Override public void updateLoads(UUID networkUuid, List<Resource<LoadAttributes>> loadResources, AttributeFilter attributeFilter) { for (Resource<LoadAttributes> loadResource : loadResources) { ensureCached(ResourceType.LOAD, networkUuid, loadResource.getVariantNum()); } delegate.updateLoads(networkUuid, loadResources, attributeFilter); } @Override public void createGenerators(UUID networkUuid, List<Resource<GeneratorAttributes>> generatorResources) { for (Resource<GeneratorAttributes> generatorResource : generatorResources) { ensureCached(ResourceType.GENERATOR, networkUuid, generatorResource.getVariantNum()); } delegate.createGenerators(networkUuid, generatorResources); } @Override public List<Resource<GeneratorAttributes>> getGenerators(UUID networkUuid, int variantNum) { ensureCached(ResourceType.GENERATOR, networkUuid, variantNum); return delegate.getGenerators(networkUuid, variantNum); } @Override public Optional<Resource<GeneratorAttributes>> getGenerator(UUID networkUuid, int variantNum, String generatorId) { ensureCached(ResourceType.GENERATOR, networkUuid, variantNum); return delegate.getGenerator(networkUuid, variantNum, generatorId); } @Override public void updateGenerators(UUID networkUuid, List<Resource<GeneratorAttributes>> generatorResources, AttributeFilter attributeFilter) { for (Resource<GeneratorAttributes> generatorResource : generatorResources) { ensureCached(ResourceType.GENERATOR, networkUuid, generatorResource.getVariantNum()); } delegate.updateGenerators(networkUuid, generatorResources, attributeFilter); } @Override public void createBatteries(UUID networkUuid, List<Resource<BatteryAttributes>> batteryResources) { for (Resource<BatteryAttributes> batteryResource : batteryResources) { ensureCached(ResourceType.BATTERY, networkUuid, batteryResource.getVariantNum()); } delegate.createBatteries(networkUuid, batteryResources); } @Override public List<Resource<BatteryAttributes>> getBatteries(UUID networkUuid, int variantNum) { ensureCached(ResourceType.BATTERY, networkUuid, variantNum); return delegate.getBatteries(networkUuid, variantNum); } @Override public Optional<Resource<BatteryAttributes>> getBattery(UUID networkUuid, int variantNum, String batteryId) { ensureCached(ResourceType.BATTERY, networkUuid, variantNum); return delegate.getBattery(networkUuid, variantNum, batteryId); } @Override public void updateBatteries(UUID networkUuid, List<Resource<BatteryAttributes>> batteryResources, AttributeFilter attributeFilter) { for (Resource<BatteryAttributes> batteryResource : batteryResources) { ensureCached(ResourceType.BATTERY, networkUuid, batteryResource.getVariantNum()); } delegate.updateBatteries(networkUuid, batteryResources, attributeFilter); } @Override public void createGrounds(UUID networkUuid, List<Resource<GroundAttributes>> groundResources) { for (Resource<GroundAttributes> groundResource : groundResources) { ensureCached(ResourceType.GROUND, networkUuid, groundResource.getVariantNum()); } delegate.createGrounds(networkUuid, groundResources); } @Override public List<Resource<GroundAttributes>> getGrounds(UUID networkUuid, int variantNum) { ensureCached(ResourceType.GROUND, networkUuid, variantNum); return delegate.getGrounds(networkUuid, variantNum); } @Override public Optional<Resource<GroundAttributes>> getGround(UUID networkUuid, int variantNum, String groundId) { ensureCached(ResourceType.GROUND, networkUuid, variantNum); return delegate.getGround(networkUuid, variantNum, groundId); } @Override public void updateGrounds(UUID networkUuid, List<Resource<GroundAttributes>> groundResources, AttributeFilter attributeFilter) { for (Resource<GroundAttributes> groundResource : groundResources) { ensureCached(ResourceType.GROUND, networkUuid, groundResource.getVariantNum()); } delegate.updateGrounds(networkUuid, groundResources, attributeFilter); } @Override public void createTwoWindingsTransformers(UUID networkUuid, List<Resource<TwoWindingsTransformerAttributes>> twoWindingsTransformerResources) { for (Resource<TwoWindingsTransformerAttributes> twoWindingsTransformerResource : twoWindingsTransformerResources) { ensureCached(ResourceType.TWO_WINDINGS_TRANSFORMER, networkUuid, twoWindingsTransformerResource.getVariantNum()); } delegate.createTwoWindingsTransformers(networkUuid, twoWindingsTransformerResources); } @Override public List<Resource<TwoWindingsTransformerAttributes>> getTwoWindingsTransformers(UUID networkUuid, int variantNum) { ensureCached(ResourceType.TWO_WINDINGS_TRANSFORMER, networkUuid, variantNum); return delegate.getTwoWindingsTransformers(networkUuid, variantNum); } @Override public Optional<Resource<TwoWindingsTransformerAttributes>> getTwoWindingsTransformer(UUID networkUuid, int variantNum, String twoWindingsTransformerId) { ensureCached(ResourceType.TWO_WINDINGS_TRANSFORMER, networkUuid, variantNum); return delegate.getTwoWindingsTransformer(networkUuid, variantNum, twoWindingsTransformerId); } @Override public void updateTwoWindingsTransformers(UUID networkUuid, List<Resource<TwoWindingsTransformerAttributes>> twoWindingsTransformerResources, AttributeFilter attributeFilter) { for (Resource<TwoWindingsTransformerAttributes> twoWindingsTransformerResource : twoWindingsTransformerResources) { ensureCached(ResourceType.TWO_WINDINGS_TRANSFORMER, networkUuid, twoWindingsTransformerResource.getVariantNum()); } delegate.updateTwoWindingsTransformers(networkUuid, twoWindingsTransformerResources, attributeFilter); } // 3 windings transformer @Override public void createThreeWindingsTransformers(UUID networkUuid, List<Resource<ThreeWindingsTransformerAttributes>> threeWindingsTransformerResources) { for (Resource<ThreeWindingsTransformerAttributes> threeWindingsTransformerResource : threeWindingsTransformerResources) { ensureCached(ResourceType.THREE_WINDINGS_TRANSFORMER, networkUuid, threeWindingsTransformerResource.getVariantNum()); } delegate.createThreeWindingsTransformers(networkUuid, threeWindingsTransformerResources); } @Override public List<Resource<ThreeWindingsTransformerAttributes>> getThreeWindingsTransformers(UUID networkUuid, int variantNum) { ensureCached(ResourceType.THREE_WINDINGS_TRANSFORMER, networkUuid, variantNum); return delegate.getThreeWindingsTransformers(networkUuid, variantNum); } @Override public Optional<Resource<ThreeWindingsTransformerAttributes>> getThreeWindingsTransformer(UUID networkUuid, int variantNum, String threeWindingsTransformerId) { ensureCached(ResourceType.THREE_WINDINGS_TRANSFORMER, networkUuid, variantNum); return delegate.getThreeWindingsTransformer(networkUuid, variantNum, threeWindingsTransformerId); } @Override public void updateThreeWindingsTransformers(UUID networkUuid, List<Resource<ThreeWindingsTransformerAttributes>> threeWindingsTransformerResources, AttributeFilter attributeFilter) { for (Resource<ThreeWindingsTransformerAttributes> threeWindingsTransformerResource : threeWindingsTransformerResources) { ensureCached(ResourceType.THREE_WINDINGS_TRANSFORMER, networkUuid, threeWindingsTransformerResource.getVariantNum()); } delegate.updateThreeWindingsTransformers(networkUuid, threeWindingsTransformerResources, attributeFilter); } @Override public void createLines(UUID networkUuid, List<Resource<LineAttributes>> lineResources) { for (Resource<LineAttributes> lineResource : lineResources) { ensureCached(ResourceType.LINE, networkUuid, lineResource.getVariantNum()); } delegate.createLines(networkUuid, lineResources); } @Override public List<Resource<LineAttributes>> getLines(UUID networkUuid, int variantNum) { ensureCached(ResourceType.LINE, networkUuid, variantNum); return delegate.getLines(networkUuid, variantNum); } @Override public Optional<Resource<LineAttributes>> getLine(UUID networkUuid, int variantNum, String lineId) { ensureCached(ResourceType.LINE, networkUuid, variantNum); return delegate.getLine(networkUuid, variantNum, lineId); } @Override public void updateLines(UUID networkUuid, List<Resource<LineAttributes>> lineResources, AttributeFilter attributeFilter) { for (Resource<LineAttributes> lineResource : lineResources) { ensureCached(ResourceType.LINE, networkUuid, lineResource.getVariantNum()); } delegate.updateLines(networkUuid, lineResources, attributeFilter); } @Override public void createShuntCompensators(UUID networkUuid, List<Resource<ShuntCompensatorAttributes>> shuntCompensatorResources) { for (Resource<ShuntCompensatorAttributes> shuntCompensatorResource : shuntCompensatorResources) { ensureCached(ResourceType.SHUNT_COMPENSATOR, networkUuid, shuntCompensatorResource.getVariantNum()); } delegate.createShuntCompensators(networkUuid, shuntCompensatorResources); } @Override public List<Resource<ShuntCompensatorAttributes>> getShuntCompensators(UUID networkUuid, int variantNum) { ensureCached(ResourceType.SHUNT_COMPENSATOR, networkUuid, variantNum); return delegate.getShuntCompensators(networkUuid, variantNum); } @Override public Optional<Resource<ShuntCompensatorAttributes>> getShuntCompensator(UUID networkUuid, int variantNum, String shuntCompensatorId) { ensureCached(ResourceType.SHUNT_COMPENSATOR, networkUuid, variantNum); return delegate.getShuntCompensator(networkUuid, variantNum, shuntCompensatorId); } @Override public void updateShuntCompensators(UUID networkUuid, List<Resource<ShuntCompensatorAttributes>> shuntCompensatorResources, AttributeFilter attributeFilter) { for (Resource<ShuntCompensatorAttributes> shuntCompensatorResource : shuntCompensatorResources) { ensureCached(ResourceType.SHUNT_COMPENSATOR, networkUuid, shuntCompensatorResource.getVariantNum()); } delegate.updateShuntCompensators(networkUuid, shuntCompensatorResources, attributeFilter); } @Override public void createVscConverterStations(UUID networkUuid, List<Resource<VscConverterStationAttributes>> vscConverterStationResources) { for (Resource<VscConverterStationAttributes> vscConverterStationResource : vscConverterStationResources) { ensureCached(ResourceType.VSC_CONVERTER_STATION, networkUuid, vscConverterStationResource.getVariantNum()); } delegate.createVscConverterStations(networkUuid, vscConverterStationResources); } @Override public List<Resource<VscConverterStationAttributes>> getVscConverterStations(UUID networkUuid, int variantNum) { ensureCached(ResourceType.VSC_CONVERTER_STATION, networkUuid, variantNum); return delegate.getVscConverterStations(networkUuid, variantNum); } @Override public Optional<Resource<VscConverterStationAttributes>> getVscConverterStation(UUID networkUuid, int variantNum, String vscConverterStationId) { ensureCached(ResourceType.VSC_CONVERTER_STATION, networkUuid, variantNum); return delegate.getVscConverterStation(networkUuid, variantNum, vscConverterStationId); } @Override public void updateVscConverterStations(UUID networkUuid, List<Resource<VscConverterStationAttributes>> vscConverterStationResources, AttributeFilter attributeFilter) { for (Resource<VscConverterStationAttributes> vscConverterStationResource : vscConverterStationResources) { ensureCached(ResourceType.VSC_CONVERTER_STATION, networkUuid, vscConverterStationResource.getVariantNum()); } delegate.updateVscConverterStations(networkUuid, vscConverterStationResources, attributeFilter); } @Override public void createLccConverterStations(UUID networkUuid, List<Resource<LccConverterStationAttributes>> lccConverterStationResources) { for (Resource<LccConverterStationAttributes> lccConverterStationResource : lccConverterStationResources) { ensureCached(ResourceType.LCC_CONVERTER_STATION, networkUuid, lccConverterStationResource.getVariantNum()); } delegate.createLccConverterStations(networkUuid, lccConverterStationResources); } @Override public List<Resource<LccConverterStationAttributes>> getLccConverterStations(UUID networkUuid, int variantNum) { ensureCached(ResourceType.LCC_CONVERTER_STATION, networkUuid, variantNum); return delegate.getLccConverterStations(networkUuid, variantNum); } @Override public Optional<Resource<LccConverterStationAttributes>> getLccConverterStation(UUID networkUuid, int variantNum, String lccConverterStationId) { ensureCached(ResourceType.LCC_CONVERTER_STATION, networkUuid, variantNum); return delegate.getLccConverterStation(networkUuid, variantNum, lccConverterStationId); } @Override public void updateLccConverterStations(UUID networkUuid, List<Resource<LccConverterStationAttributes>> lccConverterStationResources, AttributeFilter attributeFilter) { for (Resource<LccConverterStationAttributes> lccConverterStationResource : lccConverterStationResources) { ensureCached(ResourceType.LCC_CONVERTER_STATION, networkUuid, lccConverterStationResource.getVariantNum()); } delegate.updateLccConverterStations(networkUuid, lccConverterStationResources, attributeFilter); } @Override public void createStaticVarCompensators(UUID networkUuid, List<Resource<StaticVarCompensatorAttributes>> svcResources) { for (Resource<StaticVarCompensatorAttributes> svcResource : svcResources) { ensureCached(ResourceType.STATIC_VAR_COMPENSATOR, networkUuid, svcResource.getVariantNum()); } delegate.createStaticVarCompensators(networkUuid, svcResources); } @Override public List<Resource<StaticVarCompensatorAttributes>> getStaticVarCompensators(UUID networkUuid, int variantNum) { ensureCached(ResourceType.STATIC_VAR_COMPENSATOR, networkUuid, variantNum); return delegate.getStaticVarCompensators(networkUuid, variantNum); } @Override public Optional<Resource<StaticVarCompensatorAttributes>> getStaticVarCompensator(UUID networkUuid, int variantNum, String staticVarCompensatorId) { ensureCached(ResourceType.STATIC_VAR_COMPENSATOR, networkUuid, variantNum); return delegate.getStaticVarCompensator(networkUuid, variantNum, staticVarCompensatorId); } @Override public void updateStaticVarCompensators(UUID networkUuid, List<Resource<StaticVarCompensatorAttributes>> svcResources, AttributeFilter attributeFilter) { for (Resource<StaticVarCompensatorAttributes> svcResource : svcResources) { ensureCached(ResourceType.STATIC_VAR_COMPENSATOR, networkUuid, svcResource.getVariantNum()); } delegate.updateStaticVarCompensators(networkUuid, svcResources, attributeFilter); } @Override public void createHvdcLines(UUID networkUuid, List<Resource<HvdcLineAttributes>> hvdcLineResources) { for (Resource<HvdcLineAttributes> hvdcLineResource : hvdcLineResources) { ensureCached(ResourceType.HVDC_LINE, networkUuid, hvdcLineResource.getVariantNum()); } delegate.createHvdcLines(networkUuid, hvdcLineResources); } @Override public List<Resource<HvdcLineAttributes>> getHvdcLines(UUID networkUuid, int variantNum) { ensureCached(ResourceType.HVDC_LINE, networkUuid, variantNum); return delegate.getHvdcLines(networkUuid, variantNum); } @Override public Optional<Resource<HvdcLineAttributes>> getHvdcLine(UUID networkUuid, int variantNum, String hvdcLineId) { ensureCached(ResourceType.HVDC_LINE, networkUuid, variantNum); return delegate.getHvdcLine(networkUuid, variantNum, hvdcLineId); } @Override public void removeHvdcLines(UUID networkUuid, int variantNum, List<String> hvdcLinesId) { ensureCached(ResourceType.HVDC_LINE, networkUuid, variantNum); delegate.removeHvdcLines(networkUuid, variantNum, hvdcLinesId); } @Override public void updateHvdcLines(UUID networkUuid, List<Resource<HvdcLineAttributes>> hvdcLineResources, AttributeFilter attributeFilter) { for (Resource<HvdcLineAttributes> hvdcLineResource : hvdcLineResources) { ensureCached(ResourceType.HVDC_LINE, networkUuid, hvdcLineResource.getVariantNum()); } delegate.updateHvdcLines(networkUuid, hvdcLineResources, attributeFilter); } @Override public void createDanglingLines(UUID networkUuid, List<Resource<DanglingLineAttributes>> danglingLineResources) { for (Resource<DanglingLineAttributes> danglingLineResource : danglingLineResources) { ensureCached(ResourceType.DANGLING_LINE, networkUuid, danglingLineResource.getVariantNum()); } delegate.createDanglingLines(networkUuid, danglingLineResources); } @Override public List<Resource<DanglingLineAttributes>> getDanglingLines(UUID networkUuid, int variantNum) { ensureCached(ResourceType.DANGLING_LINE, networkUuid, variantNum); return delegate.getDanglingLines(networkUuid, variantNum); } @Override public Optional<Resource<DanglingLineAttributes>> getDanglingLine(UUID networkUuid, int variantNum, String danglingLineId) { ensureCached(ResourceType.DANGLING_LINE, networkUuid, variantNum); return delegate.getDanglingLine(networkUuid, variantNum, danglingLineId); } @Override public void updateDanglingLines(UUID networkUuid, List<Resource<DanglingLineAttributes>> danglingLineResources, AttributeFilter attributeFilter) { for (Resource<DanglingLineAttributes> danglingLineResource : danglingLineResources) { ensureCached(ResourceType.DANGLING_LINE, networkUuid, danglingLineResource.getVariantNum()); } delegate.updateDanglingLines(networkUuid, danglingLineResources, attributeFilter); } @Override public void removeDanglingLines(UUID networkUuid, int variantNum, List<String> danglingLinesId) { ensureCached(ResourceType.DANGLING_LINE, networkUuid, variantNum); delegate.removeDanglingLines(networkUuid, variantNum, danglingLinesId); } @Override public void createTieLines(UUID networkUuid, List<Resource<TieLineAttributes>> tieLineResources) { for (Resource<TieLineAttributes> tieLineResource : tieLineResources) { ensureCached(ResourceType.TIE_LINE, networkUuid, tieLineResource.getVariantNum()); } delegate.createTieLines(networkUuid, tieLineResources); } @Override public List<Resource<TieLineAttributes>> getTieLines(UUID networkUuid, int variantNum) { ensureCached(ResourceType.TIE_LINE, networkUuid, variantNum); return delegate.getTieLines(networkUuid, variantNum); } @Override public Optional<Resource<TieLineAttributes>> getTieLine(UUID networkUuid, int variantNum, String tieLineId) { ensureCached(ResourceType.TIE_LINE, networkUuid, variantNum); return delegate.getTieLine(networkUuid, variantNum, tieLineId); } @Override public void removeTieLines(UUID networkUuid, int variantNum, List<String> tieLinesId) { ensureCached(ResourceType.TIE_LINE, networkUuid, variantNum); delegate.removeTieLines(networkUuid, variantNum, tieLinesId); } @Override public void updateTieLines(UUID networkUuid, List<Resource<TieLineAttributes>> tieLineResources, AttributeFilter attributeFilter) { for (Resource<TieLineAttributes> tieLineResource : tieLineResources) { ensureCached(ResourceType.TIE_LINE, networkUuid, tieLineResource.getVariantNum()); } delegate.updateTieLines(networkUuid, tieLineResources, attributeFilter); } @Override public void createConfiguredBuses(UUID networkUuid, List<Resource<ConfiguredBusAttributes>> busResources) { for (Resource<ConfiguredBusAttributes> busResource : busResources) { ensureCached(ResourceType.CONFIGURED_BUS, networkUuid, busResource.getVariantNum()); } delegate.createConfiguredBuses(networkUuid, busResources); } @Override public List<Resource<ConfiguredBusAttributes>> getConfiguredBuses(UUID networkUuid, int variantNum) { ensureCached(ResourceType.CONFIGURED_BUS, networkUuid, variantNum); return delegate.getConfiguredBuses(networkUuid, variantNum); } @Override public List<Resource<ConfiguredBusAttributes>> getVoltageLevelConfiguredBuses(UUID networkUuid, int variantNum, String voltageLevelId) { ensureCached(ResourceType.CONFIGURED_BUS, networkUuid, variantNum); return delegate.getVoltageLevelConfiguredBuses(networkUuid, variantNum, voltageLevelId); } @Override public Optional<Resource<ConfiguredBusAttributes>> getConfiguredBus(UUID networkUuid, int variantNum, String busId) { ensureCached(ResourceType.CONFIGURED_BUS, networkUuid, variantNum); return delegate.getConfiguredBus(networkUuid, variantNum, busId); } @Override public void updateConfiguredBuses(UUID networkUuid, List<Resource<ConfiguredBusAttributes>> busResources, AttributeFilter attributeFilter) { for (Resource<ConfiguredBusAttributes> busResource : busResources) { ensureCached(ResourceType.CONFIGURED_BUS, networkUuid, busResource.getVariantNum()); } delegate.updateConfiguredBuses(networkUuid, busResources, attributeFilter); } @Override public void removeConfiguredBuses(UUID networkUuid, int variantNum, List<String> configuredBusesId) { ensureCached(ResourceType.CONFIGURED_BUS, networkUuid, variantNum); delegate.removeConfiguredBuses(networkUuid, variantNum, configuredBusesId); } @Override public Optional<ExtensionAttributes> getExtensionAttributes(UUID networkUuid, int variantNum, ResourceType resourceType, String identifiableId, String extensionName) { delegate.getAllExtensionsAttributesByResourceTypeAndExtensionName(networkUuid, variantNum, resourceType, extensionName); return delegate.getExtensionAttributes(networkUuid, variantNum, resourceType, identifiableId, extensionName); } @Override public Map<String, ExtensionAttributes> getAllExtensionsAttributesByIdentifiableId(UUID networkUuid, int variantNum, ResourceType resourceType, String id) { delegate.getAllExtensionsAttributesByResourceType(networkUuid, variantNum, resourceType); return delegate.getAllExtensionsAttributesByIdentifiableId(networkUuid, variantNum, resourceType, id); } }
45,520
Java
.java
758
52.634565
186
0.774387
powsybl/powsybl-network-store
3
6
33
MPL-2.0
9/4/2024, 11:40:22 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
45,520
4,779,132
SqlResDialog.java
patrickbr_ferryleaks/src/com/algebraweb/editor/client/dialogs/SqlResDialog.java
package com.algebraweb.editor.client.dialogs; import java.util.List; import java.util.Map; import com.algebraweb.editor.client.SqlResTable; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.VerticalPanel; /** * A simple dialog to present sql results provided by a JDBC instance using a * SqlResTable * * @author Patrick Brosi * */ public class SqlResDialog extends DialogBox { /** * @param result * the JDBC sql result */ public SqlResDialog(List<Map<String, String>> result) { this.setText("Evaluation results"); SqlResTable t = new SqlResTable(result.size() + 1, result.get(0).size()); t.fill(result); VerticalPanel p = new VerticalPanel(); ScrollPanel s = new ScrollPanel(); s.add(t); p.add(s); Button ok = new Button("Close"); ok.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { SqlResDialog.this.hide(); } }); p.add(ok); this.add(p); this.center(); this.show(); } }
1,223
Java
.java
43
25.837209
77
0.737382
patrickbr/ferryleaks
1
1
0
GPL-2.0
9/5/2024, 12:31:25 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,223
4,600,863
AerobaticLootTables.java
endorh_aerobatic-elytra/src/main/java/endorh/aerobaticelytra/server/loot/AerobaticLootTables.java
package endorh.aerobaticelytra.server.loot; import endorh.aerobaticelytra.AerobaticElytra; import net.minecraft.resources.ResourceLocation; public class AerobaticLootTables { public static final ResourceLocation END_SHIP_ELYTRA = AerobaticElytra.prefix("end_ship_elytra"); }
278
Java
.java
6
44.833333
98
0.862963
endorh/aerobatic-elytra
2
0
1
LGPL-3.0
9/5/2024, 12:18:57 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
278
2,793,592
ObjectFactory.java
minova-afis_aero_minova_rcp/bundles/aero.minova.rcp.form.setup/src/aero/minova/rcp/form/setup/xbs/ObjectFactory.java
package aero.minova.rcp.form.setup.xbs; import javax.xml.bind.annotation.XmlRegistry; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the aero.minova.rcp.form.setup.xbs package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: aero.minova.rcp.form.setup.xbs * */ public ObjectFactory() { } /** * Create an instance of {@link WrapperConf } * */ public WrapperConf createWrapperConf() { return new WrapperConf(); } /** * Create an instance of {@link Log4JConf } * */ public Log4JConf createLog4JConf() { return new Log4JConf(); } /** * Create an instance of {@link Menu } * */ public Menu createMenu() { return new Menu(); } /** * Create an instance of {@link ExecuteJava } * */ public ExecuteJava createExecuteJava() { return new ExecuteJava(); } /** * Create an instance of {@link Preferences } * */ public Preferences createPreferences() { return new Preferences(); } /** * Create an instance of {@link Map } * */ public Map createMap() { return new Map(); } /** * Create an instance of {@link Setup } * */ public Setup createSetup() { return new Setup(); } /** * Create an instance of {@link RequiredModules } * */ public RequiredModules createRequiredModules() { return new RequiredModules(); } /** * Create an instance of {@link Module } * */ public Module createModule() { return new Module(); } /** * Create an instance of {@link Version } * */ public Version createVersion() { return new Version(); } /** * Create an instance of {@link OneOf } * */ public OneOf createOneOf() { return new OneOf(); } /** * Create an instance of {@link MinRequired } * */ public MinRequired createMinRequired() { return new MinRequired(); } /** * Create an instance of {@link RequiredService } * */ public RequiredService createRequiredService() { return new RequiredService(); } /** * Create an instance of {@link Service } * */ public Service createService() { return new Service(); } /** * Create an instance of {@link WrapperConf.Entry } * */ public WrapperConf.Entry createWrapperConfEntry() { return new WrapperConf.Entry(); } /** * Create an instance of {@link Log4JConf.Entry } * */ public Log4JConf.Entry createLog4JConfEntry() { return new Log4JConf.Entry(); } /** * Create an instance of {@link SqlCode } * */ public SqlCode createSqlCode() { return new SqlCode(); } /** * Create an instance of {@link Script } * */ public Script createScript() { return new Script(); } /** * Create an instance of {@link MdiCode } * */ public MdiCode createMdiCode() { return new MdiCode(); } /** * Create an instance of {@link Action } * */ public Action createAction() { return new Action(); } /** * Create an instance of {@link Menu.Entry } * */ public Menu.Entry createMenuEntry() { return new Menu.Entry(); } /** * Create an instance of {@link Toolbar } * */ public Toolbar createToolbar() { return new Toolbar(); } /** * Create an instance of {@link aero.minova.rcp.form.setup.xbs.Entry } * */ public aero.minova.rcp.form.setup.xbs.Entry createEntry() { return new aero.minova.rcp.form.setup.xbs.Entry(); } /** * Create an instance of {@link XbsCode } * */ public XbsCode createXbsCode() { return new XbsCode(); } /** * Create an instance of {@link Node } * */ public Node createNode() { return new Node(); } /** * Create an instance of {@link StaticCode } * */ public StaticCode createStaticCode() { return new StaticCode(); } /** * Create an instance of {@link Static } * */ public Static createStatic() { return new Static(); } /** * Create an instance of {@link CopyFile } * */ public CopyFile createCopyFile() { return new CopyFile(); } /** * Create an instance of {@link Filecopy } * */ public Filecopy createFilecopy() { return new Filecopy(); } /** * Create an instance of {@link Dircopy } * */ public Dircopy createDircopy() { return new Dircopy(); } /** * Create an instance of {@link Schema } * */ public Schema createSchema() { return new Schema(); } /** * Create an instance of {@link Tableschema } * */ public Tableschema createTableschema() { return new Tableschema(); } /** * Create an instance of {@link ExecuteJava.Parameter } * */ public ExecuteJava.Parameter createExecuteJavaParameter() { return new ExecuteJava.Parameter(); } /** * Create an instance of {@link Preferences.Root } * */ public Preferences.Root createPreferencesRoot() { return new Preferences.Root(); } /** * Create an instance of {@link Main } * */ public Main createMain() { return new Main(); } /** * Create an instance of {@link Map.Entry } * */ public Map.Entry createMapEntry() { return new Map.Entry(); } }
6,445
Java
.java
277
17.245487
144
0.577633
minova-afis/aero.minova.rcp
6
2
82
EPL-2.0
9/4/2024, 10:15:27 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,445
4,478,002
ExitButton.java
Smujb_pixel-dungeon-souls/core/src/main/java/com/shatteredpixel/yasd/general/ui/ExitButton.java
/* * * * Pixel Dungeon * * Copyright (C) 2012-2015 Oleg Dolya * * * * Shattered Pixel Dungeon * * Copyright (C) 2014-2019 Evan Debenham * * * * Powered Pixel Dungeon * * Copyright (C) 2014-2020 Samuel Braithwaite * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/> * * */ package com.shatteredpixel.yasd.general.ui; import com.shatteredpixel.yasd.general.PDSGame; import com.shatteredpixel.yasd.general.scenes.TitleScene; import com.watabou.noosa.Game; import com.watabou.noosa.Image; public class ExitButton extends IconButton { protected Image image; public ExitButton() { super(Icons.EXIT.get()); width = 20; height = 20; } @Override protected void onClick() { if (Game.scene() instanceof TitleScene) { Game.instance.finish(); } else { PDSGame.switchNoFade( TitleScene.class ); } } }
1,473
Java
.java
47
29.148936
74
0.725159
Smujb/pixel-dungeon-souls
2
1
0
GPL-3.0
9/5/2024, 12:14:28 AM (Europe/Amsterdam)
false
false
false
false
false
true
true
false
1,473
3,612,866
GrammarBlock.java
CARiSMA-Tool_carisma-tool/plugins/carisma.evolution.uml2.umlchange/src/carisma/evolution/uml2/umlchange/datatype/GrammarBlock.java
/******************************************************************************* * Copyright (c) 2011 Software Engineering Institute, TU Dortmund. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * {SecSE group} - initial API and implementation and/or initial documentation *******************************************************************************/ package carisma.evolution.uml2.umlchange.datatype; import java.util.ArrayList; import java.util.List; /** * A class to encapsulate UMLchange grammar strings. * @author Daniel Warzecha * */ public class GrammarBlock { /** * The original String function the GrammarBlock * is initialized with. */ private String grammarString = null; /** * The alternatives. */ private List<GrammarAlternative> alternatives = null; public GrammarBlock(final String grammar) { this.grammarString = grammar.trim(); this.alternatives = new ArrayList<>(); List<String> extractedAlternatives = ParserUtils.extract( this.grammarString, ','); for (String extractedAlternative : extractedAlternatives) { this.alternatives.add(new GrammarAlternative(extractedAlternative)); } } public String getGrammarString() { return this.grammarString; } public List<GrammarAlternative> getAlternatives() { return this.alternatives; } public boolean hasNamespaceDescriptions() { for (GrammarAlternative alt : this.alternatives) { if (alt.hasNamespaceDescription()) { return true; } } return false; } public boolean isValid() { if (this.alternatives == null || this.alternatives.isEmpty()) { return false; } if (this.grammarString == null || this.grammarString.isEmpty()) { return false; } for (GrammarAlternative alt : this.alternatives) { if (!alt.isValid()) { return false; } } return true; } }
2,133
Java
.java
67
27.731343
82
0.664047
CARiSMA-Tool/carisma-tool
3
5
13
EPL-1.0
9/4/2024, 11:35:33 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,133
2,947,302
VariableErrorEvent.java
mhdirkse_counting-language/counting-language-impl/src/main/java/com/github/mhdirkse/countlang/analysis/VariableErrorEvent.java
/* * Copyright Martijn Dirkse 2021 * * This file is part of counting-language. * * counting-language is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.github.mhdirkse.countlang.analysis; import com.github.mhdirkse.countlang.tasks.StatusCode; import com.github.mhdirkse.countlang.tasks.StatusReporter; import com.github.mhdirkse.countlang.type.CountlangType; import lombok.Getter; class VariableErrorEvent { static enum Kind { DOES_NOT_EXIST, DUPLICATE_PARAMETER, TYPE_MISMATCH; } private final @Getter Kind kind; private final @Getter String name; private final @Getter int line; private final @Getter int column; private final @Getter CountlangType variableType; private final @Getter CountlangType typeMismatch; VariableErrorEvent(Kind kind, String name, int line, int column) { if(kind == Kind.TYPE_MISMATCH) { throw new IllegalArgumentException("Do not use this constructor for type mismatches - you need to set the types involved"); } this.kind = kind; this.name = name; this.line = line; this.column = column; this.variableType = null; this.typeMismatch = null; } VariableErrorEvent(String name, int line, int column, CountlangType variableType, CountlangType typeMismatch) { this.kind = Kind.TYPE_MISMATCH; this.name = name; this.line = line; this.column = column; this.variableType = variableType; this.typeMismatch = typeMismatch; } public void report(StatusReporter reporter) { switch(kind) { case DOES_NOT_EXIST: reporter.report(StatusCode.VAR_UNDEFINED, line, column, name); break; case DUPLICATE_PARAMETER: reporter.report(StatusCode.DUPLICATE_PARAMETER, line, column, name); break; case TYPE_MISMATCH: reporter.report(StatusCode.VAR_TYPE_CHANGED, line, column, name); break; } } }
2,628
Java
.java
68
32.632353
135
0.700627
mhdirkse/counting-language
5
0
7
AGPL-3.0
9/4/2024, 10:37:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,628
3,227,159
UserService.java
eduyayo_gamesboard/modules/HubServer/src/main/java/com/pigdroid/hub/service/impl/UserService.java
package com.pigdroid.hub.service.impl; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.github.sendgrid.SendGrid; import com.pigdroid.hub.dao.CRUDInterface; import com.pigdroid.hub.dao.UserDAOInterface; import com.pigdroid.hub.model.message.HubMessage; import com.pigdroid.hub.model.message.MessageContext; import com.pigdroid.hub.model.persistent.User; import com.pigdroid.hub.model.persistent.UserExample; import com.pigdroid.hub.service.MessageServiceInterface; import com.pigdroid.hub.service.UserServiceInterface; import com.pigdroid.hub.service.exception.UserCredentialsException; import flexjson.JSONSerializer; @Service @Transactional public class UserService extends BaseService<User> implements UserServiceInterface { private MessageServiceInterface messageService; public void setMessageService(MessageServiceInterface messageService) { this.messageService = messageService; } public void setUserDAO(CRUDInterface<User> in) { this.dao = in; } private UserDAOInterface getUserDao() { return (UserDAOInterface) dao; } public User createUserIfNotExists(String email, String password, String alias) throws UserCredentialsException { User user = new User(); user.setEmail(email); user.setNickName(alias); boolean exists = count(user) == 1; user.setPassword(password); boolean hasCredentials = count(user) == 1; if (!exists) { save(user); } else if (!hasCredentials) { throw new UserCredentialsException(); } return user; } public boolean exists(String email) { User user = new User(); user.setEmail(email); boolean exists = count(user) == 1; return exists; } public void doLogin(MessageContext context) { HubMessage msg = context.getMessage(); User user = checkUser(msg); if (user != null) { context.setUserEmail(msg.getFrom()); HubMessage newMsg = new HubMessage(HubMessage.TYPE_ACK, HubMessage.TYPE_LOGIN); newMsg.setPayload(createSerializer().deepSerialize(user)); newMsg.addTo(msg.getFrom()); messageService.sendMessage(context, newMsg); } else { // Login failed messageService.sendErrorMessage(context); } } private User checkUser(HubMessage msg) { String email = msg.getFrom(); String password = msg.getWhat(); User user = null; User example = new User(); example.setPassword(password); example.setEmail(email); user = get(example); return user; } public User checkUser(MessageContext context) { HubMessage msg = context.getMessage(); return checkUser(msg); } public void doRegister(MessageContext context) { HubMessage msg = context.getMessage(); String email = msg.getFrom(); String password = msg.getWhat(); String alias = msg.getPayload(); HubMessage message = null; try { createUserIfNotExists(email, password, alias); message = new HubMessage(HubMessage.TYPE_ACK, HubMessage.TYPE_REGISTER); } catch (UserCredentialsException e) { message = new HubMessage(HubMessage.TYPE_ERROR, HubMessage.TYPE_REGISTER, "USER_EXISTS"); messageService.sendMessage(context, message); } messageService.sendMessageToSession(context, message); } @Override public void doAddContact(MessageContext context) { HubMessage msg = context.getMessage(); String email = msg.getTo().get(0); User addedUser = new User(); addedUser.setEmail(email); addedUser = get(addedUser); if (addedUser != null) { JSONSerializer serializer = createSerializer(); //Found the user, add him to the list of contacts for this session. HubMessage messageToUserInSession = new HubMessage(HubMessage.TYPE_ACK, HubMessage.TYPE_ADD_CONTACT); messageToUserInSession.addTo(context.getUserEmail()); messageToUserInSession.setPayload(serializer.deepSerialize(addedUser)); //Notify the destination of the contact about this event HubMessage messageToAddedUser = new HubMessage(HubMessage.TYPE_ADD_CONTACT); messageToAddedUser.addTo(addedUser.getEmail()); User contextUser = getContextUser(context); contextUser.getContacts().add(addedUser); save(contextUser); //Avoid the serialization of private data. messageToAddedUser.setPayload(serializer.deepSerialize(contextUser)); messageService.sendMessage(context, messageToAddedUser, true); messageService.sendMessage(context, messageToUserInSession); } else { HubMessage message = new HubMessage(HubMessage.TYPE_ERROR, HubMessage.TYPE_ADD_CONTACT); message.setTo(msg.getTo()); message.setType("NOT_FOUND"); messageService.sendMessage(context, message); } } private JSONSerializer createSerializer() { JSONSerializer serializer = new JSONSerializer().exclude("contacts", "password", "games", "messages"); return serializer; } private User getContextUser(MessageContext context) { User userInSession = new User(); userInSession.setEmail(context.getUserEmail()); userInSession = get(userInSession); return userInSession; } @Override public void doRemoveContact(MessageContext context) { // TODO Auto-generated method stub } @Override public void doRetrieveRooster(MessageContext context) { User user = getContextUser(context); Set<User> contacts = new HashSet<User>(user.getContacts()); Set<User> invited = new HashSet<User>(contacts); List<User> inverseRooster = getWhoAdded(user); invited.removeAll(inverseRooster); contacts.retainAll(inverseRooster); inverseRooster.removeAll(contacts); HubMessage msg = new HubMessage(HubMessage.TYPE_ACK, HubMessage.TYPE_REQUEST_ROOSTER); JSONSerializer serializer = createSerializer(); StringBuilder builder = new StringBuilder(); builder.append("["); builder.append(serializer.deepSerialize(invited)); // Users that I invited but have not added me. builder.append(","); builder.append(serializer.deepSerialize(contacts)); // Users present for game. Added and added back builder.append(","); builder.append(serializer.deepSerialize(inverseRooster)); // Users that have added me but I have not added back. builder.append("]"); msg.setPayload(builder.toString()); msg.addTo(user.getEmail()); messageService.sendMessage(context, msg); } private List<User> getWhoAdded(User user) { UserDAOInterface dao = getUserDao(); return dao.getWhoAdded(user); } @Override public void doListUsers(MessageContext context) { String searchTerm = context.getMessage().getPayload(); UserExample userExample = new UserExample(); userExample.setEmailLike(searchTerm); userExample.setNickNameLike(searchTerm); User user = getContextUser(context); List<String> emailNotIn = new LinkedList<String>(); for (User contact : user.getContacts()) { emailNotIn.add(contact.getEmail()); } emailNotIn.add(context.getUserEmail()); userExample.setEmailNotIn(emailNotIn); List<User> list = list(userExample); HubMessage msg = new HubMessage(HubMessage.TYPE_ACK, HubMessage.TYPE_USER_LIST); msg.addTo(context.getUserEmail()); JSONSerializer serializer = createSerializer(); msg.setPayload(serializer.deepSerialize(list)); messageService.sendMessage(context, msg); } @Override public void doSendPassword(MessageContext context) { HubMessage msg = context.getMessage(); User user = getContextUser(context); if (user != null) { SendGrid sendgrid = new SendGrid("eduyayo", "mirapuru1"); sendgrid.addTo(user.getEmail()); sendgrid.setFrom("[email protected]"); sendgrid.setSubject("Game Board Password reminder!"); sendgrid.setText("Your current password is: " + user.getPassword() + "."); sendgrid.send(); HubMessage newmsg = new HubMessage(HubMessage.TYPE_ACK, HubMessage.TYPE_SEND_PASS); newmsg.addTo(user.getEmail()); messageService.sendMessage(context, newmsg); } } @Override public User getByEmail(String email) { UserExample example = new UserExample(); example.setEmail(email); return get(example); } }
8,029
Java
.java
211
34.976303
114
0.775418
eduyayo/gamesboard
4
1
0
GPL-3.0
9/4/2024, 11:06:42 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
8,029
879,224
DisplayUtils.java
activityworkshop_GpsPrune/src/tim/prune/gui/DisplayUtils.java
package tim.prune.gui; import java.text.NumberFormat; import tim.prune.I18nManager; /** * Class to provide general display util methods */ public abstract class DisplayUtils { /** Number formatter for one decimal place */ private static final NumberFormat FORMAT_ONE_DP = NumberFormat.getNumberInstance(); /** Static block to initialise the one d.p. formatter */ static { FORMAT_ONE_DP.setMaximumFractionDigits(1); FORMAT_ONE_DP.setMinimumFractionDigits(1); } /** Flexible number formatter with different decimal places */ private static final NumberFormat FORMAT_FLEX = NumberFormat.getNumberInstance(); /** * Build a String to describe a time duration * @param inNumSecs number of seconds * @return time as a string, days, hours, mins, secs as appropriate */ public static String buildDurationString(long inNumSecs) { if (inNumSecs <= 0L) return ""; if (inNumSecs < 60L) return "" + inNumSecs + I18nManager.getText("display.range.time.secs"); if (inNumSecs < 3600L) return "" + (inNumSecs / 60) + I18nManager.getText("display.range.time.mins") + " " + (inNumSecs % 60) + I18nManager.getText("display.range.time.secs"); if (inNumSecs < 86400L) return "" + (inNumSecs / 60 / 60) + I18nManager.getText("display.range.time.hours") + " " + ((inNumSecs / 60) % 60) + I18nManager.getText("display.range.time.mins"); if (inNumSecs < 432000L) return "" + (inNumSecs / 86400L) + I18nManager.getText("display.range.time.days") + " " + (inNumSecs / 60 / 60) % 24 + I18nManager.getText("display.range.time.hours") + " " + ((inNumSecs / 60) % 60) + I18nManager.getText("display.range.time.mins"); if (inNumSecs < 86400000L) return "" + (inNumSecs / 86400L) + I18nManager.getText("display.range.time.days"); return "big"; } /** * @param inNumber number to format * @return formatted number to one decimal place */ public static String formatOneDp(double inNumber) { return FORMAT_ONE_DP.format(inNumber); } /** * Format a number to a sensible precision * @param inVal value to format * @return formatted String using local format */ public static String roundedNumber(double inVal) { // Set precision of formatter int numDigits = 0; if (inVal < 1.0) numDigits = 3; else if (inVal < 10.0) numDigits = 2; else if (inVal < 100.0) numDigits = 1; // set formatter FORMAT_FLEX.setMaximumFractionDigits(numDigits); FORMAT_FLEX.setMinimumFractionDigits(numDigits); return FORMAT_FLEX.format(inVal); } /** * Convert the given hour and minute values into a string H:MM * @param inHour hour of day, 0-24 * @param inMinute minute, 0-59 * @return string, either H:MM or HH:MM */ public static String makeTimeString(int inHour, int inMinute) { StringBuilder sb = new StringBuilder(); final int hour = (inHour >= 0 && inHour <= 24) ? inHour : 0; sb.append(hour); sb.append(':'); final int minute = (inMinute >= 0 && inMinute <= 59) ? inMinute : 0; if (minute <= 9) {sb.append('0');} sb.append(minute); return sb.toString(); } }
3,044
Java
.java
83
33.939759
111
0.709492
activityworkshop/GpsPrune
68
21
25
GPL-2.0
9/4/2024, 7:09:48 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,044
4,881,669
BestellungServiceDelegate.java
heliumv_lpclientpc/src/com/lp/client/frame/delegate/BestellungServiceDelegate.java
/******************************************************************************* * HELIUM V, Open Source ERP software for sustained success * at small and medium-sized enterprises. * Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of theLicense, or * (at your option) any later version. * * According to sec. 7 of the GNU Affero General Public License, version 3, * the terms of the AGPL are supplemented with the following terms: * * "HELIUM V" and "HELIUM 5" are registered trademarks of * HELIUM V IT-Solutions GmbH. The licensing of the program under the * AGPL does not imply a trademark license. Therefore any rights, title and * interest in our trademarks remain entirely with us. If you want to propagate * modified versions of the Program under the name "HELIUM V" or "HELIUM 5", * you may only do so if you have a written permission by HELIUM V IT-Solutions * GmbH (to acquire a permission please contact HELIUM V IT-Solutions * at [email protected]). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact: [email protected] ******************************************************************************/ package com.lp.client.frame.delegate; import java.util.Locale; import java.util.Map; import javax.naming.Context; import javax.naming.InitialContext; import com.lp.client.frame.ExceptionLP; import com.lp.client.pc.LPMain; import com.lp.server.bestellung.service.BestellpositionartDto; import com.lp.server.bestellung.service.BestellungServiceFac; import com.lp.server.bestellung.service.BestellungsartDto; import com.lp.server.bestellung.service.BestellungstatusDto; import com.lp.server.bestellung.service.BestellungtextDto; import com.lp.server.bestellung.service.MahngruppeDto; import com.lp.server.system.service.MediaFac; import com.lp.util.EJBExceptionLP; @SuppressWarnings("static-access") /** * <p>Delegate fuer Bestellung Services.</p> * * <p>Copyright Logistik Pur Software GmbH (c) 2004-2008</p> * * <p>Erstellung: Uli Walch, 27. 04. 2005</p> * * <p>@author Uli Walch</p> * * @version 1.0 * * @version $Revision: 1.8 $ Date $Date: 2011/05/26 09:16:55 $ */ public class BestellungServiceDelegate extends Delegate { private Context context = null; private BestellungServiceFac bestellungServiceFac = null; public BestellungServiceDelegate() throws ExceptionLP { try { context = new InitialContext(); bestellungServiceFac = (BestellungServiceFac) context .lookup("lpserver/BestellungServiceFacBean/remote"); } catch (Throwable t) { throw new ExceptionLP(EJBExceptionLP.FEHLER, t.toString(), null); } } public BestellungtextDto bestellungtextFindByPrimaryKey(Integer iId) throws ExceptionLP { BestellungtextDto oBestellungtextDto = null; try { oBestellungtextDto = bestellungServiceFac .bestellungtextFindByPrimaryKey(iId); } catch (Throwable ex) { handleThrowable(ex); } return oBestellungtextDto; } /** * Den default Kopftext einer Bestellung holen. * * @param pLocKunde * die Sprache des Kunden * @return BestellungtextDto der Kopftext * @throws ExceptionLP */ public BestellungtextDto getBestellungkopfDefault(String pLocKunde) throws ExceptionLP { BestellungtextDto oKoftextDto = null; try { oKoftextDto = bestellungServiceFac .bestellungtextFindByMandantLocaleCNr(LPMain.getInstance() .getTheClient().getMandant(), pLocKunde, MediaFac.MEDIAART_KOPFTEXT, LPMain.getInstance() .getTheClient()); } catch (Throwable t) { handleThrowable(t); } return oKoftextDto; } /** * Den default Fusstext einer Bestellung holen. * * @param pLocKunde * die Sprache des Kunden * @return BestellungtextDto der Fusstext * @throws ExceptionLP */ public BestellungtextDto getBestellungfussDefault(String pLocKunde) throws ExceptionLP { BestellungtextDto oFusstextDto = null; try { oFusstextDto = bestellungServiceFac .bestellungtextFindByMandantLocaleCNr(LPMain.getInstance() .getTheClient().getMandant(), pLocKunde, MediaFac.MEDIAART_FUSSTEXT, LPMain.getInstance() .getTheClient()); } catch (Throwable t) { handleThrowable(t); } return oFusstextDto; } public Integer createBestellungtext(BestellungtextDto bestellungtextDto) throws ExceptionLP { Integer iId = null; try { // fuer StammdatenCRUD : alle Felder, die in der UI nicht vorhanden // sind selbst befuellen bestellungtextDto.setMandantCNr(LPMain.getInstance().getTheClient() .getMandant()); bestellungtextDto.setLocaleCNr(LPMain.getInstance().getTheClient() .getLocUiAsString()); iId = bestellungServiceFac.createBestellungtext(bestellungtextDto); } catch (Throwable ex) { handleThrowable(ex); } return iId; } public void removeBestellungtext(BestellungtextDto bestellungtextDto) throws ExceptionLP { try { bestellungServiceFac.removeBestellungtext(bestellungtextDto); } catch (Throwable ex) { handleThrowable(ex); } } public void updateBestellungtext(BestellungtextDto bestellungtextDto) throws ExceptionLP { try { bestellungServiceFac.updateBestellungtext(bestellungtextDto); } catch (Throwable ex) { handleThrowable(ex); } } public BestellungtextDto bestellungtextFindByMandantLocaleCNr( String sLocaleI, String sCNrI) throws ExceptionLP { BestellungtextDto bestellungtextDto = null; try { bestellungtextDto = bestellungServiceFac .bestellungtextFindByMandantLocaleCNr(LPMain.getInstance() .getTheClient().getMandant(), sLocaleI, sCNrI, LPMain.getInstance().getTheClient()); } catch (Throwable ex) { handleThrowable(ex); } return bestellungtextDto; } public BestellungtextDto createDefaultBestellungtext(String sMediaartI, String sTextinhaltI) throws ExceptionLP { BestellungtextDto bestellungtextDto = null; try { bestellungtextDto = bestellungServiceFac .createDefaultBestellungtext(sMediaartI, sTextinhaltI, LPMain.getInstance().getTheClient()); } catch (Throwable t) { handleThrowable(t); } return bestellungtextDto; } public String createBestellungstatus(BestellungstatusDto bestellungstatusDto) throws ExceptionLP { String cNr = null; try { cNr = bestellungServiceFac .createBestellungstatus(bestellungstatusDto); } catch (Throwable ex) { handleThrowable(ex); } return cNr; } public void createMahngruppe(MahngruppeDto mahngruppeDto) throws ExceptionLP { try { bestellungServiceFac.createMahngruppe(mahngruppeDto); } catch (Throwable ex) { handleThrowable(ex); } } public void removeBestellungsart(BestellungsartDto bestellungartDto) throws ExceptionLP { try { bestellungServiceFac.removeBestellungart(bestellungartDto, LPMain .getInstance().getTheClient()); } catch (Throwable ex) { handleThrowable(ex); } } public void removeMahngruppe(MahngruppeDto mahngruppeDto) throws ExceptionLP { try { bestellungServiceFac.removeMahngruppe(mahngruppeDto); } catch (Throwable ex) { handleThrowable(ex); } } public void removeBestellungstatus(BestellungstatusDto bestellungstatusDto) throws ExceptionLP { try { bestellungServiceFac.removeBestellungstatus(bestellungstatusDto); } catch (Throwable ex) { handleThrowable(ex); } } public void updateBestellungstatus(BestellungstatusDto bestellungstatusDto) throws ExceptionLP { try { bestellungServiceFac.updateBestellungstatus(bestellungstatusDto); } catch (Throwable ex) { handleThrowable(ex); } } public void updateBestellungsart(BestellungsartDto bestellungartDto) throws ExceptionLP { try { bestellungServiceFac.updateBestellungart(bestellungartDto, LPMain .getInstance().getTheClient()); } catch (Throwable ex) { handleThrowable(ex); } } public String createBestellungsart(BestellungsartDto bestellungartDto) throws ExceptionLP { String sBestellungart = null; try { sBestellungart = bestellungServiceFac.createBestellungart( bestellungartDto, LPMain.getInstance().getTheClient()); } catch (Throwable ex) { handleThrowable(ex); } return sBestellungart; } public BestellungsartDto bestellungsartFindByPrimaryKey(String cNr) throws ExceptionLP { BestellungsartDto dto = null; try { dto = bestellungServiceFac.bestellungartFindByPrimaryKey(cNr, LPMain.getInstance().getTheClient()); } catch (Throwable ex) { handleThrowable(ex); } return dto; } public MahngruppeDto mahngruppeFindByPrimaryKey(Integer artgruIId) throws ExceptionLP { MahngruppeDto dto = null; try { dto = bestellungServiceFac.mahngruppeFindByPrimaryKey(artgruIId); } catch (Throwable ex) { handleThrowable(ex); } return dto; } public BestellungstatusDto bestellungstatusFindByPrimaryKey(String cNr) throws ExceptionLP { BestellungstatusDto dto = null; try { dto = bestellungServiceFac.bestellungstatusFindByPrimaryKey(cNr); } catch (Throwable ex) { handleThrowable(ex); } return dto; } /** * Alle Bestellungarten in bestmoeglicher Uebersetzung von der DB holen. * * @param pLocLieferant * das Locale des Lieferanten * @return Map die Bestellungarten mit ihrer Uebersetzung * @throws ExceptionLP * @throws Throwable */ public Map<?, ?> getBestellungsart(Locale pLocLieferant) throws ExceptionLP { Map<?, ?> arten = null; try { arten = bestellungServiceFac.getBestellungart(pLocLieferant, LPMain .getInstance().getUISprLocale()); } catch (Throwable t) { handleThrowable(t); } return arten; } /** * Alle verfuegbaren Bestellpositionsarten in bestmoeglicher Uebersetzung * aus der DB holen. * * @param pLocKunde * Locale * @return Map * @throws ExceptionLP * @throws Throwable */ public Map<String, String> getBestellpositionart(Locale pLocKunde) throws ExceptionLP { Map<String, String> posarten = null; try { posarten = bestellungServiceFac.getBestellpositionart(pLocKunde, LPMain.getInstance().getUISprLocale()); } catch (Throwable t) { handleThrowable(t); } return posarten; } public String createBestellpositionart( BestellpositionartDto bestellpositionartDtoI) throws ExceptionLP { String bestellpositionartCNr = null; try { bestellpositionartCNr = bestellungServiceFac .createBestellpositionart(bestellpositionartDtoI, LPMain .getInstance().getTheClient()); } catch (Throwable t) { handleThrowable(t); } return bestellpositionartCNr; } public void updateBestellpositionart( BestellpositionartDto bestellpositionartDtoI) throws ExceptionLP { try { bestellungServiceFac .updateBestellpositionart(bestellpositionartDtoI, LPMain .getInstance().getTheClient()); } catch (Throwable t) { handleThrowable(t); } } public BestellpositionartDto bestellpositionartFindByPrimaryKey( String cNrBestellpositionartI) throws ExceptionLP { BestellpositionartDto bestellpositionartDto = null; try { bestellpositionartDto = bestellungServiceFac .bestellpositionartFindByPrimaryKey(cNrBestellpositionartI, LPMain.getInstance().getTheClient()); } catch (Throwable t) { handleThrowable(t); } return bestellpositionartDto; } public BestellungsartDto[] getAllBestellungsArt() throws ExceptionLP { BestellungsartDto[] toReturn = null; try { toReturn = bestellungServiceFac.getAllBestellungsArt(); } catch (Throwable t) { handleThrowable(t); } return toReturn; } }
12,107
Java
.java
372
29.198925
80
0.759825
heliumv/lpclientpc
1
3
0
AGPL-3.0
9/5/2024, 12:34:40 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
12,107
3,187,555
DescribeRegionsResponse.java
kuiwang_my-dev/src/main/java/com/aliyun/api/ecs/ecs20140526/response/DescribeRegionsResponse.java
package com.aliyun.api.ecs.ecs20140526.response; import java.util.List; import com.aliyun.api.AliyunResponse; import com.aliyun.api.domain.Region; import com.taobao.api.internal.mapping.ApiField; import com.taobao.api.internal.mapping.ApiListField; /** * TOP API: ecs.aliyuncs.com.DescribeRegions.2014-05-26 response. * * @author auto create * @since 1.0, null */ public class DescribeRegionsResponse extends AliyunResponse { private static final long serialVersionUID = 5139833691291141898L; /** * 地域信息组成的集合 */ @ApiListField("Regions") @ApiField("Region") private List<Region> regions; /** * 请求ID */ @ApiField("RequestId") private String requestId; public List<Region> getRegions() { return this.regions; } public String getRequestId() { return this.requestId; } public void setRegions(List<Region> regions) { this.regions = regions; } public void setRequestId(String requestId) { this.requestId = requestId; } }
1,069
Java
.java
38
23.052632
70
0.708417
kuiwang/my-dev
4
2
0
GPL-3.0
9/4/2024, 11:03:38 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,047
4,398,958
Eventual.java
httpobjects-org_httpobjects/core/src/main/java/org/httpobjects/eventual/Eventual.java
package org.httpobjects.eventual; import java.util.concurrent.Executor; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; public interface Eventual<T> { void then(Consumer<T> fn); <R> Eventual<R> map(Function<T, R> fn); <R> Eventual<R> flatMap(Function<T, Eventual<R>> fn); T join(); static <T> Eventual<T> resolved(T resolution){ final Resolvable<T> r = new Resolvable<T>(); r.resolve(resolution); return r; } static <T> Eventual<T> resolveTo(Supplier<T> action){ final Resolvable<T> r = new Resolvable<T>(); r.resolve(action.get()); return r; } static <T> Eventual<T> resolveAsyncTo(Executor executor, Supplier<T> action){ final Resolvable<T> r = new Resolvable<T>(); executor.execute(()->{ r.resolve(action.get()); }); return r; } }
939
Java
.java
28
27.357143
81
0.643653
httpobjects-org/httpobjects
2
0
0
GPL-2.0
9/5/2024, 12:11:47 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
939
878,206
FeatureVector.java
cemfi_meico/src/meico/pitches/FeatureVector.java
package meico.pitches; import com.github.cliftonlabs.json_simple.JsonArray; import com.github.cliftonlabs.json_simple.JsonObject; /** * This class represents one pitch feature, i.e. an array of FeatureElements that form the feature vector. * @author Axel Berndt. */ public class FeatureVector { private FeatureElement[] feature = null; // a feature vector is an array of feature elements /** * constructor * @param feature the feature vector, i.e. array of FeatureElements */ public FeatureVector(FeatureElement[] feature) { this.feature = feature; } /** * constructor * @param key initializes a 0-vector that conforms the given key */ public FeatureVector(Key key) { this.feature = new FeatureElement[key.getSize()]; for (int i = 0; i < this.feature.length; ++i) { this.feature[i] = new FeatureElement(); } } /** * retrun the getSize of the feature vector * @return */ public int getSize() { return this.feature.length; } /** * this method returns the element of this vector at the given index * @param index * @return */ public FeatureElement getFeatureElement(int index) { return this.feature[index]; } /** * This adds up the energy and note ids of two feature vectors. * But be aware that the vectors should have the same size. Otherwise correctness of this operation cannot be ensured. * @param feature the feature vector to be added * @return */ public boolean add(FeatureVector feature) { int maxIndex = (this.getSize() < feature.getSize()) ? this.getSize() : feature.getSize(); // to avoid IndexOutOfBounds we can only iterate to the smallest maximum index of both vectors for (int i=0; i < maxIndex; ++i) { // go through the vector elements FeatureElement e = feature.getFeatureElement(i); // get the element of the vector to be added this.feature[i].addEnergy(e.getEnergy()); // add its energy this.feature[i].addNoteIds(e.getNoteIds()); // add its note ids } return this.feature.length == feature.getSize(); // if this is true, everything is fine, otherwise it is at the discretion of the application } /** * This adds only an energy vector to the feature vector, no ids. * But be aware that the vectors should have the same size. Otherwise correctness of this operation cannot be ensured. * @param energy * @return */ public boolean addEnergy(double[] energy) { int maxIndex = (this.feature.length < energy.length) ? this.feature.length : energy.length; // to avoid IndexOutOfBounds we can only iterate to the smallest maximum index of both vectors for (int i=0; i < maxIndex; ++i) // go through the vector elements this.feature[i].addEnergy(energy[i]); // add energy return this.feature.length == energy.length; // if this is true, everything is fine, otherwise it is at the discretion of the application } /** * converts this class instance into a JSONObject * @return */ protected JsonObject toJson() { JsonArray energyVector = new JsonArray(); // the energy vector (e.g. chroma vector) JsonArray idVector = new JsonArray(); // the corresponding array of note ids for (int i=0; i < this.feature.length; ++i) { // go through all feature elements FeatureElement fe = feature[i]; energyVector.add(fe.getEnergy()); // write its energy level to the json energy vector JsonArray ids = new JsonArray(); ids.addAll(fe.getNoteIds()); // collect all the note ids that contribute to the energy idVector.add(ids); // fill the note id vector } // create the json representative of this feature vector JsonObject json = new JsonObject(); json.put("nrg", energyVector); json.put("ids", idVector); return json; } }
4,314
Java
.java
89
41.460674
196
0.620157
cemfi/meico
69
13
3
GPL-3.0
9/4/2024, 7:09:48 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,314
543,802
ItemElement51Stack.java
AllayMC_Allay/api/src/main/java/org/allaymc/api/item/interfaces/element/ItemElement51Stack.java
package org.allaymc.api.item.interfaces.element; import org.allaymc.api.item.ItemStack; public interface ItemElement51Stack extends ItemStack { }
148
Java
.java
4
35.5
55
0.859155
AllayMC/Allay
157
12
40
LGPL-3.0
9/4/2024, 7:07:37 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
148
2,411,257
Transformation.java
vionta_Salvora/src/main/java/net/vionta/salvora/config/dto/Transformation.java
package net.vionta.salvora.config.dto; import java.util.ArrayList; import java.util.List; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "transformation") public class Transformation implements NetworkPathConfiguration { public static final String LOCAL_SOURCE_TYPE = "local_file"; public static final String LOCAL_DIRECTORY_LISTING= "directory_listing"; public static final String REMOTE_NETWORK_SOURCE_TYPE = "remote_network"; public static final String LOCAL_NETWORK_SOURCE_TYPE = "local_network"; @XmlAttribute(name = "name", required = true) protected String name; @XmlAttribute(name = "path") protected String path; @XmlAttribute(name = "base-path") protected String basePath; @XmlAttribute(name = "base-internal-path") protected String baseInternalPath; @XmlAttribute(name = "internal-path") protected String internalPath; @XmlElement(name="step", type = TransformationStep.class) protected List<TransformationStep> transformationSteps = new ArrayList<TransformationStep>(); @XmlElement(name="trigger", type = Trigger.class) protected List<Trigger> triggers = new ArrayList<Trigger>(); @Override public String getPath() { return path; } public void setPath(String path) { this.path = path; } @Override public String getInternalPath() { return internalPath; } public void setInternalPath(String url) { this.internalPath = url; } @XmlAttribute(name = "type") protected String type = "file"; public List<Trigger> getTriggers() { return triggers; } public void setTriggers(List<Trigger> triggers) { this.triggers = triggers; } public String getName() { return name; } public void setName(String value) { this.name = value; } @Override public String getBasePath() { return basePath; } public void setBasePath(String value) { this.basePath = value; } @Override public String getBaseInternalPath() { return (baseInternalPath == null) ? getBasePath() : baseInternalPath; } public void setBaseInternal(String value) { this.baseInternalPath = value; } public String getType() { return type; } public void setType(String type) { this.type = type; } public List<TransformationStep> getTransformationSteps() { return transformationSteps; } public void setTransformationSteps(List<TransformationStep> transformationSteps) { this.transformationSteps = transformationSteps; } @Override public String toString() { StringBuilder rep = new StringBuilder("Transformation "); if(name!=null) rep.append(name); rep.append(" : "); if(basePath!=null) rep.append(basePath); if(path!=null) rep.append(" " ).append(path); rep.append(" -> "); if(baseInternalPath!=null) rep.append(baseInternalPath); if(internalPath!=null) rep.append(" " ).append(internalPath); rep.append("\n"); rep.append(" Steps :").append(transformationSteps.size()); rep.append(" Triggers :").append(triggers.size()); return rep.toString(); } }
3,447
Java
.java
99
29.747475
98
0.719122
vionta/Salvora
8
0
4
GPL-3.0
9/4/2024, 9:21:30 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,447
4,328,190
WeightedRandom.java
yxzhou_footprints/util/random/WeightedRandom.java
package util.random; public class WeightedRandom { /* * Weighted random sampling with a reservoir * * given a big table (checkIn - occurrence), and we need to write an efficient function to randomly select 1 checkIn * where probability is based on the occurrence. * * Example: * input (q1 - 20)(q2 - 10 )( q3 - 30) * the probability of q1 is 20/(20+10+30) = 20/60 * */ static int res; // The resultant random number static int sum = 0; //Count of numbers visited so far in stream public static int selectRandom(int query, int weight){ int precount = sum; sum += weight; // increment count of numbers seen so far // If this is the first element from stream, return it if (sum == 1) { res = query; } else { // Generate a random number from 0 to count - 1 java.util.Random random = new java.util.Random(); int i = random.nextInt(sum); // Replace the prev random number with new number with weight/(count+weight) probability if (i > precount) { // or (i <= weight) res = query; } } return res; } // Driver program to test above function. public static void main(String[] args) { int[] query = {1, 3, 5}; int[] occurrence = {20, 10, 30}; int n = query.length; for (int i = 0; i < n; ++i) System.out.printf("random number from first %d numbers is %d \n", i+1, selectRandom(query[i], occurrence[i])); } class Query{ int id; int occurrence; } }
1,720
Java
.java
48
27
119
0.57721
yxzhou/footprints
2
0
0
GPL-3.0
9/5/2024, 12:09:19 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,720
3,586,009
Pq.java
moozd_JTel/src/com/jtel/mtproto/auth/pq/Pq.java
package com.jtel.mtproto.auth.pq; /** * This file is part of JTel * IntelliJ idea. * Date : 6/9/16 * Package : com.jtel.mtproto.auth.pq * * @author <a href="mailto:[email protected]">Mohammad Mohammad Zade</a> */ /** * This class store pq number * p and q are prime factors of pq number * where p < q */ public class Pq { /** * pq number in bytes */ public byte[] pq; /** * p number in bytes */ public byte[] p; /** * q number in bytes */ public byte[] q; /** * constructor accepts one parameter, to store p and q numbers * we will do the math elsewhere. * @param pq one of the parameters of the req_pq method from tl schema is pq number in bytes * . do not generate random numbers to pass as pq number, you must getAuth it from ser * ver throw req_pq method. */ public Pq(byte[] pq){ this.pq = pq; } }
960
Java
.java
38
21.052632
101
0.602186
moozd/JTel
3
0
0
GPL-3.0
9/4/2024, 11:34:01 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
960
3,116,980
AddAsciiOutputStream.java
d-fens_drftpd/src/common/src/org/drftpd/io/AddAsciiOutputStream.java
/* * This file is part of DrFTPD, Distributed FTP Daemon. * * DrFTPD is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * DrFTPD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DrFTPD; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.drftpd.io; import java.io.IOException; import java.io.OutputStream; /** * AddAsciiOutputStream that ensures that there's an \r before every \n. * * @author <a href="mailto:[email protected]">Rana Bhattacharyya</a> * @version $Id$ */ public class AddAsciiOutputStream extends OutputStream { private OutputStream _out; private boolean _lastWasCarriageReturn = false; /** * Constructor. * * @param os * <code>java.io.OutputStream</code> to be filtered. */ public AddAsciiOutputStream(OutputStream os) { _out = os; } /** * Write a single byte. ASCII characters are defined to be the lower half of * an eight-bit code set (i.e., the most significant bit is zero). Change * "\n" to "\r\n". */ public void write(int i) throws IOException { if ((i == '\n') && !_lastWasCarriageReturn) { _out.write('\r'); } _lastWasCarriageReturn = false; if (i == '\r') { _lastWasCarriageReturn = true; } _out.write(i); } public void close() throws IOException { _out.close(); } public void flush() throws IOException { _out.flush(); } }
1,868
Java
.java
60
28.683333
77
0.715239
d-fens/drftpd
4
7
0
GPL-2.0
9/4/2024, 10:55:06 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,868
4,669,887
RecordApp.java
europeana_record-api/record-api-web/src/main/java/eu/europeana/api/record/RecordApp.java
package eu.europeana.api.record; import org.springframework.boot.SpringApplication; import org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.jena.riot.RDFFormat; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.ConfigurableApplicationContext; import dev.morphia.query.filters.Filters; import dev.morphia.query.MorphiaCursor; import eu.europeana.api.format.RdfFormat; import eu.europeana.api.record.profile.ViewProfileRegistry; import eu.europeana.api.record.db.repository.RecordRepository; import eu.europeana.api.record.io.FormatHandlerRegistry; import eu.europeana.api.record.io.FormatHandlerRegistryV2; import eu.europeana.api.record.io.json.v2.JsonV2Writer; import eu.europeana.api.record.model.ProvidedCHO; /** * Main application. Allows deploying as a war and logs instance data when deployed in Cloud Foundry */ @SpringBootApplication( scanBasePackages = {"eu.europeana.api.record"}, exclude = { // Remove these exclusions to re-enable security SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class, // DataSources are manually configured (for EM and batch DBs) DataSourceAutoConfiguration.class }) public class RecordApp extends SpringBootServletInitializer { private static final Logger LOG = LogManager.getLogger(RecordApp.class); /** * Main entry point of this application * * @param args command-line arguments * @throws IOException */ public static void main(String[] args) throws IOException { LOG.info("No args provided to application. Starting web server"); ConfigurableApplicationContext ctx = SpringApplication.run(RecordApp.class, args); /* RecordRepository repo = ctx.getBean(RecordRepository.class); ViewProfileRegistry vr = new ViewProfileRegistry(); try ( MorphiaCursor<ProvidedCHO> cursor = repo.findAll( // Filters.eq("proxies.proxyIn.datasetName", "9200515_NL_Photographs_Serbia") , vr.getProjection("media.full"))) { FormatHandlerRegistry reg = ctx.getBean(FormatHandlerRegistry.class); // reg.get(RdfFormat.JSONLD).write(cho, System.out); File dir = new File("C:\\Work\\incoming\\Record v3\\formats"); RdfFormat[] formats = { RdfFormat.XML }; for ( RdfFormat format : formats ) { File file = new File(dir, "records." + format.getExtension()); try ( FileOutputStream fos = new FileOutputStream(file) ) { reg.get(format).write(cursor, Math.min(cursor.available(), 10), fos); fos.flush(); } } //new JsonV2Writer().write(cho, System.out); } */ } }
3,551
Java
.java
68
42.808824
110
0.686869
europeana/record-api
2
0
0
EUPL-1.2
9/5/2024, 12:20:49 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,551
3,163,158
Description.java
learning-spring-boot_contest-votesapp/src/main/java/de/votesapp/commands/Description.java
package de.votesapp.commands; import lombok.Value; @Value public class Description { int priority; String name; String[] trigger; String description; public static class DescriptionBuilder { private final String name; private String[] trigger; private String description; private int priority; private DescriptionBuilder(final String name) { this.name = name; } public static DescriptionBuilder describe(final String name) { return new DescriptionBuilder(name); } public DescriptionBuilder withTrigger(final String... trigger) { this.trigger = trigger; return this; } public DescriptionBuilder withDescription(final String description) { this.description = description; return this; } public DescriptionBuilder onPosition(final int priority) { this.priority = priority; return this; } public Description done() { return new Description(priority, name, trigger, description); } } }
955
Java
.java
36
23.472222
71
0.773626
learning-spring-boot/contest-votesapp
4
2
0
GPL-3.0
9/4/2024, 11:02:10 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
955
722,333
CompositeProjector.java
saalfeldlab_paintera/src/main/java/org/janelia/saalfeldlab/paintera/composition/CompositeProjector.java
package org.janelia.saalfeldlab.paintera.composition; import bdv.viewer.Source; import bdv.viewer.SourceAndConverter; import bdv.viewer.render.AccumulateProjector; import bdv.viewer.render.AccumulateProjectorFactory; import bdv.viewer.render.VolatileProjector; import net.imglib2.Cursor; import net.imglib2.RandomAccessible; import net.imglib2.RandomAccessibleInterval; import net.imglib2.type.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; /** * @author Stephan Saalfeld */ public class CompositeProjector<A extends Type<A>> extends AccumulateProjector<A, A> { public static class CompositeProjectorFactory<A extends Type<A>> implements AccumulateProjectorFactory<A> { final private Map<Source<?>, Composite<A, A>> composites; /** * Constructor with a map that associates sources and {@link Composite Composites}. * * @param composites */ public CompositeProjectorFactory(final Map<Source<?>, Composite<A, A>> composites) { this.composites = composites; } @Override public VolatileProjector createProjector( List<VolatileProjector> sourceProjectors, List<SourceAndConverter<?>> sources, List<? extends RandomAccessible<? extends A>> sourceScreenImages, RandomAccessibleInterval<A> targetScreenImage, int numThreads, ExecutorService executorService) { final CompositeProjector<A> projector = new CompositeProjector<>( sourceProjectors, sourceScreenImages, targetScreenImage ); final ArrayList<Composite<A, A>> activeComposites = new ArrayList<>(); for (final var activeSource : sources) { activeComposites.add(composites.get(activeSource.getSpimSource())); } projector.setComposites(activeComposites); return projector; } } final protected ArrayList<Composite<A, A>> composites = new ArrayList<>(); public CompositeProjector( final List<VolatileProjector> sourceProjectors, final List<? extends RandomAccessible<? extends A>> sources, final RandomAccessibleInterval<A> target) { super(sourceProjectors, sources, target); } public void setComposites(final List<Composite<A, A>> composites) { this.composites.clear(); this.composites.addAll(composites); } @Override protected void accumulate(final Cursor<? extends A>[] accesses, final A t) { for (int i = 0; i < composites.size(); ++i) { composites.get(i).compose(t, accesses[i].get()); } } }
2,465
Java
.java
67
33.61194
108
0.777217
saalfeldlab/paintera
99
17
78
GPL-2.0
9/4/2024, 7:08:37 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,465
4,763,298
Utf16TransformationStrategy.java
abramsm_DSI-Utilities/src/it/unimi/dsi/bits/Utf16TransformationStrategy.java
package it.unimi.dsi.bits; /* * DSI utilities * * Copyright (C) 2007-2012 Sebastiano Vigna * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. * */ import java.io.Serializable; /** * @deprecated Use {@link TransformationStrategies#utf16()} and {@link TransformationStrategies#prefixFreeUtf16()}. */ @Deprecated public class Utf16TransformationStrategy implements TransformationStrategy<CharSequence>, Serializable { private static final long serialVersionUID = 1L; /** Creates a prefix-free UTF16 transformation strategy. The * strategy will map a string to its natural UTF16 bit sequence, and the resulting set of binary words will be made prefix free by adding * */ public Utf16TransformationStrategy() {} public long length( final CharSequence s ) { return ( s.length() + 1 ) * (long)Character.SIZE; } private static class Utf16CharSequenceBitVector extends AbstractBitVector implements Serializable { private static final long serialVersionUID = 1L; private transient CharSequence s; private transient long length; private transient long actualEnd; public Utf16CharSequenceBitVector( final CharSequence s ) { this.s = s; actualEnd = s.length() * (long)Character.SIZE; length = actualEnd + Character.SIZE; } public boolean getBoolean( long index ) { if ( index > length ) throw new IndexOutOfBoundsException(); if ( index >= actualEnd ) return false; final int charIndex = (int)( index / Character.SIZE ); return ( s.charAt( charIndex ) & 0x8000 >>> index % Character.SIZE ) != 0; } public long getLong( final long from, final long to ) { if ( from % Long.SIZE == 0 && to % Character.SIZE == 0 ) { long l; int pos = (int)( from / Character.SIZE ); if ( to == from + Long.SIZE ) l = ( ( to > actualEnd ? 0 : (long)s.charAt( pos + 3 ) ) << 48 | (long)s.charAt( pos + 2 ) << 32 | (long)s.charAt( pos + 1 ) << 16 | s.charAt( pos ) ); else { l = 0; final int residual = (int)( Math.min( actualEnd, to ) - from ); for( int i = residual / Character.SIZE; i-- != 0; ) l |= (long)s.charAt( pos + i ) << i * Character.SIZE; } l = ( l & 0x5555555555555555L ) << 1 | ( l >>> 1 ) & 0x5555555555555555L; l = ( l & 0x3333333333333333L ) << 2 | ( l >>> 2 ) & 0x3333333333333333L; l = ( l & 0x0f0f0f0f0f0f0f0fL ) << 4 | ( l >>> 4 ) & 0x0f0f0f0f0f0f0f0fL; return ( l & 0x00ff00ff00ff00ffL ) << 8 | ( l >>> 8 ) & 0x00ff00ff00ff00ffL; } return super.getLong( from, to ); } public long length() { return length; } } public BitVector toBitVector( final CharSequence s ) { return new Utf16CharSequenceBitVector( s ); } public long numBits() { return 0; } public TransformationStrategy<CharSequence> copy() { return new Utf16TransformationStrategy(); } }
3,437
Java
.java
81
39.098765
185
0.695561
abramsm/DSI-Utilities
1
0
0
LGPL-3.0
9/5/2024, 12:30:20 AM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
3,437
4,439,823
AdventureService.java
exasky_dnd-parker-online/back/src/main/java/com/exasky/dnd/adventure/service/AdventureService.java
package com.exasky.dnd.adventure.service; import com.exasky.dnd.adventure.model.Adventure; import com.exasky.dnd.adventure.model.Campaign; import com.exasky.dnd.adventure.model.Character; import com.exasky.dnd.adventure.model.Initiative; import com.exasky.dnd.adventure.model.card.CharacterItem; import com.exasky.dnd.adventure.model.layer.item.LayerItem; import com.exasky.dnd.adventure.model.template.CharacterTemplate; import com.exasky.dnd.adventure.repository.*; import com.exasky.dnd.adventure.rest.dto.card.ValidateCardDto; import com.exasky.dnd.adventure.rest.dto.switch_equipment.ValidateSwitchDto; import com.exasky.dnd.adventure.rest.dto.trade.ValidateTradeDto; import com.exasky.dnd.common.Constant; import com.exasky.dnd.common.exception.ValidationCheckException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.exasky.dnd.common.Utils.getCurrentUser; @Service public class AdventureService { private final AdventureRepository repository; private final CampaignRepository campaignRepository; private final CharacterRepository characterRepository; private final CharacterItemRepository characterItemRepository; private final CharacterTemplateRepository characterTemplateRepository; private final BridgeLayerItemService layerItemService; private final BoardService boardService; @Autowired public AdventureService(AdventureRepository repository, CampaignRepository campaignRepository, CharacterRepository characterRepository, CharacterItemRepository characterItemRepository, CharacterTemplateRepository characterTemplateRepository, BridgeLayerItemService layerItemService, BoardService boardService) { this.repository = repository; this.campaignRepository = campaignRepository; this.characterRepository = characterRepository; this.characterItemRepository = characterItemRepository; this.characterTemplateRepository = characterTemplateRepository; this.layerItemService = layerItemService; this.boardService = boardService; } public List<CharacterTemplate> getAllCharacterTemplate() { return characterTemplateRepository.findAll(); } public List<Adventure> getAdventures() { return this.repository.findAll(); } public Adventure getById(Long id) { return this.repository.getOne(id); } @Transactional public Adventure createOrUpdate(Adventure adventure, Campaign attachedCampaign) { Adventure attachedAdventure = Objects.nonNull(adventure.getId()) ? repository.getOne(adventure.getId()) : repository.save(new Adventure(attachedCampaign)); attachedAdventure.setName(adventure.getName()); attachedAdventure.setLevel(adventure.getLevel()); attachedAdventure.updateBoards(boardService.createOrUpdate(attachedAdventure, adventure.getBoards())); return attachedAdventure; } public Adventure copy(Adventure toCopy, Campaign campaign) { Adventure newAdventure = new Adventure(campaign); newAdventure.setName(toCopy.getName()); newAdventure.setLevel(toCopy.getLevel()); newAdventure.setBoards(boardService.copy(toCopy.getBoards(), newAdventure)); newAdventure.setTraps(layerItemService.copy(toCopy.getTraps(), newAdventure)); newAdventure.setDoors(layerItemService.copy(toCopy.getDoors(), newAdventure)); newAdventure.setChests(layerItemService.copy(toCopy.getChests(), newAdventure)); newAdventure.setMonsters(layerItemService.copy(toCopy.getMonsters(), newAdventure)); newAdventure.setOtherItems(layerItemService.copy(toCopy.getOtherItems(), newAdventure)); return newAdventure; } public void delete(Adventure attachedAdventure) { repository.delete(attachedAdventure); } public List<Campaign> getCampaignsForCurrentUser() { return campaignRepository.findAllForUser(getCurrentUser().getId()); } public Character updateCharacter(Long adventureId, Long characterId, Character toBo) { Campaign campaign = campaignRepository.getByAdventureId(adventureId); if (Objects.isNull(campaign)) { ValidationCheckException.throwError(HttpStatus.NOT_FOUND, Constant.Errors.CAMPAIGN.NOT_FOUND); } Optional<Character> first = campaign.getCharacters().stream().filter(character -> character.getId().equals(characterId)).findFirst(); if (!first.isPresent()) { ValidationCheckException.throwError(HttpStatus.NOT_FOUND, Constant.Errors.CHARACTER.NOT_FOUND); } Character toUpdate = first.get(); toUpdate.setMaxHp(toBo.getMaxHp()); toUpdate.setHp(toBo.getHp()); toUpdate.setMaxMp(toBo.getMaxMp()); toUpdate.setMp(toBo.getMp()); toUpdate.updateEquipments(toBo.getEquipments().stream() .map(characterItem -> characterItemRepository.getOne(characterItem.getId())) .collect(Collectors.toList())); toUpdate.updateBackPack(toBo.getBackPack().stream() .map(characterItem -> characterItemRepository.getOne(characterItem.getId())) .collect(Collectors.toList())); return characterRepository.save(toUpdate); } @Transactional public <T extends LayerItem> T addLayerItem(Long adventureId, T toAdd) { Adventure attachedAdventure = repository.getOne(adventureId); T newLayerItem = layerItemService.createOrUpdate(toAdd, attachedAdventure); List<T> elementListForLayerItem = getElementListForLayerItem(attachedAdventure, toAdd); elementListForLayerItem.add(newLayerItem); return newLayerItem; } @Transactional public <T extends LayerItem> T updateLayerItem(Long adventureId, T toAdd) { Adventure attachedAdventure = repository.getOne(adventureId); T attachedLayerItem = this.layerItemService.createOrUpdate(toAdd, attachedAdventure); List<T> elementListForLayerItem = getElementListForLayerItem(attachedAdventure, toAdd); T prevItem = elementListForLayerItem.stream().filter(item -> item.getId().equals(attachedLayerItem.getId())) .findFirst() .orElse(null); if (Objects.isNull(prevItem)) { ValidationCheckException.throwError(Constant.Errors.ADVENTURE.LAYER_ITEM_NOT_FOUND); } int idx = elementListForLayerItem.indexOf(prevItem); elementListForLayerItem.set(idx, attachedLayerItem); return attachedLayerItem; } @Transactional public <T extends LayerItem> void deleteLayerItem(Long adventureId, T toDelete) { Adventure attachedAdventure = repository.getOne(adventureId); T attachedLayerItem = layerItemService.getOne(toDelete); List<T> elementListForLayerItem = getElementListForLayerItem(attachedAdventure, attachedLayerItem); elementListForLayerItem.remove(attachedLayerItem); } @SuppressWarnings("unchecked") private <T extends LayerItem> List<T> getElementListForLayerItem(Adventure adv, T layerItem) { switch (layerItem.getLayerElement().getType()) { case TRAP: return (List<T>) adv.getTraps(); case DOOR: return (List<T>) adv.getDoors(); case CHEST: return (List<T>) adv.getChests(); case MONSTER: return (List<T>) adv.getMonsters(); case CHARACTER: return (List<T>) adv.getCharacters(); default: return (List<T>) adv.getOtherItems(); } } public CharacterItem getNextCardToDraw(Long adventureId) { Campaign campaign = this.campaignRepository.getByAdventureId(adventureId); if (Objects.isNull(campaign)) { ValidationCheckException.throwError(HttpStatus.NOT_FOUND, Constant.Errors.CAMPAIGN.NOT_FOUND); } //noinspection OptionalGetWithoutIsPresent Short adventureLevel = campaign.getAdventures() .stream() .filter(a -> a.getId().equals(adventureId)).findFirst().get().getLevel(); List<Long> itemOnCharacterIds = campaign.getCharacters().stream() .flatMap(c -> Stream.of(c.getEquipments(), c.getBackPack()).flatMap(Collection::stream)) .map(CharacterItem::getId) .collect(Collectors.toList()); List<Long> drawnCardIds = campaign.getDrawnItems().stream() .map(CharacterItem::getId) .collect(Collectors.toList()); Set<Long> usedItemIds = Stream.of(itemOnCharacterIds, drawnCardIds) .flatMap(Collection::stream) .collect(Collectors.toSet()); List<CharacterItem> availableCards = usedItemIds.isEmpty() ? characterItemRepository.findAllByLevelLessThanEqual(adventureLevel) : characterItemRepository.findAllByIdNotInAndLevelLessThanEqual(usedItemIds, adventureLevel); // Clear the discard if (availableCards.isEmpty()) { campaign.getDrawnItems().clear(); campaignRepository.save(campaign); availableCards = itemOnCharacterIds.isEmpty() ? characterItemRepository.findAllByLevelLessThanEqual(adventureLevel) : characterItemRepository.findAllByIdNotInAndLevelLessThanEqual(usedItemIds, adventureLevel); } return availableCards.get(new Random().nextInt(availableCards.size())); } /** * Does not add the card to the drawn items because the card should be a unique item (like star level items) */ @PreAuthorize("hasRole('ROLE_GM')") public CharacterItem drawSpecificCard(Long characterItemId) { Optional<CharacterItem> byId = characterItemRepository.findById(characterItemId); if (!byId.isPresent()) { ValidationCheckException.throwError(HttpStatus.NOT_FOUND, Constant.Errors.CHARACTER_ITEM.NOT_FOUND); } return byId.get(); } @PreAuthorize("hasRole('ROLE_GM')") public Character validateDrawnCard(Long adventureId, ValidateCardDto dto) { Campaign campaign = campaignRepository.getByAdventureId(adventureId); if (Objects.isNull(campaign)) { ValidationCheckException.throwError(HttpStatus.NOT_FOUND, Constant.Errors.CAMPAIGN.NOT_FOUND); } Optional<CharacterItem> optCharacterItem = characterItemRepository.findById(dto.getCharacterItemId()); if (!optCharacterItem.isPresent()) { ValidationCheckException.throwError(HttpStatus.NOT_FOUND, Constant.Errors.CHARACTER_ITEM.NOT_FOUND); } CharacterItem drawnCard = optCharacterItem.get(); if (Objects.isNull(dto.getEquipToEquipment())) { campaign.getDrawnItems().add(drawnCard); campaignRepository.save(campaign); } else { Character character = characterRepository.getOne(dto.getCharacterId()); (dto.getEquipToEquipment() ? character.getEquipments() : character.getBackPack()).add(drawnCard); return characterRepository.save(character); } return null; } @PreAuthorize("hasRole('ROLE_GM')") public Initiative nextTurn(Long adventureId) { Adventure adventure = getById(adventureId); if (Objects.isNull(adventure)) { ValidationCheckException.throwError(HttpStatus.NOT_FOUND, Constant.Errors.ADVENTURE.NOT_FOUND); } List<Initiative> characterTurns = adventure.getCampaign().getCharacterTurns(); short nextNumber = (short) (adventure.getCurrentInitiative().getNumber() + 1); if (nextNumber > characterTurns.size()) { nextNumber = 1; } for (Initiative init : characterTurns) { if (init.getNumber() == nextNumber) { adventure.setCurrentInitiative(init); break; } } repository.save(adventure); return adventure.getCurrentInitiative(); } @PreAuthorize("hasRole('ROLE_GM')") @Transactional public List<Character> trade(ValidateTradeDto trade) { Character from = this.characterRepository.getOne(trade.getFromCharacterId()); Character to = this.characterRepository.getOne(trade.getToCharacterId()); simpleTrade(from, to, trade.getFromCharacterEquipment(), trade.getFromCharacterIsEquipment(), trade.getToCharacterIsEquipment()); simpleTrade(to, from, trade.getToCharacterEquipment(), trade.getToCharacterIsEquipment(), trade.getFromCharacterIsEquipment()); return Arrays.asList(from, to); } private void simpleTrade(Character from, Character to, Long fromCharacterEquipmentId, Boolean fromCharacterIsEquipment, Boolean toCharacterIsEquipment) { if (Objects.nonNull(fromCharacterEquipmentId)) { List<CharacterItem> items = fromCharacterIsEquipment ? from.getEquipments() : from.getBackPack(); Optional<CharacterItem> optFromItem = items.stream().filter(item -> item.getId().equals(fromCharacterEquipmentId)).findFirst(); if (optFromItem.isPresent()) { CharacterItem fromItem = optFromItem.get(); items.remove(fromItem); (toCharacterIsEquipment != null && toCharacterIsEquipment ? to.getEquipments() : to.getBackPack()).add(fromItem); } } } @PreAuthorize("hasRole('ROLE_GM')") @Transactional public Character switchEquipment(ValidateSwitchDto switchDto) { Character toUpdate = characterRepository.getOne(switchDto.getCharacterId()); if (Objects.nonNull(switchDto.getCharacterEquippedItemId())) { Optional<CharacterItem> optEq = toUpdate.getEquipments().stream(). filter(eq -> eq.getId().equals(switchDto.getCharacterEquippedItemId())).findFirst(); if (optEq.isPresent()) { CharacterItem eq = optEq.get(); toUpdate.getEquipments().remove(eq); toUpdate.getBackPack().add(eq); } } if (Objects.nonNull(switchDto.getCharacterBackpackItemId())) { Optional<CharacterItem> optBp = toUpdate.getBackPack().stream() .filter(eq -> eq.getId().equals(switchDto.getCharacterBackpackItemId())).findFirst(); if (optBp.isPresent()) { CharacterItem bp = optBp.get(); toUpdate.getBackPack().remove(bp); toUpdate.getEquipments().add(bp); } } return toUpdate; } }
15,231
Java
.java
289
42.719723
141
0.694418
exasky/dnd-parker-online
2
0
22
LGPL-3.0
9/5/2024, 12:13:19 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,231
4,181,123
EditFragmentUserProfile.java
asifali22_Focus-Android-App/app/src/main/java/com/hybrid/freeopensourceusers/UserProfileStuff/EditFragmentUserProfile.java
package com.hybrid.freeopensourceusers.UserProfileStuff; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.TextInputLayout; import android.support.v4.app.Fragment; import android.support.v7.widget.AppCompatButton; import android.text.InputFilter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.hybrid.freeopensourceusers.Activities.New_Post; import com.hybrid.freeopensourceusers.Callback.UpdateInterest; import com.hybrid.freeopensourceusers.Callback.UpdateOrg; import com.hybrid.freeopensourceusers.Callback.UpdateStatus; import com.hybrid.freeopensourceusers.Callback.UpdateUI; import com.hybrid.freeopensourceusers.R; import com.hybrid.freeopensourceusers.SharedPrefManager.SharedPrefManager; import com.hybrid.freeopensourceusers.Utility.Utility; import com.hybrid.freeopensourceusers.Volley.VolleySingleton; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; /** * A simple {@link Fragment} subclass. */ public class EditFragmentUserProfile extends Fragment { private TextInputLayout editTextGeneralised; private TextView toolbarTitle; private EditText insideEditText; private SharedPrefManager sharedPrefManager; private AppCompatButton okButton, cancelButton; private static int FLAG; private VolleySingleton volleySingleton; private RequestQueue requestQueue; private String desc, interest, organisation, status, input; private UpdateUI updateUI; private UpdateInterest updateInterest; private UpdateOrg updateOrg; private UpdateStatus updateStatus; private ProgressDialog progressDialog; public EditFragmentUserProfile() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { FLAG = getArguments().getInt("FLAG_FINAL"); desc = getArguments().getString("DESCRIPTION"); interest = getArguments().getString("INTEREST"); organisation = getArguments().getString("ORGANISATION"); status = getArguments().getString("STATUS"); int maxValue = getArguments().getInt("MAX"); // Inflate the layout for this fragment View root = inflater.inflate(R.layout.fragment_edit_fragment_user_profile, container, false); toolbarTitle = (TextView) root.findViewById(R.id.toolbarTitle); insideEditText = (EditText) root.findViewById(R.id.insideEditText); editTextGeneralised = (TextInputLayout) root.findViewById(R.id.editTextFragmentUserProfile); okButton = (AppCompatButton) root.findViewById(R.id.okButtonUserPro); cancelButton = (AppCompatButton) root.findViewById(R.id.cancelButtonUserPro); volleySingleton = VolleySingleton.getInstance(); requestQueue = volleySingleton.getRequestQueue(); editTextGeneralised.setCounterEnabled(true); sharedPrefManager = new SharedPrefManager(getContext()); progressDialog = new ProgressDialog(getActivity()); editTextGeneralised.requestFocus(); getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { openKeyboard(); insideEditText.setSelectAllOnFocus(true); } }, 500); if (FLAG == 1) { if (desc != null) { editTextGeneralised.getEditText().setText(desc); insideEditText.setSelection(desc.length()); } toolbarTitle.setText("Update description"); editTextGeneralised.setCounterMaxLength(maxValue); } else if (FLAG == 2) { if (interest != null) { editTextGeneralised.getEditText().setText(interest); insideEditText.setSelection(interest.length()); } toolbarTitle.setText("Update interests"); editTextGeneralised.setCounterMaxLength(maxValue); setEditTextMaxLength(insideEditText, maxValue); } else if (FLAG == 3) { if (organisation != null) { editTextGeneralised.getEditText().setText(organisation); insideEditText.setSelection(organisation.length()); } toolbarTitle.setText("Update organisation"); editTextGeneralised.setCounterMaxLength(maxValue); setEditTextMaxLength(insideEditText, maxValue); } else if (FLAG == 4) { if (status != null) { editTextGeneralised.getEditText().setText(status); insideEditText.setSelection(status.length()); } toolbarTitle.setText("Update status"); editTextGeneralised.setCounterMaxLength(maxValue); setEditTextMaxLength(insideEditText, maxValue); } okButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { input = editTextGeneralised.getEditText().getText().toString().trim(); if (FLAG == 1) { updateDescription(input); } else if (FLAG == 2) { updateInterest(input); } else if (FLAG == 3) { updateOrganisation(input); } else if (FLAG == 4) { updateStatus(input); } } }); cancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().onBackPressed(); } }); return root; } private void updateStatus(final String input) { String URL = Utility.getIPADDRESS() + "updateUserStatus"; progressDialog = ProgressDialog.show(getActivity(), "Updating", "Please wait...", false, false); StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); if (!jsonObject.getBoolean("error")) { progressDialog.dismiss(); Toast.makeText(getContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show(); sharedPrefManager.updateUserStatus(input); updateStatus.statusUpdate(input); getActivity().onBackPressed(); } else if (jsonObject.getBoolean("error")) { progressDialog.dismiss(); Toast.makeText(getContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressDialog.dismiss(); Toast.makeText(getContext(), "Can't Update the status", Toast.LENGTH_SHORT).show(); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("Authorization", sharedPrefManager.getApiKey()); return params; } @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("status", input); return params; } }; requestQueue.add(stringRequest); } private void updateOrganisation(final String input) { String URL = Utility.getIPADDRESS() + "updateUserOrganisation"; progressDialog = ProgressDialog.show(getActivity(), "Updating", "Please wait...", false, false); StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); if (!jsonObject.getBoolean("error")) { progressDialog.dismiss(); Toast.makeText(getContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show(); sharedPrefManager.updateUserOrganisation(input); updateOrg.updateOrg(input); getActivity().onBackPressed(); } else if (jsonObject.getBoolean("error")) { progressDialog.dismiss(); Toast.makeText(getContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressDialog.dismiss(); Toast.makeText(getContext(), "Can't update the organisation", Toast.LENGTH_SHORT).show(); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("Authorization", sharedPrefManager.getApiKey()); return params; } @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("organisation", input); return params; } }; requestQueue.add(stringRequest); } private void updateInterest(final String input) { String URL = Utility.getIPADDRESS() + "updateUserInterest"; progressDialog = ProgressDialog.show(getActivity(), "Updating", "Please wait...", false, false); StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); if (!jsonObject.getBoolean("error")) { progressDialog.dismiss(); Toast.makeText(getContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show(); sharedPrefManager.updateUserInterest(input); updateInterest.updateInterest(input); getActivity().onBackPressed(); } else if (jsonObject.getBoolean("error")) { progressDialog.dismiss(); Toast.makeText(getContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressDialog.dismiss(); Toast.makeText(getContext(), "Can't update the Interests", Toast.LENGTH_SHORT).show(); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("Authorization", sharedPrefManager.getApiKey()); return params; } @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("interest", input); return params; } }; requestQueue.add(stringRequest); } private void updateDescription(final String input) { String URL = Utility.getIPADDRESS() + "updateUserAbout"; progressDialog = ProgressDialog.show(getActivity(), "Updating", "Please wait...", false, false); StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); if (!jsonObject.getBoolean("error")) { progressDialog.dismiss(); Toast.makeText(getContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show(); sharedPrefManager.updateUserDesc(input); updateUI.updateDESC(input); getActivity().onBackPressed(); } else if (jsonObject.getBoolean("error")) { progressDialog.dismiss(); Toast.makeText(getContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressDialog.dismiss(); Toast.makeText(getContext(), "Can't update the description", Toast.LENGTH_SHORT).show(); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("Authorization", sharedPrefManager.getApiKey()); return params; } @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("about", input); return params; } }; requestQueue.add(stringRequest); } public void setEditTextMaxLength(EditText editText, int length) { InputFilter[] FilterArray = new InputFilter[1]; FilterArray[0] = new InputFilter.LengthFilter(length); editText.setFilters(FilterArray); } @Override public void onAttach(Context context) { super.onAttach(context); try { updateUI = (UpdateUI) context; updateInterest = (UpdateInterest) context; updateOrg = (UpdateOrg) context; updateStatus = (UpdateStatus) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString() + " must implement onViewSelected"); } } public void openKeyboard() { InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.toggleSoftInputFromWindow( insideEditText.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0); } }
16,090
Java
.java
344
34.311047
115
0.609014
asifali22/Focus-Android-App
2
5
0
GPL-3.0
9/5/2024, 12:05:25 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
16,090
3,472,045
MitMInputStream.java
hantwister_o5logon-fetch/MitMSocket/MitMInputStream.java
/* (c) 2014 Harrison Neal. This file is part of o5logon-fetch. o5logon-fetch is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. o5logon-fetch is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with o5logon-fetch. If not, see <http://www.gnu.org/licenses/>. */ package MitMSocket; import java.io.IOException; import java.io.InputStream; import java.net.SocketImpl; class MitMInputStream extends InputStream { private MitMSocketImplFactory sif; private SocketImpl si; private MitMSocketImpl msi; private InputStream is; MitMInputStream(MitMSocketImplFactory sif, SocketImpl si, MitMSocketImpl msi, InputStream is) { this.sif = sif; this.si = si; this.msi = msi; this.is = is; } private boolean notifyListener(byte[] b) { MitMAction a = sif.getListener().socketInputRead(si, is, b); if (a == MitMAction.CLOSE_SOCKET) { try { msi.close(); } catch (Exception e) { e.printStackTrace(); } return false; } else if (a == MitMAction.DROP_DATA) { return false; } return true; } public int read() throws IOException { int toReturn; while ((toReturn = is.read()) != -1) { if (notifyListener(new byte[] {(byte) toReturn})) { return toReturn; } } return -1; } public int read(byte b[]) throws IOException { byte[] toReturnData = new byte[b.length]; int toReturnLength; System.arraycopy(b, 0, toReturnData, 0, b.length); while ((toReturnLength = is.read(toReturnData)) > 0) { byte[] temp = new byte[toReturnLength]; System.arraycopy(toReturnData, 0, temp, 0, toReturnLength); if (notifyListener(temp)) { System.arraycopy(toReturnData, 0, b, 0, b.length); return toReturnLength; } System.arraycopy(b, 0, toReturnData, 0, b.length); } return toReturnLength; } public int read(byte b[], int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (off < 0 || len < 0 || (off + len) > b.length) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return 0; } byte[] toReturnData = new byte[b.length]; int toReturnLength; System.arraycopy(b, 0, toReturnData, 0, b.length); while ((toReturnLength = is.read(toReturnData, off, len)) > 0) { byte[] temp = new byte[toReturnLength]; System.arraycopy(toReturnData, off, temp, 0, toReturnLength); if (notifyListener(temp)) { System.arraycopy(toReturnData, 0, b, 0, b.length); return toReturnLength; } System.arraycopy(b, 0, toReturnData, 0, b.length); } return toReturnLength; } public long skip(long n) throws IOException { return is.skip(n); } public int available() throws IOException { return is.available(); } public void close() throws IOException { is.close(); } public synchronized void mark(int readlimit) { is.mark(readlimit); } public synchronized void reset() throws IOException { is.reset(); } public boolean markSupported() { return is.markSupported(); } }
3,786
Java
.java
108
28.296296
96
0.662521
hantwister/o5logon-fetch
3
2
0
GPL-3.0
9/4/2024, 11:29:53 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,786
4,459,286
SlimeBash.java
C0W0_Project-Antiland/app/src/main/java/com/walfen/antiland/entities/properties/attack/meleeAttacks/SlimeBash.java
package com.walfen.antiland.entities.properties.attack.meleeAttacks; import com.walfen.antiland.Handler; import com.walfen.antiland.entities.creatures.active.Active; import com.walfen.antiland.gfx.Animation; import com.walfen.antiland.gfx.Assets; public class SlimeBash extends MeleeAttack { public SlimeBash(Handler handler, Active carrier) { super(handler, 1, Type.PHYSICAL, carrier); carrierAnimations.add(0, new Animation(0.3f, Assets.slimeAttackLeft)); carrierAnimations.add(1, new Animation(0.3f, Assets.slimeAttackRight)); } }
569
Java
.java
12
43.5
79
0.787004
C0W0/Project-Antiland
2
0
0
GPL-3.0
9/5/2024, 12:13:55 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
569
72,706
NoteEditorViewPager.java
Automattic_simplenote-android/Simplenote/src/main/java/com/automattic/simplenote/widgets/NoteEditorViewPager.java
package com.automattic.simplenote.widgets; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import androidx.viewpager.widget.ViewPager; public class NoteEditorViewPager extends ViewPager { private boolean mIsEnabled; public NoteEditorViewPager(Context context, AttributeSet attrs) { super(context, attrs); this.mIsEnabled = true; } @Override public boolean onInterceptTouchEvent(MotionEvent event) { return this.mIsEnabled && super.onInterceptTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { if (!mIsEnabled) { return false; } if (event.getAction() == MotionEvent.ACTION_UP) { performClick(); } return super.onTouchEvent(event); } @Override public boolean performClick() { return this.mIsEnabled && super.performClick(); } @Override public boolean arrowScroll(int direction) { return this.mIsEnabled && super.arrowScroll(direction); } public void setPagingEnabled(boolean enabled) { this.mIsEnabled = enabled; } }
1,186
Java
.java
37
25.891892
69
0.699473
Automattic/simplenote-android
1,767
299
133
GPL-2.0
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,186
2,395,477
NotificationCancelReceiver.java
SecUSo_Aktivpause/app/src/main/java/org/secuso/aktivpause/receivers/NotificationCancelReceiver.java
package org.secuso.aktivpause.receivers; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import org.secuso.aktivpause.service.TimerService; /** * @author Christopher Beckmann * @version 2.0 * @since 02.11.2017 * created 02.11.2017 */ public class NotificationCancelReceiver extends BroadcastReceiver { public static final String ACTION_NOTIFICATION_CANCELED = "org.secuso.privacyfriendlybreakreminder.ACTION_NOTIFICATION_CANCELED"; @Override public void onReceive(Context context, Intent intent) { NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (manager != null) { manager.cancel(TimerService.NOTIFICATION_ID); } } }
841
Java
.java
22
34.363636
133
0.784748
SecUSo/Aktivpause
8
3
13
GPL-3.0
9/4/2024, 9:19:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
841
4,523,962
GetPropertyFunc.java
opensource-vplatform_vplatform-plugin-function-server/Serverfunc_GetProperty/src/main/java/com/toone/v3/platform/function/GetPropertyFunc.java
package com.toone.v3.platform.function; import com.toone.v3.platform.function.common.ServerFuncCommonUtils; import com.toone.v3.platform.function.common.exception.ServerFuncException; import com.yindangu.v3.business.VDS; import com.yindangu.v3.business.plugin.business.api.func.IFuncContext; import com.yindangu.v3.business.plugin.business.api.func.IFuncOutputVo; import com.yindangu.v3.business.plugin.business.api.func.IFunction; import org.apache.commons.beanutils.PropertyUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 获取对象属性值<br> * <br> * 代码示例:GetProperty("Entity1","name"),返回值为该属性值。<br> * 参数1--对象(字符串类型);<br> * 参数2--属性名(字符串类型);<br> * 返回值为字符串类型。<br> * * @Author xugang * @Date 2021/6/17 9:38 */ public class GetPropertyFunc implements IFunction { // 函数编码 private final static String funcCode = GetPropertyRegister.Plugin_Code; private final static Logger log = LoggerFactory.getLogger(GetPropertyFunc.class); @Override public IFuncOutputVo evaluate(IFuncContext context) { IFuncOutputVo outputVo = context.newOutputVo(); Object bean = null; String propName = null; try { ServerFuncCommonUtils service = VDS.getIntance().getService(ServerFuncCommonUtils.class, ServerFuncCommonUtils.OutServer_Code); service.checkParamSize(funcCode, context, 2); bean = context.getInput(0); propName = (String) context.getInput(1); Object returnValue; try { returnValue = PropertyUtils.getProperty(bean, propName); } catch (Exception e) { throw new RuntimeException("函数【" + funcCode + "】计算失败," + propName + "对象或属性不存在、请检查对象是否存在此对象或属性!"); } outputVo.put(returnValue); outputVo.setSuccess(true); } catch (ServerFuncException e) { outputVo.setSuccess(false); outputVo.setMessage(e.getMessage()); } catch (Exception e) { outputVo.setSuccess(false); outputVo.setMessage("函数【" + funcCode + "】计算有误,参数1:" + bean + ",参数2:" + propName + ", " + e.getMessage()); log.error("函数【" + funcCode + "】计算失败,参数1:" + bean + ",参数2:" + propName, e); } return outputVo; } }
2,517
Java
.java
54
35.259259
139
0.676152
opensource-vplatform/vplatform-plugin-function-server
2
0
0
GPL-3.0
9/5/2024, 12:16:04 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,275
3,045,979
Scroll.java
endlesssolitude_ShatteredPD-DetailedDesc/core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/items/scrolls/Scroll.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2022 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.items.scrolls; import com.shatteredpixel.shatteredpixeldungeon.Dungeon; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Blindness; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Invisibility; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.MagicImmune; import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.ScrollEmpower; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero; import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Talent; import com.shatteredpixel.shatteredpixeldungeon.items.Generator; import com.shatteredpixel.shatteredpixeldungeon.items.Item; import com.shatteredpixel.shatteredpixeldungeon.items.ItemStatusHandler; import com.shatteredpixel.shatteredpixeldungeon.items.Recipe; import com.shatteredpixel.shatteredpixeldungeon.items.artifacts.UnstableSpellbook; import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.exotic.ExoticScroll; import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.exotic.ScrollOfAntiMagic; import com.shatteredpixel.shatteredpixeldungeon.items.stones.Runestone; import com.shatteredpixel.shatteredpixeldungeon.items.stones.StoneOfFear; import com.shatteredpixel.shatteredpixeldungeon.items.stones.StoneOfAggression; import com.shatteredpixel.shatteredpixeldungeon.items.stones.StoneOfAugmentation; import com.shatteredpixel.shatteredpixeldungeon.items.stones.StoneOfBlast; import com.shatteredpixel.shatteredpixeldungeon.items.stones.StoneOfBlink; import com.shatteredpixel.shatteredpixeldungeon.items.stones.StoneOfClairvoyance; import com.shatteredpixel.shatteredpixeldungeon.items.stones.StoneOfDeepSleep; import com.shatteredpixel.shatteredpixeldungeon.items.stones.StoneOfDisarming; import com.shatteredpixel.shatteredpixeldungeon.items.stones.StoneOfEnchantment; import com.shatteredpixel.shatteredpixeldungeon.items.stones.StoneOfFlock; import com.shatteredpixel.shatteredpixeldungeon.items.stones.StoneOfIntuition; import com.shatteredpixel.shatteredpixeldungeon.items.stones.StoneOfShock; import com.shatteredpixel.shatteredpixeldungeon.journal.Catalog; import com.shatteredpixel.shatteredpixeldungeon.messages.Messages; import com.shatteredpixel.shatteredpixeldungeon.sprites.HeroSprite; import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSpriteSheet; import com.shatteredpixel.shatteredpixeldungeon.utils.GLog; import com.watabou.utils.Bundle; import com.watabou.utils.Reflection; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public abstract class Scroll extends Item { public static final String AC_READ = "READ"; protected static final float TIME_TO_READ = 1f; private static final HashMap<String, Integer> runes = new HashMap<String, Integer>() { { put("KAUNAN",ItemSpriteSheet.SCROLL_KAUNAN); put("SOWILO",ItemSpriteSheet.SCROLL_SOWILO); put("LAGUZ",ItemSpriteSheet.SCROLL_LAGUZ); put("YNGVI",ItemSpriteSheet.SCROLL_YNGVI); put("GYFU",ItemSpriteSheet.SCROLL_GYFU); put("RAIDO",ItemSpriteSheet.SCROLL_RAIDO); put("ISAZ",ItemSpriteSheet.SCROLL_ISAZ); put("MANNAZ",ItemSpriteSheet.SCROLL_MANNAZ); put("NAUDIZ",ItemSpriteSheet.SCROLL_NAUDIZ); put("BERKANAN",ItemSpriteSheet.SCROLL_BERKANAN); put("ODAL",ItemSpriteSheet.SCROLL_ODAL); put("TIWAZ",ItemSpriteSheet.SCROLL_TIWAZ); } }; protected static ItemStatusHandler<Scroll> handler; protected String rune; { stackable = true; defaultAction = AC_READ; } @SuppressWarnings("unchecked") public static void initLabels() { handler = new ItemStatusHandler<>( (Class<? extends Scroll>[])Generator.Category.SCROLL.classes, runes ); } public static void save( Bundle bundle ) { handler.save( bundle ); } public static void saveSelectively( Bundle bundle, ArrayList<Item> items ) { ArrayList<Class<?extends Item>> classes = new ArrayList<>(); for (Item i : items){ if (i instanceof ExoticScroll){ if (!classes.contains(ExoticScroll.exoToReg.get(i.getClass()))){ classes.add(ExoticScroll.exoToReg.get(i.getClass())); } } else if (i instanceof Scroll){ if (!classes.contains(i.getClass())){ classes.add(i.getClass()); } } } handler.saveClassesSelectively( bundle, classes ); } @SuppressWarnings("unchecked") public static void restore( Bundle bundle ) { handler = new ItemStatusHandler<>( (Class<? extends Scroll>[])Generator.Category.SCROLL.classes, runes, bundle ); } public Scroll() { super(); reset(); } //anonymous scrolls are always IDed, do not affect ID status, //and their sprite is replaced by a placeholder if they are not known, //useful for items that appear in UIs, or which are only spawned for their effects protected boolean anonymous = false; public void anonymize(){ if (!isKnown()) image = ItemSpriteSheet.SCROLL_HOLDER; anonymous = true; } @Override public void reset(){ super.reset(); if (handler != null && handler.contains(this)) { image = handler.image(this); rune = handler.label(this); } } @Override public ArrayList<String> actions( Hero hero ) { ArrayList<String> actions = super.actions( hero ); actions.add( AC_READ ); return actions; } @Override public void execute( Hero hero, String action ) { super.execute( hero, action ); if (action.equals( AC_READ )) { if (hero.buff(MagicImmune.class) != null){ GLog.w( Messages.get(this, "no_magic") ); } else if (hero.buff( Blindness.class ) != null) { GLog.w( Messages.get(this, "blinded") ); } else if (hero.buff(UnstableSpellbook.bookRecharge.class) != null && hero.buff(UnstableSpellbook.bookRecharge.class).isCursed() && !(this instanceof ScrollOfRemoveCurse || this instanceof ScrollOfAntiMagic)){ GLog.n( Messages.get(this, "cursed") ); } else { curUser = hero; curItem = detach( hero.belongings.backpack ); doRead(); } } } public abstract void doRead(); protected void readAnimation() { Invisibility.dispel(); curUser.spend( TIME_TO_READ ); curUser.busy(); ((HeroSprite)curUser.sprite).read(); if (curUser.hasTalent(Talent.EMPOWERING_SCROLLS)){ Buff.affect(curUser, ScrollEmpower.class).reset(); updateQuickslot(); } } public boolean isKnown() { return anonymous || (handler != null && handler.isKnown( this )); } public void setKnown() { if (!anonymous) { if (!isKnown()) { handler.know(this); updateQuickslot(); } if (Dungeon.hero.isAlive()) { Catalog.setSeen(getClass()); } } } @Override public Item identify( boolean byHero ) { super.identify(byHero); if (!isKnown()) { setKnown(); } return this; } @Override public String name() { return isKnown() ? super.name() : Messages.get(this, rune); } @Override public String info() { return isKnown() ? desc() : Messages.get(this, "unknown_desc"); } @Override public boolean isUpgradable() { return false; } @Override public boolean isIdentified() { return isKnown(); } public static HashSet<Class<? extends Scroll>> getKnown() { return handler.known(); } public static HashSet<Class<? extends Scroll>> getUnknown() { return handler.unknown(); } public static boolean allKnown() { return handler.known().size() == Generator.Category.SCROLL.classes.length; } @Override public int value() { return 30 * quantity; } @Override public int energyVal() { return 6 * quantity; } public static class PlaceHolder extends Scroll { { image = ItemSpriteSheet.SCROLL_HOLDER; } @Override public boolean isSimilar(Item item) { return ExoticScroll.regToExo.containsKey(item.getClass()) || ExoticScroll.regToExo.containsValue(item.getClass()); } @Override public void doRead() {} @Override public String info() { return ""; } } public static class ScrollToStone extends Recipe { private static HashMap<Class<?extends Scroll>, Class<?extends Runestone>> stones = new HashMap<>(); static { stones.put(ScrollOfIdentify.class, StoneOfIntuition.class); stones.put(ScrollOfLullaby.class, StoneOfDeepSleep.class); stones.put(ScrollOfMagicMapping.class, StoneOfClairvoyance.class); stones.put(ScrollOfMirrorImage.class, StoneOfFlock.class); stones.put(ScrollOfRetribution.class, StoneOfBlast.class); stones.put(ScrollOfRage.class, StoneOfAggression.class); stones.put(ScrollOfRecharging.class, StoneOfShock.class); stones.put(ScrollOfRemoveCurse.class, StoneOfDisarming.class); stones.put(ScrollOfTeleportation.class, StoneOfBlink.class); stones.put(ScrollOfTerror.class, StoneOfFear.class); stones.put(ScrollOfTransmutation.class, StoneOfAugmentation.class); stones.put(ScrollOfUpgrade.class, StoneOfEnchantment.class); } @Override public boolean testIngredients(ArrayList<Item> ingredients) { if (ingredients.size() != 1 || !(ingredients.get(0) instanceof Scroll) || !stones.containsKey(ingredients.get(0).getClass())){ return false; } return true; } @Override public int cost(ArrayList<Item> ingredients) { return 0; } @Override public Item brew(ArrayList<Item> ingredients) { if (!testIngredients(ingredients)) return null; Scroll s = (Scroll) ingredients.get(0); s.quantity(s.quantity() - 1); s.identify(); return Reflection.newInstance(stones.get(s.getClass())).quantity(2); } @Override public Item sampleOutput(ArrayList<Item> ingredients) { if (!testIngredients(ingredients)) return null; Scroll s = (Scroll) ingredients.get(0); if (!s.isKnown()){ return new Runestone.PlaceHolder().quantity(2); } else { return Reflection.newInstance(stones.get(s.getClass())).quantity(2); } } } }
10,675
Java
.java
288
33.840278
115
0.766839
endlesssolitude/ShatteredPD-DetailedDesc
5
1
1
GPL-3.0
9/4/2024, 10:44:33 PM (Europe/Amsterdam)
false
false
false
false
false
true
true
false
10,675
4,106,060
HomoPolymerNodeModel.java
lindenb_knime4bio/fr.inserm.umr915.knime4ngs.nodes/src/fr/inserm/umr915/knime4ngs/nodes/vcf/homopolymer/HomoPolymerNodeModel.java
package fr.inserm.umr915.knime4ngs.nodes.vcf.homopolymer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import org.knime.core.data.DataRow; import org.knime.core.data.DataTableSpec; import org.knime.core.data.container.CloseableRowIterator; import org.knime.core.data.def.IntCell; import org.knime.core.data.def.StringCell; import org.knime.core.node.BufferedDataContainer; import org.knime.core.node.BufferedDataTable; import org.knime.core.node.InvalidSettingsException; import org.knime.core.node.defaultnodesettings.SettingsModel; import org.knime.core.node.defaultnodesettings.SettingsModelInteger; import org.knime.core.node.ExecutionContext; import fr.inserm.umr915.knime4ngs.corelib.bio.Segment; import fr.inserm.umr915.knime4ngs.corelib.knime.AbstractNodeModel; @Deprecated public class HomoPolymerNodeModel extends AbstractNodeModel { final static int DEFAULT_MAX_REPEAT=5; static final String MAX_REPEAT_PROPERTY="max.repeat"; private final SettingsModelInteger m_maxRepeat = new SettingsModelInteger(MAX_REPEAT_PROPERTY,DEFAULT_MAX_REPEAT); /** * Constructor for the node model. */ protected HomoPolymerNodeModel() { super(1,2); } @Override protected BufferedDataTable[] execute( final BufferedDataTable[] inData, final ExecutionContext exec ) throws Exception { BufferedDataContainer container1=null; BufferedDataContainer container2=null; try { // the data table spec of the single output table, // the table will have three columns: BufferedDataTable inTable=inData[0]; DataTableSpec inDataTableSpec = inTable.getDataTableSpec(); int chromCol= findColumnIndex(inDataTableSpec, "CHROM",StringCell.TYPE); int posCol= findColumnIndex(inDataTableSpec, "POS",IntCell.TYPE); container1 = exec.createDataContainer(inDataTableSpec); container2 = exec.createDataContainer(inDataTableSpec); double total=inTable.getRowCount(); int nRow=0; BufferedReader in=null; CloseableRowIterator iter=null; try { iter=inTable.iterator(); while(iter.hasNext()) { ++nRow; DataRow dataRow=iter.next(); String chrom=getString(dataRow, chromCol); int position0=getInt(dataRow, posCol)-1; int chromStart=Math.max(0,position0 - m_maxRepeat.getIntValue()); int chromEnd=position0+ m_maxRepeat.getIntValue()+1; Segment seg= new Segment(chrom, chromStart,chromEnd); URL url=new URL("http://srv-clc-02.irt.univ-nantes.prive:8080/biomachin/genome/reference?segment="+ URLEncoder.encode(seg.toString(),"UTF-8") );//TODO in=new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer genomic=new StringBuffer(chromEnd-chromStart); int c; while((c=in.read())!=-1) { genomic.append((char)c); } in.close(); int count=1; int loc= position0-chromStart; char ref= Character.toUpperCase(genomic.charAt(loc)); while(loc-1>=0) { loc--; if(ref!=Character.toUpperCase(genomic.charAt(loc))) { break; } count++; } loc= position0-chromStart+1; while(loc< genomic.length()) { if(ref!=Character.toUpperCase(genomic.charAt(loc))) { break; } loc++; count++; } //System.err.println(genomic.toString()+" "+seg+" "+count); if(count <= m_maxRepeat.getIntValue()) { container1.addRowToTable(dataRow); } else { container2.addRowToTable(dataRow); } exec.checkCanceled(); exec.setProgress(nRow/(double)total, "Repeat"); } } finally { if(in!=null) in.close(); if(iter!=null) iter.close(); } container1.close(); BufferedDataTable out1 = container1.getTable(); container1=null; container2.close(); BufferedDataTable out2 = container2.getTable(); container2=null; BufferedDataTable array[]= new BufferedDataTable[]{out1,out2}; return array; } catch(Exception err) { getLogger().error("Boum", err); err.printStackTrace(); throw err; } finally { if(container1!=null) container1.close(); if(container2!=null) container1.close(); } } @Override protected DataTableSpec[] configure(DataTableSpec[] inSpecs) throws InvalidSettingsException { if(inSpecs==null || inSpecs.length!=1) { throw new InvalidSettingsException("Expected one table"); } DataTableSpec in=inSpecs[0]; findColumnIndex(in,"CHROM",StringCell.TYPE); findColumnIndex(in,"POS",IntCell.TYPE); return new DataTableSpec[]{in,in}; } @Override protected List<SettingsModel> getSettingsModel() { List<SettingsModel> L=new ArrayList<SettingsModel>(super.getSettingsModel()); L.add(this.m_maxRepeat); return L; } }
5,733
Java
.java
159
26.339623
111
0.636924
lindenb/knime4bio
2
0
1
GPL-3.0
9/5/2024, 12:03:00 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
5,733
568,031
ExternalLogicsAndSessionRequestHandler.java
lsfusion_platform/web-client/src/main/java/lsfusion/http/controller/ExternalLogicsAndSessionRequestHandler.java
package lsfusion.http.controller; import lsfusion.base.Result; import lsfusion.base.col.heavy.OrderedMap; import lsfusion.base.file.StringWithFiles; import lsfusion.gwt.server.convert.ClientFormChangesToGwtConverter; import lsfusion.http.authentication.LSFAuthenticationToken; import lsfusion.http.provider.logics.LogicsProvider; import lsfusion.http.provider.navigator.NavigatorProviderImpl; import lsfusion.http.provider.session.SessionProvider; import lsfusion.interop.connection.ConnectionInfo; import lsfusion.interop.logics.LogicsSessionObject; import lsfusion.interop.session.*; import org.apache.commons.lang.StringUtils; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.NameValuePair; import org.apache.hc.core5.http.message.BasicNameValuePair; import org.apache.hc.core5.net.URLEncodedUtils; import javax.servlet.ServletContext; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.nio.charset.Charset; import java.rmi.RemoteException; import java.util.List; import java.util.Map; import java.util.function.Function; import static java.util.Collections.list; public class ExternalLogicsAndSessionRequestHandler extends ExternalRequestHandler { public ExternalLogicsAndSessionRequestHandler(LogicsProvider logicsProvider, SessionProvider sessionProvider, ServletContext servletContext) { super(logicsProvider); this.sessionProvider = sessionProvider; this.servletContext = servletContext; } private final SessionProvider sessionProvider; private final ServletContext servletContext; @Override protected void handleRequest(LogicsSessionObject sessionObject, HttpServletRequest request, HttpServletResponse response) throws Exception { String queryString = request.getQueryString(); String query = queryString != null ? queryString : ""; ContentType requestContentType = ExternalUtils.parseContentType(request.getContentType()); ConnectionInfo connectionInfo = NavigatorProviderImpl.getConnectionInfo(request); String[] headerNames = list(request.getHeaderNames()).toArray(new String[0]); String[] headerValues = getRequestHeaderValues(request, headerNames); OrderedMap<String, String> cookiesMap = getRequestCookies(request); String[] cookieNames = cookiesMap.keyList().toArray(new String[0]); String[] cookieValues = cookiesMap.values().toArray(new String[0]); String logicsHost = sessionObject.connection.host != null && !sessionObject.connection.host.equals("localhost") && !sessionObject.connection.host.equals("127.0.0.1") ? sessionObject.connection.host : request.getServerName(); InputStream requestInputStream = getRequestInputStream(request, requestContentType, query); Function<ExternalRequest, ConvertFileValue> convertFileValue = externalRequest -> value -> { if(value instanceof StringWithFiles) { StringWithFiles stringWithFiles = (StringWithFiles) value; return ExternalUtils.convertFileValue(stringWithFiles.prefixes, ClientFormChangesToGwtConverter.convertFileValue(stringWithFiles.files, servletContext, sessionObject, new SessionInfo(connectionInfo, externalRequest))); } return value; }; String paramSessionID = request.getParameter("session"); Result<String> sessionID = paramSessionID != null ? new Result<>(paramSessionID) : null; Result<Boolean> closeSession = new Result<>(false); ExecInterface remoteExec = ExternalUtils.getExecInterface(sessionObject.remoteLogics, sessionID, closeSession, sessionProvider.getContainer(), LSFAuthenticationToken.getAppServerToken(), connectionInfo); try { ExternalUtils.ExternalResponse externalResponse = ExternalUtils.processRequest(remoteExec, convertFileValue, requestInputStream, requestContentType, headerNames, headerValues, cookieNames, cookieValues, logicsHost, sessionObject.connection.port, sessionObject.connection.exportName, request.getScheme(), request.getMethod(), request.getServerName(), request.getServerPort(), request.getContextPath(), request.getServletPath(), request.getPathInfo() == null ? "" : request.getPathInfo(), query, request.getSession().getId()); sendResponse(response, request, externalResponse); } catch (RemoteException e) { closeSession.set(true); // closing session if there is a RemoteException throw e; } finally { if(sessionID != null && closeSession.result) { sessionProvider.getContainer().removeSession(sessionID.result); } } } // if content type is 'application/x-www-form-urlencoded' the body of the request appears to be already read somewhere else. // so we have empty InputStream and have to read body parameters from parameter map private InputStream getRequestInputStream(HttpServletRequest request, ContentType contentType, String query) throws IOException { InputStream inputStream = request.getInputStream(); if (contentType != null && ContentType.APPLICATION_FORM_URLENCODED.getMimeType().equals(contentType.getMimeType()) && inputStream.available() == 0) { Charset charset = ExternalUtils.getBodyUrlCharset(contentType); List<NameValuePair> queryParams = URLEncodedUtils.parse(query, charset); StringBuilder bodyParams = new StringBuilder(); Map parameterMap = request.getParameterMap(); for (Object o : parameterMap.entrySet()) { Object paramName = ((Map.Entry) o).getKey(); Object paramValues = ((Map.Entry) o).getValue(); if (paramName instanceof String && paramValues instanceof String[]) { for (String paramValue : (String[]) paramValues) { NameValuePair parameter = new BasicNameValuePair((String) paramName, paramValue); if (!queryParams.contains(parameter)) { if (bodyParams.length() > 0) { bodyParams.append("&"); } // params in inputStream should be URL encoded. parameterMap contains decoded params String encodedParamValue = URLEncoder.encode(paramValue, charset.name()); bodyParams.append((String) paramName).append("=").append(encodedParamValue); } } } } inputStream = new ByteArrayInputStream(bodyParams.toString().getBytes(charset)); } return inputStream; } private String[] getRequestHeaderValues(HttpServletRequest request, String[] headerNames) { String[] headerValuesArray = new String[headerNames.length]; for (int i = 0; i < headerNames.length; i++) { headerValuesArray[i] = StringUtils.join(list(request.getHeaders(headerNames[i])).iterator(), ","); } return headerValuesArray; } public static OrderedMap<String, String> getRequestCookies(HttpServletRequest request) { OrderedMap<String, String> cookiesMap = new OrderedMap<>(); Cookie[] cookies = request.getCookies(); if (cookies != null) for (Cookie cookie : cookies) ExternalHttpUtils.formatCookie(cookiesMap, cookie); return cookiesMap; } }
7,753
Java
.java
125
52.432
234
0.715093
lsfusion/platform
150
30
217
LGPL-3.0
9/4/2024, 7:07:37 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
7,753
441,698
CargoArgsTest.java
eclipse-corrosion_corrosion/org.eclipse.corrosion.tests/src/org/eclipse/corrosion/launch/CargoArgsTest.java
/********************************************************************* * Copyright (c) 2019, 2021 Fraunhofer FOKUS and others. * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Max Bureck (Fraunhofer FOKUS) - Initial implementation *******************************************************************************/ package org.eclipse.corrosion.launch; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; class CargoArgsTest { private static final String SEPARATOR = "--"; @Test void testOnlyCommand() { String command = "fmt"; CargoArgs result = CargoArgs.fromAllArguments(command); assertEquals(command, result.command); assertTrue(result.arguments.isEmpty()); assertTrue(result.options.isEmpty()); } @Test void testOnlyCommandAndSeparator() { String command = "fmt"; CargoArgs result = CargoArgs.fromAllArguments(command, SEPARATOR); assertEquals(command, result.command); assertTrue(result.arguments.isEmpty()); assertTrue(result.options.isEmpty()); } @Test void testOnlyCommandAndOptions() { String command = "build"; String opt1 = "--all"; String opt2 = "--release"; CargoArgs result = CargoArgs.fromAllArguments(command, opt1, opt2); assertEquals(command, result.command); assertEquals(Arrays.asList(opt1, opt2), result.options); assertTrue(result.arguments.isEmpty()); } @Test void testOnlyCommandAndOptionsAndSeparator() { String command = "build"; String opt1 = "--all"; String opt2 = "--release"; CargoArgs result = CargoArgs.fromAllArguments(command, opt1, opt2, SEPARATOR); assertEquals(command, result.command); assertEquals(Arrays.asList(opt1, opt2), result.options); assertTrue(result.arguments.isEmpty()); } @Test void testOnlyCommandAndArguments() { String command = "build"; List<String> arguments = List.of("--nocapture", "my_test"); List<String> all_arguments = new ArrayList<>(); all_arguments.add(command); all_arguments.add(SEPARATOR); all_arguments.addAll(arguments); String[] input = all_arguments.toArray(String[]::new); CargoArgs result = CargoArgs.fromAllArguments(input); assertEquals(command, result.command); assertTrue(result.options.isEmpty()); assertEquals(arguments, result.arguments); } @Test void testOnlyCommandAndOptionsAndArguments() { String command = "build"; List<String> options = List.of("--all", "--release"); List<String> arguments = List.of("--nocapture", "my_test"); List<String> all_arguments = new ArrayList<>(); all_arguments.add(command); all_arguments.addAll(options); all_arguments.add(SEPARATOR); all_arguments.addAll(arguments); String[] input = all_arguments.toArray(String[]::new); CargoArgs result = CargoArgs.fromAllArguments(input); assertEquals(command, result.command); assertEquals(options, result.options); assertEquals(arguments, result.arguments); } @Test void testOnlyCommandAndOptionsAndArgumentsIncludingSeparator() { String command = "build"; List<String> options = List.of("--all", "--release"); List<String> arguments = List.of("--nocapture", SEPARATOR, "my_test"); List<String> all_arguments = new ArrayList<>(); all_arguments.add(command); all_arguments.addAll(options); all_arguments.add(SEPARATOR); all_arguments.addAll(arguments); String[] input = all_arguments.toArray(String[]::new); CargoArgs result = CargoArgs.fromAllArguments(input); assertEquals(command, result.command); assertEquals(options, result.options); assertEquals(arguments, result.arguments); } }
3,888
Java
.java
104
34.692308
81
0.729205
eclipse-corrosion/corrosion
220
31
23
EPL-2.0
9/4/2024, 7:07:11 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,888
2,468,828
AppletFrame.java
LS-Lab_orbital/src/orbital/moon/awt/AppletFrame.java
/** * @(#)AppletFrame.java 0.9 1996/03/01 Andre Platzer * * Copyright (c) 1996 Andre Platzer. All Rights Reserved. */ package orbital.moon.awt; import java.awt.Frame; import java.awt.Event; import java.awt.Dimension; import java.applet.Applet; import java.applet.AppletStub; import java.applet.AppletContext; import java.net.URL; import java.awt.Image; import java.applet.AudioClip; import java.util.Enumeration; import java.util.Iterator; import java.io.InputStream; import java.io.IOException; import java.net.MalformedURLException; import java.awt.Toolkit; import java.util.Vector; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.DataLine; import javax.sound.midi.MidiSystem; import javax.sound.midi.Sequencer; import javax.sound.midi.Sequence; import orbital.awt.UIUtilities; import orbital.util.InnerCheckedException; /** * A Frame that can be started to run applets as an application. * Used to convert an applet to an application. * <p> * To start an applet as an application use a main method like: * <pre> * <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> main(<span class="Class">String</span> args[]) { * <span class="Orbital">AppletFrame</span>.showApplet(<span class="String">"<i>className</i>"</span>, <span class="String">"<i>Application Title</i>"</span>, args); * } * </pre></p> * @version $Id$ * @version $Id$ * @author Andr&eacute; Platzer */ public class AppletFrame extends Frame { // Applet to Application view Frame window /** * When orbital.AppletFrame is called as an Application, then the arguments are: * <div><kbd>java orbital.AppletFrame <i>className</i> <i>Title</i> (<i>parameter</i>=<i>value</i>)*</kbd></div> */ public static void main(String args[]) throws Exception { if (args.length < 1 || orbital.signe.isHelpRequest(args[0])) { System.out.println(usage); return; } if (args.length == 2 && orbital.signe.isHelpRequest(args[1])) { System.out.println(usage); // fall-through and let showApplet display info } UIUtilities.setDefaultLookAndFeel(); String className = args[0]; String title = args.length > 1 ? args[1] : "Application Title"; System.out.println("starting Applet " + className + " '" + title + "'"); // strip consumed arguments <className> and <Title>, and pass the remaining args to the applet int consumedArguments = args.length > 1 ? 2 : 1; String remainingArgs[] = new String[args.length - consumedArguments]; System.arraycopy(args, consumedArguments, remainingArgs, 0, remainingArgs.length); AppletFrame.showApplet(className, title, remainingArgs); } public static final String usage = "usage: " + AppletFrame.class + " <className> [<Title> (<parameter>=<value>)* | " + orbital.signe.getHelpRequest() + "]" + System.getProperty("line.separator") + "\twill display the applet <className> in a new frame called <Title>." + System.getProperty("line.separator") + "\tThe applet has access to the values assigned to the parameters." + System.getProperty("line.separator") + "\t" + orbital.signe.getHelpRequest() + "\tdisplay available parameter info for applet <className>"; /** * Get information on an applet. */ public static String info(Applet a) { final String nl = System.getProperty("line.separator"); StringBuffer sb = new StringBuffer("applet "); sb.append(a.getClass().getName()); sb.append(nl); sb.append("supports the following parameters:"); sb.append(nl); String[][] params = a.getParameterInfo(); for (int i = 0; i < params.length; i++) { for (int j = 0; j < params[i].length; j++) sb.append((j > 0 ? " -- " : "") + params[i][j]); sb.append(nl); } return sb.toString(); } public static void showApplet(String appletClassName, String title) throws ClassNotFoundException, InstantiationException, IllegalAccessException { showApplet(appletClassName, title, null); } /** * Show an instance of the applet with the given class. * @param appletClassName the fully qualified class name of the applet to instantiate. * @param title the title to display. * @param args arguments passed to the applet. * args is a list of arguments of the form <span class="String">"<i>parameter</i>=<i>value</i>"</span>. * @see #usage * @see #showApplet(Applet, String, String[]) */ public static void showApplet(String appletClassName, String title, String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // create an instance of the applet class Applet a = (Applet) Class.forName(appletClassName).newInstance(); showApplet(a, title, args); } /** * Show an Applet in a new AppletFrame. * Can be called from an Application-Applet's method main to provide * comfortable application-like behaviour. */ public static void showApplet(Applet a, String title) { showApplet(a, title, new String[0]); } /** * Show an Applet in a new AppletFrame. * Can be called from an Application-Applet's method main to provide * comfortable application-like behaviour. * @param a the applet to display in a frame. * @param title the title to display. * @param args arguments passed to the applet. * args is a list of arguments of the form <span class="String">"<i>parameter</i>=<i>value</i>"</span>. */ public static void showApplet(Applet a, String title, String args[]) { if (args.length == 1 && orbital.signe.isHelpRequest(args[0])) { System.out.println(info(a)); } // create new application frame window AppletFrame frame = new AppletFrame(title); a.setStub(new StandaloneAppletStub(a, frame, args)); // add applet to frame window frame.add("Center", a); // @version 1.0 // initialize the applet a.init(); a.start(); // resize frame window to fit applet // assumes that the applet has its preferred size set frame.pack(); // show the window frame.show(); } // constructor needed to pass window title to class Frame public AppletFrame(String name) { super(name); } /** * needed to allow window to close in Java 1.0 style. * @xxx for Rhythmomachia and Seti, x-ing sometimes does not work. */ public boolean handleEvent(Event e) { // Window Destroy event if (e.id == Event.WINDOW_DESTROY) { System.exit(0); return true; } return super.handleEvent(e); } } /** * The AppletStub of an applet run as standalone Application. */ class StandaloneAppletStub implements AppletStub { private Applet applet; private Frame frame; private String args[]; public StandaloneAppletStub(Applet applet, Frame frame, String args[]) { this.applet = applet; this.frame = frame; this.args = args; } public boolean isActive() { return true; } public URL getDocumentBase() { return getCodeBase(); } public URL getCodeBase() { try { //@xxx or applet.getClass().getResource("."); return new URL("file:///" + System.getProperty("user.dir") + "/"); } catch(MalformedURLException e) {throw new InnerCheckedException("no codebase", e);} } public String getParameter(String name) { if (args == null) return null; for (int i = 0; i < args.length; i++) { int tok = args[i].indexOf('='); if (tok < 0) continue; if (args[i].substring(0, tok).equalsIgnoreCase(name)) return args[i].substring(tok + 1); } return null; } public AppletContext getAppletContext() { return new StandaloneAppletContext(applet); } public void appletResize(int width, int height) { frame.resize(width, height); } } /** * The AppletContext of an applet run as standalone Application. */ class StandaloneAppletContext implements AppletContext { private Toolkit tk; private Applet applet; public StandaloneAppletContext(Applet applet) { this.applet = applet; this.tk = applet.getToolkit(); } public InputStream getStream(String key) {throw new UnsupportedOperationException("new to JDK1.4");} public Iterator getStreamKeys() {throw new UnsupportedOperationException("new to JDK1.4");} public void setStream(String key, InputStream stream) {throw new UnsupportedOperationException("new to JDK1.4");} public AudioClip getAudioClip(URL url) { return new AudioSystemAudioClip(url); } public Image getImage(URL url) { return tk.getImage(url); } public Applet getApplet(String name) { return null; } public Enumeration getApplets() { Vector v = new Vector(1); v.addElement(applet); return v.elements(); } public void showDocument(URL url) { String cmd = System.getProperty("os.command"); String os = System.getProperty("os.name"); if (cmd == null) if (os != null) if (os.startsWith("Windows NT") || os.startsWith("Windows 20")) cmd = "cmd /C start "; else if (os.startsWith("Windows 9") || os.startsWith("Windows ME")) cmd = "command.com /C start "; else if (os.startsWith("Linux") || os.startsWith("Unix")) cmd = "/bin/sh ${BROWSER} "; else cmd = ""; else cmd = ""; cmd += url; try { Process help = Runtime.getRuntime().exec(cmd); } catch(IOException x) {} } public void showDocument(URL url, String target) { showDocument(url); } public void showStatus(String status) { System.out.println(status); } } class AudioSystemAudioClip implements AudioClip { private URL url; private Clip clip = null; private Sequencer sequencer = null; public AudioSystemAudioClip(URL url) { this.url = url; } protected void init(URL url) throws Exception { try { AudioInputStream stream = AudioSystem.getAudioInputStream(url); AudioFormat format = stream.getFormat(); DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(), ((int) stream.getFrameLength() * format.getFrameSize())); clip = (Clip) AudioSystem.getLine(info); clip.open(stream); } catch (Exception alternative) { Sequence sequence = MidiSystem.getSequence(url); sequencer = MidiSystem.getSequencer(); sequencer.open(); sequencer.setSequence(sequence); } } private boolean opened() { if (clip == null && sequencer == null) try { init(url); } catch (Exception ignore) {} return clip != null || sequencer != null; } public void play() { if (opened()) if (clip != null) clip.start(); else sequencer.start(); } public void loop() { if (opened()) if (clip != null) clip.loop(Clip.LOOP_CONTINUOUSLY); else throw new UnsupportedOperationException("midi does not support loop"); } public void stop() { if (opened()) if (clip != null) clip.stop(); else sequencer.stop(); } protected void finalize() throws Throwable { if (clip != null) clip.close(); if (sequencer != null) sequencer.close(); } }
12,369
Java
.java
317
31.391167
522
0.624375
LS-Lab/orbital
7
3
0
GPL-2.0
9/4/2024, 9:37:03 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,369
2,364,365
CleanupTableModel.java
SQLPower_sqlpower-library/src/main/java/ca/sqlpower/swingui/table/CleanupTableModel.java
package ca.sqlpower.swingui.table; /** * A JTable table model with an additional method for cleaning up * its resources. Our EditableJTable class is aware of this interface * and will ask a CleanupTableModel to clean up when the table becomes * undisplayable. */ public interface CleanupTableModel { /** * Asks this table model to permanently clean up its resources. */ void cleanup(); }
403
Java
.java
13
28.923077
70
0.77261
SQLPower/sqlpower-library
8
16
1
GPL-3.0
9/4/2024, 9:12:51 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
403
1,861,398
ArrayUtils.java
Beezig_Beezig/src/main/java/eu/beezig/core/util/ArrayUtils.java
/* * Copyright (C) 2017-2021 Beezig Team * * This file is part of Beezig. * * Beezig is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Beezig is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Beezig. If not, see <http://www.gnu.org/licenses/>. */ package eu.beezig.core.util; import java.util.Arrays; public class ArrayUtils { public static <T> T[] getPage(T[] src, int pageNo, int pageSize) { int from = pageNo * pageSize; if(from >= src.length) return null; int to = from + pageSize; if(to > src.length) to = src.length; return Arrays.copyOfRange(src, from, to); } }
1,085
Java
.java
29
34.068966
71
0.711301
Beezig/Beezig
16
5
2
GPL-3.0
9/4/2024, 8:21:15 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,085
1,544,251
PropertiesFileExpressionCompletionTest.java
eclipse_lsp4mp/microprofile.ls/org.eclipse.lsp4mp.ls/src/test/java/org/eclipse/lsp4mp/services/properties/expressions/PropertiesFileExpressionCompletionTest.java
/******************************************************************************* * Copyright (c) 2022 Red Hat Inc. and others. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 * * Contributors: * Red Hat Inc. - initial API and implementation *******************************************************************************/ package org.eclipse.lsp4mp.services.properties.expressions; import static org.eclipse.lsp4mp.services.properties.PropertiesFileAssert.c; import static org.eclipse.lsp4mp.services.properties.PropertiesFileAssert.r; import static org.eclipse.lsp4mp.services.properties.PropertiesFileAssert.testCompletionFor; import java.util.Arrays; import java.util.stream.Collectors; import org.eclipse.lsp4mp.commons.MicroProfileProjectInfo; import org.eclipse.lsp4mp.commons.metadata.ItemMetadata; import org.eclipse.lsp4mp.ls.commons.BadLocationException; import org.junit.Test; /** * Test with property expression completion in 'microprofile-config.properties' * file. * * @author Angelo ZERR * */ public class PropertiesFileExpressionCompletionTest { @Test public void justDollarSignNoNewline() throws BadLocationException { String text = // "test.property = hello\n" + // "other.test.property = $|"; testCompletionFor(text, generateInfoFor("test.property", "other.test.property"), c("${test.property}", r(1, 22, 23))); } @Test public void justDollarSignNoNewlineItemDefaults() throws BadLocationException { String text = // "test.property = hello\n" + // "other.test.property = $|"; testCompletionFor(text, true, false, true, null, null, generateInfoFor("test.property", "other.test.property"), c("${test.property}", r(1, 22, 23))); } @Test public void justDollarSignNewline() throws BadLocationException { String text = // "test.property = hello\n" + // "other.test.property = $|\n"; testCompletionFor(text, generateInfoFor("test.property", "other.test.property"), c("${test.property}", r(1, 22, 23))); } @Test public void beforeDollarSign() throws BadLocationException { String text = // "test.property = hello\n" + // "other.test.property = |$\n"; testCompletionFor(text, generateInfoFor("test.property", "other.test.property"), 0); } @Test public void noCloseBraceNoNewline() throws BadLocationException { String text = // "test.property = hello\n" + // "other.test.property = ${|"; testCompletionFor(text, generateInfoFor("test.property", "other.test.property"), c("${test.property}", r(1, 22, 24))); } @Test public void noCloseBraceNewline() throws BadLocationException { String text = // "test.property = hello\n" + // "other.test.property = ${|\n"; testCompletionFor(text, generateInfoFor("test.property", "other.test.property"), c("${test.property}", r(1, 22, 24))); } @Test public void closeBraceNoNewline() throws BadLocationException { String text = // "test.property = hello\n" + // "other.test.property = ${|}"; testCompletionFor(text, generateInfoFor("test.property", "other.test.property"), c("${test.property}", r(1, 22, 25))); } @Test public void closeBraceNewline() throws BadLocationException { String text = // "test.property = hello\n" + // "other.test.property = ${|}\n"; testCompletionFor(text, generateInfoFor("test.property", "other.test.property"), c("${test.property}", r(1, 22, 25))); } @Test public void afterCloseBraceNoNewline() throws BadLocationException { String text = // "test.property = hello\n" + // "other.test.property = ${}|"; testCompletionFor(text, generateInfoFor("test.property", "other.test.property"), 0); } @Test public void afterCloseBraceNewline() throws BadLocationException { String text = // "test.property = hello\n" + // "other.test.property = ${}|n"; testCompletionFor(text, generateInfoFor("test.property", "other.test.property"), 0); } @Test public void partiallyFilledCompletionBefore() throws BadLocationException { String text = // "test.property = hello\n" + // "other.test.property = hi|${}"; testCompletionFor(text, generateInfoFor("test.property", "other.test.property"), 0); } @Test public void partiallyFilledJustDollarSign() throws BadLocationException { String text = // "test.property = hello\n" + // "other.test.property = hi$|"; testCompletionFor(text, generateInfoFor("test.property", "other.test.property"), c("${test.property}", r(1, 24, 25))); } @Test public void afterClosingBraceBetweenTwoLiterals() throws BadLocationException { String text = // "test.property = hello\n" + // "other.test.property = hello${}|there"; testCompletionFor(text, generateInfoFor("test.property", "other.test.property"), 0); } @Test public void pickUpPropertiesAfter() throws BadLocationException { String text = // "property.one = ${|}\n" + // "property.two = hi\n" + // "property.three = hello\n"; testCompletionFor(text, generateInfoFor("property.one", "property.two", "property.three"), // c("${property.two}", r(0, 15, 18)), // c("${property.three}", r(0, 15, 18))); } @Test public void completionAfterNewline() throws BadLocationException { String text = // "test.property = hello\n" + // "other.property = ${\\\n" + // " |"; testCompletionFor(text, generateInfoFor("test.property", "other.property"), c("${test.property}", r(1, 17, 2, 4))); } @Test public void completionAfterNewlineClosed() throws BadLocationException { String text = // "test.property = hello\n" + // "other.property = ${\\\n" + // " \\\n" + // "|}\n"; testCompletionFor(text, generateInfoFor("test.property", "other.property"), c("${test.property}", r(1, 17, 3, 1))); } @Test public void completionSpaceAfterDollar() throws BadLocationException { String text = // "test.property = hello\n" + // "other.property = $ |"; testCompletionFor(text, generateInfoFor("test.property", "other.property"), 0); } @Test public void completionNewlineAfterDollar() throws BadLocationException { String text = // "test.property = hello\n" + // "other.property = $\\\n" + // "|"; testCompletionFor(text, generateInfoFor("test.property", "other.property"), 0); } @Test public void partiallyCompletedReference() throws BadLocationException { String text = // "test.property = hello\n" + // "other.property = ${te|"; testCompletionFor(text, generateInfoFor("test.property", "other.property"), c("${test.property}", r(1, 17, 21))); } @Test public void hasCommentInIt() throws BadLocationException { String text = // "# this is an interesting property file\n" + // "test.property = hello\n" + // "other.property = ${|}"; testCompletionFor(text, generateInfoFor("test.property", "other.property"), c("${test.property}", r(2, 17, 20))); } @Test public void manyUndefinedProperties() throws BadLocationException { String text = "test.property = ${|}\n"; testCompletionFor(text, generateInfoFor("test.property", "http.port", "http.ip"), c("${http.port}", r(0, 16, 19)), // c("${http.ip}", r(0, 16, 19))); } @Test public void nonExistingProperties() throws BadLocationException { String text = "test.property = hi\n" + // "other.property = hello\n" + // "yet.another.property = ${|"; testCompletionFor(text, generateInfoFor(), // c("${test.property}", r(2, 23, 25)), // c("${other.property}", r(2, 23, 25))); } // Tests for proper cyclic dependency prevention @Test public void simpleCyclePrevention() throws BadLocationException { String text = // "test.property = ${other.property}\n" + // "other.property = ${|}"; testCompletionFor(text, generateInfoFor("test.property", "other.property"), 0); } @Test public void multiStepCyclePrevention() throws BadLocationException { String text = // "property.one = ${property.five}\n" + // "property.two = ${property.one}\n" + // "property.three = ${property.two}\n" + // "property.four = ${property.three}\n" + // "property.five = ${|}\n"; testCompletionFor(text, generateInfoFor("property.one", "property.two", "property.three", "property.four", "property.five"), 0); } @Test public void complexDependencies() throws BadLocationException { String text = // "property.one = ${property.two}${property.three}\n" + // "property.two = hello${property.four}\n" + // "property.three = hi\n" + // "property.four = ${|}"; testCompletionFor(text, generateInfoFor("property.one", "property.two", "property.three", "property.four"), c("${property.three}", r(3, 16, 19))); } @Test public void cyclicPreventionNonExistingProperties() throws BadLocationException { String text = "test.property = hi ${other.property}\n" + // "other.property = ${yet.another.property}\n" + // "yet.another.property = $|"; testCompletionFor(text, generateInfoFor(), 0); } @Test public void complexDependencies2() throws BadLocationException { String text = "A=${B}\n" + // "B=${C}${F}\n" + // "C=${|\n" + // "D=hi\n" + // "E=${D}${C}\n" + // "F=${D}"; testCompletionFor(text, generateInfoFor(), // c("${D}", r(2, 2, 4)), // c("${F}", r(2, 2, 4))); } @Test public void cyclicPreventionNonExistingAndProjectProperties() throws BadLocationException { String text = "quarkus.http.port=${port}\n" + // "port=8080${|}\n" + // "url=localhost:${port}"; testCompletionFor(text, generateInfoFor("quarkus.http.port"), 0); } @Test public void selfLoopsDontPreventCompletion() throws BadLocationException { String text = "a = ${a}\n" + // "b = $|"; testCompletionFor(text, generateInfoFor(), c("${a}", r(1, 4, 5))); } @Test public void referencedJavadPropertyWithoutDefaultValue() throws BadLocationException { String text = "a = ${|}\n" + // "b = c"; testCompletionFor(text, generateInfoFor("quarkus.http.port"), // c("${b}", r(0, 4, 7)), // c("${quarkus.http.port}", r(0, 4, 7))); } @Test public void referencedJavadPropertyWithDefaultValue() throws BadLocationException { String text = "a = ${|}\n" + // "b = c"; MicroProfileProjectInfo info = generateInfoFor("quarkus.http.port"); info.getProperties().get(0).setDefaultValue("8080"); testCompletionFor(text, info, // c("${b}", r(0, 4, 7))); } @Test public void expressionDefaultValue() throws BadLocationException { String text = "quarkus.log.level = ${ENV_LEVEL:|}"; testCompletionFor(text, true, // c("OFF", "OFF", r(0, 32, 32)), // c("SEVERE", "SEVERE", r(0, 32, 32))); } @Test public void complexExpressions1() throws BadLocationException { String text = "asdf = ${${hjkl}}\n" + // "hjkl = ${qwerty}\n" + // "foo = bar\n" + // "qwerty = ${|}\n"; testCompletionFor(text, generateInfoFor("asdf", "hjkl", "foo", "qwerty"), // c("${foo}", r(3, 9, 12))); } @Test public void complexExpressions2() throws BadLocationException { String text = "asdf = ${hjkl:${qwerty}}\n" + // "foo = bar\n" + // "qwerty = ${|}\n"; testCompletionFor(text, generateInfoFor("asdf", "hjkl", "foo", "qwerty"), // c("${foo}", r(2, 9, 12)), c("${hjkl}", r(2, 9, 12))); } @Test public void complexExpressions3() throws BadLocationException { String text = "asdf = ${${hjkl}}\n" + // "hjkl = ${asdf}\n" + // "qwerty = ${|}\n"; testCompletionFor(text, generateInfoFor("asdf", "hjkl", "qwerty"), // c("${asdf}", r(2, 9, 12)), c("${hjkl}", r(2, 9, 12))); } // Utility functions private static MicroProfileProjectInfo generateInfoFor(String... properties) { MicroProfileProjectInfo projectInfo = new MicroProfileProjectInfo(); projectInfo.setProperties(Arrays.asList(properties).stream().map(p -> { return item(p); }).collect(Collectors.toList())); return projectInfo; } private static ItemMetadata item(String name) { ItemMetadata itemMetadata = new ItemMetadata(); itemMetadata.setName(name); itemMetadata.setRequired(false); return itemMetadata; } }
12,428
Java
.java
332
33.915663
113
0.662961
eclipse/lsp4mp
21
27
51
EPL-2.0
9/4/2024, 7:58:28 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,428
542,896
ItemItemCameraStack.java
AllayMC_Allay/api/src/main/java/org/allaymc/api/item/interfaces/ItemItemCameraStack.java
package org.allaymc.api.item.interfaces; import org.allaymc.api.item.ItemStack; public interface ItemItemCameraStack extends ItemStack { }
141
Java
.java
4
33.75
56
0.859259
AllayMC/Allay
157
12
40
LGPL-3.0
9/4/2024, 7:07:37 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
141
3,918,659
WhirlpoolProtocolSoroban.java
Archive-Samourai-Wallet_whirlpool-protocol/src/main/java/com/samourai/whirlpool/protocol/WhirlpoolProtocolSoroban.java
package com.samourai.whirlpool.protocol; import com.samourai.soroban.client.RpcWallet; import com.samourai.wallet.bip47.BIP47UtilGeneric; import com.samourai.wallet.bip47.rpc.PaymentCode; import com.samourai.wallet.segwit.SegwitAddress; import com.samourai.wallet.util.Util; import com.samourai.whirlpool.client.wallet.beans.WhirlpoolNetwork; import org.bitcoinj.core.NetworkParameters; public class WhirlpoolProtocolSoroban { private static final String SOROBAN_DIR_REGISTER_INPUT_RESPONSE = "/REGISTER_INPUT_RESPONSE"; private static final String SOROBAN_DIR_COORDINATORS = "com.samourai.whirlpool.ro.coordinators."; public WhirlpoolProtocolSoroban() {} public int getRegisterInputFrequencyMs() { return 30000; } public String getDirRegisterInput(WhirlpoolNetwork whirlpoolNetwork, String poolId) { return "com.samourai.whirlpool.wo.inputs." + whirlpoolNetwork.name() + "." + poolId; } public String getDirRegisterInputResponse( RpcWallet rpcWalletClient, WhirlpoolNetwork whirlpoolNetwork, BIP47UtilGeneric bip47Util) throws Exception { return getDirShared( rpcWalletClient, whirlpoolNetwork, bip47Util, SOROBAN_DIR_REGISTER_INPUT_RESPONSE); } public String getDirRegisterInputResponse( RpcWallet rpcWalletCoordinator, PaymentCode paymentCodeClient, BIP47UtilGeneric bip47Util, NetworkParameters params) throws Exception { return getDirShared( rpcWalletCoordinator, paymentCodeClient, bip47Util, params, SOROBAN_DIR_REGISTER_INPUT_RESPONSE); } protected String getDirShared( RpcWallet rpcWalletClient, WhirlpoolNetwork whirlpoolNetwork, BIP47UtilGeneric bip47Util, String sorobanDir) throws Exception { SegwitAddress sharedAddress = bip47Util.getReceiveAddress( rpcWalletClient, whirlpoolNetwork.getSigningPaymentCode(), 0, whirlpoolNetwork.getParams()); return Util.sha512Hex(sharedAddress.getBech32AsString() + "/" + sorobanDir); } protected String getDirShared( RpcWallet rpcWalletCoordinator, PaymentCode paymentCodeClient, BIP47UtilGeneric bip47Util, NetworkParameters params, String sorobanDir) throws Exception { SegwitAddress sharedAddress = bip47Util.getSendAddress(rpcWalletCoordinator, paymentCodeClient, 0, params); return Util.sha512Hex(sharedAddress.getBech32AsString() + "/" + sorobanDir); } public String getDirCoordinators(WhirlpoolNetwork whirlpoolNetwork) { return SOROBAN_DIR_COORDINATORS + whirlpoolNetwork.name(); } }
2,643
Java
.java
66
34.5
99
0.767433
Archive-Samourai-Wallet/whirlpool-protocol
3
1
0
AGPL-3.0
9/4/2024, 11:48:53 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,643
4,808,408
IStaticAnalysisInfo.java
jesusc_bento/componetization/bento.componetization.atl/src/bento/componetization/atl/IStaticAnalysisInfo.java
package bento.componetization.atl; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import anatlyzer.atl.model.ATLModel; import anatlyzer.atlext.ATL.Helper; import anatlyzer.atlext.ATL.Rule; import anatlyzer.atlext.OCL.OperationCallExp; import anatlyzer.footprint.CallSite; public interface IStaticAnalysisInfo { Set<CallSite> getCallSites(); Set<EClass> getExplicitlyUsedTypes(); Set<EClass> getImplicitlyUsedTypes(); Set<EStructuralFeature> getUsedFeatures(); ATLModel getATL(); // Search utilities for the ATL model List<OperationCallExp> getAllInstancesUsages(EClass clazz); public HashSet<Rule> getRuleUsages(EClass clazz); public List<Helper> getHelperUsages(EClass clazz); }
848
Java
.java
23
35
60
0.835985
jesusc/bento
1
0
0
EPL-1.0
9/5/2024, 12:32:41 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
848
4,919,333
GossipUserPanel.java
chriskearney_creeper/creeper-client/src/main/java/com/comandante/creeper/cclient/GossipUserPanel.java
package com.comandante.creeper.cclient; import com.comandante.creeper.chat.Gossip; import com.comandante.creeper.chat.Users; import com.google.common.eventbus.Subscribe; import com.terminal.ui.ColorPane; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import javax.swing.border.TitledBorder; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.io.IOException; public class GossipUserPanel extends JPanel { private final JList<UserListItem> userListItems; private final DefaultListModel<UserListItem> defaultListModel; private final TitledBorder border = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.gray), "Users"); public GossipUserPanel() { defaultListModel = new DefaultListModel<>(); userListItems = new JList<>(defaultListModel); userListItems.setBackground(Color.BLACK); userListItems.setCellRenderer(new UserPaneCellRenderer()); JScrollPane pane = new JScrollPane(userListItems); pane.setBorder(BorderFactory.createEmptyBorder()); setLayout(new BorderLayout()); setBackground(Color.BLACK); setBorder(border); add(pane); setFocusable(false); setVisible(true); } public static class UserPaneCellRenderer implements ListCellRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { UserListItem userListItem = (UserListItem) value; ColorPane colorPane = new ColorPane(); colorPane.setOpaque(true); colorPane.appendANSI(userListItem.getName()); if (isSelected) { colorPane.setBackground(Color.darkGray); } else { colorPane.setBackground(Color.BLACK); } return colorPane; } } public static class UserListItem { private final String name; public UserListItem(String name) { this.name = name; } public String getName() { return name; } } @Subscribe public void usersEvent(Users users) throws IOException { defaultListModel.removeAllElements(); users.getUserMap().values().stream().sorted().forEach(s -> defaultListModel.addElement(new UserListItem(s))); userListItems.revalidate(); userListItems.repaint(); } }
2,619
Java
.java
66
32.5
134
0.711076
chriskearney/creeper
1
0
35
AGPL-3.0
9/5/2024, 12:35:57 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,619
3,839,448
JAXBObjectModifier.java
futureappssolutions_Document-Reader---PDF-Reader/app/src/main/java/com/docreader/docviewer/pdfcreator/pdfreader/filereader/office/fc/dom4j/jaxb/JAXBObjectModifier.java
/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package com.docreader.docviewer.pdfcreator.pdfreader.filereader.office.fc.dom4j.jaxb; import com.docreader.docviewer.pdfcreator.pdfreader.filereader.office.fc.dom4j.Element; /** * JAXBObjectHandler implementations can be registered with the {@link * JAXBModifier} in order to change unmarshalled XML fragments. * * @author Wonne Keysers (Realsoftware.be) */ public interface JAXBObjectModifier { /** * Called when the {@link JAXBModifier}has finished parsing the xml path * the handler was registered for. The provided object is the unmarshalled * representation of the XML fragment. It can be casted to the appropriate * implementation class that is generated by the JAXB compiler. <br> * The modified JAXB element that returns from this method will be * marshalled by the {@link JAXBModifier}and put in the DOM4J tree. * * @param jaxbElement * the JAXB object to be modified * * @return the modified JAXB object, or null when it must be removed. * * @throws Exception * possibly thrown by the implementation. */ Element modifyObject(Element jaxbElement) throws Exception; } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 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. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact [email protected]. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED 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 METASTUFF, LTD. OR ITS 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. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */
3,292
Java
.java
70
43.985714
87
0.75637
futureappssolutions/Document-Reader---PDF-Reader
3
4
1
GPL-3.0
9/4/2024, 11:44:46 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,292
1,559,526
MixinGuiStats.java
MinecraftTAS_TASmod/src/main/java/com/minecrafttas/tasmod/mixin/playbackhooks/MixinGuiStats.java
package com.minecrafttas.tasmod.mixin.playbackhooks; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import com.minecrafttas.tasmod.TASmodClient; @Mixin(targets = "net.minecraft.client.gui.achievement.GuiStats$Stats") public class MixinGuiStats { @Redirect(method = "drawListHeader(IILnet/minecraft/client/renderer/Tessellator;)V", at = @At(value = "INVOKE", target = "Lorg/lwjgl/input/Mouse;isButtonDown(I)Z", remap = false)) public boolean redirectIsButtonDown(int i) { return !TASmodClient.virtual.isKeyDown(-100); } }
628
Java
.java
12
50.666667
180
0.809135
MinecraftTAS/TASmod
28
4
32
GPL-3.0
9/4/2024, 7:59:18 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
628
1,429,391
PlaceholderHandler.java
GeorgH93_PCGF_PluginLib/pcgf_pluginlib-common/src/at/pcgamingfreaks/Message/PlaceholderHandler.java
/* * Copyright (C) 2023 GeorgH93 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package at.pcgamingfreaks.Message; import at.pcgamingfreaks.Message.Placeholder.MessageComponentPlaceholderEngine; import at.pcgamingfreaks.Message.Placeholder.Placeholder; import at.pcgamingfreaks.Message.Placeholder.Processors.IPlaceholderProcessor; import at.pcgamingfreaks.Message.Placeholder.StringPlaceholderEngine; import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NotNull; import lombok.Getter; class PlaceholderHandler { private final StringPlaceholderEngine legacyPlaceholderEngine; private final MessageComponentPlaceholderEngine messageComponentPlaceholderEngine; private int nextParameterIndex = 0; @Getter private boolean prepared = false; public PlaceholderHandler(Message message) { legacyPlaceholderEngine = new StringPlaceholderEngine(message.fallback); messageComponentPlaceholderEngine = new MessageComponentPlaceholderEngine(message); } public void register(Placeholder... placeholders) { if (placeholders.length == 1 && placeholders[0].IsStatic()) { legacyPlaceholderEngine.registerStaticPlaceholder(placeholders[0].getName(), placeholders[0].getProcessor(), placeholders[0].getParameter()); messageComponentPlaceholderEngine.registerStaticPlaceholder(placeholders[0].getName(), placeholders[0].getProcessor(), placeholders[0].getParameter()); return; } int patchAutoIndex = -1, lastIndexRequested = -99, lastIndexUsed = Math.max(nextParameterIndex - 1, 0); for(Placeholder placeholder : placeholders) { int parameterIndex = placeholder.getParameterIndex(); switch(parameterIndex) { case Placeholder.AUTO_INCREMENT_INDIVIDUALLY: parameterIndex = nextParameterIndex; break; case Placeholder.AUTO_INCREMENT_GROUP: if (lastIndexRequested != placeholder.getParameterIndex()) parameterIndex = nextParameterIndex; else parameterIndex = lastIndexUsed; break; case Placeholder.AUTO_INCREMENT_PATCH: if (patchAutoIndex == -1) patchAutoIndex = nextParameterIndex; parameterIndex = patchAutoIndex; break; case Placeholder.USE_LAST: parameterIndex = lastIndexUsed; break; case Placeholder.HIGHEST_USED: parameterIndex = Math.max(nextParameterIndex - 1, 0); break; } lastIndexRequested = placeholder.getParameterIndex(); lastIndexUsed = parameterIndex; if(placeholder.isRegex()) { registerPlaceholderRegex(placeholder.getName(), parameterIndex, placeholder.getProcessor()); } else { registerPlaceholder(placeholder.getName(), parameterIndex, placeholder.getProcessor()); } } } private void registerPlaceholder(@NotNull String placeholder, int parameterIndex, IPlaceholderProcessor placeholderProcessor) { if(parameterIndex < 0) throw new IllegalArgumentException("Placeholder parameter index must be a positive number!"); legacyPlaceholderEngine.registerPlaceholder(placeholder, parameterIndex, placeholderProcessor); messageComponentPlaceholderEngine.registerPlaceholder(placeholder, parameterIndex, placeholderProcessor); nextParameterIndex = Math.max(nextParameterIndex, parameterIndex + 1); } private void registerPlaceholderRegex(@NotNull @Language("RegExp") String placeholder, int parameterIndex, IPlaceholderProcessor placeholderProcessor) { if(parameterIndex < 0) throw new IllegalArgumentException("Placeholder parameter index must be a positive number!"); legacyPlaceholderEngine.registerPlaceholderRegex(placeholder, parameterIndex, placeholderProcessor); messageComponentPlaceholderEngine.registerPlaceholderRegex(placeholder, parameterIndex, placeholderProcessor); nextParameterIndex = Math.max(nextParameterIndex, parameterIndex + 1); } public String formatLegacy(Object... parameters) { return legacyPlaceholderEngine.processPlaceholders(parameters); } public String format(Object... parameters) { return messageComponentPlaceholderEngine.processPlaceholders(parameters); } public void prepare() { messageComponentPlaceholderEngine.prepare(); prepared = true; } }
4,738
Java
.java
107
41.168224
154
0.804762
GeorgH93/PCGF_PluginLib
26
12
17
GPL-3.0
9/4/2024, 7:50:31 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,738
2,091,433
SmppAPIServiceImpl.java
liuyanning_sms_platform/sms-netway-sender/src/main/java/com/hero/wireless/netway/service/impl/SmppAPIServiceImpl.java
package com.hero.wireless.netway.service.impl; import com.drondea.sms.channel.ChannelSession; import com.drondea.sms.common.util.SystemClock; import com.drondea.sms.message.IMessage; import com.drondea.sms.message.smpp34.SmppDeliverSmRequestMessage; import com.drondea.sms.message.smpp34.SmppDeliverSmResponseMessage; import com.drondea.sms.message.smpp34.SmppReportRequestMessage; import com.drondea.sms.session.smpp.SmppServerSession; import com.drondea.sms.type.UserChannelConfig; import com.hero.wireless.enums.NotifyStatus; import com.hero.wireless.enums.ReportStatus; import com.hero.wireless.netway.handler.AbstractMOResponseHandler; import com.hero.wireless.netway.handler.AbstractReportResponseHandler; import com.hero.wireless.web.config.DatabaseCache; import com.hero.wireless.web.entity.business.EnterpriseUser; import com.hero.wireless.web.entity.send.Inbox; import com.hero.wireless.web.entity.send.Report; import com.hero.wireless.web.entity.send.ReportNotify; import com.hero.wireless.web.util.SMSUtil; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateFormatUtils; import org.springframework.stereotype.Component; /** * @author volcano * @version V1.0 * @date 2019年11月28日下午10:54:56 */ @Component public class SmppAPIServiceImpl extends AbstractTcpService { @Override public String genLocalCacheKey(String bachNum, String userId) { return "smpp_" + bachNum + "_" + userId; } @Override public IMessage getReportMessage(ChannelSession channelSession, Report entity) { // 写入状态 SmppDeliverSmRequestMessage request = new SmppDeliverSmRequestMessage(); request.getHeader().setSequenceNumber(channelSession.getSequenceNumber().next()); String countryCode = entity.getCountry_Code(); String phoneNo = countryCode + entity.getPhone_No(); //过滤前的手机号 phoneNo = DatabaseCache.getUserCountryCodePhoneNo(entity.getEnterprise_User_Id(), phoneNo); request.setSourceAddrTon((short) 1); request.setSourceAddrNpi((short) 1); request.setSourceAddr(phoneNo); String msgId = entity.getEnterprise_Msg_Id(); if(StringUtils.isBlank(msgId)){ return null; } SmppReportRequestMessage reportRequestMessage = new SmppReportRequestMessage(); reportRequestMessage.setId(msgId); String t = DateFormatUtils.format(SystemClock.now(), "yyMMddHHmm"); String submitTime = DateFormatUtils.format(entity.getSubmit_Date(), "yyMMddHHmm"); reportRequestMessage.setSubmit_date(submitTime); reportRequestMessage.setDone_date(t); reportRequestMessage.setStat(StringUtils.defaultIfEmpty(entity.getNative_Status(), entity.getStatus_Code())); if (entity.getStatus_Code().equalsIgnoreCase(ReportStatus.SUCCESS.toString())) { reportRequestMessage.setStat("DELIVRD"); } request.setReportRequest(reportRequestMessage); UserChannelConfig channelConfig = ((SmppServerSession) channelSession).getUserChannelConfig(); request.setDestAddrTon((short) 1); request.setDestAddrNpi((short) 1); request.setDestinationAddr(channelConfig.getUserName() + StringUtils.defaultString(entity.getSub_Code(), "")); request.setRegisteredDelivery((short) 1); ReportNotify reportNotify = SMSUtil.buildReportNotify(entity); request.setMessageResponseHandler(new AbstractReportResponseHandler(reportNotify, this) { @Override public void setResponseInfo(ReportNotify reportNotify, IMessage msgRequest, IMessage msgResponse) { SmppDeliverSmResponseMessage responseMessage = (SmppDeliverSmResponseMessage) msgResponse; reportNotify.setNotify_Response_Status(String.valueOf(responseMessage.getHeader().getCommandStatus())); } }); return request; } @Override public IMessage getMOMessage(ChannelSession channelSession, Inbox inbox) { SmppDeliverSmRequestMessage request = new SmppDeliverSmRequestMessage(); request.getHeader().setSequenceNumber(channelSession.getSequenceNumber().next()); if (StringUtils.isNotBlank(inbox.getCharset())) { byte charSet = SMSUtil.getGeneralDataCodingDcs(inbox.getCharset()); request.setMsgContent(inbox.getContent(), charSet); } else { request.setMsgContent(inbox.getContent()); } //todo inbox要不要国家码 String phoneNo = inbox.getPhone_No().replaceFirst("\\+", ""); //过滤前的手机号 phoneNo = DatabaseCache.getUserCountryCodePhoneNo(inbox.getEnterprise_User_Id(),phoneNo); request.setSourceAddrTon((short) 1); request.setSourceAddrNpi((short) 1); request.setSourceAddr(phoneNo); UserChannelConfig channelConfig = ((SmppServerSession) channelSession).getUserChannelConfig(); request.setDestAddrTon((short) 1); request.setDestAddrNpi((short) 1); EnterpriseUser enterpriseUser = DatabaseCache.getEnterpriseUserCachedById(Integer.parseInt(channelConfig.getId())); if (enterpriseUser == null) { inbox.setNotify_Status_Code(NotifyStatus.FAILD.toString()); return null; } request.setDestinationAddr(getDestId(channelConfig.getUserName(), enterpriseUser.getMo_Sp_Type_Code(), inbox)); ReportNotify reportNotify = SMSUtil.buildReportNotify(inbox); request.setMessageResponseHandler(new AbstractMOResponseHandler(reportNotify, this) { @Override public void setResponseInfo(ReportNotify reportNotify, IMessage msgRequest, IMessage msgResponse) { SmppDeliverSmResponseMessage responseMessage = (SmppDeliverSmResponseMessage) msgResponse; reportNotify.setNotify_Response_Status("MO:" + responseMessage.getHeader().getCommandStatus()); } @Override public void setRequestInfo(ReportNotify reportNotify, IMessage msgRequest) { SmppDeliverSmRequestMessage request = (SmppDeliverSmRequestMessage) msgRequest; String msgContent = request.getMsgContent(); reportNotify.setContent(msgContent); reportNotify.setContent_Length(msgContent.length()); } }); return request; } }
6,425
Java
.java
119
45.588235
123
0.733996
liuyanning/sms_platform
14
5
0
AGPL-3.0
9/4/2024, 8:29:07 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
6,367
1,882,946
LibraryScanStatusService.java
ManaZeak_ManaZeak/back/src/main/java/org/manazeak/manazeak/service/library/LibraryScanStatusService.java
package org.manazeak.manazeak.service.library; import lombok.RequiredArgsConstructor; import org.manazeak.manazeak.annotations.TransactionalWithRollback; import org.manazeak.manazeak.daos.computation.ScanStatusDAO; import org.manazeak.manazeak.entity.dto.library.scan.ScanStatusDto; import org.springframework.stereotype.Service; @TransactionalWithRollback @Service @RequiredArgsConstructor public class LibraryScanStatusService { private final ScanStatusDAO scanStatusDAO; /** * @return Get the library scan status if there is one, return null is there is none. */ public ScanStatusDto getLibraryScanStatus() { return scanStatusDAO.getCurrentScanStatus(); } }
701
Java
.java
18
35.722222
89
0.824225
ManaZeak/ManaZeak
19
4
15
GPL-3.0
9/4/2024, 8:22:09 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
701
541,813
SimpleTestEventListenerComponent.java
AllayMC_Allay/server/src/test/java/org/allaymc/server/component/impl/SimpleTestEventListenerComponent.java
package org.allaymc.server.component.impl; import org.allaymc.api.eventbus.EventHandler; import org.allaymc.server.component.annotation.Identifier; import org.allaymc.server.component.event.TestEvent; import org.allaymc.server.component.interfaces.TestEventListenerComponent; /** * @author daoge_cmd */ public class SimpleTestEventListenerComponent implements TestEventListenerComponent { @Identifier public static final org.allaymc.api.utils.Identifier IDENTIFIER = new org.allaymc.api.utils.Identifier("minecraft:test_event_listener_component"); @EventHandler protected void testListener(TestEvent event) { event.setMessage("testListener() accepted to the event!"); } }
705
Java
.java
16
41
150
0.813411
AllayMC/Allay
157
12
40
LGPL-3.0
9/4/2024, 7:07:37 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
705
3,225,152
SystemWideValidationNodeConfig.java
LIBCAS_ARCLib/system/src/main/java/cz/cas/lib/arclib/service/arclibxml/systemWideValidation/SystemWideValidationNodeConfig.java
package cz.cas.lib.arclib.service.arclibxml.systemWideValidation; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.ToString; @Getter @AllArgsConstructor @ToString public class SystemWideValidationNodeConfig { private String xpathRoot; private String xpathRelative; private boolean xsltSource; }
330
Java
.java
12
25.333333
65
0.85443
LIBCAS/ARCLib
4
1
18
GPL-3.0
9/4/2024, 11:06:24 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
330
198,346
WikiHistory.java
openkm_document-management-system/src/main/java/com/openkm/extension/frontend/client/widget/wiki/WikiHistory.java
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) Paco Avila & Josep Llort * <p> * No bytes were intentionally harmed during the development of this application. * <p> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * <p> * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p> * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.extension.frontend.client.widget.wiki; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.user.client.ui.*; import com.openkm.frontend.client.Main; import com.openkm.frontend.client.bean.extension.GWTWikiPage; import com.openkm.frontend.client.extension.comunicator.GeneralComunicator; import java.util.List; /** * WikiHistory * * @author jllort * */ public class WikiHistory extends Composite { private FlexTable table; private WikiController controller; private List<GWTWikiPage> wikiPages; /** * WikiHistory */ public WikiHistory(final WikiController controller) { this.controller = controller; SimplePanel sp = new SimplePanel(); table = new FlexTable(); table.setCellPadding(5); table.setCellSpacing(0); sp.add(table); sp.setWidth("100%"); initWidget(sp); } /** * showHistory * * @param wikiPages */ public void showHistory(final List<GWTWikiPage> wikiPages, boolean locked) { this.wikiPages = wikiPages; for (GWTWikiPage wikiPage : wikiPages) { final int row = table.getRowCount(); DateTimeFormat dtf = DateTimeFormat.getFormat(Main.i18n("general.date.pattern")); table.setHTML(row, 0, dtf.format(wikiPage.getDate())); table.setHTML(row, 1, wikiPage.getUser()); // Restore button if (!locked && row > 0) { Button restoreButton = new Button(GeneralComunicator.i18n("button.restore")); restoreButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { controller.restoreWikiPage(wikiPages.get(row)); } }); restoreButton.setStyleName("okm-YesButton"); table.setWidget(row, 2, restoreButton); } else { table.setHTML(row, 2, ""); } // Show older version button if (row > 0) { Button showButton = new Button(GeneralComunicator.i18n("button.view")); showButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { controller.showHistoryWikiPageVersion(wikiPages.get(row)); } }); showButton.setStyleName("okm-ViewButton"); table.setWidget(row, 3, showButton); } else { table.setHTML(row, 3, ""); } // Show deleted if (wikiPage.isDeleted()) { HTML deleted = new HTML(GeneralComunicator.i18nExtension("wiki.deleted")); deleted.setStyleName("okm-Input-Error"); table.setWidget(row, 4, deleted); } else { table.setHTML(row, 4, ""); } table.getFlexCellFormatter().setVerticalAlignment(row, 0, HasAlignment.ALIGN_MIDDLE); table.getFlexCellFormatter().setVerticalAlignment(row, 1, HasAlignment.ALIGN_MIDDLE); } } /** * langRefresh */ public void langRefresh() { int row = 0; if (wikiPages != null) { for (GWTWikiPage wikiPage : wikiPages) { if (wikiPage.isDeleted()) { HTML deleted = new HTML(GeneralComunicator.i18nExtension("wiki.deleted")); deleted.setStyleName("okm-Input-Error"); table.setWidget(row, 4, deleted); row++; } } } } /** * reset */ public void reset() { removeAllRows(); } /** * removeAllRows */ private void removeAllRows() { while (table.getRowCount() > 0) { table.removeRow(0); } } }
4,238
Java
.java
135
28.088889
88
0.723893
openkm/document-management-system
690
302
14
GPL-2.0
9/4/2024, 7:05:34 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,238
3,158,512
TypeListModel.java
ModelWriter_WP3/Source/eu.modelwriter.visualization.jgrapx/src/eu/modelwriter/visualization/editor/wizard/TypeListModel.java
package eu.modelwriter.visualization.editor.wizard; import java.util.List; import javax.swing.ListModel; import javax.swing.event.ListDataListener; public class TypeListModel implements ListModel<Object> { private final List<Object> types; public TypeListModel(final List<Object> list) { this.types = list; } @Override public void addListDataListener(final ListDataListener l) { } @Override public Object getElementAt(final int index) { return this.types.get(index); } @Override public int getSize() { return this.types.size(); } @Override public void removeListDataListener(final ListDataListener l) { } }
660
Java
.java
24
24.291667
64
0.7744
ModelWriter/WP3
4
1
55
EPL-1.0
9/4/2024, 11:01:53 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
660
3,108,921
PdfSignatureDictionaryCheckTest.java
TNO_Quantum-Safe-DSS/validation-policy/src/test/java/eu/europa/esig/dss/validation/process/bbb/fc/PdfSignatureDictionaryCheckTest.java
/** * DSS - Digital Signature Services * Copyright (C) 2015 European Commission, provided under the CEF programme * * This file is part of the "DSS - Digital Signature Services" project. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package eu.europa.esig.dss.validation.process.bbb.fc; import eu.europa.esig.dss.detailedreport.jaxb.XmlConstraint; import eu.europa.esig.dss.detailedreport.jaxb.XmlFC; import eu.europa.esig.dss.detailedreport.jaxb.XmlStatus; import eu.europa.esig.dss.diagnostic.PDFRevisionWrapper; import eu.europa.esig.dss.diagnostic.jaxb.XmlPDFRevision; import eu.europa.esig.dss.diagnostic.jaxb.XmlPDFSignatureDictionary; import eu.europa.esig.dss.policy.jaxb.Level; import eu.europa.esig.dss.policy.jaxb.LevelConstraint; import eu.europa.esig.dss.validation.process.bbb.AbstractTestCheck; import eu.europa.esig.dss.validation.process.bbb.fc.checks.PdfSignatureDictionaryCheck; import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; public class PdfSignatureDictionaryCheckTest extends AbstractTestCheck { @Test public void valid() throws Exception { XmlPDFRevision pdfRevision = new XmlPDFRevision(); XmlPDFSignatureDictionary pdfSignatureDictionary = new XmlPDFSignatureDictionary(); pdfSignatureDictionary.setConsistent(true); pdfRevision.setPDFSignatureDictionary(pdfSignatureDictionary); LevelConstraint constraint = new LevelConstraint(); constraint.setLevel(Level.FAIL); XmlFC result = new XmlFC(); PdfSignatureDictionaryCheck sdc = new PdfSignatureDictionaryCheck(i18nProvider, result, new PDFRevisionWrapper(pdfRevision), constraint); sdc.execute(); List<XmlConstraint> constraints = result.getConstraint(); assertEquals(1, constraints.size()); assertEquals(XmlStatus.OK, constraints.get(0).getStatus()); } @Test public void invalid() throws Exception { XmlPDFRevision pdfRevision = new XmlPDFRevision(); XmlPDFSignatureDictionary pdfSignatureDictionary = new XmlPDFSignatureDictionary(); pdfSignatureDictionary.setConsistent(false); pdfRevision.setPDFSignatureDictionary(pdfSignatureDictionary); LevelConstraint constraint = new LevelConstraint(); constraint.setLevel(Level.FAIL); XmlFC result = new XmlFC(); PdfSignatureDictionaryCheck sdc = new PdfSignatureDictionaryCheck(i18nProvider, result, new PDFRevisionWrapper(pdfRevision), constraint); sdc.execute(); List<XmlConstraint> constraints = result.getConstraint(); assertEquals(1, constraints.size()); assertEquals(XmlStatus.NOT_OK, constraints.get(0).getStatus()); } }
3,460
Java
.java
66
47.575758
145
0.77301
TNO/Quantum-Safe-DSS
5
0
0
LGPL-2.1
9/4/2024, 10:49:38 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,460
4,364,547
PathCollection.java
jotagarciaz_CoPilot/CoPilotApp/app/src/main/java/com/mdh/ivanmuniz/copilotapp/collection/PathCollection.java
package com.mdh.ivanmuniz.copilotapp.collection; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.DocumentChange; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FieldValue; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.GeoPoint; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import com.google.firebase.firestore.SetOptions; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.mdh.ivanmuniz.copilotapp.object.Path; import com.mdh.ivanmuniz.copilotapp.object.Point; import com.mdh.ivanmuniz.copilotapp.user.User; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class PathCollection implements EventListener<QuerySnapshot> { // Events public static final int INSERT_EVENT = 0; public static final int REMOVE_EVENT = 1; public static final int UPDATE_EVENT = 4; public static final int PREVIEW_EVENT = 8; private static final String DB_DOCUMENT = "path"; // Properties private List<IPathCollectionEventHandler> eventListeners; private List<Path> pathList; private FirebaseFirestore database; private FirebaseStorage storage; private static PathCollection _instance; private PathCollection(){ eventListeners = new ArrayList<>(); pathList = new ArrayList<>(); // Get data from Firebase. database = FirebaseFirestore.getInstance(); storage = FirebaseStorage.getInstance(); // Listen for path changes database.collection(DB_DOCUMENT).addSnapshotListener( this ); } /* ** Get singleton */ public static PathCollection getInstance(){ if( _instance == null ) _instance = new PathCollection(); return _instance; } /* ** Add a path */ public void add( Path path ){ // Add path locally pathList.add( path ); Map<String, Object> add = new HashMap<>(); add.put( "name", path.getName() ); add.put( "description", path.getDescription() ); add.put( "editedBy", User.getInstance().getID() ); add.put( "createdBy", User.getInstance().getID() ); add.put( "creationDate", path.getCreationDate().getTime() ); add.put( "editDate", path.getEditDate().getTime() ); add.put( "pathList", createViablePointList( path ) ); final Bitmap preview = path.getPreview(); // Add path to Firebase database.collection(DB_DOCUMENT) .add( add ) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { Log.d("PathCollection", "DocumentSnapshot written with ID: " + documentReference.getId() ); // Upload the preview image uploadPreviewImage( documentReference.getId(), preview ); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w( "PathCollection", "Error adding document", e); } }); } /* ** Remove a path */ public void remove( Path path ){ // Remove from Firebase database.collection(DB_DOCUMENT).document( path.getId() ) .delete() .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d( "PathCollection", "DocumentSnapshot successfully deleted!"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w( "PathCollection", "Error deleting document", e); } }); } /* ** Change name and description for a path */ public void updateDescription(String pathId, String name, String desc ){ Map<String, Object> change = new HashMap<>(); change.put( "name", name ); change.put( "description", desc ); change.put( "editedBy", User.getInstance().getID() ); change.put( "editDate", (new Date()).getTime() ); database.collection(DB_DOCUMENT).document( pathId ) .update( change ) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d( "PathCollection", "DocumentSnapshot successfully updated!"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w( "PathCollection", "Error updating document", e); } }); } /* ** Update paths and preview image for a path */ public void update( Path path ){ if( path.getId().equals("") ) return; final String id = path.getId(); if( path.getPathList() == null || path.getPathList().size() == 0 ) return; // Upload new pathList final Map<String, Object> change = new HashMap<>(); change.put( "editedBy", User.getInstance().getID() ); change.put( "editDate", path.getEditDate().getTime() ); change.put( "pathList", createViablePointList( path ) ); database.collection(DB_DOCUMENT).document( id ) .update( change ) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d( "PathCollection", "DocumentSnapshot successfully updated!"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w( "PathCollection", "Error updating document", e); } }); // Upload new preview uploadPreviewImage( id, path.getPreview() ); // Temporary fix for instant change of preview image, in case the upload/download is slow broadcastEvent( path, PREVIEW_EVENT ); } /* ** Get a list of all paths available */ public List<Path> getPathList(){ // Return a copy, since this internal list is not supposed to be modified return new ArrayList<>( pathList ); } // Get a single path if it exists public Path getPath( String id ){ // Find the path object by id for( Path p : pathList ) { if( !p.getId().equals( id ) ) continue; // Return it return p; } // No path found return null; } /* ** Listen for Firebase events (add, updateDescription, remove) */ public void onEvent(@Nullable QuerySnapshot snapshot, @Nullable FirebaseFirestoreException e ){ if( e != null ){ Log.w("PathCollection", "listen:error", e ); return; } for (DocumentChange dc : snapshot.getDocumentChanges()) { switch (dc.getType()) { case ADDED: onFirebasePathAdd( dc.getDocument() ); break; case MODIFIED: onFirebasePathChange( dc.getDocument() ); break; case REMOVED: onFirebasePathRemove( dc.getDocument() ); break; } } } private void onFirebasePathAdd( QueryDocumentSnapshot snapshot ){ // If there is a path with empty id, we only need to updateDescription the id value final String id = snapshot.getId(); for( Path p : pathList ){ if( !p.getId().equals("") ) continue; // The new path was found, other tasks are not to be done p.setId( id ); broadcastEvent( p, UPDATE_EVENT ); return; } // Path was not found, so we need to updateDescription it Path path = new Path( snapshot.getString("name" ), snapshot.getString("description" ) ); path.setId( id ); path.setEditedBy( snapshot.getString("editedBy" ) ); path.setCreatedBy( snapshot.getString("createdBy" ) ); path.setCreatedDate( new Date( snapshot.getLong("creationDate" ) ) ); path.setEditDate( new Date( snapshot.getLong( "editDate" ) ) ); downloadPreviewImage( id ); // Get path list ArrayList<Map<String,Object>> data = (ArrayList<Map<String,Object>>)snapshot.get("pathList"); if( data != null ){ for( Map<String,Object> map : data ){ GeoPoint point = (GeoPoint)map.get("point"); long type = (long)map.get("type"); long curveDirection = (long)map.get( "curveDirection" ); path.addPoint( point.getLatitude(), point.getLongitude(), (int)type ); Point p = path.getPoint( path.getPathListSize() - 1 ); p.setLoad( tryGetState( map, "stateLoad" ) ); p.setUnload( tryGetState( map, "stateUnload" ) ); p.setWait( tryGetState( map, "stateWait" ) ); p.setInterest( tryGetState( map, "stateInterest" ) ); p.setFinish( tryGetState( map, "stateFinish" ) ); p.setCurveDirection( (int)curveDirection ); p.setCurveMagnitude( (double)map.get( "curveMagnitude" ) ); } } pathList.add( path ); broadcastEvent( path, INSERT_EVENT ); } private void onFirebasePathChange( QueryDocumentSnapshot snapshot ){ // Get the path that has changed String documentId = snapshot.getId(); downloadPreviewImage( documentId ); for( int i = 0; i < pathList.size(); i++ ){ Path path = pathList.get( i ); if( !path.equals( documentId ) ) continue; path.setName( snapshot.getString("name" ) ); path.setDescription( snapshot.getString("description" ) ); path.setEditDate( new Date( snapshot.getLong( "editDate" ) ) ); path.setEditedBy( snapshot.getString("editedBy" ) ); // Get path list ArrayList<Map<String,Object>> data = (ArrayList<Map<String,Object>>)snapshot.get("pathList"); if( data != null ){ // Clear points before getting new batch. path.clearPoints(); for( Map<String,Object> map : data ){ GeoPoint point = (GeoPoint)map.get("point"); long type = (long)map.get("type"); long curveDirection = (long)map.get( "curveDirection" ); path.addPoint( point.getLatitude(), point.getLongitude(), (int)type ); Point p = path.getPoint( path.getPathListSize() - 1 ); p.setLoad( tryGetState( map, "stateLoad" ) ); p.setUnload( tryGetState( map, "stateUnload" ) ); p.setWait( tryGetState( map, "stateWait" ) ); p.setInterest( tryGetState( map, "stateInterest" ) ); p.setFinish( tryGetState( map, "stateFinish" ) ); p.setCurveDirection( (int)curveDirection ); p.setCurveMagnitude( (double)map.get( "curveMagnitude" ) ); } } broadcastEvent( path, UPDATE_EVENT ); } } private void onFirebasePathRemove( QueryDocumentSnapshot snapshot ){ // Get id of path that was removed String documentId = snapshot.getId(); StorageReference storageRef = storage.getReference(); StorageReference imageRef = storageRef.child( "preview/" + documentId + ".png" ); imageRef.delete(); for( int i = 0; i < pathList.size(); i++ ){ Path path = pathList.get( i ); if( !path.equals( documentId ) ) continue; // Remove locally pathList.remove( path ); // Send event broadcastEvent( path, REMOVE_EVENT ); // If a path is removed, it can't be a favorite anymore, so we remove it User.getInstance().removeFavoritePath( path.getId() ); } } private void downloadPreviewImage(final String id ){ // When ID gets added, get the preview image for this path from the cloud storage StorageReference storageRef = storage.getReference(); StorageReference imageRef = storageRef.child("preview/" + id + ".png"); final long ONE_MEGABYTE = 1024 * 1024; imageRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() { @Override public void onSuccess(byte[] bytes) { // Data for "images/island.jpg" is returned, use this as needed Bitmap bitmap = BitmapFactory.decodeByteArray( bytes,0, bytes.length ); for( Path p : pathList ){ if( !p.getId().equals( id ) ) continue; p.setPreview( bitmap ); broadcastEvent( p, PREVIEW_EVENT ); break; } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Failed to get image. } }); } private void uploadPreviewImage( final String id, final Bitmap bitmap ) { // In case the image trying to be uploaded is null if( bitmap == null ) return; // Update Firebase cloud storage with new image ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] data = baos.toByteArray(); // Create a storage reference StorageReference storageRef = storage.getReference(); StorageReference imageRef = storageRef.child( "preview/" + id + ".png"); // Upload the image UploadTask uploadTask = imageRef.putBytes( data ); uploadTask.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle unsuccessful uploads } }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { // taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc. // ... downloadPreviewImage( id ); } }); } private ArrayList<Map<String, Object>> createViablePointList( Path path ){ ArrayList<Map<String, Object>> pointList = new ArrayList<>(); for( Point point : path.getPathList() ){ HashMap<String, Object> data = new HashMap<>(); data.put( "point", new GeoPoint( point.getLat(), point.getLng() ) ); data.put( "type", point.getType() ); data.put( "stateLoad", point.isLoad() ); data.put( "stateUnload", point.isUnload() ); data.put( "stateWait", point.isWait() ); data.put( "stateInterest", point.isInterest() ); data.put( "stateFinish", point.isFinish() ); data.put( "curveDirection", point.getCurveDirection() ); data.put( "curveMagnitude", point.getCurveMagnitude() ); pointList.add( data ); } return pointList; } private Boolean tryGetState( Map<String,Object> map, String stateName ){ try { if( map.containsKey( stateName ) ) return (Boolean)map.get( stateName ); return false; } catch( Exception e ) { return false; } } /* ** Events handling */ public void addListener( IPathCollectionEventHandler listener ){ eventListeners.add( listener ); } public void removeListener( IPathCollectionEventHandler listener ){ eventListeners.remove( listener ); } private void broadcastEvent( Path item, int type ) { for( IPathCollectionEventHandler handler : eventListeners) handler.onDataEvent( item, type ); } public interface IPathCollectionEventHandler { void onDataEvent( Path path, int type ); } }
17,589
Java
.java
401
32.805486
111
0.591488
jotagarciaz/CoPilot
2
0
0
LGPL-3.0
9/5/2024, 12:10:33 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
17,589
2,060,838
GetSavedListsQuery.java
Talent-Catalog_talentcatalog/server/src/main/java/org/tctalent/server/repository/db/GetSavedListsQuery.java
/* * Copyright (c) 2023 Talent Beyond Boundaries. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see https://www.gnu.org/licenses/. */ package org.tctalent.server.repository.db; import java.util.HashSet; import java.util.Set; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.springframework.data.jpa.domain.Specification; import org.springframework.lang.Nullable; import org.tctalent.server.model.db.SavedList; import org.tctalent.server.model.db.User; import org.tctalent.server.request.list.SearchSavedListRequest; /** * Specification which defines a GetSavedListsQuery * * @author John Cameron */ @RequiredArgsConstructor public class GetSavedListsQuery implements Specification<SavedList> { final private SearchSavedListRequest request; @Nullable final private User loggedInUser; @Override public Predicate toPredicate( Root<SavedList> savedList, CriteriaQuery<?> query, CriteriaBuilder cb) { Predicate conjunction = cb.conjunction(); query.distinct(true); //Only return lists which are not Selection lists - //ie lists with no associated saved search. conjunction.getExpressions().add( cb.isNull(savedList.get("savedSearch"))); // KEYWORD SEARCH if (!StringUtils.isBlank(request.getKeyword())){ String lowerCaseMatchTerm = request.getKeyword().toLowerCase(); String likeMatchTerm = "%" + lowerCaseMatchTerm + "%"; conjunction.getExpressions().add( cb.like(cb.lower(savedList.get("name")), likeMatchTerm)); } //If fixed is specified, only supply matching saved lists if (request.getFixed() != null && request.getFixed()) { conjunction.getExpressions().add(cb.equal(savedList.get("fixed"), true) ); } //If registeredJob is specified and true, only supply matching saved lists if (request.getRegisteredJob() != null && request.getRegisteredJob()) { conjunction.getExpressions().add(cb.equal(savedList.get("registeredJob"), true)); } //If sfOppIsClosed is specified, and sfJobOpp is not null, only supply saved list with // matching job closed. if (request.getSfOppClosed() != null) { //Closed condition is only meaningful if sfJobOpp is present conjunction.getExpressions().add(cb.isNotNull(savedList.get("sfJobOpp"))); conjunction.getExpressions().add(cb.equal(savedList.get("sfOppIsClosed"), request.getSfOppClosed())); } //If short name is specified, only supply matching saved lists. If false, remove if (request.getShortName() != null && request.getShortName()) { conjunction.getExpressions().add( cb.isNotNull(savedList.get("tbbShortName")) ); } else if (request.getShortName() != null && !request.getShortName()){ conjunction.getExpressions().add( cb.isNull(savedList.get("tbbShortName")) ); } // (shared OR owned OR global) Predicate ors = cb.disjunction(); if (request.getGlobal() != null && request.getGlobal()) { ors.getExpressions().add( cb.equal(savedList.get("global"), request.getGlobal()) ); } //If shared is specified, only supply searches shared with the owner if (request.getShared() != null && request.getShared()) { if (loggedInUser != null) { Set<SavedList> sharedLists = loggedInUser.getSharedLists(); Set<Long> sharedIDs = new HashSet<>(); for (SavedList sharedList : sharedLists) { sharedIDs.add(sharedList.getId()); } ors.getExpressions().add( savedList.get("id").in( sharedIDs ) ); } } //If owned by this user (ie by logged in user) if (request.getOwned() != null && request.getOwned()) { if (loggedInUser != null) { ors.getExpressions().add( cb.equal(savedList.get("createdBy"), loggedInUser) ); } } if (ors.getExpressions().size() != 0) { conjunction.getExpressions().add(ors); } return conjunction; } }
5,194
Java
.java
114
36.885965
113
0.653239
Talent-Catalog/talentcatalog
10
4
384
AGPL-3.0
9/4/2024, 8:28:04 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
5,194
4,335,917
BAFRECStrategy.java
HermannKroll_EntityCharacterization/src/main/java/de/bs/tu/ifis/evaluation/strategies/BAFRECStrategy.java
package de.bs.tu.ifis.evaluation.strategies; import de.bs.tu.ifis.evaluation.EvaluationStrategy; import de.bs.tu.ifis.evaluation.metrics.*; import de.bs.tu.ifis.model.Predicate; import edu.cmu.lti.lexical_db.ILexicalDatabase; import edu.cmu.lti.lexical_db.NictWordNet; import edu.cmu.lti.ws4j.impl.WuPalmer; import edu.cmu.lti.ws4j.util.WS4JConfiguration; import java.util.*; import java.util.stream.Collectors; /** * BAFREC implementation * ranks all predicates with the introduced BAFREC strategy * 1. categorize predicates into meta and data information * 2. rank both categorizes * 3. pick with weighted round robin * @author Hermann Kroll */ public class BAFRECStrategy extends EvaluationStrategy { private static final int META_DATA_RATIO = 3; private HashMap<Class, HashMap<Predicate, Double>> scoredPredicatesForMetric = null; private List<Predicate> predicates = null; private List<Predicate> metaPredicates = new LinkedList<>(); private HashMap<String, List<Predicate>> metaPredicatesGroupByPredicate = new HashMap<>(); private List<Predicate> dataPredicates = new LinkedList<>(); private HashMap<String, List<Predicate>> dataPredicatesGroupByPredicate = new HashMap<>(); private List<Predicate> metaPredicatesRanked = new LinkedList<>(); private List<Predicate> dataPredicatesRanked = new LinkedList<>(); private static ILexicalDatabase db = new NictWordNet(); public BAFRECStrategy(){ WS4JConfiguration.getInstance().setMFS(true); } /** * resets all internal data structures */ private void clearData(){ metaPredicates.clear(); metaPredicatesGroupByPredicate.clear(); dataPredicates.clear(); dataPredicatesGroupByPredicate.clear(); metaPredicatesRanked.clear(); dataPredicatesRanked.clear(); } /** * adds an predicate regarding its group to the specific list or creates a new list, if the group does not exists * @param p predicate * @param map map to add */ private void addPredicateToHashmapList(final Predicate p, final HashMap<String, List<Predicate>> map){ List<Predicate> predicates = map.get(p.getName()); if(predicates == null){ predicates = new LinkedList<>(); predicates.add(p); map.put(p.getName(), predicates); } else{ predicates.add(p); } } /** * categorize the predicates into meta and data information */ private void categorizePredicates(){ for(final Predicate pred: predicates){ final double metascore = scoredPredicatesForMetric.get(MetaPredicatesMetric.class).get(pred); //is meta edge if(metascore > 0.8){ metaPredicates.add(pred); addPredicateToHashmapList(pred, metaPredicatesGroupByPredicate); } //no meta edge else{ dataPredicates.add(pred); addPredicateToHashmapList(pred, dataPredicatesGroupByPredicate); } } } /** * ranks the meta information * 1. first all facts are grouped by their predicate * 2. groups are ranked by frequency * 3. select for each group the predicate with largest ontology depth or rarity * 4. add selected facts into meta result * 5. go to step 1 untill all facts are selected */ private void rankMetaPredicates(){ //Repeat until every meta predicate is ranked while(metaPredicatesRanked.size() != metaPredicates.size()) { final List<Predicate> bestEntries = new LinkedList<>(); final HashMap<Predicate, Double> predScores = new HashMap<>(); for (final String key : metaPredicatesGroupByPredicate.keySet()) { for (final Predicate p : metaPredicatesGroupByPredicate.get(key)) { if(metaPredicatesRanked.contains(p)) continue; double ontDepth = scoredPredicatesForMetric.get(OntologyDepthMetric.class).get(p); //double ontSize = scoredPredicatesForMetric.get(OntologySubtreeSizeMetric.class).get(p); if (ontDepth >= 1.0) predScores.put(p, ontDepth); else { double rarity = scoredPredicatesForMetric.get(RarityMetric.class).get(p); predScores.put(p, rarity); } } List<Map.Entry<Predicate, Double>> ranked = predScores.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toList()); if(ranked.size() > 0) { final Map.Entry<Predicate, Double> best = ranked.get(0); bestEntries.add(best.getKey()); } } predScores.clear(); for(final Predicate pred : bestEntries) { double frequency = scoredPredicatesForMetric.get(FrequencyMetric.class).get(pred); predScores.put(pred, frequency); } List<Map.Entry<Predicate, Double>> ranked = predScores.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).collect(Collectors.toList()); for (final Map.Entry<Predicate, Double> entry : ranked) { metaPredicatesRanked.add(entry.getKey()); } } } /** * tokenize a combined predicate into its words * splits at capital letters * @param predicate predicate to split * @return */ private String[] tokenizeWords(final String predicate){ return predicate.split("(?=\\p{Lu})"); } /** * implementation of the introduced wordnet similarity based on ws4j * @param p1 first predicate * @param p2 second predicate * @return a similarity of the predicate concept between 0 and 1 */ private double simWordnet(final Predicate p1, final Predicate p2){ final String[] split1 = p1.getName().split("/"); final String[] split2 = p2.getName().split("/"); final String word1 = split1[split1.length-1]; final String word2 = split2[split2.length-1]; if(word1.equals(word2)){ return 1.0; } // if words are concatenated like "broadcast area" final String[] words1 = tokenizeWords(word1); final String[] words2 = tokenizeWords(word2); // compute average word sim, if multiple words are contained if(words1.length > 1 || words2.length > 1){ double summedSim = 0.0; int count = 0; for(final String w1: words1){ for(final String w2: words2){ final String w1small = w1.toLowerCase(); final String w2small = w2.toLowerCase(); if(w1small.equals(w2small)) summedSim += 1.0; else summedSim += new WuPalmer(db).calcRelatednessOfWords(w1small, w2small); count++; } } summedSim = summedSim / count; return summedSim; } // single words -> single sim double s = new WuPalmer(db).calcRelatednessOfWords(word1, word2); return s; } /** * scores a single data predicate with the popularity metric * @param p a predicate to score * @return a score */ private double scoreDataPredicate(final Predicate p){ return scoredPredicatesForMetric.get(PopularityMetric.class).get(p); } /** * */ private void rankDataPredicates(){ if(dataPredicates.size() == 0) return; final HashMap<Predicate, HashMap<Predicate, Double>> simWordnetBetweenPredicates = new HashMap<>(); for(final Predicate p1: dataPredicates){ simWordnetBetweenPredicates.put(p1, new HashMap<>()); for(final Predicate p2: dataPredicates){ double simWordnet = simWordnet(p1,p2); simWordnetBetweenPredicates.get(p1).put(p2, simWordnet); } } final HashMap<Predicate, Double> predScores = new HashMap<>(); Predicate bestPredicate = null; double score = -1.0; for(final Predicate p1: dataPredicates){ double newScore = scoreDataPredicate(p1); predScores.put(p1, newScore); if(newScore > score){ score = newScore; bestPredicate = p1; } } dataPredicatesRanked.add(bestPredicate); final List<Predicate> notSelected = new LinkedList<>(dataPredicates); notSelected.remove(bestPredicate); while(!notSelected.isEmpty()){ for(Predicate current : notSelected) { double wordNetSum = 0; int count = 0; for(final Predicate p1 : dataPredicatesRanked){ wordNetSum += simWordnetBetweenPredicates.get(current).get(p1); count++; } wordNetSum = wordNetSum / count; double wordnetInverse = (1.0 - wordNetSum); double scoreWithWordnet = wordnetInverse * predScores.get(current); predScores.put(current, scoreWithWordnet); } score = -1.0; bestPredicate = null; for(final Predicate p1: notSelected){ double newScore = predScores.get(p1); if(newScore > score){ score = newScore; bestPredicate = p1; } } //scores are all ~0 for the not selected facts -> choose different metric if(score < 0.01){ for(Predicate current : notSelected) { predScores.put(current, scoredPredicatesForMetric.get(FreqRarMetric.class).get(current)); } } score = -1.0; bestPredicate = null; for(final Predicate p1: notSelected){ double newScore = predScores.get(p1); if(newScore > score){ score = newScore; bestPredicate = p1; } } notSelected.remove(bestPredicate); dataPredicatesRanked.add(bestPredicate); } } /** * ranks all predicates with the introduced BAFREC strategy * 1. categorize predicates into meta and data information * 2. rank both categorizes * 3. pick with weighted round robin * @param predicates given set of predicates to rank * @param scoredPredicatesForMetric hashmap in which all predicates should be scored via the necessary metrics * @return */ @Override public List<Predicate> rankPredicate(List<Predicate> predicates, HashMap<Class, HashMap<Predicate, Double>> scoredPredicatesForMetric) { //Reset all internal datastructres clearData(); this.predicates = predicates; this.scoredPredicatesForMetric = scoredPredicatesForMetric; //First sort the predicates into categories categorizePredicates(); //Rank meta & data predicates rankMetaPredicates(); rankDataPredicates(); //Result set final List<Predicate> bestPredicates = new LinkedList<>(); // Do weighted round robin pick long resultSize = predicates.size(); while(bestPredicates.size() != resultSize){ //First pick a meta information if(metaPredicatesRanked.size() > 0) { bestPredicates.add(metaPredicatesRanked.get(0)); metaPredicatesRanked.remove(0); if(bestPredicates.size() == resultSize) break; } //Next pick the amount of meta facts given by the parameter for(int i = 0; i < META_DATA_RATIO; i++) { if(dataPredicatesRanked.size() > 0) { bestPredicates.add(dataPredicatesRanked.get(0)); dataPredicatesRanked.remove(0); if(bestPredicates.size() == resultSize) break; } } } return bestPredicates; } }
12,419
Java
.java
289
32.051903
182
0.608688
HermannKroll/EntityCharacterization
2
1
1
GPL-3.0
9/5/2024, 12:09:30 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
12,419
3,144,638
IdValueConverter.java
selfbus_development-tools-incubation/sbtools-products-editor/src/main/java/org/selfbus/sbtools/prodedit/binding/IdValueConverter.java
package org.selfbus.sbtools.prodedit.binding; import org.selfbus.sbtools.prodedit.internal.I18n; /** * A {@link FormatValueConverter} with the localized format "ID {0}". */ public class IdValueConverter extends FormatValueConverter { public IdValueConverter() { super(I18n.getMessage("IdValueConverter.label")); } }
335
Java
.java
12
25.333333
69
0.772586
selfbus/development-tools-incubation
4
1
2
GPL-3.0
9/4/2024, 11:00:44 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
335
878,334
OpenAPIStereotypesUtils.java
opendata-for-all_wapiml/plugins/edu.uoc.som.wapiml/src/edu/uoc/som/wapiml/utils/OpenAPIStereotypesUtils.java
package edu.uoc.som.wapiml.utils; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.uml2.uml.NamedElement; import org.eclipse.uml2.uml.Stereotype; import org.eclipse.uml2.uml.UMLPlugin; import org.eclipse.uml2.uml.util.UMLUtil; import edu.uoc.som.openapi2.profile.OpenAPIProfilePackage; import edu.uoc.som.wapiml.resources.WAPImlResource; /** * Inspired from {@link https://github.com/dice-project/DICE-Simulation/blob/master/bundles/es.unizar.disco.simulation.models/src/es/unizar/disco/simulation/models/util/MarteStereotypesUtils.java}} * */ public class OpenAPIStereotypesUtils { private static class InternalUMLUtil extends UMLUtil{ private static final URI OPENAPI_PROFILE_URI = UMLPlugin.getEPackageNsURIToProfileLocationMap().get(OpenAPIProfilePackage.eNS_URI); private static final EObject OPENAPI_PROFILE_EPACKAGE = WAPImlResource.getUMResourceSet().getResource(OPENAPI_PROFILE_URI, true).getEObject(OPENAPI_PROFILE_URI.fragment()); protected static Stereotype getStereotype(EClass definition) { NamedElement namedElement = UMLUtil.getNamedElement(definition, OPENAPI_PROFILE_EPACKAGE); return namedElement instanceof Stereotype ? (Stereotype) namedElement : null; } } private static Stereotype getStereotype(EClass definition) { return InternalUMLUtil.getStereotype(definition); } public static String getStereotypeQn(EClass definition) { Stereotype stereotype = getStereotype(definition); return stereotype != null ? stereotype.getQualifiedName() : null; //$NON-NLS-1$ } }
1,651
Java
.java
31
49.645161
198
0.806754
opendata-for-all/wapiml
69
18
8
EPL-2.0
9/4/2024, 7:09:48 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,651
2,896,593
ItemNuggetCopper.java
hockeyhurd_Project-Zed/com/projectzed/mod/item/metals/ItemNuggetCopper.java
/* * This file is part of Project-Zed. Project-Zed is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Project-Zed is * distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along * with Project-Zed. If not, see <http://www.gnu.org/licenses/> * */ package com.projectzed.mod.item.metals; import com.hockeyhurd.hcorelib.api.item.AbstractHCoreItem; import com.projectzed.mod.ProjectZed; /** * Item class for nuggetCopper. * * @author hockeyhurd * @version 6/30/2015. */ public class ItemNuggetCopper extends AbstractHCoreItem { public ItemNuggetCopper(String name, String assetDir) { super(ProjectZed.modCreativeTab, assetDir, name); } }
1,065
Java
.java
22
46.454545
149
0.787091
hockeyhurd/Project-Zed
5
1
4
GPL-2.0
9/4/2024, 10:33:41 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,065
3,995,063
VmusagePK.java
zandinux_ODCM/odcm.client/src/odcmdb/VmusagePK.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package odcmdb; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Embeddable; /** * * @author zantaz */ @Embeddable public class VmusagePK implements Serializable { @Basic(optional = false) @Column(name = "Vm_id", nullable = false) private long vmid; @Basic(optional = false) @Column(name = "Host_id", nullable = false) private long hostid; public VmusagePK() { } public VmusagePK(long vmid, long hostid) { this.vmid = vmid; this.hostid = hostid; } public long getVmid() { return vmid; } public void setVmid(long vmid) { this.vmid = vmid; } public long getHostid() { return hostid; } public void setHostid(long hostid) { this.hostid = hostid; } @Override public int hashCode() { int hash = 0; hash += (int) vmid; hash += (int) hostid; return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof VmusagePK)) { return false; } VmusagePK other = (VmusagePK) object; if (this.vmid != other.vmid) { return false; } if (this.hostid != other.hostid) { return false; } return true; } @Override public String toString() { return "DataBase.VmusagePK[ vmid=" + vmid + ", hostid=" + hostid + " ]"; } }
1,690
Java
.java
66
19.666667
87
0.6051
zandinux/ODCM
2
1
0
GPL-2.0
9/4/2024, 11:59:28 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,690
2,074,953
PlayerTask.java
VCore-Minecraft_VCore-Old/src/main/java/de/verdox/vcore/synchronization/networkmanager/player/api/PlayerTask.java
/* * Copyright (c) 2021. Lukas Jonsson */ package de.verdox.vcore.synchronization.networkmanager.player.api; import org.jetbrains.annotations.NotNull; import java.util.Objects; import java.util.UUID; /** * @version 1.0 * @Author: Lukas Jonsson (Verdox) * @date 05.08.2021 15:00 */ public record PlayerTask(UUID uuid, UUID taskUUID, Runnable runnable) { public PlayerTask(@NotNull UUID uuid, @NotNull UUID taskUUID, @NotNull Runnable runnable) { this.uuid = uuid; this.taskUUID = taskUUID; this.runnable = runnable; } public UUID getUuid() { return uuid; } public Runnable getRunnable() { return runnable; } public UUID getTaskUUID() { return taskUUID; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof PlayerTask)) return false; PlayerTask that = (PlayerTask) o; return Objects.equals(getTaskUUID(), that.getTaskUUID()); } @Override public int hashCode() { return Objects.hash(getTaskUUID()); } }
1,099
Java
.java
39
23.102564
95
0.666032
VCore-Minecraft/VCore-Old
10
1
1
GPL-3.0
9/4/2024, 8:28:31 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,099
3,448,210
QueryJDebuggingChain.java
rydnr_queryj/queryj-debugging/src/main/java/org/acmsl/queryj/debugging/QueryJDebuggingChain.java
/* QueryJ Debugging Copyright (C) 2002-today Jose San Leandro Armendariz [email protected] This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Thanks to ACM S.L. for distributing this library under the GPL license. Contact info: [email protected] ****************************************************************************** * * Filename: QueryJDebuggingChain.java * * Author: Jose San Leandro Armendariz * * Description: QueryJ flow when debugging templates. * * Date: 2014/08/20 * Time: 10:48 * */ package org.acmsl.queryj.debugging; /* * Importing JetBrains annotations. */ import org.acmsl.commons.patterns.Chain; import org.acmsl.queryj.QueryJCommand; import org.acmsl.queryj.api.TemplateContext; import org.acmsl.queryj.api.exceptions.CannotFindTemplatesException; import org.acmsl.queryj.api.exceptions.DevelopmentModeException; import org.acmsl.queryj.api.exceptions.QueryJBuildException; import org.acmsl.queryj.api.handlers.TemplateHandler; import org.acmsl.queryj.customsql.handlers.CustomSqlCacheWritingHandler; import org.acmsl.queryj.customsql.handlers.CustomSqlProviderRetrievalHandler; import org.acmsl.queryj.customsql.handlers.CustomSqlValidationHandler; import org.acmsl.queryj.tools.QueryJChain; import org.acmsl.queryj.tools.TemplateChainProvider; import org.acmsl.queryj.tools.handlers.DatabaseMetaDataCacheWritingHandler; import org.acmsl.queryj.tools.handlers.DatabaseMetaDataLoggingHandler; import org.acmsl.queryj.tools.handlers.JdbcConnectionClosingHandler; import org.acmsl.queryj.tools.handlers.JdbcConnectionOpeningHandler; import org.acmsl.queryj.tools.handlers.JdbcMetaDataRetrievalHandler; import org.acmsl.queryj.tools.handlers.Log4JInitializerHandler; import org.acmsl.queryj.tools.handlers.ParameterValidationHandler; import org.acmsl.queryj.tools.handlers.QueryJCommandHandler; import org.acmsl.queryj.tools.handlers.mysql.MySQL4xMetaDataRetrievalHandler; import org.acmsl.queryj.tools.handlers.oracle.OracleMetaDataRetrievalHandler; import org.apache.commons.logging.Log; import org.jetbrains.annotations.NotNull; /* * Importing checkthread.org annotations. */ import org.checkthread.annotations.ThreadSafe; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.ServiceLoader; /** * QueryJ flow when debugging templates. * @author <a href="mailto:[email protected]">Jose San Leandro</a> * @since 3.0 * Created: 2014/08/20 10:48 * @param <CH> the QueryJCommandHandler. * @param <C> the template context. */ @ThreadSafe public class QueryJDebuggingChain<CH extends QueryJCommandHandler<QueryJCommand>, C extends TemplateContext> extends QueryJChain<CH> { /** * The template debugging service. */ private TemplateDebuggingService<C> m__Service; /** * Creates a {@code QueryJDebuggingChain} with given information. */ public QueryJDebuggingChain(@NotNull final TemplateDebuggingService<C> service) { immutableSetService(service); } /** * Specifies the template debugging service. * @param service such {@link TemplateDebuggingService service}. */ protected final void immutableSetService(@NotNull final TemplateDebuggingService<C> service) { this.m__Service = service; } /** * Specifies the template debugging service. * @param service such {@link TemplateDebuggingService service}. */ @SuppressWarnings("unused") protected void setService(@NotNull final TemplateDebuggingService<C> service) { immutableSetService(service); } /** * Retrieves the template debugging service. * @return the {@link TemplateDebuggingService service}. */ @NotNull public TemplateDebuggingService<C> getService() { return this.m__Service; } /** * Sends given command to a concrete chain. * @param chain the concrete chain. * @param command the command that represents which actions should be done. * @return <code>true</code> if the command is processed by the chain. * @throws QueryJBuildException if the process fails. */ @Override protected boolean process( @NotNull final Chain<QueryJCommand, QueryJBuildException, CH> chain, @NotNull final QueryJCommand command) throws QueryJBuildException { return process(chain, command, getService()); } /** * Sends given command to a concrete chain. * @param chain the concrete chain. * @param command the command that represents which actions should be done. * @param service the {@link org.acmsl.queryj.debugging.TemplateDebuggingService service}. * @return <code>true</code> if the command is processed by the chain. * @throws QueryJBuildException if the process fails. */ protected boolean process( @NotNull final Chain<QueryJCommand, QueryJBuildException, CH> chain, @NotNull final QueryJCommand command, @NotNull final TemplateDebuggingService<C> service) throws QueryJBuildException { final boolean result = false; @Nullable final Log t_Log = command.getLog(); final boolean t_bLoggingEnabled = (t_Log != null); @NotNull TemplateDebuggingCommand t_DebugCommand = TemplateDebuggingCommand.NEXT; try { @Nullable CH t_CurrentCommandHandler = null; do { if (t_DebugCommand.equals(TemplateDebuggingCommand.NEXT)) { t_CurrentCommandHandler = getNextChainLink(chain, t_CurrentCommandHandler); } else if (t_DebugCommand.equals(TemplateDebuggingCommand.PREVIOUS)) { t_CurrentCommandHandler = getPreviousChainLink(chain, t_CurrentCommandHandler); } if (t_bLoggingEnabled) { t_Log.debug("Next handler: " + t_CurrentCommandHandler); } if (t_CurrentCommandHandler != null) { t_DebugCommand = service.debug(t_CurrentCommandHandler, command); } if (t_bLoggingEnabled) { t_Log.debug( t_CurrentCommandHandler + "#handle(QueryJCommand) returned " + result); } } while (t_CurrentCommandHandler != null); } catch (@NotNull final QueryJBuildException buildException) { cleanUpOnError(buildException, command); if (t_bLoggingEnabled) { t_Log.error( "QueryJ could not generate sources correctly.", buildException); } throw buildException; } return result; } /** * {@inheritDoc} */ @NotNull @Override public String toString() { return "{ \"service\": " + this.m__Service + ", \"class\": \"QueryJDebuggingChain\"" + ", \"package\": \"org.acmsl.queryj.debugging\" }"; } }
7,934
Java
.java
203
31.778325
114
0.679605
rydnr/queryj
3
0
50
GPL-2.0
9/4/2024, 11:28:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
7,934
4,862,458
UDPTransportChannelFactory.java
fduminy_jtestplatform/integration-tests/src/test/java/org/jtestplatform/it/UDPTransportChannelFactory.java
/** * JTestPlatform is a client/server framework for testing any JVM * implementation. * * Copyright (C) 2008-2016 Fabien DUMINY (fduminy at jnode dot org) * * JTestPlatform is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * JTestPlatform is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ package org.jtestplatform.it; import org.jtestplatform.common.transport.TransportException; /** * @author Fabien DUMINY (fduminy at jnode dot org) */ public class UDPTransportChannelFactory implements InJVMTransportChannelFactory<UDPTransportChannel> { public static final UDPTransportChannelFactory INSTANCE = new UDPTransportChannelFactory(); @Override public UDPTransportChannel create(int domainID) throws TransportException { return new UDPTransportChannel(domainID); } }
1,398
Java
.java
33
39.878788
102
0.782673
fduminy/jtestplatform
1
0
0
GPL-3.0
9/5/2024, 12:34:08 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,398
1,384,562
AppCompatible.java
iSCAU_iSCAU-Android/app/src/main/java/cn/scau/scautreasure/AppCompatible.java
package cn.scau.scautreasure; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EBean; import org.androidannotations.annotations.RootContext; import org.androidannotations.annotations.sharedpreferences.Pref; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import cn.scau.scautreasure.helper.ClassHelper; import cn.scau.scautreasure.model.ClassModel; import cn.scau.scautreasure.util.CryptUtil; import cn.scau.scautreasure.util.StringUtil; import cn.scau.scautreasure.util.TextManager; /** * 兼容升级低版本数据,可能有部分配置随着版本的升级, 需要新增或去掉, * 在整个时候可以在这文件增加一个函数, 根据versionCode去判断应该执 * 行怎么的增加或移除配置操作. * * 注: 从2014-02-16开始, versionCode采用Gradle自动生成, 按照release * 当天的日期自动形成版本号,例如 20140226. * * User: Special Leung * Date: 13-7-26 * Time: 下午8:17 * Mail: [email protected] */ @EBean public class AppCompatible { @Pref cn.scau.scautreasure.AppConfig_ config; @RootContext Context ctx; @Bean ClassHelper classHelper; public void upgrade(){ int lastVersionCode = config.versionCode().get(); int currentVersionCode = getVersionCode(); if (currentVersionCode == lastVersionCode) return; if (lastVersionCode == 0){ System.out.println("update from version 7"); // dealwith the old data upgrade_version_7(); } // 当有需要补充的配置迁移操作, 可以在这里添加: // > if(lastVersionCode == 20140226 ){ what to do; } // 表示当升级前versionCode为20140226时候执行何种操作 config.versionCode().put(currentVersionCode); } /** * 兼容重构版本前(v2.1)以前的账号配置, 将旧版本的数据迁移到重构后的配置命名空间 */ private void upgrade_version_7(){ // upgrade the username and password; SharedPreferences sp_edu = ctx.getSharedPreferences("jwxt", ctx.MODE_APPEND); SharedPreferences sp_lib = ctx.getSharedPreferences("lib", ctx.MODE_APPEND); SharedPreferences sp_card = ctx.getSharedPreferences("xycard", ctx.MODE_APPEND); String edu_username = sp_edu.getString("jwxt_user", ""); String edu_password = sp_edu.getString("jwxt_password", ""); String lib_username = sp_lib.getString("lib_user", ""); String lib_password = sp_lib.getString("lib_password", ""); String card_username = sp_card.getString("xycard_user", ""); String card_password = sp_card.getString("xycard_password", ""); if(!StringUtil.isEmpty(edu_username)){ CryptUtil cryptUtil = new CryptUtil(); edu_password = cryptUtil.encrypt(edu_password); config.userName().put(edu_username); config.eduSysPassword().put(edu_password); if (!StringUtil.isEmpty(lib_username) && edu_username.equals(lib_username)){ lib_password = cryptUtil.encrypt(lib_password); config.libPassword().put(lib_password); } if (!StringUtil.isEmpty(card_username) && edu_username.equals(card_username)){ card_password = cryptUtil.encrypt(card_password); config.cardPassword().put(card_password); } } // upgrade the class table data; TextManager textManager = new TextManager(ctx, "kcb_json.dat"); if (textManager.isExist()){ try { List<ClassModel> classList = parseFromOldVersionJson(textManager.readAll()); classHelper.replaceAllLesson(classList); config.termStartDate().put("2013-09-02"); } catch (Exception e) { e.printStackTrace(); } } } private List<ClassModel> parseFromOldVersionJson(String jsonString) throws JSONException { List<ClassModel> classModelList = new ArrayList<ClassModel>(); JSONArray jsonArray = new JSONArray(jsonString); for (int i = 0; i < jsonArray.length(); i ++){ JSONObject cls = jsonArray.getJSONObject(i); ClassModel classModel = new ClassModel(); classModel.setClassname(cls.getString("classname")); classModel.setTeacher(cls.getString("teacher")); classModel.setDay(cls.getString("day")); classModel.setNode(cls.getString("note")); classModel.setStrWeek(Integer.valueOf(cls.getString("strWeek"))); classModel.setEndWeek(Integer.valueOf(cls.getString("endWeek"))); classModel.setDsz(cls.getString("dsz")); classModel.setLocation(cls.getString("location")); classModelList.add(classModel); } return classModelList; } /** * 获得当前App的versionCode; * * @return versionCode; */ private int getVersionCode(){ PackageManager packageManager = ctx.getPackageManager(); PackageInfo packInfo = null; try { packInfo = packageManager.getPackageInfo(ctx.getPackageName(), 0); int version = packInfo.versionCode; return version; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } // if error return 0; } }
5,774
Java
.java
131
33.580153
94
0.655107
iSCAU/iSCAU-Android
28
8
5
GPL-3.0
9/4/2024, 7:47:52 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
5,434
381,800
EDSLocationBase.java
sovworks_edslite/app/src/lite/java/com/sovworks/eds/android/locations/EDSLocationBase.java
package com.sovworks.eds.android.locations; import android.content.Context; import android.net.Uri; import com.sovworks.eds.android.Logger; import com.sovworks.eds.android.errors.UserException; import com.sovworks.eds.android.settings.UserSettings; import com.sovworks.eds.crypto.SecureBuffer; import com.sovworks.eds.fs.FileSystem; import com.sovworks.eds.fs.Path; import com.sovworks.eds.fs.util.ActivityTrackingFSWrapper; import com.sovworks.eds.fs.util.ContainerFSWrapper; import com.sovworks.eds.fs.util.StringPathUtil; import com.sovworks.eds.locations.EDSLocation; import com.sovworks.eds.locations.Location; import com.sovworks.eds.locations.LocationsManager; import com.sovworks.eds.locations.LocationsManagerBase; import com.sovworks.eds.locations.OMLocationBase; import com.sovworks.eds.settings.Settings; import com.sovworks.eds.settings.SettingsCommon; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; public abstract class EDSLocationBase extends OMLocationBase implements Cloneable, EDSLocation { public static final String INTERNAL_SETTINGS_FILE_NAME = ".eds-settings"; public static class ExternalSettings extends OMLocationBase.ExternalSettings implements EDSLocation.ExternalSettings { public ExternalSettings() { } @Override public boolean shouldOpenReadOnly() { return _openReadOnly; } @Override public void setOpenReadOnly(boolean val) { _openReadOnly = val; } @Override public int getAutoCloseTimeout() { return _autoCloseTimeout; } @Override public void setAutoCloseTimeout(int timeout) { _autoCloseTimeout = timeout; } @Override public void saveToJSONObject(JSONObject jo) throws JSONException { super.saveToJSONObject(jo); jo.put(SETTINGS_OPEN_READ_ONLY, shouldOpenReadOnly()); if (_autoCloseTimeout > 0) jo.put(SETTINGS_AUTO_CLOSE_TIMEOUT, _autoCloseTimeout); else jo.remove(SETTINGS_AUTO_CLOSE_TIMEOUT); } @Override public void loadFromJSONOjbect(JSONObject jo) throws JSONException { super.loadFromJSONOjbect(jo); setOpenReadOnly(jo.optBoolean(SETTINGS_OPEN_READ_ONLY, false)); _autoCloseTimeout = jo.optInt(SETTINGS_AUTO_CLOSE_TIMEOUT, 0); } private static final String SETTINGS_OPEN_READ_ONLY = "read_only"; private static final String SETTINGS_AUTO_CLOSE_TIMEOUT = "auto_close_timeout"; private boolean _openReadOnly; private int _autoCloseTimeout; } public static class InternalSettings implements EDSLocation.InternalSettings { public InternalSettings() { } public String save() { JSONObject jo = new JSONObject(); try { save(jo); } catch (JSONException e) { throw new RuntimeException(e); } return jo.toString(); } public void load(String data) { JSONObject jo; try { jo = new JSONObject(data); } catch (JSONException e) { jo = new JSONObject(); } load(jo); } @Override public String toString() { return save(); } protected void save(JSONObject jo) throws JSONException { } protected void load(JSONObject jo) { } } public static Location getContainerLocationFromUri(Uri locationUri, LocationsManagerBase lm) throws Exception { String uriString = locationUri.getQueryParameter(LOCATION_URI_PARAM); if (uriString == null) //maybe it's a legacy container uriString = locationUri.getQueryParameter("container_location"); return lm.getLocation(Uri.parse(uriString)); } protected EDSLocationBase(EDSLocationBase sibling) { super(sibling); } protected EDSLocationBase(Settings settings, SharedData sharedData) { super(settings, sharedData); } @Override public long getLastActivityTime() { if(isOpen()) { ActivityTrackingFSWrapper fs; try { fs = getFS(); return fs.getLastActivityTime(); } catch (IOException e) { Logger.log(e); } } return 0; } @Override public synchronized ContainerFSWrapper getFS() throws IOException { if (getSharedData().fs == null) { if (!isOpenOrMounted()) throw new IOException("Cannot access closed container."); boolean readOnly = getExternalSettings().shouldOpenReadOnly(); try { getSharedData().fs = createFS(readOnly); } catch (UserException e) { throw new RuntimeException(e); } try { readInternalSettings(); applyInternalSettings(); } catch (IOException e) { Logger.showAndLog(getContext(), e); } } return (ContainerFSWrapper) getSharedData().fs; } @Override public String getTitle() { String title = super.getTitle(); if (title == null) { Location containerLocation = getLocation(); if(containerLocation.isFileSystemOpen()) { try { title = new StringPathUtil(containerLocation.getCurrentPath().getPathString()).getFileNameWithoutExtension(); } catch (Exception e) { title = "error"; } } else title = containerLocation.toString(); } return title; } @Override public boolean hasPassword() { return true; } @Override public boolean isEncrypted() { return true; } @Override public void readInternalSettings() throws IOException { Path settingsPath; try { settingsPath = getFS().getRootPath().combine(INTERNAL_SETTINGS_FILE_NAME); } catch (IOException e) { settingsPath = null; } if (settingsPath == null || !settingsPath.isFile()) getSharedData().internalSettings.load(""); else getSharedData().internalSettings.load(com.sovworks.eds.fs.util.Util.readFromFile(settingsPath)); } @Override public InternalSettings getInternalSettings() { return getSharedData().internalSettings; } @Override public ExternalSettings getExternalSettings() { return (ExternalSettings) super.getExternalSettings(); } @Override public void writeInternalSettings() throws IOException { FileSystem fs = getFS(); com.sovworks.eds.fs.util.Util.writeToFile(fs.getRootPath().getDirectory(), INTERNAL_SETTINGS_FILE_NAME, getInternalSettings().save()); } @Override public boolean isReadOnly() { return super.isReadOnly() || getExternalSettings().shouldOpenReadOnly(); } @Override public void applyInternalSettings() throws IOException { } @Override public void saveExternalSettings() { if(!_globalSettings.neverSaveHistory()) super.saveExternalSettings(); } @Override public Location getLocation() { return getSharedData().containerLocation; } public Context getContext() { return getSharedData().context; } protected static class SharedData extends OMLocationBase.SharedData { public SharedData(String id, InternalSettings settings, Location location, Context ctx) { super(id); internalSettings = settings; containerLocation = location; context = ctx; } public final InternalSettings internalSettings; public final Location containerLocation; public final Context context; } protected static final String LOCATION_URI_PARAM = "location"; protected abstract FileSystem createBaseFS(boolean readOnly) throws IOException, UserException; @Override protected SharedData getSharedData() { return (SharedData)super.getSharedData(); } @Override protected ExternalSettings loadExternalSettings() { ExternalSettings res = new ExternalSettings(); res.setProtectionKeyProvider(new ProtectionKeyProvider() { @Override public SecureBuffer getProtectionKey() { try { return UserSettings.getSettings(getContext()).getSettingsProtectionKey(); } catch (SettingsCommon.InvalidSettingsPassword invalidSettingsPassword) { return null; } } }); res.load(_globalSettings,getId()); return res; } @Override protected ArrayList<Path> loadPaths(Collection<String> paths) throws IOException { return LocationsManager.getPathsFromLocations( LocationsManager.getLocationsManager(getContext()).getLocations(paths) ); } protected Uri.Builder makeUri(String uriScheme) { Uri.Builder ub = new Uri.Builder(); ub.scheme(uriScheme); if(_currentPathString!=null) ub.path(_currentPathString); else ub.path("/"); ub.appendQueryParameter(LOCATION_URI_PARAM, getLocation().getLocationUri().toString()); return ub; } protected FileSystem createFS(boolean readOnly) throws IOException, UserException { FileSystem baseFS = createBaseFS(readOnly); return new ContainerFSWrapper(baseFS); } protected static InternalSettings createInternalSettings() { return new InternalSettings(); } }
8,578
Java
.java
336
22.386905
136
0.765087
sovworks/edslite
276
64
36
GPL-2.0
9/4/2024, 7:06:52 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
8,578
812,549
UTOffhand.java
ACGaming_UniversalTweaks/src/main/java/mod/acgaming/universaltweaks/tweaks/misc/offhand/mixin/UTOffhand.java
package mod.acgaming.universaltweaks.tweaks.misc.offhand.mixin; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemShield; import net.minecraft.util.EnumHand; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.eventhandler.Event; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import mod.acgaming.universaltweaks.UniversalTweaks; import mod.acgaming.universaltweaks.config.UTConfigGeneral; import mod.acgaming.universaltweaks.config.UTConfigTweaks; @Mod.EventBusSubscriber(modid = UniversalTweaks.MODID) public class UTOffhand { // Don't place blocks in the offhand when blocks or food are in the mainhand @SubscribeEvent(priority = EventPriority.HIGHEST) public static void utOffhandBlock(PlayerInteractEvent.RightClickBlock event) { if (!UTConfigTweaks.MISC.utOffhandToggle) return; if (UTConfigGeneral.DEBUG.utDebugToggle) UniversalTweaks.LOGGER.debug("UTOffhand ::: Right click block event"); EntityPlayer player = event.getEntityPlayer(); Item heldItemMainhand = player.getHeldItemMainhand().getItem(); Item heldItemOffhand = player.getHeldItemOffhand().getItem(); if (event.getHand() == EnumHand.OFF_HAND && heldItemOffhand instanceof ItemBlock && (heldItemMainhand instanceof ItemBlock || heldItemMainhand instanceof ItemFood)) event.setUseItem(Event.Result.DENY); } // Don't interact with entities when wielding shields @SubscribeEvent(priority = EventPriority.HIGHEST) public static void utOffhandEntity(PlayerInteractEvent.EntityInteract event) { if (!UTConfigTweaks.MISC.utOffhandToggle) return; if (UTConfigGeneral.DEBUG.utDebugToggle) UniversalTweaks.LOGGER.debug("UTOffhand ::: Right click entity event"); EntityPlayer player = event.getEntityPlayer(); Item heldItemMainhand = player.getHeldItemMainhand().getItem(); Item heldItemOffhand = player.getHeldItemOffhand().getItem(); if (event.getHand() == EnumHand.MAIN_HAND && heldItemOffhand instanceof ItemShield || event.getHand() == EnumHand.OFF_HAND && heldItemMainhand instanceof ItemShield) { event.setResult(Event.Result.DENY); event.setCanceled(true); } } }
2,567
Java
.java
49
46.755102
120
0.7666
ACGaming/UniversalTweaks
80
31
19
LGPL-3.0
9/4/2024, 7:08:56 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,567
4,115,401
LocalServerInit.java
subshare_subshare/org.subshare/org.subshare.ls.server.cproc/src/main/java/org/subshare/ls/server/cproc/LocalServerInit.java
package org.subshare.ls.server.cproc; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.subshare.core.locker.sync.LockerSyncDaemonImpl; import org.subshare.core.locker.transport.LockerTransportFactoryRegistry; import org.subshare.core.pgp.PgpAuthenticationCallback; import org.subshare.core.pgp.PgpRegistry; import org.subshare.core.pgp.man.PgpPrivateKeyPassphraseStoreImpl; import org.subshare.core.pgp.sync.PgpSyncDaemonImpl; import org.subshare.core.pgp.transport.PgpTransportFactoryRegistryImpl; import org.subshare.core.repo.metaonly.MetaOnlyRepoSyncDaemonImpl; import org.subshare.core.repo.sync.RepoSyncTimerImpl; import org.subshare.ls.server.cproc.ssl.AcceptAllDynamicX509TrustManagerCallback; import org.subshare.rest.client.locker.transport.RestLockerTransportFactory; import org.subshare.rest.client.pgp.transport.RestPgpTransportFactory; import org.subshare.rest.client.transport.CryptreeRestRepoTransportFactoryImpl; import co.codewizards.cloudstore.core.repo.transport.RepoTransportFactoryRegistry; public class LocalServerInit { private static final Logger logger = LoggerFactory.getLogger(LocalServerInit.class); private static boolean initPrepareDone; private static boolean initFinishDone; private LocalServerInit() { } public static synchronized void initPrepare() { if (! initPrepareDone) { PgpTransportFactoryRegistryImpl.getInstance().getPgpTransportFactoryOrFail(RestPgpTransportFactory.class).setDynamicX509TrustManagerCallbackClass(AcceptAllDynamicX509TrustManagerCallback.class); LockerTransportFactoryRegistry.getInstance().getLockerTransportFactoryOrFail(RestLockerTransportFactory.class).setDynamicX509TrustManagerCallbackClass(AcceptAllDynamicX509TrustManagerCallback.class); final CryptreeRestRepoTransportFactoryImpl cryptreeRestRepoTransportFactoryImpl = RepoTransportFactoryRegistry.getInstance().getRepoTransportFactoryOrFail(CryptreeRestRepoTransportFactoryImpl.class); cryptreeRestRepoTransportFactoryImpl.setDynamicX509TrustManagerCallbackClass(AcceptAllDynamicX509TrustManagerCallback.class); // cryptreeRestRepoTransportFactoryImpl.setUserRepoKeyRingLookup(new UserRepoKeyRingLookupImpl()); final PgpAuthenticationCallback pgpAuthenticationCallback = PgpPrivateKeyPassphraseStoreImpl.getInstance().getPgpAuthenticationCallback(); PgpRegistry.getInstance().setPgpAuthenticationCallback(pgpAuthenticationCallback); initPrepareDone = true; // Important: We do not yet start the daemons here (i.e. do not invoke PgpSyncDaemonImpl.getInstance(), // LockerSyncDaemonImpl.getInstance() or similar), because the user did not yet enter any password when // this method is invoked. This method only prepares everything so that we *can* start the daemons, now. } } public static synchronized void initFinish() { if (! initFinishDone) { // *Now* we start the daemons (if they don't run, yet). We perform a sync *now* in the background // to make sure the PGP stuff is synced, before the Locker stuff. If the daemons simply run in the // background on their own, we don't have any control over the order. This is not essentially necessary, // but it reduces error-log-messages ;-) final Thread localServerInitFinishThread = new Thread() { @Override public void run() { // Blocking syncs performed serially (one after the other): PgpSyncDaemonImpl.getInstance().sync(); LockerSyncDaemonImpl.getInstance().sync(); MetaOnlyRepoSyncDaemonImpl.getInstance().sync(); // The following is *not* blocking (the above invocations are) => the repo-syncs are in the background. RepoSyncTimerImpl.getInstance(); } }; localServerInitFinishThread.start(); initFinishDone = true; } } // public static synchronized void initUserRepoKeyRing() { // final UserRegistry userRegistry = UserRegistry.getInstance(); // final List<User> usersWithUserRepoKey = new ArrayList<User>(1); // for (final User user : userRegistry.getUsers()) { // if (user.getUserRepoKeyRing() != null) // usersWithUserRepoKey.add(user); // } // // if (usersWithUserRepoKey.size() > 1) // throw new IllegalStateException("There are multiple users with a UserRepoKey! Should only be exactly one!"); // // // TODO hook a listener to throw an exception as soon as a 2nd user has a UserRepoKey for early-detection of this illegal state. // } }
4,383
Java
.java
73
57.287671
202
0.817229
subshare/subshare
2
1
16
AGPL-3.0
9/5/2024, 12:03:20 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,383
541,755
ClassNames.java
AllayMC_Allay/codegen/src/main/java/org/allaymc/codegen/ClassNames.java
package org.allaymc.codegen; import com.palantir.javapoet.ClassName; /** * @author daoge_cmd */ public interface ClassNames { // jdk ClassName STRING = ClassName.get("java.lang", "String"); ClassName HASH_MAP = ClassName.get("java.util", "HashMap"); ClassName MAP = ClassName.get("java.util", "Map"); ClassName REGISTRIES = ClassName.get("org.allaymc.api.registry", "Registries"); ClassName LIST = ClassName.get("java.util", "List"); // 3rd libs ClassName GETTER = ClassName.get("lombok", "Getter"); // allay ClassName API_IDENTIFIER = ClassName.get("org.allaymc.api.utils", "Identifier"); ClassName DEP_IDENTIFIER = ClassName.get("org.allaymc.dependence", "Identifier"); ClassName BLOCK_BEHAVIOR = ClassName.get("org.allaymc.api.block", "BlockBehavior"); ClassName BLOCK_ID = ClassName.get("org.allaymc.api.block.data", "BlockId"); ClassName BLOCK_PROPERTY_TYPE = ClassName.get("org.allaymc.api.block.property.type", "BlockPropertyType"); ClassName BLOCK_PROPERTY_TYPES = ClassName.get("org.allaymc.api.block.property.type", "BlockPropertyTypes"); ClassName BLOCK_TYPE = ClassName.get("org.allaymc.api.block.type", "BlockType"); ClassName BLOCK_TYPES = ClassName.get("org.allaymc.api.block.type", "BlockTypes"); ClassName BLOCK_TYPE_DEFAULT_INITIALIZER = ClassName.get("org.allaymc.server.block.type", "BlockTypeDefaultInitializer"); ClassName BLOCK_TAG = ClassName.get("org.allaymc.api.block.tag", "BlockTag"); ClassName ALLAY_BLOCK_TYPE = ClassName.get("org.allaymc.server.block.type", "AllayBlockType"); ClassName ENUM_PROPERTY = ClassName.get("org.allaymc.api.block.property.type", "EnumPropertyType"); ClassName BOOLEAN_PROPERTY = ClassName.get("org.allaymc.api.block.property.type", "BooleanPropertyType"); ClassName INT_PROPERTY = ClassName.get("org.allaymc.api.block.property.type", "IntPropertyType"); ClassName MATERIAL_TYPE = ClassName.get("org.allaymc.api.block.material", "MaterialType"); ClassName BIOME_TYPE = ClassName.get("org.allaymc.api.world.biome", "BiomeType"); ClassName BIOME_ARRAY = ClassName.get("org.allaymc.api.world.biome", "BiomeId[]"); ClassName ENTITY = ClassName.get("org.allaymc.api.entity", "Entity"); ClassName ENTITY_ID = ClassName.get("org.allaymc.api.entity.data", "EntityId"); ClassName ENTITY_TYPE = ClassName.get("org.allaymc.api.entity.type", "EntityType"); ClassName ENTITY_TYPES = ClassName.get("org.allaymc.api.entity.type", "EntityTypes"); ClassName ALLAY_ENTITY_TYPE = ClassName.get("org.allaymc.server.entity.type", "AllayEntityType"); ClassName ENTITY_TYPE_DEFAULT_INITIALIZER = ClassName.get("org.allaymc.server.entity.type", "EntityTypeDefaultInitializer"); ClassName ITEM_ID = ClassName.get("org.allaymc.api.item.data", "ItemId"); ClassName ITEM_STACK = ClassName.get("org.allaymc.api.item", "ItemStack"); ClassName ITEM_TYPE = ClassName.get("org.allaymc.api.item.type", "ItemType"); ClassName ITEM_TYPES = ClassName.get("org.allaymc.api.item.type", "ItemTypes"); ClassName ALLAY_ITEM_TYPE = ClassName.get("org.allaymc.server.item.type", "AllayItemType"); ClassName ITEM_TYPE_DEFAULT_INITIALIZER = ClassName.get("org.allaymc.server.item.type", "ItemTypeDefaultInitializer"); ClassName ITEM_TAG = ClassName.get("org.allaymc.api.item.tag", "ItemTag"); ClassName TR_KEYS = ClassName.get("org.allaymc.api.i18n", "TrKeys"); ClassName MINECRAFT_VERSION_SENSITIVE = ClassName.get("org.allaymc.api.annotation", "MinecraftVersionSensitive"); ClassName SOUND = ClassName.get("org.allaymc.api.world", "Sound"); }
3,635
Java
.java
49
69.530612
128
0.739726
AllayMC/Allay
157
12
40
LGPL-3.0
9/4/2024, 7:07:37 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,635
4,268,718
GlassFragment.java
SirBlobman_DragonFire/src/main/java/com/DragonFire/item/custom/GlassFragment.java
package com.DragonFire.item.custom; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.ItemStack; import net.minecraft.util.NonNullList; public class GlassFragment extends QuickItem { public GlassFragment() { super("glass_fragment"); setHasSubtypes(true); } @Override public String getUnlocalizedName(ItemStack is) { int meta = is.getMetadata(); String add; if(meta < 16) { EnumDyeColor dye = EnumDyeColor.byDyeDamage(meta); add = dye.getUnlocalizedName(); } else { if(meta == 16) add = "obsidian"; else if(meta == 17) add = "clear"; else add = "invalid"; } String name = super.getUnlocalizedName(); String nname = (name + "." + add); return nname; } @Override public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> list) { if(isInCreativeTab(tab)) { for (int i = 0; i < 18; ++i) { ItemStack is = new ItemStack(this, 1, i); list.add(is); } } } }
1,183
Java
.java
36
24.5
76
0.597161
SirBlobman/DragonFire
2
1
0
GPL-3.0
9/5/2024, 12:07:24 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,183
3,455,320
ExecutionContext.java
victims_victims-plugin-jenkins-legacy/src/main/java/com/redhat/victims/plugin/jenkins/ExecutionContext.java
package com.redhat.victims.plugin.jenkins; /* * #%L * This file is part of victims-plugin-jenkins. * %% * Copyright (C) 2013 The Victims Project * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% */ import java.io.PrintStream; import com.redhat.victims.VictimsResultCache; import com.redhat.victims.database.VictimsDBInterface; /** * Context to pass to each command. * * @author gmurphy */ public final class ExecutionContext { private VictimsResultCache cache; private VictimsDBInterface database; private PrintStream log; private Settings settings; /** * @return The log to use within this execution context. */ public PrintStream getLog() { return this.log; } /** * @return The cache to store artifacts in */ public VictimsResultCache getCache() { return this.cache; } /** * @return Configuration to apply to this execution context. */ public Settings getSettings() { return settings; } /** * @return victims DB */ public VictimsDBInterface getDatabase() { return database; } /** * Send all messages to this log. * * @param l * The log to associate with this execution context. */ public void setLog(PrintStream l) { this.log = l; } /** * Set victims database * * @param database * Victims database */ public void setDatabase(VictimsDBInterface database) { this.database = database; } /** * Set victims cache * * @param victimsResultCache * Result cache for scanned dependencies */ public void setCache(VictimsResultCache victimsResultCache) { this.cache = victimsResultCache; } /** * Applies the given settings to the execution context. */ public void setSettings(final Settings setup) { this.settings = setup; } /** * Returns true if the setting is in fatal mode. Used when determining if * the rule should fail a build. * * @param mode * The configuration item to check if in fatal mode. * @return True when the mode is in fatal mode. */ public boolean inFatalMode(String mode) { String val = settings.get(mode); return val != null && val.equalsIgnoreCase(Settings.MODE_FATAL); } /** * Returns true if the value associated with the supplied key isn't set to * disabled. * * @param setting * The setting to check if is disabled. * @return True if the setting is enabled. */ public boolean isEnabled(String setting) { String val = settings.get(setting); return val != null && !val.equalsIgnoreCase(Settings.MODE_DISABLED); } /** * Returns true if automatic updates are enabled. * * @return True if automatic updates of database are enabled. */ public boolean updatesEnabled() { String val = settings.get(Settings.UPDATE_DATABASE); return val != null && (val.equalsIgnoreCase(Settings.UPDATES_AUTO) || val .equalsIgnoreCase(Settings.UPDATES_DAILY)); } /** * @return True if daily updates are enabled */ public boolean updateDaily() { String val = settings.get(Settings.UPDATE_DATABASE); return val != null && val.equalsIgnoreCase(Settings.UPDATES_DAILY); } /** * @return True if automatic updates are enabled and run for each build */ public boolean updateAlways() { String val = settings.get(Settings.UPDATE_DATABASE); return val != null && val.equalsIgnoreCase(Settings.UPDATES_AUTO); } }
3,992
Java
.java
141
25.64539
78
0.722266
victims/victims-plugin-jenkins-legacy
3
1
0
AGPL-3.0
9/4/2024, 11:29:00 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
3,992
4,906,886
NetconfDeviceDataBroker.java
aryantaheri_controller/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceDataBroker.java
/* * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html. */ package org.opendaylight.controller.sal.connect.netconf.sal; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener; import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer; import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener; import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction; import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction; import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction; import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain; import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionCapabilities; import org.opendaylight.controller.sal.connect.netconf.sal.tx.NetconfDeviceReadOnlyTx; import org.opendaylight.controller.sal.connect.netconf.sal.tx.NetconfDeviceReadWriteTx; import org.opendaylight.controller.sal.connect.netconf.sal.tx.NetconfDeviceWriteOnlyTx; import org.opendaylight.controller.sal.connect.util.RemoteDeviceId; import org.opendaylight.controller.sal.core.api.RpcImplementation; import org.opendaylight.yangtools.concepts.ListenerRegistration; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.model.api.SchemaContext; final class NetconfDeviceDataBroker implements DOMDataBroker { private final RemoteDeviceId id; private final RpcImplementation rpc; private final NetconfSessionCapabilities netconfSessionPreferences; private final DataNormalizer normalizer; public NetconfDeviceDataBroker(final RemoteDeviceId id, final RpcImplementation rpc, final SchemaContext schemaContext, NetconfSessionCapabilities netconfSessionPreferences) { this.id = id; this.rpc = rpc; this.netconfSessionPreferences = netconfSessionPreferences; normalizer = new DataNormalizer(schemaContext); } @Override public DOMDataReadOnlyTransaction newReadOnlyTransaction() { return new NetconfDeviceReadOnlyTx(rpc, normalizer, id); } @Override public DOMDataReadWriteTransaction newReadWriteTransaction() { return new NetconfDeviceReadWriteTx(newReadOnlyTransaction(), newWriteOnlyTransaction()); } @Override public DOMDataWriteTransaction newWriteOnlyTransaction() { return new NetconfDeviceWriteOnlyTx(id, rpc, normalizer, netconfSessionPreferences.isCandidateSupported(), netconfSessionPreferences.isRollbackSupported()); } @Override public ListenerRegistration<DOMDataChangeListener> registerDataChangeListener(final LogicalDatastoreType store, final YangInstanceIdentifier path, final DOMDataChangeListener listener, final DataChangeScope triggeringScope) { throw new UnsupportedOperationException("Data change listeners not supported for netconf mount point"); } @Override public DOMTransactionChain createTransactionChain(final TransactionChainListener listener) { // TODO implement throw new UnsupportedOperationException("Transaction chains not supported for netconf mount point"); } }
3,570
Java
.java
59
56.474576
229
0.828669
aryantaheri/controller
1
0
0
EPL-1.0
9/5/2024, 12:35:26 AM (Europe/Amsterdam)
false
false
true
false
true
true
true
false
3,570
2,429,052
InventoryPartitioner.java
P3pp3rF1y_SophisticatedCore/src/main/java/net/p3pp3rf1y/sophisticatedcore/inventory/InventoryPartitioner.java
package net.p3pp3rf1y.sophisticatedcore.inventory; import com.mojang.datafixers.util.Pair; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; import net.minecraft.nbt.StringTag; import net.minecraft.nbt.Tag; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.p3pp3rf1y.sophisticatedcore.settings.memory.MemorySettingsCategory; import javax.annotation.Nullable; import java.util.*; import java.util.function.Supplier; public class InventoryPartitioner { public static final String BASE_INDEXES_TAG = "baseIndexes"; private IInventoryPartHandler[] inventoryPartHandlers; private int[] baseIndexes; private final InventoryHandler parent; public InventoryPartitioner(CompoundTag tag, InventoryHandler parent, Supplier<MemorySettingsCategory> getMemorySettings) { this.parent = parent; deserializeNBT(tag, getMemorySettings); } private int getIndexForSlot(int slot) { if (slot < 0) {return -1;} int i = 0; for (; i < baseIndexes.length; i++) { if (slot - baseIndexes[i] < 0) { return i - 1; } } return i - 1; } public IInventoryPartHandler getPartBySlot(int slot) { if (slot < 0 || slot >= parent.getSlots()) { return IInventoryPartHandler.EMPTY; } int index = getIndexForSlot(slot); if (index < 0 || index >= inventoryPartHandlers.length) { return IInventoryPartHandler.EMPTY; } return inventoryPartHandlers[index]; } @Nullable public Pair<ResourceLocation, ResourceLocation> getNoItemIcon(int slot) { return getPartBySlot(slot).getNoItemIcon(slot); } public void onSlotLimitChange() { for (IInventoryPartHandler inventoryPartHandler : inventoryPartHandlers) { inventoryPartHandler.onSlotLimitChange(); } } public Set<Integer> getNoSortSlots() { Set<Integer> noSortSlots = new HashSet<>(); for (IInventoryPartHandler inventoryPartHandler : inventoryPartHandlers) { noSortSlots.addAll(inventoryPartHandler.getNoSortSlots()); } return noSortSlots; } public boolean isFilterItem(Item item) { for (IInventoryPartHandler inventoryPartHandler : inventoryPartHandlers) { if (inventoryPartHandler.isFilterItem(item)) { return true; } } return false; } public Map<Item, Set<Integer>> getFilterItems() { Map<Item, Set<Integer>> filterItems = new HashMap<>(); for (IInventoryPartHandler inventoryPartHandler : inventoryPartHandlers) { for (Map.Entry<Item, Set<Integer>> entry : inventoryPartHandler.getFilterItems().entrySet()) { filterItems.computeIfAbsent(entry.getKey(), k -> new HashSet<>()).addAll(entry.getValue()); } } return filterItems; } public void onInit() { for (IInventoryPartHandler inventoryPartHandler : inventoryPartHandlers) { inventoryPartHandler.onInit(); } } public record SlotRange(int firstSlot, int numberOfSlots) { } public Optional<SlotRange> getFirstSpace(int maxNumberOfSlots) { for (int partIndex = 0; partIndex < inventoryPartHandlers.length; partIndex++) { if (inventoryPartHandlers[partIndex].canBeReplaced()) { int firstSlot = baseIndexes[partIndex]; int numberOfSlots = baseIndexes.length > partIndex + 1 ? baseIndexes[partIndex + 1] - firstSlot : parent.getSlots() - firstSlot; numberOfSlots = Math.min(numberOfSlots, maxNumberOfSlots); return numberOfSlots > 0 ? Optional.of(new SlotRange(baseIndexes[partIndex], numberOfSlots)) : Optional.empty(); } } return Optional.empty(); } public void addInventoryPart(int inventorySlot, int numberOfSlots, IInventoryPartHandler inventoryPartHandler) { int index = getIndexForSlot(inventorySlot); if (index < 0 || index >= inventoryPartHandlers.length || baseIndexes[index] != inventorySlot) { return; } List<IInventoryPartHandler> newParts = new ArrayList<>(); List<Integer> newBaseIndexes = new ArrayList<>(); for (int i = 0; i < index; i++) { newParts.add(inventoryPartHandlers[i]); newBaseIndexes.add(baseIndexes[i]); } newParts.add(inventoryPartHandler); newBaseIndexes.add(inventorySlot); int newNextSlot = inventorySlot + numberOfSlots; if (inventoryPartHandlers[index].getSlots() > newNextSlot) { newParts.add(new IInventoryPartHandler.Default(parent, parent.getSlots() - newNextSlot)); newBaseIndexes.add(newNextSlot); } for (int i = index + 1; i < inventoryPartHandlers.length; i++) { newParts.add(inventoryPartHandlers[i]); newBaseIndexes.add(baseIndexes[i]); } updatePartsAndIndexesFromLists(newParts, newBaseIndexes); inventoryPartHandler.onInit(); parent.onFilterItemsChanged(); } public void removeInventoryPart(int inventorySlot) { int index = getIndexForSlot(inventorySlot); if (index < 0 || index >= inventoryPartHandlers.length || baseIndexes[index] != inventorySlot) { return; } if (inventoryPartHandlers.length == 1) { updatePartsAndIndexesFromLists(List.of(new IInventoryPartHandler.Default(parent, parent.getSlots())), List.of(0)); parent.onFilterItemsChanged(); return; } int slotsAtPartIndex = (baseIndexes.length > index + 1 ? baseIndexes[index + 1] : parent.getSlots()) - baseIndexes[index]; List<IInventoryPartHandler> newParts = new ArrayList<>(); List<Integer> newBaseIndexes = new ArrayList<>(); boolean replacedNext = false; for (int i = 0; i < index; i++) { if (i == index - 1 && inventoryPartHandlers[i] instanceof IInventoryPartHandler.Default && baseIndexes.length > index + 1 && inventoryPartHandlers[index + 1] instanceof IInventoryPartHandler.Default) { newParts.add(new IInventoryPartHandler.Default(parent, inventoryPartHandlers[i].getSlots() + inventoryPartHandlers[index + 1].getSlots() + slotsAtPartIndex)); newBaseIndexes.add(baseIndexes[i]); replacedNext = true; continue; } newParts.add(inventoryPartHandlers[i]); newBaseIndexes.add(baseIndexes[i]); } if (!replacedNext && baseIndexes.length > index + 1) { if (inventoryPartHandlers[index + 1] instanceof IInventoryPartHandler.Default) { newParts.add(new IInventoryPartHandler.Default(parent, inventoryPartHandlers[index + 1].getSlots() + slotsAtPartIndex)); newBaseIndexes.add(inventorySlot); } else { newParts.add(new IInventoryPartHandler.Default(parent, slotsAtPartIndex)); newBaseIndexes.add(inventorySlot); newParts.add(inventoryPartHandlers[index + 1]); newBaseIndexes.add(baseIndexes[index + 1]); } } for (int i = index + 2; i < inventoryPartHandlers.length; i++) { newParts.add(inventoryPartHandlers[i]); newBaseIndexes.add(baseIndexes[i]); } updatePartsAndIndexesFromLists(newParts, newBaseIndexes); parent.onFilterItemsChanged(); } private void updatePartsAndIndexesFromLists(List<IInventoryPartHandler> newParts, List<Integer> newBaseIndexes) { inventoryPartHandlers = newParts.toArray(new IInventoryPartHandler[0]); baseIndexes = new int[newBaseIndexes.size()]; for (int i = 0; i < newBaseIndexes.size(); i++) { baseIndexes[i] = newBaseIndexes.get(i); } parent.saveInventory(); } public CompoundTag serializeNBT() { CompoundTag ret = new CompoundTag(); ret.putIntArray(BASE_INDEXES_TAG, baseIndexes); ListTag partNames = new ListTag(); for (IInventoryPartHandler inventoryPartHandler : inventoryPartHandlers) { partNames.add(StringTag.valueOf(inventoryPartHandler.getName())); } ret.put("inventoryPartNames", partNames); return ret; } private void deserializeNBT(CompoundTag tag, Supplier<MemorySettingsCategory> getMemorySettings) { if (!tag.contains(BASE_INDEXES_TAG)) { this.inventoryPartHandlers = new IInventoryPartHandler[] {new IInventoryPartHandler.Default(parent, parent.getSlots())}; this.baseIndexes = new int[] {0}; return; } baseIndexes = tag.getIntArray(BASE_INDEXES_TAG); inventoryPartHandlers = new IInventoryPartHandler[baseIndexes.length]; ListTag partNamesTag = tag.getList("inventoryPartNames", Tag.TAG_STRING); int i = 0; for (Tag t : partNamesTag) { SlotRange slotRange = new SlotRange(baseIndexes[i], (i + 1 < baseIndexes.length ? baseIndexes[i + 1] : parent.getSlots()) - baseIndexes[i]); inventoryPartHandlers[i] = InventoryPartRegistry.instantiatePart(t.getAsString(), parent, slotRange, getMemorySettings); i++; } } }
8,225
Java
.java
195
38.923077
204
0.763454
P3pp3rF1y/SophisticatedCore
8
29
9
GPL-3.0
9/4/2024, 9:24:15 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
8,225
4,003,766
LicenseInformationPanel.java
switchonproject_cids-custom-switchon/src/main/java/de/cismet/cids/custom/switchon/wizards/panels/LicenseInformationPanel.java
/*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ package de.cismet.cids.custom.switchon.wizards.panels; import org.apache.log4j.Logger; import org.openide.WizardDescriptor; import org.openide.util.NbBundle; import de.cismet.cids.custom.switchon.wizards.GenericAbstractWizardPanel; import de.cismet.cids.custom.switchon.wizards.MetaDataWizardAction; import de.cismet.cids.custom.switchon.wizards.NameProvider; import de.cismet.cids.dynamics.CidsBean; /** * DOCUMENT ME! * * @author Gilles Baatz * @version $Revision$, $Date$ */ public class LicenseInformationPanel extends GenericAbstractWizardPanel<LicenseInformationVisualPanel> implements NameProvider { //~ Static fields/initializers --------------------------------------------- private static final Logger LOG = Logger.getLogger(LicenseInformationPanel.class); //~ Constructors ----------------------------------------------------------- /** * Creates a new LicenseInformationPanel object. */ public LicenseInformationPanel() { super(LicenseInformationVisualPanel.class); setGeneralInformation(org.openide.util.NbBundle.getMessage( LicenseInformationVisualPanel.class, "LicenseInformationVisualPanel.infoBoxPanel.generalInformation")); // NOI18N } //~ Methods ---------------------------------------------------------------- @Override protected void read(final WizardDescriptor wizard) { final CidsBean resource = (CidsBean)wizard.getProperty(MetaDataWizardAction.PROP_RESOURCE_BEAN); getComponent().setCidsBean(resource); } @Override protected void store(final WizardDescriptor wizard) { // do nothing } @Override public String getName() { return NbBundle.getMessage(LicenseInformationPanel.class, "LicenseInformationPanel.name"); } }
2,013
Java
.java
50
35.66
104
0.643077
switchonproject/cids-custom-switchon
2
0
2
LGPL-3.0
9/4/2024, 11:59:47 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
2,013
2,046,329
ChangeManagerBean.java
docdoku_docdoku-plm-server/docdoku-plm-server-ejb/src/main/java/com/docdoku/plm/server/ChangeManagerBean.java
/* * DocDoku, Professional Open Source * Copyright 2006 - 2020 DocDoku SARL * * This file is part of DocDokuPLM. * * DocDokuPLM is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * DocDokuPLM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with DocDokuPLM. If not, see <http://www.gnu.org/licenses/>. */ package com.docdoku.plm.server; import com.docdoku.plm.server.core.change.*; import com.docdoku.plm.server.core.common.User; import com.docdoku.plm.server.core.common.UserKey; import com.docdoku.plm.server.core.document.DocumentIteration; import com.docdoku.plm.server.core.document.DocumentIterationKey; import com.docdoku.plm.server.core.document.DocumentRevision; import com.docdoku.plm.server.core.exceptions.*; import com.docdoku.plm.server.core.meta.Tag; import com.docdoku.plm.server.core.product.PartIteration; import com.docdoku.plm.server.core.product.PartIterationKey; import com.docdoku.plm.server.core.security.ACL; import com.docdoku.plm.server.core.security.UserGroupMapping; import com.docdoku.plm.server.core.services.IChangeManagerLocal; import com.docdoku.plm.server.core.services.IUserManagerLocal; import com.docdoku.plm.server.dao.*; import com.docdoku.plm.server.factory.ACLFactory; import javax.annotation.security.RolesAllowed; import javax.ejb.Local; import javax.ejb.Stateless; import javax.inject.Inject; import javax.persistence.EntityManager; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; /** * @author Florent Garin */ @Local(IChangeManagerLocal.class) @Stateless(name = "ChangeManagerBean") public class ChangeManagerBean implements IChangeManagerLocal { @Inject private EntityManager em; @Inject private ACLDAO aclDAO; @Inject private ACLFactory aclFactory; @Inject private ChangeItemDAO changeItemDAO; @Inject private DocumentRevisionDAO documentRevisionDAO; @Inject private MilestoneDAO milestoneDAO; @Inject private PartRevisionDAO partRevisionDAO; @Inject private TagDAO tagDAO; @Inject private IUserManagerLocal userManager; private static final Logger LOGGER = Logger.getLogger(ChangeManagerBean.class.getName()); @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeIssue getChangeIssue(String pWorkspaceId, int pId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeIssueNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeIssue changeIssue = loadChangeIssue(pId); checkChangeItemReadAccess(changeIssue, user); return changeIssue; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public List<ChangeIssue> getChangeIssues(String pWorkspaceId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); List<ChangeIssue> allChangeIssues = changeItemDAO.findAllChangeIssues(pWorkspaceId); List<ChangeIssue> visibleChangeIssues = new ArrayList<>(); for (ChangeIssue changeIssue : allChangeIssues) { try { checkChangeItemReadAccess(changeIssue, user); visibleChangeIssues.add(changeIssue); } catch (AccessRightException e) { LOGGER.log(Level.FINEST, null, e); } } return visibleChangeIssues; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public List<ChangeIssue> getIssuesWithName(String pWorkspaceId, String q, int maxResults) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); List<ChangeIssue> allChangeIssues = changeItemDAO.findAllChangeIssuesWithReferenceLike(pWorkspaceId, q, maxResults); List<ChangeIssue> visibleChangeIssues = new ArrayList<>(); for (ChangeIssue changeIssue : allChangeIssues) { try { checkChangeItemReadAccess(changeIssue, user); visibleChangeIssues.add(changeIssue); } catch (AccessRightException e) { LOGGER.log(Level.FINEST, null, e); } } return visibleChangeIssues; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeIssue createChangeIssue(String pWorkspaceId, String name, String description, String initiator, ChangeItemPriority priority, String assignee, ChangeItemCategory category) throws UserNotFoundException, AccessRightException, WorkspaceNotFoundException, WorkspaceNotEnabledException, NotAllowedException, AccountNotFoundException { User user = userManager.checkWorkspaceWriteAccess(pWorkspaceId); User assigneeUser = null; if (assignee != null && !assignee.isEmpty() && pWorkspaceId != null && !pWorkspaceId.isEmpty()) { if (!userManager.isUserEnabled(assignee, pWorkspaceId)) { throw new NotAllowedException("NotAllowedException71"); } assigneeUser = em.find(User.class, new UserKey(pWorkspaceId, assignee)); } ChangeIssue change = new ChangeIssue(name, user.getWorkspace(), user, assigneeUser, new Date(), description, priority, category, initiator); changeItemDAO.createChangeItem(change); return change; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeIssue updateChangeIssue(int pId, String pWorkspaceId, String description, ChangeItemPriority priority, String assignee, ChangeItemCategory category) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeIssueNotFoundException, AccessRightException, WorkspaceNotEnabledException, AccountNotFoundException, NotAllowedException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeIssue changeIssue = loadChangeIssue(pId); checkChangeItemWriteAccess(changeIssue, user); changeIssue.setDescription(description); changeIssue.setPriority(priority); changeIssue.setCategory(category); if (assignee != null && !assignee.isEmpty()) { if (!userManager.isUserEnabled(assignee, pWorkspaceId)) { throw new NotAllowedException("NotAllowedException71"); } changeIssue.setAssignee(em.find(User.class, new UserKey(pWorkspaceId, assignee))); } else { changeIssue.setAssignee(null); } return changeIssue; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public void deleteChangeIssue(int pId) throws ChangeIssueNotFoundException, UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, AccessRightException, EntityConstraintException, WorkspaceNotEnabledException { ChangeIssue changeIssue = loadChangeIssue(pId); User user = userManager.checkWorkspaceReadAccess(changeIssue.getWorkspaceId()); checkChangeItemWriteAccess(changeIssue, user); if (changeItemDAO.hasChangeRequestsLinked(changeIssue)) { throw new EntityConstraintException("EntityConstraintException26"); } changeItemDAO.deleteChangeItem(changeIssue); } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeIssue saveChangeIssueAffectedDocuments(String pWorkspaceId, int pId, DocumentIterationKey[] pAffectedDocuments) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeIssueNotFoundException, AccessRightException, DocumentRevisionNotFoundException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeIssue changeIssue = loadChangeIssue(pId); checkChangeItemWriteAccess(changeIssue, user); changeIssue.setAffectedDocuments(getDocumentIterations(pAffectedDocuments)); return changeIssue; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeIssue saveChangeIssueAffectedParts(String pWorkspaceId, int pId, PartIterationKey[] pAffectedParts) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeIssueNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeIssue changeIssue = loadChangeIssue(pId); checkChangeItemWriteAccess(changeIssue, user); Set<PartIteration> partIterations = getPartIterations(pAffectedParts); changeIssue.setAffectedParts(partIterations); return changeIssue; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeIssue saveChangeIssueTags(String pWorkspaceId, int pId, String[] tagsLabel) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeIssueNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeIssue changeIssue = loadChangeIssue(pId); checkChangeItemWriteAccess(changeIssue, user); Set<Tag> tags = new HashSet<>(); for (String label : tagsLabel) { tags.add(new Tag(user.getWorkspace(), label)); } List<Tag> existingTags = Arrays.asList(tagDAO.findAllTags(user.getWorkspaceId())); Set<Tag> tagsToCreate = new HashSet<>(tags); tagsToCreate.removeAll(existingTags); for (Tag t : tagsToCreate) { try { tagDAO.createTag(t, true); } catch (CreationException | TagAlreadyExistsException ex) { LOGGER.log(Level.SEVERE, null, ex); } } changeIssue.setTags(tags); return changeIssue; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeIssue removeChangeIssueTag(String pWorkspaceId, int pId, String tagName) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeIssueNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeIssue changeIssue = loadChangeIssue(pId); checkChangeItemWriteAccess(changeIssue, user); return (ChangeIssue) changeItemDAO.removeTag(changeIssue, tagName); } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeRequest getChangeRequest(String pWorkspaceId, int pId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeRequestNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeRequest changeRequest = loadChangeRequest(pId); checkChangeItemReadAccess(changeRequest, user); return filterLinkedChangeIssues(changeRequest, user); } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public List<ChangeRequest> getChangeRequests(String pWorkspaceId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); List<ChangeRequest> allChangeRequests = changeItemDAO.findAllChangeRequests(pWorkspaceId); List<ChangeRequest> visibleChangeRequests = new ArrayList<>(); for (ChangeRequest changeRequest : allChangeRequests) { try { checkChangeItemReadAccess(changeRequest, user); visibleChangeRequests.add(filterLinkedChangeIssues(changeRequest, user)); } catch (AccessRightException e) { LOGGER.log(Level.FINEST, null, e); } } return visibleChangeRequests; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public List<ChangeRequest> getRequestsWithName(String pWorkspaceId, String name, int maxResults) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); List<ChangeRequest> allChangeRequests = changeItemDAO.findAllChangeRequestsWithReferenceLike(pWorkspaceId, name, maxResults); List<ChangeRequest> visibleChangeRequests = new ArrayList<>(); for (ChangeRequest changeRequest : allChangeRequests) { try { checkChangeItemReadAccess(changeRequest, user); visibleChangeRequests.add(filterLinkedChangeIssues(changeRequest, user)); } catch (AccessRightException e) { LOGGER.log(Level.FINEST, null, e); } } return visibleChangeRequests; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeRequest createChangeRequest(String pWorkspaceId, String name, String description, int milestoneId, ChangeItemPriority priority, String assignee, ChangeItemCategory category) throws UserNotFoundException, AccessRightException, WorkspaceNotFoundException, WorkspaceNotEnabledException, AccountNotFoundException, NotAllowedException { User user = userManager.checkWorkspaceWriteAccess(pWorkspaceId); User assigneeUser = null; if (assignee != null && !assignee.isEmpty() && pWorkspaceId != null && !pWorkspaceId.isEmpty()) { if (!userManager.isUserEnabled(assignee, pWorkspaceId)) { throw new NotAllowedException("NotAllowedException71"); } assigneeUser = em.find(User.class, new UserKey(pWorkspaceId, assignee)); } ChangeRequest changeRequest = new ChangeRequest(name, user.getWorkspace(), user, assigneeUser, new Date(), description, priority, category, em.find(Milestone.class, milestoneId)); changeItemDAO.createChangeItem(changeRequest); return changeRequest; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeRequest updateChangeRequest(int pId, String pWorkspaceId, String description, int milestoneId, ChangeItemPriority priority, String assignee, ChangeItemCategory category) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeRequestNotFoundException, AccessRightException, WorkspaceNotEnabledException, AccountNotFoundException, NotAllowedException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeRequest changeRequest = loadChangeRequest(pId); checkChangeItemWriteAccess(changeRequest, user); changeRequest.setDescription(description); changeRequest.setPriority(priority); changeRequest.setCategory(category); if (assignee != null && !assignee.isEmpty()) { if (!userManager.isUserEnabled(assignee, pWorkspaceId)) { throw new NotAllowedException("NotAllowedException71"); } changeRequest.setAssignee(em.find(User.class, new UserKey(pWorkspaceId, assignee))); } else { changeRequest.setAssignee(null); } changeRequest.setMilestone(em.find(Milestone.class, milestoneId)); return changeRequest; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public void deleteChangeRequest(String pWorkspaceId, int pId) throws ChangeRequestNotFoundException, UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, AccessRightException, EntityConstraintException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeRequest changeRequest = loadChangeRequest(pId); if (changeItemDAO.hasChangeOrdersLinked(changeRequest)) { throw new EntityConstraintException("EntityConstraintException10"); } checkChangeItemWriteAccess(changeRequest, user); changeItemDAO.deleteChangeItem(changeRequest); } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeRequest saveChangeRequestAffectedDocuments(String pWorkspaceId, int pId, DocumentIterationKey[] pAffectedDocuments) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeRequestNotFoundException, AccessRightException, DocumentRevisionNotFoundException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeRequest changeRequest = loadChangeRequest(pId); checkChangeItemWriteAccess(changeRequest, user); changeRequest.setAffectedDocuments(getDocumentIterations(pAffectedDocuments)); return changeRequest; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeRequest saveChangeRequestAffectedParts(String pWorkspaceId, int pId, PartIterationKey[] pAffectedParts) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeRequestNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeRequest changeRequest = loadChangeRequest(pId); checkChangeItemWriteAccess(changeRequest, user); Set<PartIteration> partIterations = getPartIterations(pAffectedParts); changeRequest.setAffectedParts(partIterations); return changeRequest; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeRequest saveChangeRequestAffectedIssues(String pWorkspaceId, int pId, int[] pLinkIds) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeRequestNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeRequest changeRequest = loadChangeRequest(pId); checkChangeItemWriteAccess(changeRequest, user); Set<ChangeIssue> changeIssues = Arrays.stream(pLinkIds) .mapToObj(changeItemDAO::loadChangeIssue) .filter(Objects::nonNull) .collect(Collectors.toSet()); changeRequest.setAddressedChangeIssues(changeIssues); return changeRequest; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeRequest saveChangeRequestTags(String pWorkspaceId, int pId, String[] tagsLabel) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeRequestNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeRequest changeRequest = loadChangeRequest(pId); checkChangeItemWriteAccess(changeRequest, user); Set<Tag> tags = new HashSet<>(); for (String label : tagsLabel) { tags.add(new Tag(user.getWorkspace(), label)); } List<Tag> existingTags = Arrays.asList(tagDAO.findAllTags(user.getWorkspaceId())); Set<Tag> tagsToCreate = new HashSet<>(tags); tagsToCreate.removeAll(existingTags); for (Tag t : tagsToCreate) { try { tagDAO.createTag(t, true); } catch (CreationException | TagAlreadyExistsException ex) { LOGGER.log(Level.SEVERE, null, ex); } } changeRequest.setTags(tags); return changeRequest; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeRequest removeChangeRequestTag(String pWorkspaceId, int pId, String tagName) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeIssueNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeIssue changeRequest = loadChangeIssue(pId); checkChangeItemWriteAccess(changeRequest, user); return (ChangeRequest) changeItemDAO.removeTag(changeRequest, tagName); } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeOrder getChangeOrder(String pWorkspaceId, int pId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeOrderNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeOrder changeOrder = loadChangeOrder(pId); checkChangeItemReadAccess(changeOrder, user); return filterLinkedChangeRequests(changeOrder, user); } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public List<ChangeOrder> getChangeOrders(String pWorkspaceId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); List<ChangeOrder> allChangeOrders = changeItemDAO.findAllChangeOrders(pWorkspaceId); List<ChangeOrder> visibleChangeOrders = new ArrayList<>(); for (ChangeOrder changeOrder : allChangeOrders) { try { checkChangeItemReadAccess(changeOrder, user); visibleChangeOrders.add(filterLinkedChangeRequests(changeOrder, user)); } catch (AccessRightException e) { LOGGER.log(Level.FINEST, null, e); } } return visibleChangeOrders; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeOrder createChangeOrder(String pWorkspaceId, String name, String description, int milestoneId, ChangeItemPriority priority, String assignee, ChangeItemCategory category) throws UserNotFoundException, AccessRightException, WorkspaceNotFoundException, WorkspaceNotEnabledException, AccountNotFoundException, NotAllowedException { User user = userManager.checkWorkspaceWriteAccess(pWorkspaceId); User assigneeUser = null; if (assignee != null && !assignee.isEmpty() && pWorkspaceId != null && !pWorkspaceId.isEmpty()) { if (!userManager.isUserEnabled(assignee, pWorkspaceId)) { throw new NotAllowedException("NotAllowedException71"); } assigneeUser = em.find(User.class, new UserKey(pWorkspaceId, assignee)); } ChangeOrder changeOrder = new ChangeOrder(name, user.getWorkspace(), user, assigneeUser, new Date(), description, priority, category, em.find(Milestone.class, milestoneId)); changeItemDAO.createChangeItem(changeOrder); return changeOrder; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeOrder updateChangeOrder(int pId, String pWorkspaceId, String description, int milestoneId, ChangeItemPriority priority, String assignee, ChangeItemCategory category) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeOrderNotFoundException, AccessRightException, WorkspaceNotEnabledException, AccountNotFoundException, NotAllowedException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeOrder changeOrder = loadChangeOrder(pId); checkChangeItemWriteAccess(changeOrder, user); changeOrder.setDescription(description); changeOrder.setPriority(priority); changeOrder.setCategory(category); if (assignee != null && !assignee.isEmpty()) { if (!userManager.isUserEnabled(assignee, pWorkspaceId)) { throw new NotAllowedException("NotAllowedException71"); } changeOrder.setAssignee(em.find(User.class, new UserKey(pWorkspaceId, assignee))); } else { changeOrder.setAssignee(null); } changeOrder.setMilestone(em.find(Milestone.class, milestoneId)); return changeOrder; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public void deleteChangeOrder(int pId) throws ChangeOrderNotFoundException, UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, AccessRightException, WorkspaceNotEnabledException { ChangeOrder changeOrder = loadChangeOrder(pId); User user = userManager.checkWorkspaceReadAccess(changeOrder.getWorkspaceId()); checkChangeItemWriteAccess(changeOrder, user); changeItemDAO.deleteChangeItem(changeOrder); } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeOrder saveChangeOrderAffectedDocuments(String pWorkspaceId, int pId, DocumentIterationKey[] pAffectedDocuments) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeOrderNotFoundException, AccessRightException, DocumentRevisionNotFoundException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeOrder changeOrder = loadChangeOrder(pId); checkChangeItemWriteAccess(changeOrder, user); changeOrder.setAffectedDocuments(getDocumentIterations(pAffectedDocuments)); return changeOrder; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeOrder saveChangeOrderAffectedParts(String pWorkspaceId, int pId, PartIterationKey[] pAffectedParts) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeOrderNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeOrder changeOrder = loadChangeOrder(pId); checkChangeItemWriteAccess(changeOrder, user); Set<PartIteration> partIterations = getPartIterations(pAffectedParts); changeOrder.setAffectedParts(partIterations); return changeOrder; } private Set<PartIteration> getPartIterations(PartIterationKey[] pAffectedParts) { return Arrays.stream(pAffectedParts) .map(partKey -> partRevisionDAO.loadPartR(partKey.getPartRevision()).getIteration(partKey.getIteration())) .filter(Objects::nonNull) .collect(Collectors.toSet()); } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeOrder saveChangeOrderAffectedRequests(String pWorkspaceId, int pId, int[] pLinkIds) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeOrderNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeOrder changeOrder = loadChangeOrder(pId); checkChangeItemWriteAccess(changeOrder, user); Set<ChangeRequest> changeRequests = Arrays.stream(pLinkIds) .mapToObj(changeItemDAO::loadChangeRequest) .filter(Objects::nonNull) .collect(Collectors.toSet()); changeOrder.setAddressedChangeRequests(changeRequests); return changeOrder; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeOrder saveChangeOrderTags(String pWorkspaceId, int pId, String[] tagsLabel) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeOrderNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeOrder changeOrder = loadChangeOrder(pId); checkChangeItemWriteAccess(changeOrder, user); Set<Tag> tags = new HashSet<>(); for (String label : tagsLabel) { tags.add(new Tag(user.getWorkspace(), label)); } List<Tag> existingTags = Arrays.asList(tagDAO.findAllTags(user.getWorkspaceId())); Set<Tag> tagsToCreate = new HashSet<>(tags); tagsToCreate.removeAll(existingTags); for (Tag t : tagsToCreate) { try { tagDAO.createTag(t, true); } catch (CreationException | TagAlreadyExistsException ex) { LOGGER.log(Level.SEVERE, null, ex); } } changeOrder.setTags(tags); return changeOrder; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeOrder removeChangeOrderTag(String pWorkspaceId, int pId, String tagName) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeIssueNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeIssue changeOrder = loadChangeIssue(pId); checkChangeItemWriteAccess(changeOrder, user); return (ChangeOrder) changeItemDAO.removeTag(changeOrder, tagName); } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public Milestone getMilestone(String pWorkspaceId, int pId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, MilestoneNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); Milestone milestone = milestoneDAO.loadMilestone(pId); checkMilestoneReadAccess(milestone, user); return milestone; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public Milestone getMilestoneByTitle(String pWorkspaceId, String pTitle) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, MilestoneNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); Milestone milestone = milestoneDAO.loadMilestone(pTitle, pWorkspaceId); checkMilestoneReadAccess(milestone, user); return milestone; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public List<Milestone> getMilestones(String pWorkspaceId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); List<Milestone> allMilestones = milestoneDAO.findAllMilestone(pWorkspaceId); List<Milestone> visibleMilestones = new ArrayList<>(allMilestones); for (Milestone milestone : allMilestones) { try { checkMilestoneReadAccess(milestone, user); } catch (AccessRightException e) { visibleMilestones.remove(milestone); LOGGER.log(Level.FINEST, null, e); } } return visibleMilestones; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public Milestone createMilestone(String pWorkspaceId, String title, String description, Date dueDate) throws UserNotFoundException, AccessRightException, WorkspaceNotFoundException, MilestoneAlreadyExistsException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceWriteAccess(pWorkspaceId); Milestone milestone = new Milestone(title, dueDate, description, user.getWorkspace()); milestoneDAO.createMilestone(milestone); return milestone; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public Milestone updateMilestone(int pId, String pWorkspaceId, String title, String description, Date dueDate) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, MilestoneNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); Milestone milestone = milestoneDAO.loadMilestone(pId); checkMilestoneWriteAccess(milestone, user); milestone.setTitle(title); milestone.setDescription(description); milestone.setDueDate(dueDate); return milestone; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public void deleteMilestone(String pWorkspaceId, int pId) throws MilestoneNotFoundException, UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, AccessRightException, EntityConstraintException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); Milestone milestone = milestoneDAO.loadMilestone(pId); checkMilestoneWriteAccess(milestone, user); int numberOfOrders = milestoneDAO.getNumberOfOrders(milestone.getId(), milestone.getWorkspaceId()); if (numberOfOrders > 0) { throw new EntityConstraintException("EntityConstraintException8"); } int numberOfRequests = milestoneDAO.getNumberOfRequests(milestone.getId(), milestone.getWorkspaceId()); if (numberOfRequests > 0) { throw new EntityConstraintException("EntityConstraintException9"); } milestoneDAO.deleteMilestone(milestone); } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public List<ChangeRequest> getChangeRequestsByMilestone(String pWorkspaceId, int pId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, MilestoneNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); Milestone milestone = milestoneDAO.loadMilestone(pId); checkMilestoneReadAccess(milestone, user); List<ChangeRequest> affectedRequests = milestoneDAO.getAllRequests(pId, pWorkspaceId); List<ChangeRequest> visibleChangeRequests = new ArrayList<>(); for (ChangeRequest changeRequest : affectedRequests) { try { checkChangeItemReadAccess(changeRequest, user); visibleChangeRequests.add(filterLinkedChangeIssues(changeRequest, user)); } catch (AccessRightException e) { LOGGER.log(Level.FINEST, null, e); } } return visibleChangeRequests; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public List<ChangeOrder> getChangeOrdersByMilestone(String pWorkspaceId, int pId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, MilestoneNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); Milestone milestone = milestoneDAO.loadMilestone(pId); checkMilestoneReadAccess(milestone, user); List<ChangeOrder> affectedOrders = milestoneDAO.getAllOrders(pId, pWorkspaceId); List<ChangeOrder> visibleChangeOrders = new ArrayList<>(); for (ChangeOrder changeOrder : affectedOrders) { try { checkChangeItemReadAccess(changeOrder, user); visibleChangeOrders.add(filterLinkedChangeRequests(changeOrder, user)); } catch (AccessRightException e) { LOGGER.log(Level.FINEST, null, e); } } return visibleChangeOrders; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public int getNumberOfRequestByMilestone(String pWorkspaceId, int milestoneId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, WorkspaceNotEnabledException { userManager.checkWorkspaceReadAccess(pWorkspaceId); return milestoneDAO.getNumberOfRequests(milestoneId, pWorkspaceId); } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public int getNumberOfOrderByMilestone(String pWorkspaceId, int milestoneId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, WorkspaceNotEnabledException { userManager.checkWorkspaceReadAccess(pWorkspaceId); return milestoneDAO.getNumberOfOrders(milestoneId, pWorkspaceId); } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeIssue updateACLForChangeIssue(String pWorkspaceId, int pId, Map<String, String> pUserEntries, Map<String, String> pGroupEntries) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeIssueNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeIssue changeIssue = loadChangeIssue(pId); checkChangeItemGrantAccess(changeIssue, user); updateACLForChangeItem(pWorkspaceId, changeIssue, pUserEntries, pGroupEntries); return changeIssue; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeRequest updateACLForChangeRequest(String pWorkspaceId, int pId, Map<String, String> pUserEntries, Map<String, String> pGroupEntries) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeRequestNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeRequest changeRequest = loadChangeRequest(pId); checkChangeItemGrantAccess(changeRequest, user); updateACLForChangeItem(pWorkspaceId, changeRequest, pUserEntries, pGroupEntries); return changeRequest; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeOrder updateACLForChangeOrder(String pWorkspaceId, int pId, Map<String, String> pUserEntries, Map<String, String> pGroupEntries) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeOrderNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeOrder changeOrder = loadChangeOrder(pId); checkChangeItemGrantAccess(changeOrder, user); updateACLForChangeItem(pWorkspaceId, changeOrder, pUserEntries, pGroupEntries); return changeOrder; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public Milestone updateACLForMilestone(String pWorkspaceId, int pId, Map<String, String> pUserEntries, Map<String, String> pGroupEntries) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, MilestoneNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); Milestone milestone = milestoneDAO.loadMilestone(pId); checkMilestoneWriteAccess(milestone, user); if (milestone.getACL() == null) { // Check if already a ACL Rule ACL acl = aclFactory.createACL(pWorkspaceId, pUserEntries, pGroupEntries); milestone.setACL(acl); } else { ACL acl = milestone.getACL(); aclFactory.updateACL(pWorkspaceId, acl, pUserEntries, pGroupEntries); } return milestone; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeIssue removeACLFromChangeIssue(String pWorkspaceId, int pId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeIssueNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeIssue changeIssue = loadChangeIssue(pId); checkChangeItemGrantAccess(changeIssue, user); removeACLFromChangeItem(changeIssue); return changeIssue; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeRequest removeACLFromChangeRequest(String pWorkspaceId, int pId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeRequestNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeRequest changeRequest = loadChangeRequest(pId); checkChangeItemGrantAccess(changeRequest, user); removeACLFromChangeItem(changeRequest); return changeRequest; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public ChangeOrder removeACLFromChangeOrder(String pWorkspaceId, int pId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, ChangeOrderNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); ChangeOrder changeOrder = loadChangeOrder(pId); checkChangeItemGrantAccess(changeOrder, user); removeACLFromChangeItem(changeOrder); return changeOrder; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public Milestone removeACLFromMilestone(String pWorkspaceId, int pId) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, MilestoneNotFoundException, AccessRightException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pWorkspaceId); Milestone milestone = milestoneDAO.loadMilestone(pId); checkMilestoneWriteAccess(milestone, user); ACL acl = milestone.getACL(); if (acl != null) { aclDAO.removeACLEntries(acl); milestone.setACL(null); } return milestone; } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public boolean isChangeItemWritable(ChangeItem pChangeItem) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pChangeItem.getWorkspaceId()); try { checkChangeItemWriteAccess(pChangeItem, user); return true; } catch (AccessRightException e) { LOGGER.log(Level.FINEST, null, e); return false; } } @RolesAllowed(UserGroupMapping.REGULAR_USER_ROLE_ID) @Override public boolean isMilestoneWritable(Milestone pMilestone) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException, WorkspaceNotEnabledException { User user = userManager.checkWorkspaceReadAccess(pMilestone.getWorkspaceId()); try { checkMilestoneWriteAccess(pMilestone, user); return true; } catch (AccessRightException e) { LOGGER.log(Level.FINEST, null, e); return false; } } private void updateACLForChangeItem(String pWorkspaceId, ChangeItem changeItem, Map<String, String> pUserEntries, Map<String, String> pGroupEntries) { if (changeItem.getACL() == null) { ACL acl = aclFactory.createACL(pWorkspaceId, pUserEntries, pGroupEntries); changeItem.setACL(acl); } else { aclFactory.updateACL(pWorkspaceId, changeItem.getACL(), pUserEntries, pGroupEntries); } } private void removeACLFromChangeItem(ChangeItem changeItem) { ACL acl = changeItem.getACL(); if (acl != null) { aclDAO.removeACLEntries(acl); changeItem.setACL(null); } } private User checkChangeItemGrantAccess(ChangeItem pChangeItem, User pUser) throws AccessRightException, UserNotFoundException, WorkspaceNotFoundException, WorkspaceNotEnabledException { if (pUser.isAdministrator()) { return pUser; } else if (pUser.getLogin().equals(pChangeItem.getAuthor().getLogin())) { checkChangeItemWriteAccess(pChangeItem, pUser); return pUser; } else { throw new AccessRightException(pUser); } } private User checkChangeItemWriteAccess(ChangeItem pChangeItem, User pUser) throws AccessRightException, UserNotFoundException, WorkspaceNotFoundException, WorkspaceNotEnabledException { if (pUser.isAdministrator()) { return pUser; } if (pChangeItem.getACL() == null) { return userManager.checkWorkspaceWriteAccess(pChangeItem.getWorkspaceId()); } else if (pChangeItem.getACL().hasWriteAccess(pUser)) { return pUser; } else { throw new AccessRightException(pUser); } } private User checkChangeItemReadAccess(ChangeItem pChangeItem, User pUser) throws AccessRightException { if (pUser.isAdministrator() || pChangeItem.getACL() == null || pChangeItem.getACL().hasReadAccess(pUser)) { return pUser; } else { throw new AccessRightException(pUser); } } private User checkMilestoneWriteAccess(Milestone pMilestone, User pUser) throws AccessRightException, UserNotFoundException, WorkspaceNotFoundException, WorkspaceNotEnabledException { if (pUser.isAdministrator()) { return pUser; } if (pMilestone.getACL() == null) { return userManager.checkWorkspaceWriteAccess(pMilestone.getWorkspaceId()); } else if (pMilestone.getACL().hasWriteAccess(pUser)) { return pUser; } else { throw new AccessRightException(pUser); } } private User checkMilestoneReadAccess(Milestone pMilestone, User pUser) throws AccessRightException { if (pUser.isAdministrator() || pMilestone.getACL() == null || pMilestone.getACL().hasReadAccess(pUser)) { return pUser; } else { throw new AccessRightException(pUser); } } private ChangeRequest filterLinkedChangeIssues(ChangeRequest changeRequest, User user) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException { em.detach(changeRequest); Set<ChangeIssue> addressedChangeIssues = changeRequest.getAddressedChangeIssues(); Set<ChangeIssue> visibleChangeIssues = new HashSet<>(); for (ChangeIssue changeIssue : addressedChangeIssues) { try { checkChangeItemReadAccess(changeIssue, user); visibleChangeIssues.add(changeIssue); } catch (AccessRightException e) { LOGGER.log(Level.FINEST, null, e); } } changeRequest.setAddressedChangeIssues(visibleChangeIssues); return changeRequest; } private ChangeOrder filterLinkedChangeRequests(ChangeOrder changeOrder, User user) throws UserNotFoundException, UserNotActiveException, WorkspaceNotFoundException { em.detach(changeOrder); Set<ChangeRequest> allChangeRequests = changeOrder.getAddressedChangeRequests(); Set<ChangeRequest> visibleChangeRequests = new HashSet<>(); for (ChangeRequest changeRequest : allChangeRequests) { try { checkChangeItemReadAccess(changeRequest, user); visibleChangeRequests.add(filterLinkedChangeIssues(changeRequest, user)); } catch (AccessRightException e) { LOGGER.log(Level.FINEST, null, e); } } changeOrder.setAddressedChangeRequests(visibleChangeRequests); return changeOrder; } private Set<DocumentIteration> getDocumentIterations(DocumentIterationKey[] pAffectedDocuments) throws DocumentRevisionNotFoundException { Set<DocumentIteration> documentIterations = new HashSet<>(); for (DocumentIterationKey docKey : pAffectedDocuments) { DocumentRevision documentRevision = documentRevisionDAO.loadDocR(docKey.getDocumentRevision()); DocumentIteration iteration; if (docKey.getIteration() > 0) { iteration = documentRevision.getIteration(docKey.getIteration()); } else { iteration = documentRevision.getLastCheckedInIteration(); } if (iteration != null) { documentIterations.add(iteration); } } return documentIterations; } private ChangeIssue loadChangeIssue(int pId) throws ChangeIssueNotFoundException { return Optional.of(changeItemDAO.loadChangeIssue(pId)) .orElseThrow(() -> new ChangeIssueNotFoundException(pId)); } private ChangeRequest loadChangeRequest(int pId) throws ChangeRequestNotFoundException { return Optional.of(changeItemDAO.loadChangeRequest(pId)) .orElseThrow(() -> new ChangeRequestNotFoundException(pId)); } private ChangeOrder loadChangeOrder(int pId) throws ChangeOrderNotFoundException { return Optional.of(changeItemDAO.loadChangeOrder(pId)) .orElseThrow(() -> new ChangeOrderNotFoundException(pId)); } }
50,043
Java
.java
868
48.769585
400
0.743536
docdoku/docdoku-plm-server
11
10
1
AGPL-3.0
9/4/2024, 8:27:28 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
50,043
744,089
NotifyAnswerImpl.java
Etisalat-Egypt_Rodan/src/intruder/diameter/gateway/src/main/java/com/rodan/intruder/diameter/gateway/handler/model/NotifyAnswerImpl.java
/* * Etisalat Egypt, Open Source * Copyright 2021, Etisalat Egypt and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ /** * @author Ayman ElSherif */ package com.rodan.intruder.diameter.gateway.handler.model; import com.rodan.intruder.diameter.entities.event.model.NotifyAnswer; import com.rodan.intruder.diameter.entities.event.model.ResultCode; import lombok.Builder; import lombok.Getter; import lombok.ToString; @Getter @ToString(callSuper = true) public class NotifyAnswerImpl extends DiameterMessageImpl implements NotifyAnswer { @Builder public NotifyAnswerImpl(ResultCode resultCode, String sessionId) { super(resultCode, sessionId); } }
1,344
Java
.java
34
37.264706
83
0.784839
Etisalat-Egypt/Rodan
94
31
1
AGPL-3.0
9/4/2024, 7:08:37 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,344
548,467
InvitesWindow.java
ratrecommends_dice-heroes/desktop/src/com/vlaaad/dice/services/ui/InvitesWindow.java
/* * Dice heroes is a turn based rpg-strategy game where characters are dice. * Copyright (C) 2016 Vladislav Protsenko * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.vlaaad.dice.services.ui; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.EventListener; import com.badlogic.gdx.scenes.scene2d.Touchable; import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.utils.Array; import com.vlaaad.common.ui.GameWindow; import com.vlaaad.dice.Config; /** * Created 27.07.14 by vlaaad */ public class InvitesWindow extends GameWindow<InvitesWindow.Callback> { private Callback callback; public static interface Callback { void onSelected(String player); void onCancelled(); } private Table list = new Table(); { list.defaults().expandX().fillX().pad(4); } private String selected; public void setPlayers(Array<String> players) { list.clear(); for (String player : players) { TextButton button = new TextButton(player, Config.skin); button.addListener(createListener(player)); list.add(button).row(); } } private EventListener createListener(final String player) { return new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { selected = player; hide(); } }; } @Override protected void initialize() { Table content = new Table(Config.skin); content.setTouchable(Touchable.enabled); content.setBackground("ui-store-window-background"); content.add(new ScrollPane(list)).size(100, 100); table.add(content); } @Override protected void doShow(Callback callback) { this.callback = callback; } @Override protected void onHide() { if (selected != null) { callback.onSelected(selected); selected = null; } else { callback.onCancelled(); } } }
2,846
Java
.java
77
31.272727
75
0.695431
ratrecommends/dice-heroes
156
28
4
GPL-3.0
9/4/2024, 7:07:37 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
2,846
880,264
LolChatError.java
stirante_lol-client-java-api/src/main/java/generated/LolChatError.java
package generated; import com.google.gson.annotations.SerializedName; public class LolChatError { public String cid; @SerializedName("class") public String classField; public String code; public String id; public String pid; public String subtype; public String text; public String ts; public String type; }
321
Java
.java
14
21
50
0.819079
stirante/lol-client-java-api
68
14
3
GPL-3.0
9/4/2024, 7:09:48 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
321
2,065,776
DefaultPlayerSkinCheckService.java
particle-org_particle/ParticleServer/src/main/java/com/particle/game/player/DefaultPlayerSkinCheckService.java
package com.particle.game.player; import com.google.inject.Singleton; import com.particle.api.inject.RequestStaticInject; import com.particle.api.player.PlayerSkinCheckServiceApi; import com.particle.model.entity.model.skin.PlayerSkinData; import java.util.concurrent.Executor; @Singleton @RequestStaticInject public class DefaultPlayerSkinCheckService implements PlayerSkinCheckServiceApi { @Override public void checkSkin(PlayerSkinData skin, CheckResultCallback checkResultCallback, Executor checkThread) { } }
529
Java
.java
13
38.538462
111
0.861598
particle-org/particle
11
3
0
LGPL-2.1
9/4/2024, 8:28:13 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
529
3,744,324
MixinItemFlintAndSteel.java
MinecraftTAS_KillTheRNG/src/main/java/com/minecrafttas/killtherng/mixin/ktrng/patches/MixinItemFlintAndSteel.java
package com.minecrafttas.killtherng.mixin.ktrng.patches; import java.util.Random; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @Mixin(net.minecraft.item.ItemFlintAndSteel.class) public class MixinItemFlintAndSteel{ /** * null */ @Redirect(method = "onItemUse(Lnet/minecraft/entity/player/EntityPlayer;Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/EnumHand;Lnet/minecraft/util/EnumFacing;FFF)Lnet/minecraft/util/EnumActionResult;", at = @At(value = "INVOKE", target = "Ljava/util/Random;nextFloat()F", ordinal = 0)) public float redirect_random_569_1(Random rand) { if (com.minecrafttas.killtherng.KillTheRNG.commonRandom.random_569.isEnabled()) { return com.minecrafttas.killtherng.KillTheRNG.commonRandom.random_569.nextFloat(); } else { com.minecrafttas.killtherng.KillTheRNG.commonRandom.random_569.nextFloat(); return rand.nextFloat(); } } }
1,007
Java
.java
20
48.1
321
0.80468
MinecraftTAS/KillTheRNG
3
3
1
GPL-3.0
9/4/2024, 11:40:51 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,007
3,602,403
NullType.java
MartinRixham_Yirgacheffe/compiler/src/main/java/yirgacheffe/compiler/type/NullType.java
package yirgacheffe.compiler.type; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import yirgacheffe.compiler.Result; import yirgacheffe.compiler.error.Coordinate; import yirgacheffe.compiler.member.Interface; import yirgacheffe.compiler.member.NullInterface; import yirgacheffe.compiler.operator.BooleanOperator; public class NullType implements Type { private String name; public NullType(String name) { this.name = name; } public NullType() { this.name = "java.lang.Object"; } public Interface reflect() { return new NullInterface(); } public Interface reflect(Type type) { return new NullInterface(); } public String toJVMType() { return "Ljava/lang/Object;"; } public String toFullyQualifiedType() { return this.name.replace(".", "/"); } public Result construct(Coordinate coordinate) { return new Result(); } public int width() { return 1; } public int getReturnInstruction() { return Opcodes.ARETURN; } public int getStoreInstruction() { return Opcodes.ASTORE; } public int getArrayStoreInstruction() { return Opcodes.AASTORE; } public int getLoadInstruction() { return Opcodes.ALOAD; } public int getZero() { return Opcodes.ACONST_NULL; } public boolean isAssignableTo(Type other) { return true; } public boolean hasParameter() { return false; } public String getSignature() { return this.toJVMType(); } public String[] getSignatureTypes() { return new String[0]; } public boolean isPrimitive() { return false; } public Result newArray() { return new Result(); } public Result convertTo(Type type) { return new Result(); } public Result swapWith(Type type) { return new Result(); } public Type intersect(Type type) { return this; } public Result compare(BooleanOperator operator, Label label) { return new Result(); } public Result attempt() { return new Result(); } public Type getTypeParameter(String typeName) { return new NullType(); } @Override public String toString() { return this.name; } }
2,086
Java
.java
117
15.461538
61
0.759402
MartinRixham/Yirgacheffe
3
0
2
GPL-3.0
9/4/2024, 11:34:56 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
2,086
1,333,078
AgileSoundProvider.java
lanceewing_agile-gdx/core/src/main/java/com/agifans/agile/agilib/AgileSoundProvider.java
package com.agifans.agile.agilib; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import com.agifans.agile.agilib.jagi.sound.Sound; import com.agifans.agile.agilib.jagi.sound.SoundProvider; /** * An implementation of the JAGI SoundProvider interface that loads the Sound * in a form more easily used by AGILE. */ public class AgileSoundProvider implements SoundProvider { @Override public Sound loadSound(InputStream is) throws IOException { // At this point, JAGI has already read the 5 byte header, i.e. // 0x12 0x34, etc., which means that the InputStream does not contain // the length. We therefore have to fully read the resource from // the InputStream so as to create the byte array required by // the AGILE Sound resource. Avoiding Java 9 at present, as it is // unclear whether GWT will support this. int numOfBytesReads; byte[] data = new byte[256]; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); while ((numOfBytesReads = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, numOfBytesReads); } buffer.flush(); return new AgileSoundWrapper(new com.agifans.agile.agilib.Sound(buffer.toByteArray())); } public static class AgileSoundWrapper implements Sound { private com.agifans.agile.agilib.Sound agileSound; public AgileSoundWrapper(com.agifans.agile.agilib.Sound agileSound) { this.agileSound = agileSound; } public com.agifans.agile.agilib.Sound getAgileSound() { return agileSound; } } }
1,709
Java
.java
38
37.736842
95
0.704698
lanceewing/agile-gdx
37
2
3
GPL-2.0
9/4/2024, 7:36:56 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,709
3,283,710
AbstractHtmlGeneratorTest.java
eclipse-archived_codewind-openapi-eclipse/dev/org.eclipse.codewind.openapi.test/src/org/eclipse/codewind/openapi/test/html/AbstractHtmlGeneratorTest.java
/******************************************************************************* * Copyright (c) 2019 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.codewind.openapi.test.html; import org.eclipse.codewind.openapi.test.AbstractGenerateTest; import org.eclipse.codewind.openapi.ui.commands.AbstractOpenApiGeneratorCommand; import org.eclipse.codewind.openapi.ui.commands.GenerateHtmlCommand; public abstract class AbstractHtmlGeneratorTest extends AbstractGenerateTest { public AbstractHtmlGeneratorTest(String name) { super(name); } @Override protected AbstractOpenApiGeneratorCommand getCommand() { return new GenerateHtmlCommand(); } protected void verify() { super.verify(); verifyGeneratedFile("index.html"); } }
1,178
Java
.java
29
38.517241
81
0.695538
eclipse-archived/codewind-openapi-eclipse
4
12
9
EPL-2.0
9/4/2024, 11:09:57 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,178
1,583,055
GuiPlayerTabOverlayMixin.java
Polyfrost_VanillaHUD/src/main/java/org/polyfrost/vanillahud/mixin/minecraft/GuiPlayerTabOverlayMixin.java
package org.polyfrost.vanillahud.mixin.minecraft; import cc.polyfrost.oneconfig.config.core.OneColor; import cc.polyfrost.oneconfig.internal.hud.HudCore; import cc.polyfrost.oneconfig.renderer.TextRenderer; import com.google.common.collect.Ordering; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.*; import net.minecraft.client.network.NetworkPlayerInfo; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.scoreboard.*; import net.minecraft.util.*; import org.polyfrost.vanillahud.VanillaHUD; import org.polyfrost.vanillahud.hooks.TabHook; import org.polyfrost.vanillahud.hud.TabList; import org.polyfrost.vanillahud.utils.TabListManager; import org.spongepowered.asm.mixin.*; import org.spongepowered.asm.mixin.injection.*; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.invoke.arg.Args; import java.util.List; // 1100 priority to load before Patcher @Mixin(value = GuiPlayerTabOverlay.class, priority = 1100) public abstract class GuiPlayerTabOverlayMixin { @Shadow private IChatComponent header, footer; @Shadow @Final private Minecraft mc; @Unique private static final IChatComponent tab$exampleHeader = new ChatComponentText("Tab List"); @Unique private static final IChatComponent tab$exampleFooter = new ChatComponentText("VanillaHud"); @Unique private int entryX, entryWidth; @Unique List<NetworkPlayerInfo> renderingList; @Unique private List<NetworkPlayerInfo> currentList; @ModifyVariable(method = "renderPlayerlist", at = @At(value = "STORE", ordinal = 0), ordinal = 9) private int resetY(int y) { return 1; } @ModifyVariable(method = "renderPlayerlist", at = @At(value = "STORE", ordinal = 0), ordinal = 7) private int captureEntryWidth(int width) { entryWidth = width; return width; } @ModifyVariable(method = "renderPlayerlist", at = @At(value = "STORE", ordinal = 0), ordinal = 14) private int captureEntryX(int x) { entryX = x; return x; } @ModifyConstant(method = "renderPlayerlist", constant = @Constant(intValue = 13)) private int pingWidth(int constant) { int width = 3; if (TabList.TabHud.numberPing && TabList.TabHud.pingType) { int maxWidth = 0; for (NetworkPlayerInfo info : renderingList) { int textWidth = mc.fontRendererObj.getStringWidth(String.valueOf(info.getResponseTime())); if (textWidth > maxWidth) maxWidth = textWidth; } width += maxWidth; } else { width += 10; } return Math.max(width, 13); } @Redirect(method = "renderPlayerlist", at = @At(value = "FIELD", target = "Lnet/minecraft/client/gui/GuiPlayerTabOverlay;header:Lnet/minecraft/util/IChatComponent;")) private IChatComponent modifyHeader(GuiPlayerTabOverlay instance) { if (!TabList.TabHud.showHeader) return null; if (HudCore.editing) return tab$exampleHeader; return header; } @Redirect(method = "renderPlayerlist", at = @At(value = "FIELD", target = "Lnet/minecraft/client/gui/GuiPlayerTabOverlay;footer:Lnet/minecraft/util/IChatComponent;")) private IChatComponent modifyFooter(GuiPlayerTabOverlay instance) { if (!TabList.TabHud.showFooter) return null; if (HudCore.editing) return tab$exampleFooter; return footer; } @Inject(method = "renderPlayerlist", at = @At(value = "HEAD")) private void translate(int width, Scoreboard scoreboardIn, ScoreObjective scoreObjectiveIn, CallbackInfo ci) { TabList.TabHud hud = TabList.hud; GlStateManager.pushMatrix(); GlStateManager.translate((float) (-width / 2) * hud.getScale() + hud.position.getCenterX(), hud.position.getY() + hud.getPaddingY(), 0); GlStateManager.scale(hud.getScale(), hud.getScale(), 1f); } @Inject(method = "renderPlayerlist", at = @At(value = "TAIL")) private void pop(int width, Scoreboard scoreboardIn, ScoreObjective scoreObjectiveIn, CallbackInfo ci) { GlStateManager.popMatrix(); } @Redirect(method = "renderPlayerlist", at = @At(value = "INVOKE", target = "Lcom/google/common/collect/Ordering;sortedCopy(Ljava/lang/Iterable;)Ljava/util/List;")) private List<NetworkPlayerInfo> list(Ordering<NetworkPlayerInfo> instance, Iterable<NetworkPlayerInfo> elements) { List<NetworkPlayerInfo> list = instance.sortedCopy(elements); if (TabList.TabHud.selfAtTop && !VanillaHUD.isCompactTab()) { for (NetworkPlayerInfo info : list) { if (info.getGameProfile().getId().equals(mc.thePlayer.getGameProfile().getId())) { list.remove(info); list.add(0, info); break; } } } return renderingList = HudCore.editing ? TabListManager.devInfo : list; } @ModifyArgs(method = "renderPlayerlist", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/GuiPlayerTabOverlay;drawRect(IIIII)V", ordinal = 0)) private void cancelRects(Args args) { TabHook.cancelRect = true; } @ModifyArgs(method = "renderPlayerlist", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/GuiPlayerTabOverlay;drawRect(IIIII)V", ordinal = 1)) private void captureWidth(Args args) { TabList.width = (int) args.get(2) - (int) args.get(0); TabList.height = args.get(3); TabHook.cancelRect = true; } @ModifyArgs(method = "renderPlayerlist", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/GuiPlayerTabOverlay;drawRect(IIIII)V", ordinal = 3)) private void captureHeight(Args args) { TabList.height = args.get(3); TabHook.cancelRect = true; } @ModifyArgs(method = "renderPlayerlist", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/GuiPlayerTabOverlay;drawRect(IIIII)V", ordinal = 2)) private void widget(Args args) { if (TabHook.gettingSize) TabHook.cancelRect = true; } @ModifyConstant(method = "renderPlayerlist", constant = @Constant(intValue = 20, ordinal = 0)) private int limit(int constant) { return (HudCore.editing ? 10 : constant); } @Inject(method = "renderPlayerlist", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/FontRenderer;drawStringWithShadow(Ljava/lang/String;FFI)I"), slice = @Slice( from = @At(value = "INVOKE", target = "Lnet/minecraft/client/network/NetworkPlayerInfo;getGameProfile()Lcom/mojang/authlib/GameProfile;", ordinal = 1), to = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/GuiPlayerTabOverlay;drawPing(IIILnet/minecraft/client/network/NetworkPlayerInfo;)V") )) private void preHeadTransform(int width, Scoreboard scoreboardIn, ScoreObjective scoreObjectiveIn, CallbackInfo ci) { if (TabHook.gettingSize) return; GlStateManager.pushMatrix(); GlStateManager.translate(TabList.TabHud.showHead ? 0 : -8, 0, 0); } @Redirect(method = "renderPlayerlist", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/FontRenderer;drawStringWithShadow(Ljava/lang/String;FFI)I")) private int drawText(FontRenderer instance, String text, float x, float y, int color) { if (!TabHook.gettingSize) { GlStateManager.pushMatrix(); GlStateManager.enableBlend(); GlStateManager.enableAlpha(); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); TextRenderer.drawScaledString(text, x, y, color, TextRenderer.TextType.toType(TabList.TabHud.textType), 1); GlStateManager.disableAlpha(); GlStateManager.disableBlend(); GlStateManager.popMatrix(); } return 0; } @Inject(method = "renderPlayerlist", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/FontRenderer;drawStringWithShadow(Ljava/lang/String;FFI)I", shift = At.Shift.AFTER), slice = @Slice( from = @At(value = "INVOKE", target = "Lnet/minecraft/client/network/NetworkPlayerInfo;getGameProfile()Lcom/mojang/authlib/GameProfile;", ordinal = 1), to = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/GuiPlayerTabOverlay;drawPing(IIILnet/minecraft/client/network/NetworkPlayerInfo;)V") )) private void postHeadTransform(int width, Scoreboard scoreboardIn, ScoreObjective scoreObjectiveIn, CallbackInfo ci) { if (TabHook.gettingSize) return; GlStateManager.popMatrix(); } @Redirect(method = "renderPlayerlist", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/Gui;drawScaledCustomSizeModalRect(IIFFIIIIFF)V", ordinal = 0)) private void playerHead(int x, int y, float u, float v, int uWidth, int vHeight, int width, int height, float tileWidth, float tileHeight) { if (!TabList.TabHud.showHead || TabHook.gettingSize) return; Gui.drawScaledCustomSizeModalRect(x, y, u, v, uWidth, vHeight, width, height, tileWidth, tileHeight); } @Redirect(method = "renderPlayerlist", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/Gui;drawScaledCustomSizeModalRect(IIFFIIIIFF)V", ordinal = 1)) private void playerHead1(int x, int y, float u, float v, int uWidth, int vHeight, int width, int height, float tileWidth, float tileHeight) { if (!TabList.TabHud.showHead || TabHook.gettingSize) return; if (TabList.TabHud.betterHatLayer) { GlStateManager.translate(-0.5f, -0.5f, 0f); Gui.drawScaledCustomSizeModalRect(x, y, u, v, uWidth, vHeight, 9, 9, tileWidth, tileHeight); GlStateManager.translate(0.5f, 0.5f, 0f); } else { Gui.drawScaledCustomSizeModalRect(x, y, u, v, uWidth, vHeight, width, height, tileWidth, tileHeight); } } @Unique private NetworkPlayerInfo info; @Inject(method = "drawScoreboardValues", at = @At("HEAD")) private void captureInfo(ScoreObjective scoreObjective, int i, String string, int j, int k, NetworkPlayerInfo networkPlayerInfo, CallbackInfo ci) { info = networkPlayerInfo; } @Redirect(method = "renderPlayerlist", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/GuiPlayerTabOverlay;drawScoreboardValues(Lnet/minecraft/scoreboard/ScoreObjective;ILjava/lang/String;IILnet/minecraft/client/network/NetworkPlayerInfo;)V")) private void scoreboard(GuiPlayerTabOverlay instance, ScoreObjective scoreObjective, int i, String string, int j, int k, NetworkPlayerInfo networkPlayerInfo) { if (TabHook.gettingSize) return; GlStateManager.pushMatrix(); GlStateManager.enableBlend(); GlStateManager.enableAlpha(); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); ((GuiPlayerTabOverlayAccessor) instance).renderScore(scoreObjective, i, string, j, k, networkPlayerInfo); GlStateManager.disableAlpha(); GlStateManager.disableBlend(); GlStateManager.popMatrix(); } @Redirect(method = "drawScoreboardValues", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/FontRenderer;drawStringWithShadow(Ljava/lang/String;FFI)I", ordinal = 1)) private int translate(FontRenderer instance, String text, float x, float y, int color) { if (!TabHook.gettingSize) { int ping = info.getResponseTime(); boolean offset = TabList.TabHud.numberPing && TabList.TabHud.hideFalsePing && (ping <= 1 || ping >= 999) || !TabList.TabHud.showPing; float textWidth = mc.fontRendererObj.getStringWidth(text); float textX = offset ? entryX + entryWidth - textWidth - 1 : x; TextRenderer.drawScaledString(text, textX, y, color, TextRenderer.TextType.toType(TabList.TabHud.textType), 1F); } return 0; } @Redirect(method = "renderPlayerlist", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/GuiPlayerTabOverlay;drawPing(IIILnet/minecraft/client/network/NetworkPlayerInfo;)V")) private void redirectDrawPing(GuiPlayerTabOverlay instance, int width, int x, int y, NetworkPlayerInfo networkPlayerInfoIn) { if (TabHook.gettingSize) return; if (!TabList.TabHud.showPing) return; if (TabList.TabHud.numberPing) { int ping = networkPlayerInfoIn.getResponseTime(); if (TabList.TabHud.hideFalsePing && (ping <= 1 || ping >= 999)) return; OneColor color = tab$getColor(ping); String pingString = String.valueOf(ping); int textWidth = mc.fontRendererObj.getStringWidth(String.valueOf(ping)); if (!TabList.TabHud.pingType) { GlStateManager.scale(0.5F, 0.5F, 0.5F); TextRenderer.drawScaledString(pingString, 2 * (x + width) - textWidth - 4, 2 * y + 4, color.getRGB(), TextRenderer.TextType.toType(TabList.TabHud.textType), 1F); GlStateManager.scale(2F, 2F, 2F); } else TextRenderer.drawScaledString(pingString, x + width - textWidth - 1, y, color.getRGB(), TextRenderer.TextType.toType(TabList.TabHud.textType), 1F); } else { GlStateManager.pushMatrix(); GlStateManager.enableBlend(); GlStateManager.enableAlpha(); GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0); ((GuiPlayerTabOverlayAccessor) instance).renderPing(width, x, y, networkPlayerInfoIn); GlStateManager.disableAlpha(); GlStateManager.disableBlend(); GlStateManager.popMatrix(); } } @Unique private static OneColor tab$getColor(int ping) { return ping >= 400 ? TabList.TabHud.pingLevelSix : ping >= 300 ? TabList.TabHud.pingLevelFive : ping >= 200 ? TabList.TabHud.pingLevelFour : ping >= 145 ? TabList.TabHud.pingLevelThree : ping >= 75 ? TabList.TabHud.pingLevelTwo : TabList.TabHud.pingLevelOne; } @ModifyConstant(method = "renderPlayerlist", constant = @Constant(intValue = 553648127)) private int tabOpacity(int opacity) { return TabList.TabHud.tabWidgetColor.getRGB(); } @ModifyConstant(method = "renderPlayerlist", constant = @Constant(intValue = 80)) private int changePlayerCount(int original) { return TabList.TabHud.getTabPlayerLimit(); } @ModifyVariable(method = "renderPlayerlist", at = @At(value = "STORE"), ordinal = 0) private List<NetworkPlayerInfo> setLimit(List<NetworkPlayerInfo> value) { currentList = value.subList(0, Math.min(value.size(), TabList.TabHud.getTabPlayerLimit())); return currentList; } @Redirect(method = "renderPlayerlist", at = @At(value = "INVOKE", target = "Ljava/lang/Math;min(II)I", ordinal = 1)) private int noLimit(int a, int b) { if (!TabList.TabHud.fixWidth) return Math.min(a, b); return a; } @Inject(method = "renderPlayerlist", at = @At("TAIL")) private void alpha(int width, Scoreboard scoreboardIn, ScoreObjective scoreObjectiveIn, CallbackInfo ci) { GlStateManager.enableAlpha(); //somehow this fixes hud edit bug } }
15,376
Java
.java
264
49.965909
262
0.688143
Polyfrost/VanillaHUD
21
7
0
GPL-3.0
9/4/2024, 8:01:14 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
15,376
4,153,510
FoodItemAddRepository.java
F1rst-Unicorn_stocks/client-core/src/main/java/de/njsm/stocks/client/business/FoodItemAddRepository.java
/* * stocks is client-server program to manage a household's food stock * Copyright (C) 2019 The stocks developers * * This file is part of the stocks program suite. * * stocks is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * stocks is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ package de.njsm.stocks.client.business; import de.njsm.stocks.client.business.entities.*; import io.reactivex.rxjava3.core.Maybe; import java.time.Instant; import java.util.List; public interface FoodItemAddRepository { Maybe<FoodForItemCreation> getFood(Id<Food> food); Maybe<List<LocationForSelection>> getLocations(); Maybe<List<ScaledUnitForSelection>> getUnits(); Maybe<Instant> getMaxEatByOfPresentItemsOf(Id<Food> food); Maybe<Instant> getMaxEatByEverOf(Id<Food> food); Maybe<IdImpl<Location>> getLocationWithMostItemsOfType(Id<Food> food); Maybe<IdImpl<Location>> getLocationMostItemsHaveBeenAddedTo(Id<Food> food); Maybe<IdImpl<Location>> getAnyLocation(); }
1,528
Java
.java
35
40.857143
79
0.775152
F1rst-Unicorn/stocks
2
0
0
GPL-3.0
9/5/2024, 12:04:31 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,528
4,149,176
EqualityTest.java
aherbert_gdsc-core/gdsc-core/src/test/java/uk/ac/sussex/gdsc/core/utils/EqualityTest.java
/*- * #%L * Genome Damage and Stability Centre Core Package * * Contains core utilities for image analysis and is used by: * * GDSC ImageJ Plugins - Microscopy image analysis * * GDSC SMLM ImageJ Plugins - Single molecule localisation microscopy (SMLM) * %% * Copyright (C) 2011 - 2023 Alex Herbert * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ package uk.ac.sussex.gdsc.core.utils; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.logging.Logger; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import uk.ac.sussex.gdsc.test.utils.TestLogging.TestLevel; import uk.ac.sussex.gdsc.test.utils.functions.FormatSupplier; @SuppressWarnings({"javadoc"}) class EqualityTest { private static Logger logger; @BeforeAll public static void beforeAll() { logger = Logger.getLogger(EqualityTest.class.getName()); } @AfterAll public static void afterAll() { logger = null; } static final int MAX_ITER = 2000000; @Test void doubleCanSetAbsoluteError() { final DoubleEquality eq = new DoubleEquality(0, 0); Assertions.assertEquals(0, eq.getMaxRelativeError()); Assertions.assertEquals(0, eq.getMaxAbsoluteError()); Assertions.assertFalse(eq.almostEqualRelativeOrAbsolute(1, 1.001)); eq.setMaxAbsoluteError(0.01); Assertions.assertEquals(0, eq.getMaxRelativeError()); Assertions.assertEquals(0.01, eq.getMaxAbsoluteError()); Assertions.assertTrue(eq.almostEqualRelativeOrAbsolute(1, 1.001)); } @Test void doubleCanSetRelativeError() { final DoubleEquality eq = new DoubleEquality(0, 0); Assertions.assertEquals(0, eq.getMaxRelativeError()); Assertions.assertEquals(0, eq.getMaxAbsoluteError()); Assertions.assertFalse(eq.almostEqualRelativeOrAbsolute(1, 1.001)); eq.setMaxRelativeError(0.01); Assertions.assertEquals(0.01, eq.getMaxRelativeError()); Assertions.assertEquals(0, eq.getMaxAbsoluteError()); Assertions.assertTrue(eq.almostEqualRelativeOrAbsolute(1, 1.001)); } @Test void floatCanSetAbsoluteError() { final FloatEquality eq = new FloatEquality(0, 0); Assertions.assertEquals(0, eq.getMaxRelativeError()); Assertions.assertEquals(0, eq.getMaxAbsoluteError()); Assertions.assertFalse(eq.almostEqualRelativeOrAbsolute(1f, 1.001f)); eq.setMaxAbsoluteError(0.01f); Assertions.assertEquals(0f, eq.getMaxRelativeError()); Assertions.assertEquals(0.01f, eq.getMaxAbsoluteError()); Assertions.assertTrue(eq.almostEqualRelativeOrAbsolute(1f, 1.001f)); } @Test void floatCanSetRelativeError() { final FloatEquality eq = new FloatEquality(0, 0); Assertions.assertEquals(0, eq.getMaxRelativeError()); Assertions.assertEquals(0, eq.getMaxAbsoluteError()); Assertions.assertFalse(eq.almostEqualRelativeOrAbsolute(1f, 1.001f)); eq.setMaxRelativeError(0.01f); Assertions.assertEquals(0.01f, eq.getMaxRelativeError()); Assertions.assertEquals(0f, eq.getMaxAbsoluteError()); Assertions.assertTrue(eq.almostEqualRelativeOrAbsolute(1f, 1.001f)); } @Test void doubleCanComputeAlmostEqualComplement() { final double d1 = 1; final double d2 = Math.nextUp(d1); final double d3 = Math.nextUp(d2); Assertions.assertTrue(DoubleEquality.almostEqualComplement(d1, d1, 0L, 0)); Assertions.assertFalse(DoubleEquality.almostEqualComplement(d1, d2, 0L, 0)); Assertions.assertFalse(DoubleEquality.almostEqualComplement(d2, d1, 0L, 0)); Assertions.assertTrue(DoubleEquality.almostEqualComplement(d1, d2, 1L, 0)); Assertions.assertTrue(DoubleEquality.almostEqualComplement(d2, d1, 1L, 0)); Assertions.assertFalse(DoubleEquality.almostEqualComplement(d1, d3, 1L, 0)); Assertions.assertFalse(DoubleEquality.almostEqualComplement(d3, d1, 1L, 0)); Assertions.assertTrue(DoubleEquality.almostEqualComplement(d1, d3, 2L, 0)); Assertions.assertTrue(DoubleEquality.almostEqualComplement(d3, d1, 2L, 0)); Assertions.assertFalse(DoubleEquality.almostEqualComplement(d1, d3, 0L, 1e-16)); Assertions.assertFalse(DoubleEquality.almostEqualComplement(d3, d1, 0L, 1e-16)); Assertions.assertTrue(DoubleEquality.almostEqualComplement(d1, d3, 0L, 1e-15)); Assertions.assertTrue(DoubleEquality.almostEqualComplement(d3, d1, 0L, 1e-15)); } @Test void floatCanComputeAlmostEqualComplement() { final float d1 = 1; final float d2 = Math.nextUp(d1); final float d3 = Math.nextUp(d2); Assertions.assertTrue(FloatEquality.almostEqualComplement(d1, d1, 0, 0)); Assertions.assertFalse(FloatEquality.almostEqualComplement(d1, d2, 0, 0)); Assertions.assertFalse(FloatEquality.almostEqualComplement(d2, d1, 0, 0)); Assertions.assertTrue(FloatEquality.almostEqualComplement(d1, d2, 1, 0)); Assertions.assertTrue(FloatEquality.almostEqualComplement(d2, d1, 1, 0)); Assertions.assertFalse(FloatEquality.almostEqualComplement(d1, d3, 1, 0)); Assertions.assertFalse(FloatEquality.almostEqualComplement(d3, d1, 1, 0)); Assertions.assertTrue(FloatEquality.almostEqualComplement(d1, d3, 2, 0)); Assertions.assertTrue(FloatEquality.almostEqualComplement(d3, d1, 2, 0)); Assertions.assertFalse(FloatEquality.almostEqualComplement(d1, d3, 0, 1e-7f)); Assertions.assertFalse(FloatEquality.almostEqualComplement(d3, d1, 0, 1e-7f)); Assertions.assertTrue(FloatEquality.almostEqualComplement(d1, d3, 0, 1e-6f)); Assertions.assertTrue(FloatEquality.almostEqualComplement(d3, d1, 0, 1e-6f)); } @Test void doubleCanCompareComplement() { final double d1 = 1; final double d2 = Math.nextUp(d1); final double d3 = Math.nextUp(d2); Assertions.assertEquals(-1, DoubleEquality.compareComplement(d1, d2, 0)); Assertions.assertEquals(1, DoubleEquality.compareComplement(d2, d1, 0)); Assertions.assertEquals(0, DoubleEquality.compareComplement(d1, d2, 1)); Assertions.assertEquals(-1, DoubleEquality.compareComplement(d1, d3, 1)); Assertions.assertEquals(1, DoubleEquality.compareComplement(d3, d1, 1)); Assertions.assertEquals(0, DoubleEquality.compareComplement(d1, d3, 2)); } @Test void floatCanCompareComplement() { final float d1 = 1; final float d2 = Math.nextUp(d1); final float d3 = Math.nextUp(d2); Assertions.assertEquals(-1, FloatEquality.compareComplement(d1, d2, 0)); Assertions.assertEquals(1, FloatEquality.compareComplement(d2, d1, 0)); Assertions.assertEquals(0, FloatEquality.compareComplement(d1, d2, 1)); Assertions.assertEquals(-1, FloatEquality.compareComplement(d1, d3, 1)); Assertions.assertEquals(1, FloatEquality.compareComplement(d3, d1, 1)); Assertions.assertEquals(0, FloatEquality.compareComplement(d1, d3, 2)); } @Test void doubleRelativeErrorIsCorrectUntilUlpsIsSmall() { final int precision = new BigDecimal(Double.toString(Double.MAX_VALUE)).precision(); // TestLog.debug(logger,"Double max precision = %d", precision); for (int sig = 1; sig <= precision; sig++) { final BigDecimal error = new BigDecimal("1e-" + sig); final double e = error.doubleValue(); final double tolerance = e * 0.01; final BigDecimal one_m_error = BigDecimal.ONE.subtract(error); final BigDecimal one_one_m_error = BigDecimal.ONE.divide(one_m_error, sig * 10, RoundingMode.HALF_UP); // TestLog.debug(logger,"Error = %s %s %s", error, one_m_error, one_one_m_error); int same = 0; int total = 0; for (int leadingDigit = 1; leadingDigit <= 9; leadingDigit++) { for (int trailingDigit = 1; trailingDigit <= 9; trailingDigit++) { BigDecimal v1 = BigDecimal.valueOf(trailingDigit); v1 = v1.scaleByPowerOfTen(-(sig - 1)); final BigDecimal toAdd = BigDecimal.valueOf(leadingDigit); v1 = v1.add(toAdd); // Get number with a set relative error final BigDecimal v2low = v1.multiply(one_m_error); final BigDecimal v2high = v1.multiply(one_one_m_error); // bd1 = bd1.round(new MathContext(sig, RoundingMode.HALF_DOWN)); final double d = v1.doubleValue(); final double d1 = v2low.doubleValue(); final double d2 = v2high.doubleValue(); final long ulps1 = Double.doubleToLongBits(d) - Double.doubleToLongBits(d1); final long ulps2 = Double.doubleToLongBits(d2) - Double.doubleToLongBits(d); final double rel1 = DoubleEquality.relativeError(d, d1); final double rel2 = DoubleEquality.relativeError(d, d2); // TestLog.debug(logger,"%d %s < %s < %s = %d %d %g %g", sig, v2low, v1, v2high, ulps1, // ulps2, rel1, rel2); if (ulps1 > 100) { Assertions.assertEquals(e, rel1, tolerance); Assertions.assertEquals(e, rel2, tolerance); } if (ulps1 == ulps2) { same++; } total++; } } Assertions.assertTrue(same < total); } } @Test void floatRelativeErrorIsCorrectUntilUlpsIsSmall() { final int precision = new BigDecimal(Float.toString(Float.MAX_VALUE)).precision(); // TestLog.debug(logger,"Float max precision = %d", precision); for (int sig = 1; sig <= precision; sig++) { final BigDecimal error = new BigDecimal("1e-" + sig); final double e = error.doubleValue(); final double tolerance = e * 0.01; final BigDecimal one_m_error = BigDecimal.ONE.subtract(error); final BigDecimal one_one_m_error = BigDecimal.ONE.divide(one_m_error, sig * 10, RoundingMode.HALF_UP); // TestLog.debug(logger,"Error = %s %s %s", error, one_m_error, one_one_m_error); int same = 0; int total = 0; for (int leadingDigit = 1; leadingDigit <= 9; leadingDigit++) { for (int trailingDigit = 1; trailingDigit <= 9; trailingDigit++) { BigDecimal v1 = BigDecimal.valueOf(trailingDigit); v1 = v1.scaleByPowerOfTen(-(sig - 1)); final BigDecimal toAdd = BigDecimal.valueOf(leadingDigit); v1 = v1.add(toAdd); // Get number with a set relative error final BigDecimal v2low = v1.multiply(one_m_error); final BigDecimal v2high = v1.multiply(one_one_m_error); // bd1 = bd1.round(new MathContext(sig, RoundingMode.HALF_DOWN)); final float d = v1.floatValue(); final float d1 = v2low.floatValue(); final float d2 = v2high.floatValue(); final int ulps1 = Float.floatToIntBits(d) - Float.floatToIntBits(d1); final int ulps2 = Float.floatToIntBits(d2) - Float.floatToIntBits(d); final float rel1 = FloatEquality.relativeError(d, d1); final float rel2 = FloatEquality.relativeError(d, d2); // TestLog.debug(logger,"%d %s < %s < %s = %d %d %g %g", sig, v2low, v1, v2high, ulps1, // ulps2, rel1, rel2); if (ulps1 > 100) { Assertions.assertEquals(e, rel1, tolerance); Assertions.assertEquals(e, rel2, tolerance); } if (ulps1 == ulps2) { same++; } total++; } } Assertions.assertTrue(same < total); } } @Test void doubleCanComputeRelativeEpsilonFromSignificantBits() { Assertions.assertEquals(0, DoubleEquality.getRelativeEpsilon(0)); Assertions.assertEquals(0, DoubleEquality.getRelativeEpsilon(53)); for (int s = 1; s <= 52; s++) { final double e = Math.pow(2, -s); Assertions.assertEquals(e, DoubleEquality.getRelativeEpsilon(s)); } } @Test void floatCanComputeRelativeEpsilonFromSignificantBits() { Assertions.assertEquals(0, FloatEquality.getRelativeEpsilon(0)); Assertions.assertEquals(0, FloatEquality.getRelativeEpsilon(24)); for (int s = 1; s < 23; s++) { final double e = Math.pow(2, -s); Assertions.assertEquals(e, FloatEquality.getRelativeEpsilon(s)); } } @Test void doubleCanComputeEquality() { final double maxRelativeError = 1e-3f; final double maxAbsoluteError = 1e-16f; final DoubleEquality equality = new DoubleEquality(maxRelativeError, maxAbsoluteError); for (int i = 0; i < 100; i++) { final double f = i / 10000.0; final double f2 = f * (1.00f + maxRelativeError - 1e-3f); final double f3 = f * (1.0f + 2.0f * maxRelativeError); Assertions.assertTrue(equality.almostEqualRelativeOrAbsolute(f, f), () -> String.format("not equal %f", f)); Assertions.assertTrue(equality.almostEqualRelativeOrAbsolute(f, f2), () -> String.format("not equal %f", f)); if (i > 0) { Assertions.assertFalse(equality.almostEqualRelativeOrAbsolute(f, f3), () -> String.format("equal %f", f)); } } } @Test void floatCanComputeEquality() { final float maxRelativeError = 1e-3f; final float maxAbsoluteError = 1e-16f; final FloatEquality equality = new FloatEquality(maxRelativeError, maxAbsoluteError); for (int i = 0; i < 100; i++) { final float f = (float) (i / 10000.0); final float f2 = f * (1.00f + maxRelativeError - 1e-3f); final float f3 = f * (1.0f + 2.0f * maxRelativeError); Assertions.assertTrue(equality.almostEqualRelativeOrAbsolute(f, f), () -> String.format("not equal %f", f)); Assertions.assertTrue(equality.almostEqualRelativeOrAbsolute(f, f2), () -> String.format("not equal %f", f)); if (i > 0) { Assertions.assertFalse(equality.almostEqualRelativeOrAbsolute(f, f3), () -> String.format("equal %f", f)); } } } @Test void canComputeComplement() { // computeComplement(100f); // computeComplement(10f); // computeComplement(1f); // computeComplement(1e-1f); // computeComplement(1e-2f); // computeComplement(1e-3f); // computeComplement(1e-4f); // computeComplement(1e-5f); // computeComplement(1e-6f); // computeComplement(1e-7f); // computeComplement(1e-8f); // computeComplement(1e-9f); // computeComplement(1e-10f); // computeComplement(1e-11f); // computeComplement(1e-12f); // computeComplement(1e-13f); // computeComplement(1e-14f); // computeComplement(1e-15f); // computeComplement(1e-16f); // computeComplement(1e-26f); // computeComplement(1e-36f); // Simple tests Assertions.assertEquals(1, DoubleEquality.complement(0, Double.MIN_VALUE)); Assertions.assertEquals(1, DoubleEquality.complement(0, -Double.MIN_VALUE)); Assertions.assertEquals(2, DoubleEquality.complement(-Double.MIN_VALUE, Double.MIN_VALUE)); Assertions.assertEquals(2, DoubleEquality.signedComplement(Double.MIN_VALUE, -Double.MIN_VALUE)); Assertions.assertEquals(-2, DoubleEquality.signedComplement(-Double.MIN_VALUE, Double.MIN_VALUE)); Assertions.assertEquals(Long.MAX_VALUE, DoubleEquality.signedComplement(Double.MAX_VALUE, -Double.MAX_VALUE)); Assertions.assertEquals(Long.MIN_VALUE, DoubleEquality.signedComplement(-Double.MAX_VALUE, Double.MAX_VALUE)); Assertions.assertEquals(1, FloatEquality.complement(0, Float.MIN_VALUE)); Assertions.assertEquals(1, FloatEquality.complement(0, -Float.MIN_VALUE)); Assertions.assertEquals(2, FloatEquality.complement(-Float.MIN_VALUE, Float.MIN_VALUE)); Assertions.assertEquals(2, FloatEquality.signedComplement(Float.MIN_VALUE, -Float.MIN_VALUE)); Assertions.assertEquals(-2, FloatEquality.signedComplement(-Float.MIN_VALUE, Float.MIN_VALUE)); Assertions.assertEquals(Integer.MAX_VALUE, FloatEquality.signedComplement(Float.MAX_VALUE, -Float.MAX_VALUE)); Assertions.assertEquals(Integer.MIN_VALUE, FloatEquality.signedComplement(-Float.MAX_VALUE, Float.MAX_VALUE)); // Check the complement is correct around a change of sign test(-Double.MAX_VALUE, Double.MAX_VALUE); test(-1e10, 1e40); test(-1e2, 1e2); test(-10, 10); test(-1, 1); test(-1e-1, 1e-1); test(-1e-2, 1e-2); test(1e-2, 1e-4); test(1e-2, 2e-2); test(1.0001, 1.0002); test(-Float.MAX_VALUE, Float.MAX_VALUE); test(-1e10f, 1e20f); test(-1e2f, 1e2f); test(-10f, 10f); test(-1f, 1f); test(-1e-1f, 1e-1f); test(-1e-2f, 1e-2f); test(1e-2f, 1e-4f); test(1e-2f, 2e-2f); test(1.0001f, 1.0002f); } private static void test(double lower, double upper) { if (lower > upper) { final double tmp = lower; lower = upper; upper = tmp; } final long h = DoubleEquality.complement(0, upper); final long l = DoubleEquality.complement(0, lower); long expected = (lower > 0) ? h - l : h + l; if (expected < 0) { expected = Long.MAX_VALUE; } else { final long c = DoubleEquality.signedComplement(lower, upper); Assertions.assertTrue(c < 0); Assertions.assertEquals(expected, -c); Assertions.assertEquals(expected, DoubleEquality.signedComplement(upper, lower)); } // log("%g - %g = %d", upper, lower, d); Assertions.assertEquals(expected, DoubleEquality.complement(lower, upper)); } private static void test(float lower, float upper) { if (lower > upper) { final float tmp = lower; lower = upper; upper = tmp; } final int h = FloatEquality.complement(0, upper); final int l = FloatEquality.complement(0, lower); int expected = (lower > 0) ? h - l : h + l; if (expected < 0) { expected = Integer.MAX_VALUE; } // log("%g - %g = %d", upper, lower, d); Assertions.assertEquals(expected, FloatEquality.complement(lower, upper)); } /** * Used to check what the int difference between float actually is. * * @param value the value */ @SuppressWarnings("unused") private static void computeComplement(float value) { final float f3 = value + value * 1e-2f; final float f4 = value - value * 1e-2f; logger.log(TestLevel.TEST_INFO, FormatSupplier.getSupplier("%g -> %g = %d : %d (%g : %g)", value, f3, FloatEquality.complement(f3, value), DoubleEquality.complement(f3, value), FloatEquality.relativeError(value, f3), DoubleEquality.relativeError(value, f3))); logger.log(TestLevel.TEST_INFO, FormatSupplier.getSupplier("%g -> %g = %d : %d (%g : %g)", value, f4, FloatEquality.complement(f4, value), DoubleEquality.complement(f4, value), FloatEquality.relativeError(value, f4), DoubleEquality.relativeError(value, f4))); } }
19,200
Java
.java
423
39.605201
99
0.69372
aherbert/gdsc-core
2
1
0
GPL-3.0
9/5/2024, 12:04:22 AM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
19,200
3,777,705
FreeMarkerSupport.java
delin10_EasyWork/easywork-template-engine/src/main/java/nil/ed/easywork/template/support/FreeMarkerSupport.java
package nil.ed.easywork.template.support; import freemarker.core.Environment; import freemarker.template.DefaultListAdapter; import freemarker.template.DefaultMapAdapter; import freemarker.template.TemplateHashModel; import nil.ed.easywork.template.FreeMarkerTemplateEngineAdapter; import org.apache.commons.lang3.reflect.FieldUtils; import java.lang.reflect.Field; import java.util.List; import java.util.regex.Pattern; /** * @author lidelin. */ public class FreeMarkerSupport { private static final Field ENV_ROOT_DATA_MODEL_FIELD; private static final Pattern PLACE_HOLDER_PATTERN = Pattern.compile("\\$\\{[\\s\\S]*?}"); public static boolean hasPlaceHolder(String v) { return PLACE_HOLDER_PATTERN.matcher(v).find(); } static { ENV_ROOT_DATA_MODEL_FIELD = FieldUtils.getDeclaredField(Environment.class, "rootDataModel", true); } public static String renderPlaceHolder(String v, TemplateHashModel model) { return FreeMarkerTemplateEngineAdapter.INSTANCE.process(v, model); } @SuppressWarnings("unchecked") public static <T> List<T> getList(String name, Environment env) { try { return (List<T>) ((DefaultListAdapter) env.getDataModel().get(name)).getWrappedObject(); } catch (Exception e) { throw new RuntimeException(e); } } public static Object getRawContext(Environment env) { try { TemplateHashModel model = (TemplateHashModel) ENV_ROOT_DATA_MODEL_FIELD.get(env); if (model instanceof DefaultMapAdapter) { return ((DefaultMapAdapter) model).getWrappedObject(); } throw new IllegalArgumentException("Unsupported Type: " + model.getClass()); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }
1,858
Java
.java
45
35
106
0.710161
delin10/EasyWork
3
1
0
GPL-3.0
9/4/2024, 11:42:06 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,858
4,520,184
TikzStructureGenerator.java
UoY-RoboStar_robocert-textual/robostar.robocert.textual/src/robostar/robocert/textual/generator/tikz/util/TikzStructureGenerator.java
/* * Copyright (c) 2022 University of York and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0. * * SPDX-License-Identifier: EPL-2.0 */ package robostar.robocert.textual.generator.tikz.util; /** * Handles generation of pieces of low-level TikZ code. * * @author Matt Windsor */ public class TikzStructureGenerator { /** * Emits TikZ code for a node. * * @param style styling information for the node. * @param name name of the node. * @param content content for the label of the node. * @return a string representing the TikZ node code. */ public String node(String style, String name, String content) { return command("node").optional(style).node(name).argument(content).render(); } /** * Emits TikZ code for a coordinate. * * @param name name of the coordinate. * @return a string representing the TikZ coordinate code. */ public String coordinate(String name) { return command("coordinate").node(name).render(); } /** * Opens a builder for creating a command. * * @param name name of the command. * @return a command builder. */ public Command command(String name) { return new Command(name); } /** * Opens a builder for creating a path. * * @param style style of the path. * @return a path builder. */ public Path draw(String style) { return new Path(this, style); } }
1,541
Java
.java
55
24.763636
81
0.69527
UoY-RoboStar/robocert-textual
2
0
55
EPL-2.0
9/5/2024, 12:15:50 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,541
1,666,841
ServerConfigurationUtils.java
exoplatform_mobile-android/app/src/main/java/org/exoplatform/utils/ServerConfigurationUtils.java
/* * Copyright (C) 2003-2014 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Created by The eXo Platform SAS * Author : eXoPlatform * [email protected] * Jul 12, 2011 */ package org.exoplatform.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import org.xmlpull.v1.XmlSerializer; import org.exoplatform.model.ExoAccount; import android.content.Context; import android.os.Environment; import android.util.Xml; /** * Help to deal with writing and reading from xml config file */ public class ServerConfigurationUtils { public static String version; private static final String TAG = ServerConfigurationUtils.class.getName(); public ServerConfigurationUtils(Context context) { } /** * Retrieve server list from XML config file * * @param context * @param fileName * @return a list of servers, or an empty list, but never null */ public static ArrayList<ExoAccount> getServerListFromFile(Context context, String fileName) { Log.i(TAG, "getServerListFromFile: " + fileName); ArrayList<ExoAccount> arrServerList = new ArrayList<ExoAccount>(); FileInputStream fis = null; try { fis = context.openFileInput(fileName); DocumentBuilderFactory doc_build_fact = DocumentBuilderFactory.newInstance(); DocumentBuilder doc_builder = doc_build_fact.newDocumentBuilder(); Document obj_doc = doc_builder.parse(fis); if (null != obj_doc) { org.w3c.dom.Element feed = obj_doc.getDocumentElement(); NodeList obj_nod_list = feed.getElementsByTagName("server"); for (int i = 0; i < obj_nod_list.getLength(); i++) { Node itemNode = obj_nod_list.item(i); if (itemNode.getNodeType() == Node.ELEMENT_NODE) { Element itemElement = (Element) itemNode; ExoAccount serverObj = new ExoAccount(); serverObj.accountName = itemElement.getAttribute("name"); serverObj.serverUrl = itemElement.getAttribute(ExoConstants.EXO_URL_SERVER); serverObj.username = itemElement.getAttribute(ExoConstants.EXO_URL_USERNAME); try { serverObj.password = SimpleCrypto.decrypt(ExoConstants.EXO_MASTER_PASSWORD, itemElement.getAttribute("password")); } catch (Exception ee) { // Catch runtime exception throw while decrypt password Log.e(TAG, "Could not decrypt password: " + ee.getLocalizedMessage()); Log.w(TAG, "Leaving password attribute empty"); serverObj.password = ""; } serverObj.isRememberEnabled = Boolean.parseBoolean(itemElement.getAttribute(ExoConstants.EXO_REMEMBER_ME)); serverObj.isAutoLoginEnabled = Boolean.parseBoolean(itemElement.getAttribute(ExoConstants.EXO_AUTOLOGIN)); serverObj.userFullName = itemElement.getAttribute(ExoConstants.EXO_USER_FULLNAME); try { String logTime = itemElement.getAttribute(ExoConstants.EXO_LAST_LOGIN); if (logTime != null) serverObj.lastLoginDate = Long.parseLong(logTime); else { serverObj.lastLoginDate = -1; Log.i(TAG, "Last login date unknown"); } } catch (NumberFormatException e) { serverObj.lastLoginDate = -1; Log.i(TAG, "Last login date unknown"); } serverObj.avatarUrl = itemElement.getAttribute(ExoConstants.EXO_URL_AVATAR); arrServerList.add(serverObj); } } } } catch (FileNotFoundException e) { Log.i(TAG, "File not found"); return arrServerList; } catch (IOException e) { // if (Config.GD_ERROR_LOGS_ENABLED) Log.e(TAG, "getServerListWithFileName - " + e.getLocalizedMessage()); return arrServerList; } catch (ParserConfigurationException e) { // if (Config.GD_ERROR_LOGS_ENABLED) Log.e(TAG, "getServerListWithFileName - " + e.getLocalizedMessage()); return arrServerList; } catch (SAXException e) { // if (Config.GD_ERROR_LOGS_ENABLED) Log.e(TAG, "getServerListWithFileName - " + e.getLocalizedMessage()); return arrServerList; } catch (Exception e) { Log.e(TAG, "getServerListWithFileName - " + e.getLocalizedMessage()); return arrServerList; } finally { if (fis != null) try { fis.close(); } catch (IOException e) { Log.d(TAG, Log.getStackTraceString(e)); } } return arrServerList; } /** * Check whether new config file for app exists * * @param context * @return */ public static boolean newAppConfigExists(Context context) { return context.getFileStreamPath(ExoConstants.EXO_SERVER_SETTING_FILE).exists(); } /** * Check if previous config file exists * * @param context * @return */ public static String checkPreviousAppConfig(Context context) { /* check external storage available */ String state = Environment.getExternalStorageState(); File oldConfig; if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) || Environment.MEDIA_MOUNTED.equals(state)) { oldConfig = new File(Environment.getExternalStorageDirectory().getPath() + "/eXo/" + ExoConstants.EXO_OLD_SERVER_SETTING_FILE); } else { oldConfig = new File(context.getDir("eXo", Context.MODE_WORLD_READABLE).getPath() + "/" + ExoConstants.EXO_OLD_SERVER_SETTING_FILE); } if (oldConfig.exists()) return oldConfig.getAbsolutePath(); return null; } /** * Retrieve server list from XML config file * * @param fileName * @return */ public static ArrayList<ExoAccount> getServerListFromOldConfigFile(String fileName) { Log.i(TAG, "getServerListFromOldConfigFile: " + fileName); ArrayList<ExoAccount> arrServerList = new ArrayList<ExoAccount>(); File file = new File(fileName); try { FileInputStream fis = new FileInputStream(file); DocumentBuilderFactory doc_build_fact = DocumentBuilderFactory.newInstance(); DocumentBuilder doc_builder = doc_build_fact.newDocumentBuilder(); Document obj_doc = doc_builder.parse(fis); if (null != obj_doc) { org.w3c.dom.Element feed = obj_doc.getDocumentElement(); NodeList obj_nod_list = feed.getElementsByTagName("server"); for (int i = 0; i < obj_nod_list.getLength(); i++) { Node itemNode = obj_nod_list.item(i); if (itemNode.getNodeType() == Node.ELEMENT_NODE) { Element itemElement = (Element) itemNode; ExoAccount serverObj = new ExoAccount(); serverObj.accountName = itemElement.getAttribute("name"); serverObj.serverUrl = itemElement.getAttribute("serverURL"); Log.i(TAG, "server: " + serverObj.accountName + " - url: " + serverObj.serverUrl); if (serverObj.serverUrl != null) if (!serverObj.serverUrl.equals("")) arrServerList.add(serverObj); } } } fis.close(); if (file.delete()) Log.i(TAG, "delete old config file"); else Log.e("Error", "Can not delete old config file: " + fileName); } catch (FileNotFoundException e) { Log.i(TAG, "File not found"); return null; } catch (IOException e) { // if (Config.GD_ERROR_LOGS_ENABLED) Log.e("IOException", "getServerListFromOldConfigFile"); } catch (ParserConfigurationException e) { // if (Config.GD_ERROR_LOGS_ENABLED) Log.e("ParserConfigurationException", "getServerListFromOldConfigFile"); } catch (SAXException e) { // if (Config.GD_ERROR_LOGS_ENABLED) Log.e("SAXException", "getServerListFromOldConfigFile"); } catch (Exception e) { Log.e("Exception", "getServerListFromOldConfigFile - decryption exception : " + e.getLocalizedMessage()); } return arrServerList; } /** * Create XML config file from server list * * @param context * @param objList * @param fileName * @param appVersion * @return */ public static boolean generateXmlFileWithServerList(Context context, ArrayList<ExoAccount> objList, String fileName, String appVersion) { Log.i(TAG, "generateXmlFileWithServerList: " + fileName); try { FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE); // we create a XmlSerializer in order to write xml data XmlSerializer serializer = Xml.newSerializer(); // we set the FileOutputStream as output for the serializer, using // UTF-8 encoding serializer.setOutput(fos, "UTF-8"); // Write <?xml declaration with encoding (if encoding not null) and // standalone flag (if standalone not null) serializer.startDocument(null, Boolean.TRUE); // set indentation option // serializer.setFeature(name, // state)("http://xmlpull.org/v1/doc/features.htmlindent-output", // true); // start a tag called "root" serializer.startTag(null, "xml").startTag(null, "version"); serializer.attribute(null, "number", appVersion); serializer.endTag(null, "version"); // } serializer.startTag(null, "Servers"); // i indent code just to have a view similar to xml-tree for (int i = 0; i < objList.size(); i++) { ExoAccount serverObj = objList.get(i); Log.d(TAG, "Writing account " + serverObj); serializer.startTag(null, "server"); serializer.attribute(null, "name", serverObj.accountName); serializer.attribute(null, ExoConstants.EXO_URL_SERVER, serverObj.serverUrl); serializer.attribute(null, ExoConstants.EXO_URL_USERNAME, serverObj.username); /* encrypt password */ try { serializer.attribute(null, "password", SimpleCrypto.encrypt(ExoConstants.EXO_MASTER_PASSWORD, serverObj.password)); } catch (Exception e) { Log.e(TAG, "Error while encrypting password: " + e.getLocalizedMessage()); Log.w(TAG, "Writing password in clear"); serializer.attribute(null, "password", serverObj.password); } serializer.attribute(null, ExoConstants.EXO_REMEMBER_ME, String.valueOf(serverObj.isRememberEnabled)); serializer.attribute(null, ExoConstants.EXO_AUTOLOGIN, String.valueOf(serverObj.isAutoLoginEnabled)); serializer.attribute(null, ExoConstants.EXO_USER_FULLNAME, serverObj.userFullName); serializer.attribute(null, ExoConstants.EXO_LAST_LOGIN, String.valueOf(serverObj.lastLoginDate)); serializer.attribute(null, ExoConstants.EXO_URL_AVATAR, serverObj.avatarUrl); serializer.endTag(null, "server"); } serializer.endTag(null, "Servers"); serializer.endTag(null, "xml"); serializer.endDocument(); // write xml data into the FileOutputStream serializer.flush(); // finally we close the file stream fos.close(); return true; } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } } }
12,473
Java
.java
291
35.635739
128
0.671389
exoplatform/mobile-android
15
31
1
LGPL-3.0
9/4/2024, 8:12:36 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
12,473
5,000,093
ICommentProvider.java
theArchonius_mervin/plugins/at.bitandart.zoubek.mervin/src/at/bitandart/zoubek/mervin/swt/comments/data/ICommentProvider.java
/******************************************************************************* * Copyright (c) 2016, 2017 Florian Zoubek. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Florian Zoubek - initial API and implementation *******************************************************************************/ package at.bitandart.zoubek.mervin.swt.comments.data; import java.util.List; import at.bitandart.zoubek.mervin.swt.comments.CommentListViewer; /** * Base interface for classes that provide comments and comment groups for * comment widgets like {@link CommentListViewer}. * * @author Florian Zoubek * */ public interface ICommentProvider { /** * returns the list of top-level comment groups * * @return an ordered list of comment groups containing the actual comments. * Comments must always reside in a group and a column. */ public List<ICommentGroup> getCommentGroups(Object input); /** * returns the list of visible comment columns * * @return an ordered list of comment columns containing the actual comments * to view. Comments must always reside in a group and a column. */ public List<ICommentColumn> getVisibleCommentColumns(Object input); /** * returns the list of all comment columns * * @return an ordered list of all comment columns used by the column * overview. */ public List<ICommentColumn> getAllCommentColumns(Object input); /** * returns the comments for a given group. * * @param group * the group to retrieve the comments for. * @param column * the column to retrieve the comments for. * @return the comments of the group in the given column */ public List<IComment> getComments(Object input, ICommentGroup group, ICommentColumn column); }
2,007
Java
.java
53
35.320755
93
0.682939
theArchonius/mervin
1
1
0
EPL-1.0
9/5/2024, 12:38:41 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
2,007
5,086,190
NetworkHandler.java
CraftedCart_Modular-FluxFields/src/main/java/io/github/craftedcart/modularfluxfields/handler/NetworkHandler.java
package io.github.craftedcart.modularfluxfields.handler; import io.github.craftedcart.modularfluxfields.network.*; import io.github.craftedcart.modularfluxfields.reference.Reference; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.relauncher.Side; /** * Created by CraftedCart on 23/11/2015 (DD/MM/YYYY) */ public class NetworkHandler { public static SimpleNetworkWrapper network; public static void init() { network = NetworkRegistry.INSTANCE.newSimpleChannel(Reference.MOD_ID); network.registerMessage(MessageFFProjectorGuiSaveSizing.Handler.class, MessageFFProjectorGuiSaveSizing.class, 0, Side.SERVER); network.registerMessage(MessageRequestOpenGui.Handler.class, MessageRequestOpenGui.class, 1, Side.SERVER); network.registerMessage(MessageFFProjectorGuiSaveSecurity.Handler.class, MessageFFProjectorGuiSaveSecurity.class, 2, Side.SERVER); network.registerMessage(MessageFFProjectorSendPowerStatsToClient.Handler.class, MessageFFProjectorSendPowerStatsToClient.class, 3, Side.CLIENT); network.registerMessage(MessageRequestPowerStats.Handler.class, MessageRequestPowerStats.class, 4, Side.SERVER); network.registerMessage(MessageSetInputSide.Handler.class, MessageSetInputSide.class, 5, Side.SERVER); network.registerMessage(MessageSetOutputSide.Handler.class, MessageSetOutputSide.class, 6, Side.SERVER); } }
1,520
Java
.java
22
64.318182
152
0.823845
CraftedCart/Modular-FluxFields
1
0
1
GPL-2.0
9/5/2024, 12:40:46 AM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
1,520
4,398,939
HTLog.java
httpobjects-org_httpobjects/core/src/main/java/org/httpobjects/impl/HTLog.java
package org.httpobjects.impl; public class HTLog { private final String context; public HTLog(String context) { this.context = context; } public HTLog(Object context) { this(context.getClass().getSimpleName()); } public void debug(String m){ logAtLevel("debug", m); } public void error(String m){ logAtLevel("error", m); } public void error(String m, Throwable t){ t.printStackTrace(); logAtLevel("error", m); } public void info(String m){ logAtLevel("info", m); } public void log(String m){ info(m); } public void logAtLevel(String level, String m){ System.out.println("[" + context + "/" + level + "] " + m); } public void logThrowable(Throwable t, String m){ t.printStackTrace(); log(t.getClass().getSimpleName() + " " + m); } }
902
Java
.java
33
21.181818
67
0.594438
httpobjects-org/httpobjects
2
0
0
GPL-2.0
9/5/2024, 12:11:47 AM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
902
894,425
SortSpec.java
dentsusoken_iPLAss/iplass-core/src/main/java/org/iplass/mtp/entity/query/SortSpec.java
/* * Copyright (C) 2011 DENTSU SOKEN INC. All Rights Reserved. * * Unless you have purchased a commercial license, * the following license terms apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.iplass.mtp.entity.query; import org.iplass.mtp.entity.query.value.ValueExpression; import org.iplass.mtp.entity.query.value.primary.EntityField; /** * ORDER BYのソート仕様を表す。 * * @author K.Higuchi * */ public class SortSpec implements ASTNode { //TODO v3.2でAbstractSortSpec継承に private static final long serialVersionUID = -8115669253085961836L; public enum SortType { ASC,DESC; } public enum NullOrderingSpec { FIRST,LAST } private ValueExpression sortKey; private SortType type; private NullOrderingSpec nullOrderingSpec; public SortSpec() { } public SortSpec(String sortKeyField, SortType type) { super(); this.sortKey = new EntityField(sortKeyField); this.type = type; } public SortSpec(ValueExpression sortKey, SortType type) { super(); this.sortKey = sortKey; this.type = type; } public SortSpec(ValueExpression sortKey, SortType type, NullOrderingSpec nullOrderingSpec) { super(); this.sortKey = sortKey; this.type = type; this.nullOrderingSpec = nullOrderingSpec; } public ASTNode accept(ASTTransformer transformer) { return transformer.visit(this); } public void accept(QueryVisitor visitor) { if (visitor.visit(this)) { sortKey.accept(visitor); } } public ValueExpression getSortKey() { return sortKey; } public void setSortKey(ValueExpression sortKey) { this.sortKey = sortKey; } public SortType getType() { return type; } public void setType(SortType type) { this.type = type; } public NullOrderingSpec getNullOrderingSpec() { return nullOrderingSpec; } public void setNullOrderingSpec(NullOrderingSpec nullOrderingSpec) { this.nullOrderingSpec = nullOrderingSpec; } public SortSpec nulls(NullOrderingSpec nullOrderingSpec) { this.nullOrderingSpec = nullOrderingSpec; return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(sortKey); if (type != null) { sb.append(" "); sb.append(type); } if (nullOrderingSpec != null) { sb.append(" NULLS "); sb.append(nullOrderingSpec); } return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((nullOrderingSpec == null) ? 0 : nullOrderingSpec.hashCode()); result = prime * result + ((sortKey == null) ? 0 : sortKey.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SortSpec other = (SortSpec) obj; if (nullOrderingSpec != other.nullOrderingSpec) return false; if (sortKey == null) { if (other.sortKey != null) return false; } else if (!sortKey.equals(other.sortKey)) return false; if (type != other.type) return false; return true; } }
3,947
Java
.java
134
25.246269
94
0.712638
dentsusoken/iPLAss
66
25
61
AGPL-3.0
9/4/2024, 7:09:48 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
3,919
3,154,456
Injector.java
vicboma1_Injector/source/src/main/java/core/Injector.java
package core; import core.mapping.InjectionMapping; /** * Created with IntelliJ IDEA. * User: vicboma * Date: 14/02/14 * Time: 18:39 * To change this template use File | Settings | File Templates. */ public interface Injector { void injectInto(Object instance) throws Exception ; <T> T getInstance(Class<? extends T> modelClass) throws Exception ; <T> Boolean hasMapping(Class<? extends T> modelClass); Injector parent(); void parent(Injector parent); void dispose() throws Exception; <T> T unmap(Class<T> modelClass) throws Exception; Injector createChild() throws Exception; InjectionMapping map(); }
656
Java
.java
21
27.714286
71
0.732372
vicboma1/Injector
4
0
0
GPL-2.0
9/4/2024, 11:01:36 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
656
2,782,097
ExtrasManager.java
matthewjpyates_werewolfchat/werewolf-chat/app/src/main/java/com/werewolfchat/startup/ExtrasManager.java
package com.werewolfchat.startup; import android.content.Context; import android.content.Intent; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; import com.werewolfchat.startup.ntru.encrypt.EncryptionKeyPair; import com.werewolfchat.startup.ntru.encrypt.EncryptionPublicKey; import com.werewolfchat.startup.ntru.encrypt.NtruEncrypt; import java.util.ArrayList; import static com.werewolfchat.startup.Utility.ENCRYPTION_PARAMS; import static com.werewolfchat.startup.Utility.dumb_debugging; public class ExtrasManager { public void copyOverExtrasAndChangeClassToPrepareToStartNewActivity(Context context, Class classToStart) { this.setIntent(this.copyExtrasToNewIntent(new Intent(context, classToStart))); } public void setExtraIfInputIsNotNull(String extraFieldToSet, Object valueToSet) { if(valueToSet == null) return; switch (extraFieldToSet) { case PRIVATE_SERVER_URL_EXTRA: setPrivateServerURL((String) valueToSet); break; case DIST_END_ID_EXTRA: setDestEndID((String) valueToSet); break; case DIST_END_KEY_EXTRA: setDestKey((byte[]) valueToSet); break; case PUBLIC_KEY_BYTE_ARRAY_EXTRA: setPubKey((byte[]) valueToSet); break; case PRIVATE_KEY_BYTE_ARRAY_EXTRA: setPrivKey((byte[]) valueToSet); break; case CHAT_ID_EXTRA: setChatID((String) valueToSet); break; case FIREBASE_UID_EXTRA: setFirebaseUID((String) valueToSet); break; case FIREBASE_EMAIL_EXTRA: setFirebaseEmail((String) valueToSet); break; case PROXY_INFO: if(((String[]) valueToSet).length == 3) setProxyInfo((String[]) valueToSet); break; case TIME_OUT_EXTRA: if((Integer) valueToSet > 0) setTimeOut((Integer) valueToSet); break; case USING_SELF_SIGNED_TLS_CERT_EXTRA: setUsingSelfSignedTLSCert((boolean) valueToSet); break; case TOKEN_STR: setTokenString((String) valueToSet); break; case AUTO_PUB_STR: setAutoPub((boolean) valueToSet); } } public void setAutoPub(boolean input) { this.autoPub = input; this.intent.putExtra(AUTO_PUB_STR, input); } public Intent getIntent() { return intent; } public void setUsingSelfSignedTLSCert(boolean input) { this.intent.putExtra(USING_SELF_SIGNED_TLS_CERT_EXTRA, input); this.usingselfSignedCert = input; } public void setIntent(Intent intent) { this.intent = intent; } public int getProxyPort() { if(this.hasProxyPort) return proxyPort; return -1; } public void setProxyInfo(String[] input) { this.proxyPort = Integer.parseInt(input[1]); this.proxy_info = input; this.hasProxyPort = true; this.intent.putExtra(PROXY_INFO, input); } public int getTimeOut() { if(hasTimeOut) return timeOut; timeOut = 2000; hasTimeOut = true; return timeOut; } public void setTimeOut(int timeOut) { this.timeOut = timeOut; this.hasTimeOut = true; this.intent.putExtra(TIME_OUT_EXTRA, timeOut); } public ArrayList<String> getExtraStrings() { return extraStrings; } public void setExtraStrings(ArrayList<String> extraStrings) { this.extraStrings = extraStrings; } public String getPrivateServerURL() { return privateServerURL; } public void setPrivateServerURL(String privateServerURL) { this.privateServerURL = privateServerURL; this.hasPrivateServerURL = true; this.intent.putExtra(PRIVATE_SERVER_URL_EXTRA, privateServerURL); } public String getChatID() { return chatID; } public void setChatID(String chatID) { this.chatID = chatID; this.hasChatID = true; this.intent.putExtra(CHAT_ID_EXTRA, chatID); } public String getDestEndID() { return destEndID; } public void setDestEndID(String destEndID) { this.destEndID = destEndID; this.hasDistEndID = true; this.intent.putExtra(DIST_END_ID_EXTRA, destEndID); } public String getFirebaseUID() { return firebaseUID; } public void setFirebaseUID(String firebaseUID) { this.firebaseUID = firebaseUID; this.hasFirebaseUID = true; this.intent.putExtra(FIREBASE_UID_EXTRA, firebaseUID); } public String getFirebaseEmail() { return firebaseEmail; } public void setFirebaseEmail(String firebaseEmail) { this.firebaseEmail = firebaseEmail; this.hasFirebaseEmail = true; this.intent.putExtra(FIREBASE_EMAIL_EXTRA, firebaseEmail); } public byte[] getPubKey() { return pubKey; } public void setPubKey(byte[] pubKey) { this.pubKey = pubKey; this.hasPublicKey = true; this.intent.putExtra(PUBLIC_KEY_BYTE_ARRAY_EXTRA, pubKey); } public byte[] getPrivKey() { return privKey; } public String getTokenString() { return this.tokenString; } public void loadKeyPair(EncryptionKeyPair ekp) { this.setPubKey(ekp.getPublic().getEncoded()); this.setPrivKey(ekp.getPrivate().getEncoded()); } public EncryptionKeyPair getKeyPair() { return new EncryptionKeyPair(this.getPubKey(), this.getPrivKey()); } public void setPrivKey(byte[] privKey) { this.privKey = privKey; this.hasPrivateKey = true; this.intent.putExtra(PRIVATE_KEY_BYTE_ARRAY_EXTRA, privKey); } public byte[] getDestKey() { return destKey; } public EncryptionPublicKey getDestKeyAsEncryptionPublicKey() { return new EncryptionPublicKey(this.getDestKey()); } public void setDestKey(byte[] destKey) { this.destKey = destKey; this.hasDistEndKey = true; this.intent.putExtra(DIST_END_KEY_EXTRA, destKey); } public TokenManager makeNewTokenManager() { return new TokenManager(this.getChatID(), this.getPrivateServerURL(), this.getKeyPair(), new NtruEncrypt(ENCRYPTION_PARAMS)); } public TokenManager makeNewTokenManager(String newStr) { TokenManager tm = new TokenManager(this.getChatID(), this.getPrivateServerURL(), this.getKeyPair(), new NtruEncrypt(ENCRYPTION_PARAMS)); tm.setTokenString(newStr); return tm; } public void setTokenString(String inputTokenStr) { this.tokenString = inputTokenStr; this.hasTokenString = true; this.intent.putExtra(TOKEN_STR, tokenString); } public Intent intent; public int proxyPort, timeOut; public ArrayList<String> extraStrings; public String privateServerURL, chatID, destEndID, firebaseUID, firebaseEmail, tokenString; public byte[] pubKey, privKey, destKey; public static final String PRIVATE_SERVER_URL_EXTRA = "private_server_url"; public static final String DIST_END_ID_EXTRA = "dest_end_id"; public static final String DIST_END_KEY_EXTRA = "dest_end_key"; public static final String PUBLIC_KEY_BYTE_ARRAY_EXTRA = "enckp_pub"; public static final String PRIVATE_KEY_BYTE_ARRAY_EXTRA = "enckp_priv"; public static final String CHAT_ID_EXTRA = "chat_id"; public static final String FIREBASE_UID_EXTRA = "firebase_uid"; public static final String FIREBASE_EMAIL_EXTRA = "firebase_email"; public static final String PROXY_INFO = "proxy_info"; public static final String TIME_OUT_EXTRA = "time_out"; public static final String USING_SELF_SIGNED_TLS_CERT_EXTRA = "use_self_signed_cert"; public static final String TOKEN_STR = "token_str"; public static final String AUTO_PUB_STR = "auto_pub"; public boolean hasPrivateServerURL, hasDistEndID, hasDistEndKey, hasPublicKey, hasPrivateKey; public boolean hasChatID, hasFirebaseUID, hasFirebaseEmail, hasProxyPort, hasTimeOut, usingselfSignedCert; public boolean hasTokenString, autoPub; public String[] proxy_info; // hostname:port:type public void setBoolsToFalse() { this.hasPrivateServerURL = false; this.hasDistEndID = false; this.hasDistEndKey = false; this.hasPublicKey = false; this.hasPrivateKey = false; this.hasChatID = false; this.hasFirebaseUID = false; this.hasFirebaseEmail = false; this.hasProxyPort = false; this.hasTimeOut = false; this.usingselfSignedCert = false; this.hasTokenString = false; this.autoPub = false; } public void loadIntent() { if(this.intent.hasExtra(PRIVATE_SERVER_URL_EXTRA)) this.setPrivateServerURL(this.intent.getStringExtra(PRIVATE_SERVER_URL_EXTRA)); if(this.intent.hasExtra(DIST_END_ID_EXTRA)) this.setDestEndID(this.intent.getStringExtra(DIST_END_ID_EXTRA)); if(this.intent.hasExtra(DIST_END_KEY_EXTRA)) this.setDestKey(this.intent.getByteArrayExtra(DIST_END_KEY_EXTRA)); if(this.intent.hasExtra(PUBLIC_KEY_BYTE_ARRAY_EXTRA)) this.setPubKey(this.intent.getByteArrayExtra(PUBLIC_KEY_BYTE_ARRAY_EXTRA)); if(this.intent.hasExtra(PRIVATE_KEY_BYTE_ARRAY_EXTRA)) this.setPrivKey(this.intent.getByteArrayExtra(PRIVATE_KEY_BYTE_ARRAY_EXTRA)); if(this.intent.hasExtra(CHAT_ID_EXTRA)) this.setChatID(this.intent.getStringExtra(CHAT_ID_EXTRA)); if(this.intent.hasExtra(FIREBASE_UID_EXTRA)) this.setFirebaseUID(this.intent.getStringExtra(FIREBASE_UID_EXTRA)); if(this.intent.hasExtra(FIREBASE_EMAIL_EXTRA)) this.setFirebaseEmail(this.intent.getStringExtra(FIREBASE_EMAIL_EXTRA)); if(this.intent.hasExtra(PROXY_INFO)) this.setProxyInfo(this.intent.getStringArrayExtra(PROXY_INFO)); if(this.intent.hasExtra(TIME_OUT_EXTRA)) this.setTimeOut(this.intent.getIntExtra(TIME_OUT_EXTRA, -1)); if(this.intent.hasExtra(USING_SELF_SIGNED_TLS_CERT_EXTRA)) this.usingselfSignedCert = true; if (this.intent.hasExtra(TOKEN_STR)) this.setTokenString(this.intent.getStringExtra(TOKEN_STR)); if (this.intent.hasExtra(AUTO_PUB_STR)) this.autoPub = this.intent.getBooleanExtra(AUTO_PUB_STR, false); } public void makeExtraStringList() { this.extraStrings = new ArrayList<String>(); this.extraStrings.add(PRIVATE_SERVER_URL_EXTRA); this.extraStrings.add(DIST_END_ID_EXTRA); this.extraStrings.add(DIST_END_KEY_EXTRA); this.extraStrings.add(PUBLIC_KEY_BYTE_ARRAY_EXTRA); this.extraStrings.add(PRIVATE_KEY_BYTE_ARRAY_EXTRA); this.extraStrings.add(CHAT_ID_EXTRA); this.extraStrings.add(FIREBASE_UID_EXTRA); this.extraStrings.add(FIREBASE_EMAIL_EXTRA); this.extraStrings.add(PROXY_INFO); this.extraStrings.add(TIME_OUT_EXTRA); this.extraStrings.add(USING_SELF_SIGNED_TLS_CERT_EXTRA); this.extraStrings.add(TOKEN_STR); this.extraStrings.add(AUTO_PUB_STR); } public void wipeIntent() { for(String extra : this.extraStrings) { this.intent.removeExtra(extra); } } public Intent copyExtrasToNewIntent(Intent newIntent) { if(this.intent.getExtras() == null) return newIntent; newIntent = newIntent.putExtras(this.intent.getExtras()); return newIntent; } public ExtrasManager(Intent inputIntent) { this.intent = inputIntent; this.makeExtraStringList(); this.setBoolsToFalse(); this.loadIntent(); } public boolean areAllTheDistEndExtrasSet() { return this.hasDistEndID && this.hasDistEndKey; } public boolean areAllTheLocalPKIExtrasSet() { return this.hasChatID && this.hasPublicKey && this.hasPrivateKey; } public boolean areAllTheFireBaseExtrasSet() { return this.hasFirebaseUID && this.hasFirebaseEmail; } public RequestQueue makeVolley(Context context) { RequestQueue volleyToReturn; int tempTimeout = 4000; if(this.timeOut > 0) tempTimeout = this.timeOut; if(this.hasProxyPort && proxyPort > 0) { dumb_debugging("the timeout is "+Integer.toString(tempTimeout)); volleyToReturn = Volley.newRequestQueue(context, new ProxiedHurlStack(this.proxy_info[0],Integer.parseInt(this.proxy_info[1]) , tempTimeout, this.proxy_info[2])); } else { volleyToReturn = Volley.newRequestQueue(context); } return volleyToReturn; } public boolean areWeOnAPrivateServer() { return this.hasPrivateServerURL; } }
14,222
Java
.java
334
31.290419
182
0.619486
matthewjpyates/werewolfchat
6
3
0
GPL-3.0
9/4/2024, 10:14:27 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
14,222
880,347
LolEndOfGameTFTEndOfGamePieceViewModel.java
stirante_lol-client-java-api/src/main/java/generated/LolEndOfGameTFTEndOfGamePieceViewModel.java
package generated; import java.util.List; public class LolEndOfGameTFTEndOfGamePieceViewModel { public String icon; public List<LolEndOfGameTFTEndOfGameItemViewModel> items; public Integer level; public String name; public Integer price; public List<LolEndOfGameTFTEndOfGameTraitViewModel> traits; }
309
Java
.java
10
29
60
0.868243
stirante/lol-client-java-api
68
14
3
GPL-3.0
9/4/2024, 7:09:48 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
309
2,631,602
BookLoanRequestController.java
kgu-clab_clab-platforms-server/src/main/java/page/clab/api/domain/library/bookLoanRecord/adapter/in/web/BookLoanRequestController.java
package page.clab.api.domain.library.bookLoanRecord.adapter.in.web; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import page.clab.api.domain.library.bookLoanRecord.application.dto.request.BookLoanRecordRequestDto; import page.clab.api.domain.library.bookLoanRecord.application.port.in.RequestBookLoanUseCase; import page.clab.api.global.common.dto.ApiResponse; import page.clab.api.global.exception.CustomOptimisticLockingFailureException; @RestController @RequestMapping("/api/v1/book-loan-records") @RequiredArgsConstructor @Tag(name = "Library - Book Loan", description = "도서관 도서 대출") public class BookLoanRequestController { private final RequestBookLoanUseCase requestBookLoanUseCase; @Operation(summary = "[U] 도서 대출 요청", description = "ROLE_USER 이상의 권한이 필요함") @PreAuthorize("hasRole('USER')") @PostMapping("") public ApiResponse<Long> requestBookLoan( @Valid @RequestBody BookLoanRecordRequestDto requestDto ) throws CustomOptimisticLockingFailureException { Long id = requestBookLoanUseCase.requestBookLoan(requestDto); return ApiResponse.success(id); } }
1,600
Java
.java
30
48.866667
100
0.823259
kgu-clab/clab-platforms-server
7
0
5
GPL-3.0
9/4/2024, 9:53:10 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,556