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,315,002
|
C.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/MultiMove/test2/in/p2/C.java
|
package p2;
import p1.A;
import p1.*;
import p1.B;
public class C{
A a;
p1.A p1a;
B b;
p1.B p1B;
}
| 102
|
Java
|
.java
| 10
| 8.9
| 15
| 0.677419
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 102
|
1,318,318
|
A_test230.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/SelectionAnalyzerWorkSpace/SelectionAnalyzerTests/validSelection/A_test230.java
|
package validSelection;
public class A_test230 {
public void foo() {
{/*[*/
foo();
/*]*/}
}
}
| 103
|
Java
|
.java
| 8
| 10.75
| 24
| 0.589474
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 103
|
1,316,820
|
A.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test64/in/A.java
|
public class A {
public int a;
public void m(B b) {
a++;
}
}
class B {
public void m() {
}
}
| 101
|
Java
|
.java
| 10
| 8.3
| 21
| 0.576087
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 101
|
4,906,329
|
ObjectMapper.java
|
aryantaheri_controller/opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/attributes/mapping/ObjectMapper.java
|
/*
* Copyright (c) 2013 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.netconf.confignetconfconnector.mapping.attributes.mapping;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import java.util.Map;
import java.util.Map.Entry;
import javax.management.openmbean.ArrayType;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenType;
import javax.management.openmbean.SimpleType;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.DependencyAttribute;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListDependenciesAttribute;
import org.opendaylight.controller.config.yangjmxgenerator.attribute.TOAttribute;
import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.AttributeIfcSwitchStatement;
public class ObjectMapper extends AttributeIfcSwitchStatement<AttributeMappingStrategy<?, ? extends OpenType<?>>> {
public Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> prepareMapping(
Map<String, AttributeIfc> configDefinition) {
Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> strategies = Maps.newHashMap();
for (Entry<String, AttributeIfc> attrEntry : configDefinition.entrySet()) {
strategies.put(attrEntry.getKey(), prepareStrategy(attrEntry.getValue()));
}
return strategies;
}
public AttributeMappingStrategy<?, ? extends OpenType<?>> prepareStrategy(AttributeIfc attributeIfc) {
if(attributeIfc instanceof DependencyAttribute) {
serviceNameOfDepAttr = ((DependencyAttribute)attributeIfc).getDependency().getSie().getQName().getLocalName();
namespaceOfDepAttr = ((DependencyAttribute)attributeIfc).getDependency().getSie().getQName().getNamespace().toString();
} else if (attributeIfc instanceof ListDependenciesAttribute) {
serviceNameOfDepAttr = ((ListDependenciesAttribute)attributeIfc).getDependency().getSie().getQName().getLocalName();
namespaceOfDepAttr = ((ListDependenciesAttribute)attributeIfc).getDependency().getSie().getQName().getNamespace().toString();
}
return switchAttribute(attributeIfc);
}
private Map<String, String> createJmxToYangMapping(TOAttribute attributeIfc) {
Map<String, String> retVal = Maps.newHashMap();
for (Entry<String, AttributeIfc> entry : attributeIfc.getJmxPropertiesToTypesMap().entrySet()) {
retVal.put(entry.getKey(), (entry.getValue()).getAttributeYangName());
}
return retVal;
}
@Override
protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseJavaSimpleAttribute(SimpleType<?> openType) {
return new SimpleAttributeMappingStrategy(openType);
}
@Override
protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseJavaArrayAttribute(ArrayType<?> openType) {
AttributeMappingStrategy<?, ? extends OpenType<?>> innerStrategy = new SimpleAttributeMappingStrategy(
(SimpleType<?>) openType.getElementOpenType());
return new ArrayAttributeMappingStrategy(openType, innerStrategy);
}
@Override
protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseJavaCompositeAttribute(CompositeType openType) {
Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> innerStrategies = Maps.newHashMap();
Map<String, String> attributeMapping = Maps.newHashMap();
for (String innerAttributeKey : openType.keySet()) {
innerStrategies.put(innerAttributeKey, caseJavaAttribute(openType.getType(innerAttributeKey)));
attributeMapping.put(innerAttributeKey, innerAttributeKey);
}
return new CompositeAttributeMappingStrategy(openType, innerStrategies, attributeMapping);
}
@Override
protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseJavaUnionAttribute(OpenType<?> openType) {
Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> innerStrategies = Maps.newHashMap();
Map<String, String> attributeMapping = Maps.newHashMap();
CompositeType compositeType = (CompositeType) openType;
for (String innerAttributeKey : compositeType.keySet()) {
innerStrategies.put(innerAttributeKey, caseJavaAttribute(compositeType.getType(innerAttributeKey)));
attributeMapping.put(innerAttributeKey, innerAttributeKey);
}
return new UnionCompositeAttributeMappingStrategy(compositeType, innerStrategies, attributeMapping);
}
private String serviceNameOfDepAttr;
private String namespaceOfDepAttr;
@Override
protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseDependencyAttribute(
SimpleType<?> openType) {
return new ObjectNameAttributeMappingStrategy(openType,
serviceNameOfDepAttr, namespaceOfDepAttr);
}
@Override
protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseTOAttribute(CompositeType openType) {
Map<String, AttributeMappingStrategy<?, ? extends OpenType<?>>> innerStrategies = Maps.newHashMap();
Preconditions.checkState(getLastAttribute() instanceof TOAttribute);
TOAttribute lastTO = (TOAttribute) getLastAttribute();
for (Entry<String, AttributeIfc> innerAttrEntry : ((TOAttribute)getLastAttribute()).getJmxPropertiesToTypesMap().entrySet()) {
innerStrategies.put(innerAttrEntry.getKey(), prepareStrategy(innerAttrEntry.getValue()));
}
return new CompositeAttributeMappingStrategy(openType, innerStrategies,
createJmxToYangMapping(lastTO));
}
@Override
protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseListAttribute(ArrayType<?> openType) {
Preconditions.checkState(getLastAttribute() instanceof ListAttribute);
return new ArrayAttributeMappingStrategy(openType,
prepareStrategy(((ListAttribute) getLastAttribute()).getInnerAttribute()));
}
@Override
protected AttributeMappingStrategy<?, ? extends OpenType<?>> caseListDependeciesAttribute(ArrayType<?> openType) {
Preconditions.checkState(getLastAttribute() instanceof ListDependenciesAttribute);
return new ArrayAttributeMappingStrategy(openType, caseDependencyAttribute(SimpleType.OBJECTNAME));
}
}
| 6,857
|
Java
|
.java
| 110
| 55.127273
| 137
| 0.757373
|
aryantaheri/controller
| 1
| 0
| 0
|
EPL-1.0
|
9/5/2024, 12:35:26 AM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| true
| true
| 6,857
|
1,405,831
|
RecipeShopSellList.java
|
oonym_l2InterludeServer/L2J_Server/java/net/sf/l2j/gameserver/serverpackets/RecipeShopSellList.java
|
/*
* 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, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* http://www.gnu.org/copyleft/gpl.html
*/
package net.sf.l2j.gameserver.serverpackets;
import net.sf.l2j.gameserver.model.L2ManufactureItem;
import net.sf.l2j.gameserver.model.L2ManufactureList;
import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
/**
* This class ... dddd d(ddd)
* @version $Revision: 1.1.2.1.2.3 $ $Date: 2005/03/27 15:29:39 $
*/
public class RecipeShopSellList extends L2GameServerPacket
{
private static final String _S__D9_RecipeShopSellList = "[S] d9 RecipeShopSellList";
private final L2PcInstance _buyer, _manufacturer;
public RecipeShopSellList(L2PcInstance buyer, L2PcInstance manufacturer)
{
_buyer = buyer;
_manufacturer = manufacturer;
}
@Override
protected final void writeImpl()
{
L2ManufactureList createList = _manufacturer.getCreateList();
if (createList != null)
{
// dddd d(ddd)
writeC(0xd9);
writeD(_manufacturer.getObjectId());
writeD((int) _manufacturer.getCurrentMp());// Creator's MP
writeD(_manufacturer.getMaxMp());// Creator's MP
writeD(_buyer.getAdena());// Buyer Adena
int count = createList.size();
writeD(count);
L2ManufactureItem temp;
for (int i = 0; i < count; i++)
{
temp = createList.getList().get(i);
writeD(temp.getRecipeId());
writeD(0x00); // unknown
writeD(temp.getCost());
}
}
}
/*
* (non-Javadoc)
* @see net.sf.l2j.gameserver.serverpackets.ServerBasePacket#getType()
*/
@Override
public String getType()
{
return _S__D9_RecipeShopSellList;
}
}
| 2,317
|
Java
|
.java
| 69
| 29.565217
| 86
| 0.714221
|
oonym/l2InterludeServer
| 22
| 13
| 0
|
GPL-2.0
|
9/4/2024, 7:49:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| true
| true
| 2,317
|
3,345,561
|
SmallFireballMeta.java
|
LimeIncOfficial_Stealth-Craft/src/main/java/net/minestom/server/entity/metadata/item/SmallFireballMeta.java
|
package net.minestom.server.entity.metadata.item;
import net.minestom.server.entity.Entity;
import net.minestom.server.entity.Metadata;
import net.minestom.server.entity.metadata.ObjectDataProvider;
import net.minestom.server.entity.metadata.ProjectileMeta;
import net.minestom.server.item.Material;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class SmallFireballMeta extends ItemContainingMeta implements ObjectDataProvider, ProjectileMeta {
public static final byte OFFSET = ItemContainingMeta.MAX_OFFSET;
public static final byte MAX_OFFSET = OFFSET + 0;
private Entity shooter;
public SmallFireballMeta(@NotNull Entity entity, @NotNull Metadata metadata) {
super(entity, metadata, Material.FIRE_CHARGE);
}
@Override
@Nullable
public Entity getShooter() {
return shooter;
}
@Override
public void setShooter(@Nullable Entity shooter) {
this.shooter = shooter;
}
@Override
public int getObjectData() {
return this.shooter == null ? 0 : this.shooter.getEntityId();
}
@Override
public boolean requiresVelocityPacketAtSpawn() {
return true;
}
}
| 1,212
|
Java
|
.java
| 33
| 32.060606
| 105
| 0.758974
|
LimeIncOfficial/Stealth-Craft
| 4
| 0
| 0
|
GPL-3.0
|
9/4/2024, 11:14:21 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 1,212
|
4,906,452
|
NetconfSSHServer.java
|
aryantaheri_controller/opendaylight/netconf/netconf-ssh/src/main/java/org/opendaylight/controller/netconf/ssh/NetconfSSHServer.java
|
/*
* Copyright (c) 2013 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.netconf.ssh;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.concurrent.ThreadSafe;
import org.opendaylight.controller.netconf.auth.AuthProvider;
import org.opendaylight.controller.netconf.ssh.threads.Handshaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.local.LocalAddress;
/**
* Thread that accepts client connections. Accepted socket is forwarded to {@link org.opendaylight.controller.netconf.ssh.threads.Handshaker},
* which is executed in {@link #handshakeExecutor}.
*/
@ThreadSafe
public final class NetconfSSHServer extends Thread implements AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(NetconfSSHServer.class);
private static final AtomicLong sessionIdCounter = new AtomicLong();
private final ServerSocket serverSocket;
private final LocalAddress localAddress;
private final EventLoopGroup bossGroup;
private Optional<AuthProvider> authProvider = Optional.absent();
private final ExecutorService handshakeExecutor;
private final char[] pem;
private volatile boolean up;
private NetconfSSHServer(final int serverPort, final LocalAddress localAddress, final EventLoopGroup bossGroup, final char[] pem) throws IOException {
super(NetconfSSHServer.class.getSimpleName());
this.bossGroup = bossGroup;
this.pem = pem;
logger.trace("Creating SSH server socket on port {}", serverPort);
this.serverSocket = new ServerSocket(serverPort);
if (serverSocket.isBound() == false) {
throw new IllegalStateException("Socket can't be bound to requested port :" + serverPort);
}
logger.trace("Server socket created.");
this.localAddress = localAddress;
this.up = true;
handshakeExecutor = Executors.newFixedThreadPool(10);
}
public static NetconfSSHServer start(final int serverPort, final LocalAddress localAddress, final EventLoopGroup bossGroup, final char[] pemArray) throws IOException {
final NetconfSSHServer netconfSSHServer = new NetconfSSHServer(serverPort, localAddress, bossGroup, pemArray);
netconfSSHServer.start();
return netconfSSHServer;
}
public synchronized AuthProvider getAuthProvider() {
Preconditions.checkState(authProvider.isPresent(), "AuthenticationProvider is not set up, cannot authenticate user");
return authProvider.get();
}
public synchronized void setAuthProvider(final AuthProvider authProvider) {
if(this.authProvider != null) {
logger.debug("Changing auth provider to {}", authProvider);
}
this.authProvider = Optional.fromNullable(authProvider);
}
@Override
public void close() throws IOException {
up = false;
logger.trace("Closing SSH server socket.");
serverSocket.close();
bossGroup.shutdownGracefully();
logger.trace("SSH server socket closed.");
}
@VisibleForTesting
public InetSocketAddress getLocalSocketAddress() {
return (InetSocketAddress) serverSocket.getLocalSocketAddress();
}
@Override
public void run() {
while (up) {
Socket acceptedSocket = null;
try {
acceptedSocket = serverSocket.accept();
} catch (final IOException e) {
if (up == false) {
logger.trace("Exiting server thread", e);
} else {
logger.warn("Exception occurred during socket.accept", e);
}
}
if (acceptedSocket != null) {
try {
final Handshaker task = new Handshaker(acceptedSocket, localAddress, sessionIdCounter.incrementAndGet(), getAuthProvider(), bossGroup, pem);
handshakeExecutor.submit(task);
} catch (final IOException e) {
logger.warn("Cannot set PEMHostKey, closing connection", e);
closeSocket(acceptedSocket);
} catch (final IllegalStateException e) {
logger.warn("Cannot accept connection, closing", e);
closeSocket(acceptedSocket);
}
}
}
logger.debug("Server thread is exiting");
}
private void closeSocket(final Socket acceptedSocket) {
try {
acceptedSocket.close();
} catch (final IOException e) {
logger.warn("Ignoring exception while closing socket", e);
}
}
}
| 5,300
|
Java
|
.java
| 117
| 37.512821
| 171
| 0.697832
|
aryantaheri/controller
| 1
| 0
| 0
|
EPL-1.0
|
9/5/2024, 12:35:26 AM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| true
| true
| 5,300
|
2,593,040
|
NativeDate.java
|
JPortal-system_system/jdk12-06222165c35f/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeDate.java
|
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.internal.objects;
import static java.lang.Double.NaN;
import static java.lang.Double.isInfinite;
import static java.lang.Double.isNaN;
import static jdk.nashorn.internal.runtime.ECMAErrors.rangeError;
import static jdk.nashorn.internal.runtime.ECMAErrors.typeError;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.Callable;
import jdk.nashorn.internal.objects.annotations.Attribute;
import jdk.nashorn.internal.objects.annotations.Constructor;
import jdk.nashorn.internal.objects.annotations.Function;
import jdk.nashorn.internal.objects.annotations.ScriptClass;
import jdk.nashorn.internal.objects.annotations.SpecializedFunction;
import jdk.nashorn.internal.objects.annotations.Where;
import jdk.nashorn.internal.parser.DateParser;
import jdk.nashorn.internal.runtime.JSType;
import jdk.nashorn.internal.runtime.PropertyMap;
import jdk.nashorn.internal.runtime.ScriptEnvironment;
import jdk.nashorn.internal.runtime.ScriptObject;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.linker.Bootstrap;
import jdk.nashorn.internal.runtime.linker.InvokeByName;
/**
* ECMA 15.9 Date Objects
*
*/
@ScriptClass("Date")
public final class NativeDate extends ScriptObject {
private static final String INVALID_DATE = "Invalid Date";
private static final int YEAR = 0;
private static final int MONTH = 1;
private static final int DAY = 2;
private static final int HOUR = 3;
private static final int MINUTE = 4;
private static final int SECOND = 5;
private static final int MILLISECOND = 6;
private static final int FORMAT_DATE_TIME = 0;
private static final int FORMAT_DATE = 1;
private static final int FORMAT_TIME = 2;
private static final int FORMAT_LOCAL_DATE_TIME = 3;
private static final int FORMAT_LOCAL_DATE = 4;
private static final int FORMAT_LOCAL_TIME = 5;
// Constants defined in ECMA 15.9.1.10
private static final int hoursPerDay = 24;
private static final int minutesPerHour = 60;
private static final int secondsPerMinute = 60;
private static final int msPerSecond = 1_000;
private static final int msPerMinute = 60_000;
private static final double msPerHour = 3_600_000;
private static final double msPerDay = 86_400_000;
private static int[][] firstDayInMonth = {
{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}, // normal year
{0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335} // leap year
};
private static String[] weekDays = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
private static String[] months = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
private static final Object TO_ISO_STRING = new Object();
private static InvokeByName getTO_ISO_STRING() {
return Global.instance().getInvokeByName(TO_ISO_STRING,
new Callable<InvokeByName>() {
@Override
public InvokeByName call() {
return new InvokeByName("toISOString", ScriptObject.class, Object.class, Object.class);
}
});
}
private double time;
private final TimeZone timezone;
// initialized by nasgen
private static PropertyMap $nasgenmap$;
private NativeDate(final double time, final ScriptObject proto, final PropertyMap map) {
super(proto, map);
final ScriptEnvironment env = Global.getEnv();
this.time = time;
this.timezone = env._timezone;
}
NativeDate(final double time, final ScriptObject proto) {
this(time, proto, $nasgenmap$);
}
NativeDate(final double time, final Global global) {
this(time, global.getDatePrototype(), $nasgenmap$);
}
private NativeDate (final double time) {
this(time, Global.instance());
}
private NativeDate() {
this(System.currentTimeMillis());
}
@Override
public String getClassName() {
return "Date";
}
// ECMA 8.12.8 [[DefaultValue]] (hint)
@Override
public Object getDefaultValue(final Class<?> hint) {
// When the [[DefaultValue]] internal method of O is called with no hint,
// then it behaves as if the hint were Number, unless O is a Date object
// in which case it behaves as if the hint were String.
return super.getDefaultValue(hint == null ? String.class : hint);
}
/**
* Constructor - ECMA 15.9.3.1 new Date
*
* @param isNew is this Date constructed with the new operator
* @param self self references
* @return Date representing now
*/
@SpecializedFunction(isConstructor=true)
public static Object construct(final boolean isNew, final Object self) {
final NativeDate result = new NativeDate();
return isNew ? result : toStringImpl(result, FORMAT_DATE_TIME);
}
/**
* Constructor - ECMA 15.9.3.1 new Date (year, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] )
*
* @param isNew is this Date constructed with the new operator
* @param self self reference
* @param args arguments
* @return new Date
*/
@Constructor(arity = 7)
public static Object construct(final boolean isNew, final Object self, final Object... args) {
if (! isNew) {
return toStringImpl(new NativeDate(), FORMAT_DATE_TIME);
}
NativeDate result;
switch (args.length) {
case 0:
result = new NativeDate();
break;
case 1:
double num;
final Object arg = JSType.toPrimitive(args[0]);
if (JSType.isString(arg)) {
num = parseDateString(arg.toString());
} else {
num = timeClip(JSType.toNumber(args[0]));
}
result = new NativeDate(num);
break;
default:
result = new NativeDate(0);
final double[] d = convertCtorArgs(args);
if (d == null) {
result.setTime(Double.NaN);
} else {
final double time = timeClip(utc(makeDate(d), result.getTimeZone()));
result.setTime(time);
}
break;
}
return result;
}
@Override
public String safeToString() {
final String str = isValidDate() ? toISOStringImpl(this) : INVALID_DATE;
return "[Date " + str + "]";
}
@Override
public String toString() {
return isValidDate() ? toString(this) : INVALID_DATE;
}
/**
* ECMA 15.9.4.2 Date.parse (string)
*
* @param self self reference
* @param string string to parse as date
* @return Date interpreted from the string, or NaN for illegal values
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static double parse(final Object self, final Object string) {
return parseDateString(JSType.toString(string));
}
/**
* ECMA 15.9.4.3 Date.UTC (year, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] )
*
* @param self self reference
* @param args mandatory args are year, month. Optional are date, hours, minutes, seconds and milliseconds
* @return a time clip according to the ECMA specification
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 7, where = Where.CONSTRUCTOR)
public static double UTC(final Object self, final Object... args) {
final NativeDate nd = new NativeDate(0);
final double[] d = convertCtorArgs(args);
final double time = d == null ? Double.NaN : timeClip(makeDate(d));
nd.setTime(time);
return time;
}
/**
* ECMA 15.9.4.4 Date.now ( )
*
* @param self self reference
* @return a Date that points to the current moment in time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static double now(final Object self) {
// convert to double as long does not represent the primitive JS number type
return (double) System.currentTimeMillis();
}
/**
* ECMA 15.9.5.2 Date.prototype.toString ( )
*
* @param self self reference
* @return string value that represents the Date in the current time zone
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static String toString(final Object self) {
return toStringImpl(self, FORMAT_DATE_TIME);
}
/**
* ECMA 15.9.5.3 Date.prototype.toDateString ( )
*
* @param self self reference
* @return string value with the "date" part of the Date in the current time zone
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static String toDateString(final Object self) {
return toStringImpl(self, FORMAT_DATE);
}
/**
* ECMA 15.9.5.4 Date.prototype.toTimeString ( )
*
* @param self self reference
* @return string value with "time" part of Date in the current time zone
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static String toTimeString(final Object self) {
return toStringImpl(self, FORMAT_TIME);
}
/**
* ECMA 15.9.5.5 Date.prototype.toLocaleString ( )
*
* @param self self reference
* @return string value that represents the Data in the current time zone and locale
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static String toLocaleString(final Object self) {
return toStringImpl(self, FORMAT_LOCAL_DATE_TIME);
}
/**
* ECMA 15.9.5.6 Date.prototype.toLocaleDateString ( )
*
* @param self self reference
* @return string value with the "date" part of the Date in the current time zone and locale
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static String toLocaleDateString(final Object self) {
return toStringImpl(self, FORMAT_LOCAL_DATE);
}
/**
* ECMA 15.9.5.7 Date.prototype.toLocaleTimeString ( )
*
* @param self self reference
* @return string value with the "time" part of Date in the current time zone and locale
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static String toLocaleTimeString(final Object self) {
return toStringImpl(self, FORMAT_LOCAL_TIME);
}
/**
* ECMA 15.9.5.8 Date.prototype.valueOf ( )
*
* @param self self reference
* @return valueOf - a number which is this time value
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double valueOf(final Object self) {
final NativeDate nd = getNativeDate(self);
return (nd != null) ? nd.getTime() : Double.NaN;
}
/**
* ECMA 15.9.5.9 Date.prototype.getTime ( )
*
* @param self self reference
* @return time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getTime(final Object self) {
final NativeDate nd = getNativeDate(self);
return (nd != null) ? nd.getTime() : Double.NaN;
}
/**
* ECMA 15.9.5.10 Date.prototype.getFullYear ( )
*
* @param self self reference
* @return full year
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object getFullYear(final Object self) {
return getField(self, YEAR);
}
/**
* ECMA 15.9.5.11 Date.prototype.getUTCFullYear( )
*
* @param self self reference
* @return UTC full year
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getUTCFullYear(final Object self) {
return getUTCField(self, YEAR);
}
/**
* B.2.4 Date.prototype.getYear ( )
*
* @param self self reference
* @return year
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getYear(final Object self) {
final NativeDate nd = getNativeDate(self);
return (nd != null && nd.isValidDate()) ? (yearFromTime(nd.getLocalTime()) - 1900) : Double.NaN;
}
/**
* ECMA 15.9.5.12 Date.prototype.getMonth ( )
*
* @param self self reference
* @return month
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getMonth(final Object self) {
return getField(self, MONTH);
}
/**
* ECMA 15.9.5.13 Date.prototype.getUTCMonth ( )
*
* @param self self reference
* @return UTC month
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getUTCMonth(final Object self) {
return getUTCField(self, MONTH);
}
/**
* ECMA 15.9.5.14 Date.prototype.getDate ( )
*
* @param self self reference
* @return date
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getDate(final Object self) {
return getField(self, DAY);
}
/**
* ECMA 15.9.5.15 Date.prototype.getUTCDate ( )
*
* @param self self reference
* @return UTC Date
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getUTCDate(final Object self) {
return getUTCField(self, DAY);
}
/**
* ECMA 15.9.5.16 Date.prototype.getDay ( )
*
* @param self self reference
* @return day
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getDay(final Object self) {
final NativeDate nd = getNativeDate(self);
return (nd != null && nd.isValidDate()) ? weekDay(nd.getLocalTime()) : Double.NaN;
}
/**
* ECMA 15.9.5.17 Date.prototype.getUTCDay ( )
*
* @param self self reference
* @return UTC day
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getUTCDay(final Object self) {
final NativeDate nd = getNativeDate(self);
return (nd != null && nd.isValidDate()) ? weekDay(nd.getTime()) : Double.NaN;
}
/**
* ECMA 15.9.5.18 Date.prototype.getHours ( )
*
* @param self self reference
* @return hours
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getHours(final Object self) {
return getField(self, HOUR);
}
/**
* ECMA 15.9.5.19 Date.prototype.getUTCHours ( )
*
* @param self self reference
* @return UTC hours
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getUTCHours(final Object self) {
return getUTCField(self, HOUR);
}
/**
* ECMA 15.9.5.20 Date.prototype.getMinutes ( )
*
* @param self self reference
* @return minutes
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getMinutes(final Object self) {
return getField(self, MINUTE);
}
/**
* ECMA 15.9.5.21 Date.prototype.getUTCMinutes ( )
*
* @param self self reference
* @return UTC minutes
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getUTCMinutes(final Object self) {
return getUTCField(self, MINUTE);
}
/**
* ECMA 15.9.5.22 Date.prototype.getSeconds ( )
*
* @param self self reference
* @return seconds
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getSeconds(final Object self) {
return getField(self, SECOND);
}
/**
* ECMA 15.9.5.23 Date.prototype.getUTCSeconds ( )
*
* @param self self reference
* @return UTC seconds
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getUTCSeconds(final Object self) {
return getUTCField(self, SECOND);
}
/**
* ECMA 15.9.5.24 Date.prototype.getMilliseconds ( )
*
* @param self self reference
* @return milliseconds
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getMilliseconds(final Object self) {
return getField(self, MILLISECOND);
}
/**
* ECMA 15.9.5.25 Date.prototype.getUTCMilliseconds ( )
*
* @param self self reference
* @return UTC milliseconds
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getUTCMilliseconds(final Object self) {
return getUTCField(self, MILLISECOND);
}
/**
* ECMA 15.9.5.26 Date.prototype.getTimezoneOffset ( )
*
* @param self self reference
* @return time zone offset or NaN if N/A
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double getTimezoneOffset(final Object self) {
final NativeDate nd = getNativeDate(self);
if (nd != null && nd.isValidDate()) {
final long msec = (long) nd.getTime();
return - nd.getTimeZone().getOffset(msec) / msPerMinute;
}
return Double.NaN;
}
/**
* ECMA 15.9.5.27 Date.prototype.setTime (time)
*
* @param self self reference
* @param time time
* @return time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double setTime(final Object self, final Object time) {
final NativeDate nd = getNativeDate(self);
final double num = timeClip(JSType.toNumber(time));
nd.setTime(num);
return num;
}
/**
* ECMA 15.9.5.28 Date.prototype.setMilliseconds (ms)
*
* @param self self reference
* @param args milliseconds
* @return time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static double setMilliseconds(final Object self, final Object... args) {
final NativeDate nd = getNativeDate(self);
setFields(nd, MILLISECOND, args, true);
return nd.getTime();
}
/**
* ECMA 15.9.5.29 Date.prototype.setUTCMilliseconds (ms)
*
* @param self self reference
* @param args utc milliseconds
* @return time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static double setUTCMilliseconds(final Object self, final Object... args) {
final NativeDate nd = getNativeDate(self);
setFields(nd, MILLISECOND, args, false);
return nd.getTime();
}
/**
* ECMA 15.9.5.30 Date.prototype.setSeconds (sec [, ms ] )
*
* @param self self reference
* @param args seconds (milliseconds optional second argument)
* @return time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
public static double setSeconds(final Object self, final Object... args) {
final NativeDate nd = getNativeDate(self);
setFields(nd, SECOND, args, true);
return nd.getTime();
}
/**
* ECMA 15.9.5.31 Date.prototype.setUTCSeconds (sec [, ms ] )
*
* @param self self reference
* @param args UTC seconds (milliseconds optional second argument)
* @return time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
public static double setUTCSeconds(final Object self, final Object... args) {
final NativeDate nd = getNativeDate(self);
setFields(nd, SECOND, args, false);
return nd.getTime();
}
/**
* ECMA 15.9.5.32 Date.prototype.setMinutes (min [, sec [, ms ] ] )
*
* @param self self reference
* @param args minutes (seconds and milliseconds are optional second and third arguments)
* @return time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 3)
public static double setMinutes(final Object self, final Object... args) {
final NativeDate nd = getNativeDate(self);
setFields(nd, MINUTE, args, true);
return nd.getTime();
}
/**
* ECMA 15.9.5.33 Date.prototype.setUTCMinutes (min [, sec [, ms ] ] )
*
* @param self self reference
* @param args minutes (seconds and milliseconds are optional second and third arguments)
* @return time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 3)
public static double setUTCMinutes(final Object self, final Object... args) {
final NativeDate nd = getNativeDate(self);
setFields(nd, MINUTE, args, false);
return nd.getTime();
}
/**
* ECMA 15.9.5.34 Date.prototype.setHours (hour [, min [, sec [, ms ] ] ] )
*
* @param self self reference
* @param args hour (optional arguments after are minutes, seconds, milliseconds)
* @return time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 4)
public static double setHours(final Object self, final Object... args) {
final NativeDate nd = getNativeDate(self);
setFields(nd, HOUR, args, true);
return nd.getTime();
}
/**
* ECMA 15.9.5.35 Date.prototype.setUTCHours (hour [, min [, sec [, ms ] ] ] )
*
* @param self self reference
* @param args hour (optional arguments after are minutes, seconds, milliseconds)
* @return time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 4)
public static double setUTCHours(final Object self, final Object... args) {
final NativeDate nd = getNativeDate(self);
setFields(nd, HOUR, args, false);
return nd.getTime();
}
/**
* ECMA 15.9.5.36 Date.prototype.setDate (date)
*
* @param self self reference
* @param args date
* @return time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static double setDate(final Object self, final Object... args) {
final NativeDate nd = getNativeDate(self);
setFields(nd, DAY, args, true);
return nd.getTime();
}
/**
* ECMA 15.9.5.37 Date.prototype.setUTCDate (date)
*
* @param self self reference
* @param args UTC date
* @return time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static double setUTCDate(final Object self, final Object... args) {
final NativeDate nd = getNativeDate(self);
setFields(nd, DAY, args, false);
return nd.getTime();
}
/**
* ECMA 15.9.5.38 Date.prototype.setMonth (month [, date ] )
*
* @param self self reference
* @param args month (optional second argument is date)
* @return time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
public static double setMonth(final Object self, final Object... args) {
final NativeDate nd = getNativeDate(self);
setFields(nd, MONTH, args, true);
return nd.getTime();
}
/**
* ECMA 15.9.5.39 Date.prototype.setUTCMonth (month [, date ] )
*
* @param self self reference
* @param args UTC month (optional second argument is date)
* @return time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 2)
public static double setUTCMonth(final Object self, final Object... args) {
final NativeDate nd = ensureNativeDate(self);
setFields(nd, MONTH, args, false);
return nd.getTime();
}
/**
* ECMA 15.9.5.40 Date.prototype.setFullYear (year [, month [, date ] ] )
*
* @param self self reference
* @param args year (optional second and third arguments are month and date)
* @return time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 3)
public static double setFullYear(final Object self, final Object... args) {
final NativeDate nd = ensureNativeDate(self);
if (nd.isValidDate()) {
setFields(nd, YEAR, args, true);
} else {
final double[] d = convertArgs(args, 0, YEAR, YEAR, 3);
if (d != null) {
nd.setTime(timeClip(utc(makeDate(makeDay(d[0], d[1], d[2]), 0), nd.getTimeZone())));
} else {
nd.setTime(NaN);
}
}
return nd.getTime();
}
/**
* ECMA 15.9.5.41 Date.prototype.setUTCFullYear (year [, month [, date ] ] )
*
* @param self self reference
* @param args UTC full year (optional second and third arguments are month and date)
* @return time
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 3)
public static double setUTCFullYear(final Object self, final Object... args) {
final NativeDate nd = ensureNativeDate(self);
if (nd.isValidDate()) {
setFields(nd, YEAR, args, false);
} else {
final double[] d = convertArgs(args, 0, YEAR, YEAR, 3);
nd.setTime(timeClip(makeDate(makeDay(d[0], d[1], d[2]), 0)));
}
return nd.getTime();
}
/**
* ECMA B.2.5 Date.prototype.setYear (year)
*
* @param self self reference
* @param year year
* @return NativeDate
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static double setYear(final Object self, final Object year) {
final NativeDate nd = getNativeDate(self);
if (isNaN(nd.getTime())) {
nd.setTime(utc(0, nd.getTimeZone()));
}
final double yearNum = JSType.toNumber(year);
if (isNaN(yearNum)) {
nd.setTime(NaN);
return nd.getTime();
}
int yearInt = (int)yearNum;
if (0 <= yearInt && yearInt <= 99) {
yearInt += 1900;
}
setFields(nd, YEAR, new Object[] {yearInt}, true);
return nd.getTime();
}
/**
* ECMA 15.9.5.42 Date.prototype.toUTCString ( )
*
* @param self self reference
* @return string representation of date
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static String toUTCString(final Object self) {
return toGMTStringImpl(self);
}
/**
* ECMA B.2.6 Date.prototype.toGMTString ( )
*
* See {@link NativeDate#toUTCString(Object)}
*
* @param self self reference
* @return string representation of date
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static String toGMTString(final Object self) {
return toGMTStringImpl(self);
}
/**
* ECMA 15.9.5.43 Date.prototype.toISOString ( )
*
* @param self self reference
* @return string representation of date
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static String toISOString(final Object self) {
return toISOStringImpl(self);
}
/**
* ECMA 15.9.5.44 Date.prototype.toJSON ( key )
*
* Provides a string representation of this Date for use by {@link NativeJSON#stringify(Object, Object, Object, Object)}
*
* @param self self reference
* @param key ignored
* @return JSON representation of this date
*/
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object toJSON(final Object self, final Object key) {
// NOTE: Date.prototype.toJSON is generic. Accepts other objects as well.
final Object selfObj = Global.toObject(self);
if (!(selfObj instanceof ScriptObject)) {
return null;
}
final ScriptObject sobj = (ScriptObject)selfObj;
final Object value = sobj.getDefaultValue(Number.class);
if (value instanceof Number) {
final double num = ((Number)value).doubleValue();
if (isInfinite(num) || isNaN(num)) {
return null;
}
}
try {
final InvokeByName toIsoString = getTO_ISO_STRING();
final Object func = toIsoString.getGetter().invokeExact(sobj);
if (Bootstrap.isCallable(func)) {
return toIsoString.getInvoker().invokeExact(func, sobj, key);
}
throw typeError("not.a.function", ScriptRuntime.safeToString(func));
} catch (final RuntimeException | Error e) {
throw e;
} catch (final Throwable t) {
throw new RuntimeException(t);
}
}
// -- Internals below this point
private static double parseDateString(final String str) {
final DateParser parser = new DateParser(str);
if (parser.parse()) {
final Integer[] fields = parser.getDateFields();
double d = makeDate(fields);
if (fields[DateParser.TIMEZONE] != null) {
d -= fields[DateParser.TIMEZONE] * 60000;
} else {
d = utc(d, Global.getEnv()._timezone);
}
d = timeClip(d);
return d;
}
return Double.NaN;
}
private static void zeroPad(final StringBuilder sb, final int n, final int length) {
for (int l = 1, d = 10; l < length; l++, d *= 10) {
if (n < d) {
sb.append('0');
}
}
sb.append(n);
}
@SuppressWarnings("fallthrough")
private static String toStringImpl(final Object self, final int format) {
final NativeDate nd = getNativeDate(self);
if (nd != null && nd.isValidDate()) {
final StringBuilder sb = new StringBuilder(40);
final double t = nd.getLocalTime();
switch (format) {
case FORMAT_DATE_TIME:
case FORMAT_DATE :
case FORMAT_LOCAL_DATE_TIME:
// EEE MMM dd yyyy
sb.append(weekDays[weekDay(t)])
.append(' ')
.append(months[monthFromTime(t)])
.append(' ');
zeroPad(sb, dayFromTime(t), 2);
sb.append(' ');
zeroPad(sb, yearFromTime(t), 4);
if (format == FORMAT_DATE) {
break;
}
sb.append(' ');
case FORMAT_TIME:
final TimeZone tz = nd.getTimeZone();
final double utcTime = nd.getTime();
int offset = tz.getOffset((long) utcTime) / 60000;
final boolean inDaylightTime = offset != tz.getRawOffset() / 60000;
// Convert minutes to HHmm timezone offset
offset = (offset / 60) * 100 + offset % 60;
// HH:mm:ss GMT+HHmm
zeroPad(sb, hourFromTime(t), 2);
sb.append(':');
zeroPad(sb, minFromTime(t), 2);
sb.append(':');
zeroPad(sb, secFromTime(t), 2);
sb.append(" GMT")
.append(offset < 0 ? '-' : '+');
zeroPad(sb, Math.abs(offset), 4);
sb.append(" (")
.append(tz.getDisplayName(inDaylightTime, TimeZone.SHORT, Locale.US))
.append(')');
break;
case FORMAT_LOCAL_DATE:
// yyyy-MM-dd
zeroPad(sb, yearFromTime(t), 4);
sb.append('-');
zeroPad(sb, monthFromTime(t) + 1, 2);
sb.append('-');
zeroPad(sb, dayFromTime(t), 2);
break;
case FORMAT_LOCAL_TIME:
// HH:mm:ss
zeroPad(sb, hourFromTime(t), 2);
sb.append(':');
zeroPad(sb, minFromTime(t), 2);
sb.append(':');
zeroPad(sb, secFromTime(t), 2);
break;
default:
throw new IllegalArgumentException("format: " + format);
}
return sb.toString();
}
return INVALID_DATE;
}
private static String toGMTStringImpl(final Object self) {
final NativeDate nd = getNativeDate(self);
if (nd != null && nd.isValidDate()) {
final StringBuilder sb = new StringBuilder(29);
final double t = nd.getTime();
// EEE, dd MMM yyyy HH:mm:ss z
sb.append(weekDays[weekDay(t)])
.append(", ");
zeroPad(sb, dayFromTime(t), 2);
sb.append(' ')
.append(months[monthFromTime(t)])
.append(' ');
zeroPad(sb, yearFromTime(t), 4);
sb.append(' ');
zeroPad(sb, hourFromTime(t), 2);
sb.append(':');
zeroPad(sb, minFromTime(t), 2);
sb.append(':');
zeroPad(sb, secFromTime(t), 2);
sb.append(" GMT");
return sb.toString();
}
throw rangeError("invalid.date");
}
private static String toISOStringImpl(final Object self) {
final NativeDate nd = getNativeDate(self);
if (nd != null && nd.isValidDate()) {
final StringBuilder sb = new StringBuilder(24);
final double t = nd.getTime();
// yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
zeroPad(sb, yearFromTime(t), 4);
sb.append('-');
zeroPad(sb, monthFromTime(t) + 1, 2);
sb.append('-');
zeroPad(sb, dayFromTime(t), 2);
sb.append('T');
zeroPad(sb, hourFromTime(t), 2);
sb.append(':');
zeroPad(sb, minFromTime(t), 2);
sb.append(':');
zeroPad(sb, secFromTime(t), 2);
sb.append('.');
zeroPad(sb, msFromTime(t), 3);
sb.append("Z");
return sb.toString();
}
throw rangeError("invalid.date");
}
// ECMA 15.9.1.2 Day (t)
private static double day(final double t) {
return Math.floor(t / msPerDay);
}
// ECMA 15.9.1.2 TimeWithinDay (t)
private static double timeWithinDay(final double t) {
final double val = t % msPerDay;
return val < 0? val + msPerDay : val;
}
// ECMA 15.9.1.3 InLeapYear (t)
private static boolean isLeapYear(final int y) {
return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
}
// ECMA 15.9.1.3 DaysInYear (y)
private static int daysInYear(final int y) {
return isLeapYear(y) ? 366 : 365;
}
// ECMA 15.9.1.3 DayFromYear (y)
private static double dayFromYear(final double y) {
return 365 * (y - 1970)
+ Math.floor((y -1969) / 4.0)
- Math.floor((y - 1901) / 100.0)
+ Math.floor((y - 1601) / 400.0);
}
// ECMA 15.9.1.3 Year Number
private static double timeFromYear(final int y) {
return dayFromYear(y) * msPerDay;
}
// ECMA 15.9.1.3 Year Number
private static int yearFromTime(final double t) {
int y = (int) Math.floor(t / (msPerDay * 365.2425)) + 1970;
final double t2 = timeFromYear(y);
if (t2 > t) {
y--;
} else if (t2 + msPerDay * daysInYear(y) <= t) {
y++;
}
return y;
}
private static int dayWithinYear(final double t, final int year) {
return (int) (day(t) - dayFromYear(year));
}
private static int monthFromTime(final double t) {
final int year = yearFromTime(t);
final int day = dayWithinYear(t, year);
final int[] firstDay = firstDayInMonth[isLeapYear(year) ? 1 : 0];
int month = 0;
while (month < 11 && firstDay[month + 1] <= day) {
month++;
}
return month;
}
private static int dayFromTime(final double t) {
final int year = yearFromTime(t);
final int day = dayWithinYear(t, year);
final int[] firstDay = firstDayInMonth[isLeapYear(year) ? 1 : 0];
int month = 0;
while (month < 11 && firstDay[month + 1] <= day) {
month++;
}
return 1 + day - firstDay[month];
}
private static int dayFromMonth(final int month, final int year) {
assert(month >= 0 && month <= 11);
final int[] firstDay = firstDayInMonth[isLeapYear(year) ? 1 : 0];
return firstDay[month];
}
private static int weekDay(final double time) {
final int day = (int) (day(time) + 4) % 7;
return day < 0 ? day + 7 : day;
}
// ECMA 15.9.1.9 LocalTime
private static double localTime(final double time, final TimeZone tz) {
return time + tz.getOffset((long) time);
}
// ECMA 15.9.1.9 UTC
private static double utc(final double time, final TimeZone tz) {
return time - tz.getOffset((long) (time - tz.getRawOffset()));
}
// ECMA 15.9.1.10 Hours, Minutes, Second, and Milliseconds
private static int hourFromTime(final double t) {
final int h = (int) (Math.floor(t / msPerHour) % hoursPerDay);
return h < 0 ? h + hoursPerDay: h;
}
private static int minFromTime(final double t) {
final int m = (int) (Math.floor(t / msPerMinute) % minutesPerHour);
return m < 0 ? m + minutesPerHour : m;
}
private static int secFromTime(final double t) {
final int s = (int) (Math.floor(t / msPerSecond) % secondsPerMinute);
return s < 0 ? s + secondsPerMinute : s;
}
private static int msFromTime(final double t) {
final int m = (int) (t % msPerSecond);
return m < 0 ? m + msPerSecond : m;
}
private static int valueFromTime(final int unit, final double t) {
switch (unit) {
case YEAR: return yearFromTime(t);
case MONTH: return monthFromTime(t);
case DAY: return dayFromTime(t);
case HOUR: return hourFromTime(t);
case MINUTE: return minFromTime(t);
case SECOND: return secFromTime(t);
case MILLISECOND: return msFromTime(t);
default: throw new IllegalArgumentException(Integer.toString(unit));
}
}
// ECMA 15.9.1.11 MakeTime (hour, min, sec, ms)
private static double makeTime(final double hour, final double min, final double sec, final double ms) {
return hour * 3600000 + min * 60000 + sec * 1000 + ms;
}
// ECMA 15.9.1.12 MakeDay (year, month, date)
private static double makeDay(final double year, final double month, final double date) {
final double y = year + Math.floor(month / 12);
int m = (int) (month % 12);
if (m < 0) {
m += 12;
}
double d = dayFromYear(y);
d += dayFromMonth(m, (int) y);
return d + date - 1;
}
// ECMA 15.9.1.13 MakeDate (day, time)
private static double makeDate(final double day, final double time) {
return day * msPerDay + time;
}
private static double makeDate(final Integer[] d) {
final double time = makeDay(d[0], d[1], d[2]) * msPerDay;
return time + makeTime(d[3], d[4], d[5], d[6]);
}
private static double makeDate(final double[] d) {
final double time = makeDay(d[0], d[1], d[2]) * msPerDay;
return time + makeTime(d[3], d[4], d[5], d[6]);
}
// Convert Date constructor args, checking for NaN, filling in defaults etc.
private static double[] convertCtorArgs(final Object[] args) {
final double[] d = new double[7];
boolean nullReturn = false;
// should not bailout on first NaN or infinite. Need to convert all
// subsequent args for possible side-effects via valueOf/toString overrides
// on argument objects.
for (int i = 0; i < d.length; i++) {
if (i < args.length) {
final double darg = JSType.toNumber(args[i]);
if (isNaN(darg) || isInfinite(darg)) {
nullReturn = true;
}
d[i] = (long)darg;
} else {
d[i] = i == 2 ? 1 : 0; // day in month defaults to 1
}
}
if (0 <= d[0] && d[0] <= 99) {
d[0] += 1900;
}
return nullReturn? null : d;
}
// This method does the hard work for all setter methods: If a value is provided
// as argument it is used, otherwise the value is calculated from the existing time value.
private static double[] convertArgs(final Object[] args, final double time, final int fieldId, final int start, final int length) {
final double[] d = new double[length];
boolean nullReturn = false;
// Need to call toNumber on all args for side-effects - even if an argument
// fails to convert to number, subsequent toNumber calls needed for possible
// side-effects via valueOf/toString overrides.
for (int i = start; i < start + length; i++) {
if (fieldId <= i && i < fieldId + args.length) {
final double darg = JSType.toNumber(args[i - fieldId]);
if (isNaN(darg) || isInfinite(darg)) {
nullReturn = true;
}
d[i - start] = (long) darg;
} else {
// Date.prototype.set* methods require first argument to be defined
if (i == fieldId) {
nullReturn = true;
}
if (!nullReturn && !isNaN(time)) {
d[i - start] = valueFromTime(i, time);
}
}
}
return nullReturn ? null : d;
}
// ECMA 15.9.1.14 TimeClip (time)
private static double timeClip(final double time) {
if (isInfinite(time) || isNaN(time) || Math.abs(time) > 8.64e15) {
return Double.NaN;
}
return (long)time;
}
private static NativeDate ensureNativeDate(final Object self) {
return getNativeDate(self);
}
private static NativeDate getNativeDate(final Object self) {
if (self instanceof NativeDate) {
return (NativeDate)self;
} else if (self != null && self == Global.instance().getDatePrototype()) {
return Global.instance().getDefaultDate();
} else {
throw typeError("not.a.date", ScriptRuntime.safeToString(self));
}
}
private static double getField(final Object self, final int field) {
final NativeDate nd = getNativeDate(self);
return (nd != null && nd.isValidDate()) ? (double)valueFromTime(field, nd.getLocalTime()) : Double.NaN;
}
private static double getUTCField(final Object self, final int field) {
final NativeDate nd = getNativeDate(self);
return (nd != null && nd.isValidDate()) ? (double)valueFromTime(field, nd.getTime()) : Double.NaN;
}
private static void setFields(final NativeDate nd, final int fieldId, final Object[] args, final boolean local) {
int start, length;
if (fieldId < HOUR) {
start = YEAR;
length = 3;
} else {
start = HOUR;
length = 4;
}
final double time = local ? nd.getLocalTime() : nd.getTime();
final double d[] = convertArgs(args, time, fieldId, start, length);
if (! nd.isValidDate()) {
return;
}
double newTime;
if (d == null) {
newTime = NaN;
} else {
if (start == YEAR) {
newTime = makeDate(makeDay(d[0], d[1], d[2]), timeWithinDay(time));
} else {
newTime = makeDate(day(time), makeTime(d[0], d[1], d[2], d[3]));
}
if (local) {
newTime = utc(newTime, nd.getTimeZone());
}
newTime = timeClip(newTime);
}
nd.setTime(newTime);
}
private boolean isValidDate() {
return !isNaN(time);
}
private double getLocalTime() {
return localTime(time, timezone);
}
private double getTime() {
return time;
}
private void setTime(final double time) {
this.time = time;
}
private TimeZone getTimeZone() {
return timezone;
}
}
| 45,416
|
Java
|
.java
| 1,197
| 29.753551
| 135
| 0.600899
|
JPortal-system/system
| 7
| 2
| 1
|
GPL-3.0
|
9/4/2024, 9:49:36 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 45,416
|
1,318,014
|
A_testZeroLengthSelection0_in.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractConstant/canExtract/A_testZeroLengthSelection0_in.java
|
//5, 18 -> 5, 18 AllowLoadtime == false
package p;
class A {
void f() {
int i= 100;
}
}
| 93
|
Java
|
.java
| 7
| 11.857143
| 41
| 0.574713
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 93
|
1,318,099
|
A_testFail15.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractConstant/cannotExtract/A_testFail15.java
|
//5, 10 -> 5, 13 AllowLoadtime == true
package p;
class S {
int i= 1;
}
| 75
|
Java
|
.java
| 5
| 13.8
| 40
| 0.6
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 75
|
4,949,095
|
HashUtil.java
|
PeterFalken_baseJSF/src/main/java/com/bitjester/apps/common/utils/HashUtil.java
|
package com.bitjester.apps.common.utils;
import org.apache.commons.codec.digest.DigestUtils;
public abstract class HashUtil {
/*
public static String calc_HashMD5(String input) throws Exception {
if (null == input)
return null;
// Salt for Hash is the same input string
return DigestUtils.md5Hex(input + input);
}
*/
public static String calc_HashSHA(String input) throws Exception {
if (null == input)
return null;
// Salt for Hash is the same input string
return DigestUtils.sha256Hex(input + input);
}
}
| 534
|
Java
|
.java
| 18
| 27.166667
| 67
| 0.756335
|
PeterFalken/baseJSF
| 1
| 2
| 0
|
GPL-2.0
|
9/5/2024, 12:36:54 AM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 534
|
1,311,434
|
ByteArrayOutputStream.java
|
TheLogicMaster_clearwing-vm/runtime/src/java/io/ByteArrayOutputStream.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 java.io;
import java.util.Arrays;
/**
* A specialized {@link OutputStream} for class for writing content to an
* (internal) byte array. As bytes are written to this stream, the byte array
* may be expanded to hold more bytes. When the writing is considered to be
* finished, a copy of the byte array can be requested from the class.
*
* @see ByteArrayInputStream
*/
public class ByteArrayOutputStream extends OutputStream {
/**
* The byte array containing the bytes written.
*/
protected byte[] buf;
/**
* The number of bytes written.
*/
protected int count;
/**
* Constructs a new ByteArrayOutputStream with a default size of 32 bytes.
* If more than 32 bytes are written to this instance, the underlying byte
* array will expand.
*/
public ByteArrayOutputStream() {
buf = new byte[32];
}
/**
* Constructs a new {@code ByteArrayOutputStream} with a default size of
* {@code size} bytes. If more than {@code size} bytes are written to this
* instance, the underlying byte array will expand.
*
* @param size
* initial size for the underlying byte array, must be
* non-negative.
* @throws IllegalArgumentException
* if {@code size} < 0.
*/
public ByteArrayOutputStream(int size) {
if (size >= 0) {
buf = new byte[size];
} else {
throw new IllegalArgumentException("size < 0");
}
}
/**
* Closes this stream. This releases system resources used for this stream.
*
* @throws IOException
* if an error occurs while attempting to close this stream.
*/
@Override
public void close() throws IOException {
/**
* Although the spec claims "A closed stream cannot perform output
* operations and cannot be reopened.", this implementation must do
* nothing.
*/
super.close();
}
private void expand(int i) {
/* Can the buffer handle @i more bytes, if not expand it */
if (count + i <= buf.length) {
return;
}
byte[] newbuf = new byte[(count + i) * 2];
System.arraycopy(buf, 0, newbuf, 0, count);
buf = newbuf;
}
/**
* Resets this stream to the beginning of the underlying byte array. All
* subsequent writes will overwrite any bytes previously stored in this
* stream.
*/
public synchronized void reset() {
count = 0;
}
/**
* Returns the total number of bytes written to this stream so far.
*
* @return the number of bytes written to this stream.
*/
public int size() {
return count;
}
/**
* Returns the contents of this ByteArrayOutputStream as a byte array. Any
* changes made to the receiver after returning will not be reflected in the
* byte array returned to the caller.
*
* @return this stream's current contents as a byte array.
*/
public synchronized byte[] toByteArray() {
byte[] newArray = new byte[count];
System.arraycopy(buf, 0, newArray, 0, count);
return newArray;
}
/**
* Returns the contents of this ByteArrayOutputStream as a string. Any
* changes made to the receiver after returning will not be reflected in the
* string returned to the caller.
*
* @return this stream's current contents as a string.
*/
@Override
public String toString() {
return new String(buf, 0, count);
}
/**
* Returns the contents of this ByteArrayOutputStream as a string. Each byte
* {@code b} in this stream is converted to a character {@code c} using the
* following function:
* {@code c == (char)(((hibyte & 0xff) << 8) | (b & 0xff))}. This method is
* deprecated and either {@link #toString()} or {@link #toString(String)}
* should be used.
*
* @param hibyte
* the high byte of each resulting Unicode character.
* @return this stream's current contents as a string with the high byte set
* to {@code hibyte}.
* @deprecated Use {@link #toString()}.
*/
@Deprecated
public String toString(int hibyte) {
char[] newBuf = new char[size()];
for (int i = 0; i < newBuf.length; i++) {
newBuf[i] = (char) (((hibyte & 0xff) << 8) | (buf[i] & 0xff));
}
return new String(newBuf);
}
/**
* Returns the contents of this ByteArrayOutputStream as a string converted
* according to the encoding declared in {@code charsetName}.
*
* @param charsetName
* a string representing the encoding to use when translating
* this stream to a string.
* @return this stream's current contents as an encoded string.
* @throws UnsupportedEncodingException
* if the provided encoding is not supported.
*/
public String toString(String charsetName) throws UnsupportedEncodingException {
return new String(buf, 0, count, charsetName);
}
/**
* Writes {@code count} bytes from the byte array {@code buffer} starting at
* offset {@code index} to this stream.
*
* @param buffer
* the buffer to be written.
* @param offset
* the initial position in {@code buffer} to retrieve bytes.
* @param len
* the number of bytes of {@code buffer} to write.
* @throws NullPointerException
* if {@code buffer} is {@code null}.
* @throws IndexOutOfBoundsException
* if {@code offset < 0} or {@code len < 0}, or if
* {@code offset + len} is greater than the length of
* {@code buffer}.
*/
@Override
public synchronized void write(byte[] buffer, int offset, int len) {
Arrays.checkOffsetAndCount(buffer.length, offset, len);
if (len == 0) {
return;
}
expand(len);
System.arraycopy(buffer, offset, buf, this.count, len);
this.count += len;
}
/**
* Writes the specified byte {@code oneByte} to the OutputStream. Only the
* low order byte of {@code oneByte} is written.
*
* @param oneByte
* the byte to be written.
*/
@Override
public synchronized void write(int oneByte) {
if (count == buf.length) {
expand(1);
}
buf[count++] = (byte) oneByte;
}
/**
* Takes the contents of this stream and writes it to the output stream
* {@code out}.
*
* @param out
* an OutputStream on which to write the contents of this stream.
* @throws IOException
* if an error occurs while writing to {@code out}.
*/
public synchronized void writeTo(OutputStream out) throws IOException {
out.write(buf, 0, count);
}
}
| 7,819
|
Java
|
.java
| 214
| 30.495327
| 84
| 0.624012
|
TheLogicMaster/clearwing-vm
| 38
| 3
| 1
|
GPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 7,819
|
1,315,730
|
As.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/UseSupertypeWherePossible/test68/in/As.java
|
package p;
/** typecomment template*/
public class As {
void f(){
A a= A.getA();
a.m1();
}
}
| 98
|
Java
|
.java
| 8
| 10.625
| 26
| 0.604396
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 98
|
1,315,302
|
A_test51_in.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTemp/canRename/A_test51_in.java
|
package p;
class A {
void m() {
final int a = 3;
final int b = 3;
final int b = 3;
final int b = 3;
}
}
| 120
|
Java
|
.java
| 9
| 10.555556
| 24
| 0.531532
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 120
|
2,593,089
|
Symbol.java
|
JPortal-system_system/jdk12-06222165c35f/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Symbol.java
|
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.internal.runtime;
import java.io.Serializable;
import jdk.nashorn.internal.objects.NativeSymbol;
/**
* This class represents a unique, non-String Object property key as defined in ECMAScript 6.
*/
public final class Symbol implements Serializable {
private final String name;
private static final long serialVersionUID = -2988436597549486913L;
/**
* Symbol constructor
* @param name symbol name
*/
public Symbol(final String name) {
this.name = name;
}
@Override
public String toString() {
return "Symbol(" + name + ")";
}
/**
* Return the symbol's name
* @return the name
*/
public final String getName() {
return name;
}
private Object writeReplace() {
// If this symbol is a globally registered one, replace it with a
// GlobalSymbol in serialized stream.
return NativeSymbol.keyFor(null, this) == name ? new GlobalSymbol(name) : this;
}
/**
* Represents a globally registered (with NativeSymbol._for) symbol in the
* serialized stream. Upon deserialization, it resolves to the globally
* registered symbol.
*/
private static class GlobalSymbol implements Serializable {
private static final long serialVersionUID = 1L;
private final String name;
GlobalSymbol(final String name) {
this.name = name;
}
private Object readResolve() {
return NativeSymbol._for(null, name);
}
}
}
| 2,755
|
Java
|
.java
| 72
| 33.486111
| 93
| 0.710112
|
JPortal-system/system
| 7
| 2
| 1
|
GPL-3.0
|
9/4/2024, 9:49:36 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 2,755
|
1,311,565
|
ChangeMethodSignatureParticipant.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/core/refactoring/participants/ChangeMethodSignatureParticipant.java
|
/*******************************************************************************
* Copyright (c) 2007, 2008 IBM Corporation and others.
*
* 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.jdt.core.refactoring.participants;
import org.eclipse.ltk.core.refactoring.participants.RefactoringArguments;
import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
/**
* A participant to participate in refactorings that change method signatures.
* <p>
* Change method signature participants are registered via the extension point <code>
* org.eclipse.jdt.core.manipulation.changeMethodSignatureParticipants</code>.
* Extensions to this extension point must extend this abstract class.
* </p>
*
* @since 1.2
*/
public abstract class ChangeMethodSignatureParticipant extends RefactoringParticipant {
private ChangeMethodSignatureArguments fArguments;
@Override
protected final void initialize(RefactoringArguments arguments) {
fArguments= (ChangeMethodSignatureArguments) arguments;
}
/**
* Returns the change method signature arguments.
*
* @return the change method signature arguments
*/
public ChangeMethodSignatureArguments getArguments() {
return fArguments;
}
}
| 1,601
|
Java
|
.java
| 41
| 36.95122
| 87
| 0.721543
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| true
| true
| true
| 1,601
|
4,571,678
|
Astronaut.java
|
NikolayKostadinov_Java-OOP/ExamPreparation/03 Java OOP Retake Exam - 18 April 2021/SpaceStation/src/main/java/spaceStation/models/astronauts/Astronaut.java
|
package spaceStation.models.astronauts;
import spaceStation.models.bags.Bag;
public interface Astronaut {
String getName();
double getOxygen();
boolean canBreath();
Bag getBag();
void breath();
}
| 222
|
Java
|
.java
| 9
| 20.777778
| 39
| 0.73913
|
NikolayKostadinov/Java-OOP
| 2
| 0
| 0
|
GPL-3.0
|
9/5/2024, 12:17:49 AM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 222
|
3,682,784
|
compare.java
|
ingelabs_mauve/gnu/testlet/java/lang/Float/compare.java
|
//Tags: JDK1.4
//Copyright (C) 2004 David Gilbert <[email protected]>
//This file is part of Mauve.
//Mauve 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, or (at your option)
//any later version.
//Mauve 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 Mauve; see the file COPYING. If not, write to
//the Free Software Foundation, 59 Temple Place - Suite 330,
//Boston, MA 02111-1307, USA.
package gnu.testlet.java.lang.Float;
import gnu.testlet.TestHarness;
import gnu.testlet.Testlet;
/**
* Some tests for the compare() method in the {@link Float} class.
*/
public class compare implements Testlet
{
/**
* Runs the test using the specified harness.
*
* @param harness the test harness (<code>null</code> not permitted).
*/
public void test(TestHarness harness)
{
harness.check(Float.compare(0.0f, 1.0f) < 0);
harness.check(Float.compare(0.0f, 0.0f) == 0);
harness.check(Float.compare(1.0f, 0.0f) > 0);
harness.check(Float.compare(Float.POSITIVE_INFINITY, 0.0f) > 0);
harness.check(Float.compare(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY) == 0);
harness.check(Float.compare(0.0f, Float.POSITIVE_INFINITY) < 0);
harness.check(Float.compare(Float.NEGATIVE_INFINITY, 0.0f) < 0);
harness.check(Float.compare(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY) == 0);
harness.check(Float.compare(0.0f, Float.NEGATIVE_INFINITY) > 0);
harness.check(Float.compare(Float.NaN, 0.0f) > 0);
harness.check(Float.compare(Float.NaN, Float.NaN) == 0);
harness.check(Float.compare(0.0f, Float.NaN) < 0);
harness.check(Float.compare(0.0f, -0.0f) > 0);
harness.check(Float.compare(-0.0f, 0.0f) < 0);
}
}
| 2,100
|
Java
|
.java
| 46
| 42.434783
| 88
| 0.728165
|
ingelabs/mauve
| 3
| 2
| 0
|
GPL-2.0
|
9/4/2024, 11:38:21 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 2,100
|
1,318,574
|
B.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test16/out/B.java
|
package p;
class B{
public static void m(){
A.F= null;
A.F= null;
A.F= null;
A.F= null;
A.F= null;
A.F= null;
}
}
| 128
|
Java
|
.java
| 11
| 9.363636
| 24
| 0.57265
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 128
|
1,405,960
|
castle.java
|
oonym_l2InterludeServer/L2J_Server/java/net/sf/l2j/gameserver/handler/voicedcommandhandlers/castle.java
|
/*
* 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, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* http://www.gnu.org/copyleft/gpl.html
*/
package net.sf.l2j.gameserver.handler.voicedcommandhandlers;
import net.sf.l2j.gameserver.handler.IVoicedCommandHandler;
import net.sf.l2j.gameserver.instancemanager.CastleManager;
import net.sf.l2j.gameserver.model.actor.instance.L2DoorInstance;
import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
import net.sf.l2j.gameserver.model.entity.Castle;
import net.sf.l2j.gameserver.serverpackets.Ride;
/**
*
*
*/
public class castle implements IVoicedCommandHandler
{
private static final String[] VOICED_COMMANDS =
{
"open doors",
"close doors",
"ride wyvern"
};
@Override
public boolean useVoicedCommand(String command, L2PcInstance activeChar, String target)
{
if (command.startsWith("open doors") && target.equals("castle") && (activeChar.isClanLeader()))
{
L2DoorInstance door = (L2DoorInstance) activeChar.getTarget();
Castle castle = CastleManager.getInstance().getCastleById(activeChar.getClan().getHasCastle());
if ((door == null) || (castle == null))
{
return false;
}
if (castle.checkIfInZone(door.getX(), door.getY(), door.getZ()))
{
door.openMe();
}
}
else if (command.startsWith("close doors") && target.equals("castle") && (activeChar.isClanLeader()))
{
L2DoorInstance door = (L2DoorInstance) activeChar.getTarget();
Castle castle = CastleManager.getInstance().getCastleById(activeChar.getClan().getHasCastle());
if ((door == null) || (castle == null))
{
return false;
}
if (castle.checkIfInZone(door.getX(), door.getY(), door.getZ()))
{
door.closeMe();
}
}
else if (command.startsWith("ride wyvern") && target.equals("castle"))
{
if ((activeChar.getClan().getHasCastle() > 0) && activeChar.isClanLeader())
{
if (!activeChar.disarmWeapons())
{
return false;
}
Ride mount = new Ride(activeChar.getObjectId(), Ride.ACTION_MOUNT, 12621);
activeChar.sendPacket(mount);
activeChar.broadcastPacket(mount);
activeChar.setMountType(mount.getMountType());
}
}
return true;
}
@Override
public String[] getVoicedCommandList()
{
return VOICED_COMMANDS;
}
}
| 2,981
|
Java
|
.java
| 88
| 29.715909
| 104
| 0.709902
|
oonym/l2InterludeServer
| 22
| 13
| 0
|
GPL-2.0
|
9/4/2024, 7:49:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| true
| true
| 2,981
|
1,318,234
|
A_testGenerics2_out.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ConvertAnonymousToNested/canConvert/A_testGenerics2_out.java
|
package p;
//public, nonstatic, final
class A<T>{
public final class Inner extends A<T> {
}
void f(){
new Inner();
}
}
| 126
|
Java
|
.java
| 9
| 12.222222
| 40
| 0.672414
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 126
|
4,322,389
|
SolidityContract.java
|
VictorGil_social-ledger/src/main/java/org/ethereum/util/blockchain/SolidityContract.java
|
/*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ 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.
*
* The ethereumJ 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 the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.util.blockchain;
import org.ethereum.core.Block;
/**
* Interface to Ethereum contract compiled with Solidity with
* respect to language function signatures encoding and
* storage layout
*
* Below is Java <=> Solidity types mapping:
*
* Input arguments Java -> Solidity mapping is the following:
* Number, BigInteger, String (hex) -> any integer type
* byte[], String (hex) -> bytesN, byte[]
* String -> string
* Java array of the above types -> Solidity dynamic array of the corresponding type
*
* Output arguments Solidity -> Java mapping:
* any integer type -> BigInteger
* string -> String
* bytesN, byte[] -> byte[]
* Solidity dynamic array -> Java array
*
* Created by Anton Nashatyrev on 23.03.2016.
*/
public interface SolidityContract extends Contract {
/**
* Submits the transaction which invokes the specified contract function
* with corresponding arguments
*
* TODO: either return pending transaction execution result
* or return Future which is available upon block including trnasaction
* or combine both approaches
*/
SolidityCallResult callFunction(String functionName, Object ... args);
/**
* Submits the transaction which invokes the specified contract function
* with corresponding arguments and sends the specified value to the contract
*/
SolidityCallResult callFunction(long value, String functionName, Object ... args);
/**
* Call the function without submitting a transaction and without
* modifying the contract state.
* Synchronously returns function execution result
* (see output argument mapping in class doc)
*/
Object[] callConstFunction(String functionName, Object ... args);
/**
* Call the function without submitting a transaction and without
* modifying the contract state. The function is executed with the
* contract state actual after including the specified block.
*
* Synchronously returns function execution result
* (see output argument mapping in class doc)
*/
Object[] callConstFunction(Block callBlock, String functionName, Object... args);
/**
* Gets the contract function. This object can be passed as a call argument for another
* function with a function type parameter
*/
SolidityFunction getFunction(String name);
/**
* Returns the Solidity JSON ABI (Application Binary Interface)
*/
String getABI();
}
| 3,302
|
Java
|
.java
| 81
| 36.962963
| 91
| 0.728914
|
VictorGil/social-ledger
| 2
| 0
| 0
|
GPL-3.0
|
9/5/2024, 12:09:08 AM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 3,302
|
3,796,018
|
StatLong.java
|
lifeofcoder_jdk8u/jdk/src/share/classes/sun/java2d/marlin/stats/StatLong.java
|
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.java2d.marlin.stats;
/**
* Statistics as long values
*/
public class StatLong {
public final String name;
public long count = 0l;
public long sum = 0l;
public long min = Integer.MAX_VALUE;
public long max = Integer.MIN_VALUE;
public StatLong(final String name) {
this.name = name;
}
public void reset() {
count = 0l;
sum = 0l;
min = Integer.MAX_VALUE;
max = Integer.MIN_VALUE;
}
public void add(final int val) {
count++;
sum += val;
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
}
public void add(final long val) {
count++;
sum += val;
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(128);
toString(sb);
return sb.toString();
}
public final StringBuilder toString(final StringBuilder sb) {
sb.append(name).append('[').append(count);
sb.append("] sum: ").append(sum).append(" avg: ");
sb.append(trimTo3Digits(((double) sum) / count));
sb.append(" [").append(min).append(" | ").append(max).append("]");
return sb;
}
/**
* Adjust the given double value to keep only 3 decimal digits
*
* @param value value to adjust
* @return double value with only 3 decimal digits
*/
public static double trimTo3Digits(final double value) {
return ((long) (1e3d * value)) / 1e3d;
}
}
| 2,871
|
Java
|
.java
| 86
| 27.72093
| 76
| 0.642754
|
lifeofcoder/jdk8u
| 3
| 3
| 0
|
GPL-2.0
|
9/4/2024, 11:42:40 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 2,871
|
1,320,628
|
A.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameMethodInInterface/test20/in/A.java
|
//renaming I.m to k
package p;
interface I {
void m();
}
interface J{
void m();
}
interface J2 extends J{
void m();
}
class A{
public void m(){}
}
class C extends A implements I, J{
}
| 188
|
Java
|
.java
| 16
| 10.5
| 34
| 0.686047
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 188
|
4,613,360
|
TaskEditorBloatMonitor.java
|
eclipse-mylyn_org_eclipse_mylyn_tasks/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TaskEditorBloatMonitor.java
|
/*******************************************************************************
* Copyright (c) 2004, 2012 Tasktop Technologies 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
* https://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.mylyn.tasks.ui.editors.TaskEditor;
import org.eclipse.mylyn.tasks.ui.editors.TaskEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
/**
* @author Mik Kersten
* @author Steffen Pingel
*/
public class TaskEditorBloatMonitor {
private final static int MAX_EDITORS = 12;
public static void editorOpened(IEditorPart editorPartOpened) {
IWorkbenchPage page = editorPartOpened.getSite().getPage();
List<IEditorReference> toClose = new ArrayList<IEditorReference>();
int totalTaskEditors = 0;
for (IEditorReference editorReference : page.getEditorReferences()) {
if (TaskEditor.ID_EDITOR.equals(editorReference.getId())) {
totalTaskEditors++;
}
}
if (totalTaskEditors > MAX_EDITORS) {
for (IEditorReference editorReference : page.getEditorReferences()) {
try {
if (editorPartOpened != editorReference.getPart(false)
&& TaskEditor.ID_EDITOR.equals(editorReference.getId())) {
TaskEditorInput taskEditorInput = (TaskEditorInput) editorReference.getEditorInput();
TaskEditor taskEditor = (TaskEditor) editorReference.getEditor(false);
if (taskEditor == null) {
toClose.add(editorReference);
} else if (!taskEditor.equals(editorPartOpened) && !taskEditor.isDirty()
&& taskEditorInput.getTask() != null
&& taskEditorInput.getTask().getSynchronizationState().isSynchronized()) {
toClose.add(editorReference);
}
}
if ((totalTaskEditors - toClose.size()) <= MAX_EDITORS) {
break;
}
} catch (PartInitException e) {
// ignore
}
}
}
if (toClose.size() > 0) {
page.closeEditors(toClose.toArray(new IEditorReference[toClose.size()]), true);
}
}
}
| 2,454
|
Java
|
.java
| 64
| 34.59375
| 91
| 0.688655
|
eclipse-mylyn/org.eclipse.mylyn.tasks
| 2
| 0
| 4
|
EPL-2.0
|
9/5/2024, 12:19:21 AM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 2,454
|
2,513,783
|
pjsip_redirect_op.java
|
caihongwang_ChatMe/src/org/pjsip/pjsua/pjsip_redirect_op.java
|
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.8
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.pjsip.pjsua;
public enum pjsip_redirect_op {
PJSIP_REDIRECT_REJECT,
PJSIP_REDIRECT_ACCEPT,
PJSIP_REDIRECT_PENDING,
PJSIP_REDIRECT_STOP;
public final int swigValue() {
return swigValue;
}
public static pjsip_redirect_op swigToEnum(int swigValue) {
pjsip_redirect_op[] swigValues = pjsip_redirect_op.class.getEnumConstants();
if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue)
return swigValues[swigValue];
for (pjsip_redirect_op swigEnum : swigValues)
if (swigEnum.swigValue == swigValue)
return swigEnum;
throw new IllegalArgumentException("No enum " + pjsip_redirect_op.class + " with value " + swigValue);
}
@SuppressWarnings("unused")
private pjsip_redirect_op() {
this.swigValue = SwigNext.next++;
}
@SuppressWarnings("unused")
private pjsip_redirect_op(int swigValue) {
this.swigValue = swigValue;
SwigNext.next = swigValue+1;
}
@SuppressWarnings("unused")
private pjsip_redirect_op(pjsip_redirect_op swigEnum) {
this.swigValue = swigEnum.swigValue;
SwigNext.next = this.swigValue+1;
}
private final int swigValue;
private static class SwigNext {
private static int next = 0;
}
}
| 1,632
|
Java
|
.java
| 44
| 33.363636
| 106
| 0.65526
|
caihongwang/ChatMe
| 7
| 8
| 1
|
LGPL-3.0
|
9/4/2024, 9:43:57 PM (Europe/Amsterdam)
| false
| true
| true
| true
| false
| true
| true
| true
| 1,632
|
2,762,433
|
Alpha.java
|
zeruth_RuneLitePlus-Injector/RuneLitePlus/src/main/java/net/runelite/client/config/Alpha.java
|
/*
* Copyright (c) 2018, Ron Young <https://github.com/raiyni>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.config;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Used with ConfigItem, determines if to use alpha slider on colors
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Alpha
{
}
| 1,819
|
Java
|
.java
| 39
| 44.923077
| 82
| 0.792909
|
zeruth/RuneLitePlus-Injector
| 6
| 8
| 0
|
AGPL-3.0
|
9/4/2024, 10:13:45 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 1,819
|
1,314,878
|
Foo.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceIndirection/test20/out/Foo.java
|
package p;
public class Foo<E, F, G extends Comparable<E>> {
/**
* @param <E>
* @param <F>
* @param <G>
* @param <H>
* @param foo
* @param h
* @return
*/
public static <E, F, G extends Comparable<E>, H> H bar(Foo<E, F, G> foo, H h) {
return foo.getFoo(h);
}
<H> H getFoo(H h) {
return null;
}
{
Foo f= new Foo();
Foo.bar(f, null); // <-- invoke here
}
}
| 392
|
Java
|
.java
| 22
| 15.090909
| 80
| 0.559229
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 392
|
49,428
|
OnItemClickListener.java
|
SuperMonster003_AutoJs6/app/src/main/java/org/autojs/autojs/ui/widget/OnItemClickListener.java
|
package org.autojs.autojs.ui.widget;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
/**
* Created by Stardust on Mar 27, 2017.
*/
public interface OnItemClickListener {
void onItemClick(RecyclerView parent, View item, int position);
}
| 274
|
Java
|
.java
| 9
| 28.333333
| 67
| 0.800766
|
SuperMonster003/AutoJs6
| 2,371
| 703
| 117
|
MPL-2.0
|
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| true
| true
| true
| 274
|
1,315,896
|
Froehlichkeit.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/InlineConstant/canInline/test15/in/Froehlichkeit.java
|
// 14, 16 -> 14, 32 replaceAll == true, removeDeclaration == false
package schweiz.zuerich.zuerich;
public abstract class Froehlichkeit {
static class MeineFroehlichkeit extends Froehlichkeit {
MeineFroehlichkeit(Object o) {}
}
private static Object something= new Object();
private static final Froehlichkeit dieFroehlichkeit= new MeineFroehlichkeit(something);
public Froehlichkeit holenFroehlichkeit() {
class MeineFroehlichkeit {
}
return dieFroehlichkeit;
}
public Froehlichkeit deineFroehlichkeit() {
Object something= "";
return dieFroehlichkeit;
}
}
| 581
|
Java
|
.java
| 18
| 30.055556
| 88
| 0.798574
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 581
|
1,315,099
|
C.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameNonPrivateField/testEnumConst/out/C.java
|
import static p.A.*;
import p.A;
public class C {
public boolean foo() {
return REDDISH == A.GREEN.REDDISH;
}
}
| 116
|
Java
|
.java
| 7
| 15
| 36
| 0.697248
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 116
|
4,473,633
|
Request.java
|
GeoscienceAustralia_FSDF-Metadata-Tool/core/src/main/java/org/fao/geonet/kernel/region/Request.java
|
/*
* Copyright (C) 2001-2016 Food and Agriculture Organization of the
* United Nations (FAO-UN), United Nations World Food Programme (WFP)
* and United Nations Environment Programme (UNEP)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
* Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
* Rome - Italy. email: [email protected]
*/
package org.fao.geonet.kernel.region;
import com.google.common.base.Optional;
import org.jdom.Element;
import java.util.Collection;
/**
* Represents a search request for regions. All predicates will be ORed together.
*
* @author jeichar
*/
public abstract class Request {
public static final String REGIONS_EL = "regions";
private static final String COUNT_ATT = "count";
/**
* Add label search predicate to the search request. If this method is called multiple times
* the predicates are ORed together. IE it will find regions that contains label1 OR label2
*
* @return this
*/
public abstract Request label(String labelParam);
/**
* Add categoryId search predicate to the search request. If this method is called multiple
* times the predicates are ORed together. IE it will find regions that are either in label1 OR
* label2
*
* @return this
*/
public abstract Request categoryId(String categoryIdParam);
/**
* Set the max number of results that will be loaded. A value < 0 will load all results
*
* @return this
*/
public abstract Request maxRecords(int maxRecordsParam);
/**
* Execute the request and get the matching regions
*
* @return the collection of Regions found that match the predicates
*/
public abstract Collection<Region> execute() throws Exception;
/**
* Add an region id search predicate to the search request. If this method is called multiple
* times the predicates are ORed together. IE it will find regions that have EITHER id1 OR
* id2
*
* @return this
*/
public abstract Request id(String regionId);
/**
* Executes query and returns the found region or null. IllegalStateException is thrown if
* there is > 1 results.
*
* @return the region or null
* @throws IllegalStateException if there was more than one region found
*/
public Region get() throws Exception {
Collection<Region> regions = execute();
if (regions.size() > 1) {
throw new IllegalStateException("there is more than one region found");
}
if (regions.isEmpty()) {
return null;
} else {
return regions.iterator().next();
}
}
/**
* Formats all the regions found as xml
*/
public Element xmlResult() throws Exception {
Collection<Region> regions = execute();
Element result = new Element(REGIONS_EL).setAttribute("class", "array");
result.setAttribute(COUNT_ATT, Integer.toString(regions.size()));
for (Region region : regions) {
result.addContent(region.toElement());
}
return result;
}
/**
* Given the request information attempt to determine the last modified value.
*
* This should be an efficient operation if the operation takes too long to determine (for
* example loading many regions and determining the last modified of all of them) then {@link
* Long#MAX_VALUE} should be returned. This will mean that the lastModified check will be
* skipped and the response will be returned to the client each time.
*
* {@link Long#MAX_VALUE} can also be returned if it is too difficult (implementation wise or
* otherwise)
*
* If the id or category id does not apply then Optional.absent() should be returned since this
* should not affect the last modified score. This can be used as a kind of "applicable"
*
* Examples: <ul> <li> If the request is a category or a specific region ID it can be easily
* calculated what the last modified date was. </li> <li> The last modified date is known for
* the entire data set then it can be easily calculated for any request </li> <li> If each
* category could have a different last modified then perhaps only id and category requests can
* have a last modified or the most recent last modified of all categories could be the taken
* </li> </ul>
*
* @return Optional.absent() if the search parameters are not applicable to this Region
* implementation, {@link Long#MAX_VALUE} if the value cannot be accurately calculated for the
* parameters set on the search object otherwise the last modified value of the last modified
* region that would be in the response if request is executed.
*/
public abstract Optional<Long> getLastModified() throws Exception;
}
| 5,555
|
Java
|
.java
| 127
| 38.385827
| 100
| 0.701515
|
GeoscienceAustralia/FSDF-Metadata-Tool
| 2
| 0
| 0
|
GPL-2.0
|
9/5/2024, 12:14:28 AM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 5,555
|
2,044,626
|
SafeClose.java
|
AstroImageJ_astroimagej/Nom_Fits/src/main/java/nom/tam/util/SafeClose.java
|
package nom.tam.util;
/*
* #%L
* nom.tam FITS library
* %%
* Copyright (C) 1996 - 2024 nom-tam-fits
* %%
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
* #L%
*/
import java.io.Closeable;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @deprecated Use <b>try-with-resources</b> constructs of Java 8+ instead.
*/
public final class SafeClose {
private static final Logger LOG = LoggerHelper.getLogger(SafeClose.class);
private SafeClose() {
// Not needed
}
/**
* Attmpts to an IO resources catching any {@link IOException} that might
* result. If the resource cannot be closed, the class will log the
* exception, but return normally.
*
* @param io
* The IO resource to close.
*/
public static void close(Closeable io) {
if (io != null) {
try {
io.close();
} catch (IOException e) {
LOG.log(Level.WARNING, "could not close stream: " + e.getMessage(), e);
}
}
}
}
| 2,254
|
Java
|
.java
| 61
| 32.852459
| 87
| 0.699588
|
AstroImageJ/astroimagej
| 13
| 10
| 36
|
GPL-3.0
|
9/4/2024, 8:27:28 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| true
| true
| 2,254
|
3,785,820
|
TargetOwnerPet.java
|
Hl4p3x_L2jaCis/aCis_gameserver/java/net/sf/l2j/gameserver/handler/targethandlers/TargetOwnerPet.java
|
package net.sf.l2j.gameserver.handler.targethandlers;
import net.sf.l2j.gameserver.enums.skills.SkillTargetType;
import net.sf.l2j.gameserver.handler.ITargetHandler;
import net.sf.l2j.gameserver.model.actor.Creature;
import net.sf.l2j.gameserver.model.actor.Playable;
import net.sf.l2j.gameserver.model.actor.Summon;
import net.sf.l2j.gameserver.network.SystemMessageId;
import net.sf.l2j.gameserver.network.serverpackets.SystemMessage;
import net.sf.l2j.gameserver.skills.L2Skill;
public class TargetOwnerPet implements ITargetHandler
{
@Override
public SkillTargetType getTargetType()
{
return SkillTargetType.OWNER_PET;
}
@Override
public Creature[] getTargetList(Creature caster, Creature target, L2Skill skill)
{
if (!(caster instanceof Summon))
return EMPTY_TARGET_ARRAY;
return new Creature[]
{
caster.getActingPlayer()
};
}
@Override
public Creature getFinalTarget(Creature caster, Creature target, L2Skill skill)
{
if (!(caster instanceof Summon))
return null;
return caster.getActingPlayer();
}
@Override
public boolean meetCastConditions(Playable caster, Creature target, L2Skill skill, boolean isCtrlPressed)
{
if (target == null || caster.getActingPlayer() != target)
{
caster.sendPacket(SystemMessageId.INVALID_TARGET);
return false;
}
if (target.isDead())
{
caster.sendPacket(SystemMessage.getSystemMessage(SystemMessageId.S1_CANNOT_BE_USED).addSkillName(skill));
return false;
}
return true;
}
}
| 1,493
|
Java
|
.java
| 49
| 27.816327
| 108
| 0.798319
|
Hl4p3x/L2jaCis
| 3
| 1
| 0
|
GPL-3.0
|
9/4/2024, 11:42:16 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 1,493
|
1,316,217
|
A.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface/test36/in/A.java
|
package p;
class A {
public void m() {}
public void m1() {}
void test(){
A a0= new A();
f(a0);
}
void f(A a){
a.m1();
}
}
| 134
|
Java
|
.java
| 12
| 9.166667
| 20
| 0.532787
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 134
|
1,319,550
|
A_test1120.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/generics_out/A_test1120.java
|
package generics_out;
public class A_test1120 {
<T extends Comparable<? super T>> void method(List<T> list) {
extracted(list);
}
protected <T extends Comparable<? super T>> void extracted(List<T> list) {
/*[*/toExtract(list);/*]*/
}
static <T extends Comparable<? super T>> void toExtract(List<T> list) {
return;
}
}
| 333
|
Java
|
.java
| 12
| 25.416667
| 75
| 0.694006
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 333
|
1,310,080
|
ZAutoCompleteMatch.java
|
zextras_carbonio-mailbox/client/src/main/java/com/zimbra/client/ZAutoCompleteMatch.java
|
// SPDX-FileCopyrightText: 2022 Synacor, Inc.
// SPDX-FileCopyrightText: 2022 Zextras <https://www.zextras.com>
//
// SPDX-License-Identifier: GPL-2.0-only
package com.zimbra.client;
import org.json.JSONException;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.soap.Element;
import com.zimbra.common.soap.MailConstants;
import java.util.Comparator;
public class ZAutoCompleteMatch implements ToZJSONObject {
private String mRanking;
private String mType;
private String mEmail;
private String mFolderId;
private String mId;
private String mDisplay;
private String mFirstName;
private String mMiddleName;
private String mLastName;
private String mFullName;
private String mNickname;
private String mCompany;
private String mFileAs;
private boolean isGroup;
private boolean exp;
private ZMailbox mMailbox;
public ZAutoCompleteMatch(Element e, ZMailbox mailbox) throws ServiceException {
mMailbox = mailbox;
mRanking = e.getAttribute(MailConstants.A_RANKING);
mType = e.getAttribute(MailConstants.A_MATCH_TYPE);
mEmail = e.getAttribute(MailConstants.A_EMAIL, null);
mFolderId = e.getAttribute(MailConstants.A_FOLDER, null);
mId = e.getAttribute(MailConstants.A_ID, null);
mDisplay = e.getAttribute(MailConstants.A_DISPLAYNAME, null);
isGroup = e.getAttributeBool(MailConstants.A_IS_GROUP, false);
exp = e.getAttributeBool(MailConstants.A_EXP, false);
mFirstName = e.getAttribute(MailConstants.A_FIRSTNAME, null);
mMiddleName = e.getAttribute(MailConstants.A_MIDDLENAME, null);
mLastName = e.getAttribute(MailConstants.A_LASTNAME, null);
mFullName = e.getAttribute(MailConstants.A_FULLNAME, null);
mNickname = e.getAttribute(MailConstants.A_NICKNAME, null);
mCompany = e.getAttribute(MailConstants.A_COMPANY, null);
mFileAs = e.getAttribute(MailConstants.A_FILEAS, null);
}
public ZMailbox getMailbox() {
return mMailbox;
}
public String getRanking() {
return mRanking;
}
public String getType() {
return mType;
}
public String getFolderId() {
return mFolderId;
}
public ZFolder getFolder() throws ServiceException {
return mMailbox.getFolderById(mFolderId);
}
public String getId() {
return mId;
}
public boolean isGalContact() {
return mType.equals("gal");
}
public String getEmail() {
return mEmail;
}
public String getDisplayName() {
return mDisplay;
}
public String getValue() {
if (mDisplay != null)
return mDisplay;
return mEmail;
}
public String getFirstName() {
return mFirstName;
}
public String getMiddleName() {
return mMiddleName;
}
public String getLastName() {
return mLastName;
}
public String getFullName() {
return mFullName;
}
public String getNickname() {
return mNickname;
}
public String getCompany() {
return mCompany;
}
public String getFileAs() {
return mFileAs;
}
public ZJSONObject toZJSONObject() throws JSONException {
ZJSONObject jo = new ZJSONObject();
jo.put("ranking", mRanking);
jo.put("type", mType);
if (mEmail != null) jo.put("email", mEmail);
if (mFolderId != null) jo.put("l", mFolderId);
if (mId != null) jo.put("id", mId);
if (mDisplay != null) jo.put("display", mDisplay);
if (isGroup) jo.put("isGroup", isGroup);
if (exp) jo.put("exp", exp);
if (mFirstName != null) jo.put("first", mFirstName);
if (mMiddleName != null) jo.put("middle", mMiddleName);
if (mLastName != null) jo.put("last", mLastName);
if (mFullName != null) jo.put("full", mFullName);
if (mNickname != null) jo.put("nick", mNickname);
if (mCompany != null) jo.put("company", mCompany);
if (mFileAs != null) jo.put("fileas", mFileAs);
return jo;
}
public String dump() {
return ZJSONObject.toString(this);
}
public static class MatchComparator implements Comparator<ZAutoCompleteMatch> {
public int compare(ZAutoCompleteMatch a, ZAutoCompleteMatch b) {
int r1 = Integer.parseInt(a.mRanking);
int r2 = Integer.parseInt(b.mRanking);
if (r1 != r2)
return r1 - r2;
if (a.isGalContact() ^ !b.isGalContact())
return a.isGalContact() ? 1 : -1;
return a.getValue().compareTo(b.getValue());
}
}
}
| 4,625
|
Java
|
.java
| 132
| 29.045455
| 84
| 0.668011
|
zextras/carbonio-mailbox
| 32
| 6
| 6
|
GPL-2.0
|
9/4/2024, 7:33:43 PM (Europe/Amsterdam)
| false
| true
| false
| true
| true
| true
| true
| true
| 4,625
|
867,611
|
JsonRpc2_0Rx.java
|
bing-chou_etherscan-explorer/web3j-app/core/src/main/java/org/web3j/protocol/rx/JsonRpc2_0Rx.java
|
package org.web3j.protocol.rx;
import java.io.IOException;
import java.math.BigInteger;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors;
import rx.Observable;
import rx.Scheduler;
import rx.Subscriber;
import rx.schedulers.Schedulers;
import rx.subscriptions.Subscriptions;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.DefaultBlockParameterNumber;
import org.web3j.protocol.core.filters.BlockFilter;
import org.web3j.protocol.core.filters.LogFilter;
import org.web3j.protocol.core.filters.PendingTransactionFilter;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.core.methods.response.Log;
import org.web3j.protocol.core.methods.response.Transaction;
import org.web3j.utils.Observables;
/**
* web3j reactive API implementation.
*/
public class JsonRpc2_0Rx {
private final Web3j web3j;
private final ScheduledExecutorService scheduledExecutorService;
private final Scheduler scheduler;
public JsonRpc2_0Rx(Web3j web3j, ScheduledExecutorService scheduledExecutorService) {
this.web3j = web3j;
this.scheduledExecutorService = scheduledExecutorService;
this.scheduler = Schedulers.from(scheduledExecutorService);
}
public Observable<String> ethBlockHashObservable(long pollingInterval) {
return Observable.create(subscriber -> {
BlockFilter blockFilter = new BlockFilter(
web3j, subscriber::onNext);
run(blockFilter, subscriber, pollingInterval);
});
}
public Observable<String> ethPendingTransactionHashObservable(long pollingInterval) {
return Observable.create(subscriber -> {
PendingTransactionFilter pendingTransactionFilter = new PendingTransactionFilter(
web3j, subscriber::onNext);
run(pendingTransactionFilter, subscriber, pollingInterval);
});
}
public Observable<Log> ethLogObservable(
org.web3j.protocol.core.methods.request.EthFilter ethFilter, long pollingInterval) {
return Observable.create((Subscriber<? super Log> subscriber) -> {
LogFilter logFilter = new LogFilter(
web3j, subscriber::onNext, ethFilter);
run(logFilter, subscriber, pollingInterval);
});
}
private <T> void run(
org.web3j.protocol.core.filters.Filter<T> filter, Subscriber<? super T> subscriber,
long pollingInterval) {
filter.run(scheduledExecutorService, pollingInterval);
subscriber.add(Subscriptions.create(filter::cancel));
}
public Observable<Transaction> transactionObservable(long pollingInterval) {
return blockObservable(true, pollingInterval)
.flatMapIterable(JsonRpc2_0Rx::toTransactions);
}
public Observable<Transaction> pendingTransactionObservable(long pollingInterval) {
return ethPendingTransactionHashObservable(pollingInterval)
.flatMap(transactionHash ->
web3j.ethGetTransactionByHash(transactionHash).observable())
.filter(ethTransaction -> ethTransaction.getTransaction().isPresent())
.map(ethTransaction -> ethTransaction.getTransaction().get());
}
public Observable<EthBlock> blockObservable(
boolean fullTransactionObjects, long pollingInterval) {
return ethBlockHashObservable(pollingInterval)
.flatMap(blockHash ->
web3j.ethGetBlockByHash(blockHash, fullTransactionObjects).observable());
}
public Observable<EthBlock> replayBlocksObservable(
DefaultBlockParameter startBlock, DefaultBlockParameter endBlock,
boolean fullTransactionObjects) {
return replayBlocksObservable(startBlock, endBlock, fullTransactionObjects, true);
}
public Observable<EthBlock> replayBlocksObservable(
DefaultBlockParameter startBlock, DefaultBlockParameter endBlock,
boolean fullTransactionObjects, boolean ascending) {
// We use a scheduler to ensure this Observable runs asynchronously for users to be
// consistent with the other Observables
return replayBlocksObservableSync(startBlock, endBlock, fullTransactionObjects, ascending)
.subscribeOn(scheduler);
}
private Observable<EthBlock> replayBlocksObservableSync(
DefaultBlockParameter startBlock, DefaultBlockParameter endBlock,
boolean fullTransactionObjects) {
return replayBlocksObservableSync(startBlock, endBlock, fullTransactionObjects, true);
}
private Observable<EthBlock> replayBlocksObservableSync(
DefaultBlockParameter startBlock, DefaultBlockParameter endBlock,
boolean fullTransactionObjects, boolean ascending) {
BigInteger startBlockNumber = null;
BigInteger endBlockNumber = null;
try {
startBlockNumber = getBlockNumber(startBlock);
endBlockNumber = getBlockNumber(endBlock);
} catch (IOException e) {
Observable.error(e);
}
if (ascending) {
return Observables.range(startBlockNumber, endBlockNumber)
.flatMap(i -> web3j.ethGetBlockByNumber(
new DefaultBlockParameterNumber(i),
fullTransactionObjects).observable());
} else {
return Observables.range(startBlockNumber, endBlockNumber, false)
.flatMap(i -> web3j.ethGetBlockByNumber(
new DefaultBlockParameterNumber(i),
fullTransactionObjects).observable());
}
}
public Observable<Transaction> replayTransactionsObservable(
DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {
return replayBlocksObservable(startBlock, endBlock, true)
.flatMapIterable(JsonRpc2_0Rx::toTransactions);
}
public Observable<EthBlock> catchUpToLatestBlockObservable(
DefaultBlockParameter startBlock, boolean fullTransactionObjects,
Observable<EthBlock> onCompleteObservable) {
// We use a scheduler to ensure this Observable runs asynchronously for users to be
// consistent with the other Observables
return catchUpToLatestBlockObservableSync(
startBlock, fullTransactionObjects, onCompleteObservable)
.subscribeOn(scheduler);
}
public Observable<EthBlock> catchUpToLatestBlockObservable(
DefaultBlockParameter startBlock, boolean fullTransactionObjects) {
return catchUpToLatestBlockObservable(
startBlock, fullTransactionObjects, Observable.empty());
}
private Observable<EthBlock> catchUpToLatestBlockObservableSync(
DefaultBlockParameter startBlock, boolean fullTransactionObjects,
Observable<EthBlock> onCompleteObservable) {
BigInteger startBlockNumber;
BigInteger latestBlockNumber;
try {
startBlockNumber = getBlockNumber(startBlock);
latestBlockNumber = getLatestBlockNumber();
} catch (IOException e) {
return Observable.error(e);
}
if (startBlockNumber.compareTo(latestBlockNumber) > -1) {
return onCompleteObservable;
} else {
return Observable.concat(
replayBlocksObservableSync(
new DefaultBlockParameterNumber(startBlockNumber),
new DefaultBlockParameterNumber(latestBlockNumber),
fullTransactionObjects),
Observable.defer(() -> catchUpToLatestBlockObservableSync(
new DefaultBlockParameterNumber(latestBlockNumber.add(BigInteger.ONE)),
fullTransactionObjects,
onCompleteObservable)));
}
}
public Observable<Transaction> catchUpToLatestTransactionObservable(
DefaultBlockParameter startBlock) {
return catchUpToLatestBlockObservable(
startBlock, true, Observable.empty())
.flatMapIterable(JsonRpc2_0Rx::toTransactions);
}
public Observable<EthBlock> catchUpToLatestAndSubscribeToNewBlocksObservable(
DefaultBlockParameter startBlock, boolean fullTransactionObjects,
long pollingInterval) {
return catchUpToLatestBlockObservable(
startBlock, fullTransactionObjects,
blockObservable(fullTransactionObjects, pollingInterval));
}
public Observable<Transaction> catchUpToLatestAndSubscribeToNewTransactionsObservable(
DefaultBlockParameter startBlock, long pollingInterval) {
return catchUpToLatestAndSubscribeToNewBlocksObservable(
startBlock, true, pollingInterval)
.flatMapIterable(JsonRpc2_0Rx::toTransactions);
}
private BigInteger getLatestBlockNumber() throws IOException {
return getBlockNumber(DefaultBlockParameterName.LATEST);
}
private BigInteger getBlockNumber(
DefaultBlockParameter defaultBlockParameter) throws IOException {
if (defaultBlockParameter instanceof DefaultBlockParameterNumber) {
return ((DefaultBlockParameterNumber) defaultBlockParameter).getBlockNumber();
} else {
EthBlock latestEthBlock = web3j.ethGetBlockByNumber(
defaultBlockParameter, false).send();
return latestEthBlock.getBlock().getNumber();
}
}
private static List<Transaction> toTransactions(EthBlock ethBlock) {
// If you ever see an exception thrown here, it's probably due to an incomplete chain in
// Geth/Parity. You should resync to solve.
return ethBlock.getBlock().getTransactions().stream()
.map(transactionResult -> (Transaction) transactionResult.get())
.collect(Collectors.toList());
}
}
| 10,249
|
Java
|
.java
| 204
| 39.901961
| 99
| 0.702697
|
bing-chou/etherscan-explorer
| 70
| 53
| 5
|
GPL-3.0
|
9/4/2024, 7:09:22 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| true
| true
| true
| 10,249
|
4,895,392
|
FoHyphenationPushCharCountAttribute.java
|
jbjonesjr_geoproponis/external/odfdom-java-0.8.10-incubating-sources/org/odftoolkit/odfdom/dom/attribute/fo/FoHyphenationPushCharCountAttribute.java
|
/************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
*
* Use is subject to license terms.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0. You can also
* obtain a copy of the License at http://odftoolkit.org/docs/license.txt
*
* 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.
*
************************************************************************/
/*
* This file is automatically generated.
* Don't edit manually.
*/
package org.odftoolkit.odfdom.dom.attribute.fo;
import org.odftoolkit.odfdom.dom.OdfDocumentNamespace;
import org.odftoolkit.odfdom.pkg.OdfAttribute;
import org.odftoolkit.odfdom.pkg.OdfFileDom;
import org.odftoolkit.odfdom.pkg.OdfName;
/**
* DOM implementation of OpenDocument attribute {@odf.attribute fo:hyphenation-push-char-count}.
*
*/
public class FoHyphenationPushCharCountAttribute extends OdfAttribute {
public static final OdfName ATTRIBUTE_NAME = OdfName.newName(OdfDocumentNamespace.FO, "hyphenation-push-char-count");
/**
* Create the instance of OpenDocument attribute {@odf.attribute fo:hyphenation-push-char-count}.
*
* @param ownerDocument The type is <code>OdfFileDom</code>
*/
public FoHyphenationPushCharCountAttribute(OdfFileDom ownerDocument) {
super(ownerDocument, ATTRIBUTE_NAME);
}
/**
* Returns the attribute name.
*
* @return the <code>OdfName</code> for {@odf.attribute fo:hyphenation-push-char-count}.
*/
@Override
public OdfName getOdfName() {
return ATTRIBUTE_NAME;
}
/**
* @return Returns the name of this attribute.
*/
@Override
public String getName() {
return ATTRIBUTE_NAME.getLocalName();
}
/**
* @param value The <code>int</code> value of the attribute.
*/
public void setIntValue(int value) {
super.setValue(String.valueOf(value));
}
/**
* @return Returns the <code>int</code> value of the attribute
*/
public int intValue() {
String val = super.getValue();
try {
return Integer.parseInt(val);
} catch (NumberFormatException e) {
// TODO: validation handling/logging
throw (e);
}
}
/**
* Returns the default value of {@odf.attribute fo:hyphenation-push-char-count}.
*
* @return the default value as <code>String</code> dependent of its element name
* return <code>null</code> if the default value does not exist
*/
@Override
public String getDefault() {
return null;
}
/**
* Default value indicator. As the attribute default value is dependent from its element, the attribute has only a default, when a parent element exists.
*
* @return <code>true</code> if {@odf.attribute fo:hyphenation-push-char-count} has an element parent
* otherwise return <code>false</code> as undefined.
*/
@Override
public boolean hasDefault() {
return false;
}
/**
* @return Returns whether this attribute is known to be of type ID (i.e. xml:id ?)
*/
@Override
public boolean isId() {
return false;
}
}
| 3,520
|
Java
|
.java
| 106
| 30.783019
| 154
| 0.710464
|
jbjonesjr/geoproponis
| 1
| 0
| 0
|
GPL-2.0
|
9/5/2024, 12:35:10 AM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 3,520
|
867,748
|
Int120.java
|
bing-chou_etherscan-explorer/web3j-app/abi/src/main/java/org/web3j/abi/datatypes/generated/Int120.java
|
package org.web3j.abi.datatypes.generated;
import java.math.BigInteger;
import org.web3j.abi.datatypes.Int;
/**
* Auto generated code.
* <p><strong>Do not modifiy!</strong>
* <p>Please use org.web3j.codegen.AbiTypesGenerator in the
* <a href="https://github.com/web3j/web3j/tree/master/codegen">codegen module</a> to update.
*/
public class Int120 extends Int {
public static final Int120 DEFAULT = new Int120(BigInteger.ZERO);
public Int120(BigInteger value) {
super(120, value);
}
public Int120(long value) {
this(BigInteger.valueOf(value));
}
}
| 594
|
Java
|
.java
| 18
| 29.444444
| 93
| 0.722028
|
bing-chou/etherscan-explorer
| 70
| 53
| 5
|
GPL-3.0
|
9/4/2024, 7:09:22 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 594
|
1,316,757
|
A.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test52/in/A.java
|
package p;
class A {
B b;
void m(int i) {
}
}
class B extends A {
}
class C extends B {
void test() {
super.m(2);
}
}
| 127
|
Java
|
.java
| 13
| 8.076923
| 19
| 0.607143
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 127
|
3,269,632
|
ElementTypeRegistryTest.java
|
Samsung_gmf-runtime/org.eclipse.gmf.tests.runtime.emf.type.core/src/org/eclipse/gmf/tests/runtime/emf/type/core/ElementTypeRegistryTest.java
|
/******************************************************************************
* Copyright (c) 2005, 2015 IBM Corporation, Christian W. Damus, 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
*
* Contributors:
* IBM Corporation - initial API and implementation
* Christian W. Damus - bug 457888
****************************************************************************/
package org.eclipse.gmf.tests.runtime.emf.type.core;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import junit.framework.Test;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EcoreFactory;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.transaction.RecordingCommand;
import org.eclipse.emf.transaction.RollbackException;
import org.eclipse.emf.transaction.TransactionalCommandStack;
import org.eclipse.gmf.runtime.common.core.command.ICommand;
import org.eclipse.gmf.runtime.emf.type.core.AbstractAdviceBindingDescriptor;
import org.eclipse.gmf.runtime.emf.type.core.AdviceBindingAddedEvent;
import org.eclipse.gmf.runtime.emf.type.core.AdviceBindingInheritance;
import org.eclipse.gmf.runtime.emf.type.core.AdviceBindingRemovedEvent;
import org.eclipse.gmf.runtime.emf.type.core.ClientContextManager;
import org.eclipse.gmf.runtime.emf.type.core.EditHelperContext;
import org.eclipse.gmf.runtime.emf.type.core.ElementTypeAddedEvent;
import org.eclipse.gmf.runtime.emf.type.core.ElementTypeRegistry;
import org.eclipse.gmf.runtime.emf.type.core.ElementTypeRegistryAdapter;
import org.eclipse.gmf.runtime.emf.type.core.ElementTypeRemovedEvent;
import org.eclipse.gmf.runtime.emf.type.core.IAdviceBindingDescriptor;
import org.eclipse.gmf.runtime.emf.type.core.IClientContext;
import org.eclipse.gmf.runtime.emf.type.core.IContainerDescriptor;
import org.eclipse.gmf.runtime.emf.type.core.IEditHelperContext;
import org.eclipse.gmf.runtime.emf.type.core.IElementMatcher;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.emf.type.core.IElementTypeFactory;
import org.eclipse.gmf.runtime.emf.type.core.IElementTypeRegistryListener;
import org.eclipse.gmf.runtime.emf.type.core.IElementTypeRegistryListener2;
import org.eclipse.gmf.runtime.emf.type.core.IMetamodelType;
import org.eclipse.gmf.runtime.emf.type.core.ISpecializationType;
import org.eclipse.gmf.runtime.emf.type.core.MetamodelType;
import org.eclipse.gmf.runtime.emf.type.core.SpecializationType;
import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice;
import org.eclipse.gmf.runtime.emf.type.core.edithelper.IEditHelperAdvice;
import org.eclipse.gmf.runtime.emf.type.core.internal.impl.DefaultElementTypeFactory;
import org.eclipse.gmf.runtime.emf.type.core.internal.impl.DefaultMetamodelType;
import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest;
import org.eclipse.gmf.tests.runtime.emf.type.core.employee.Department;
import org.eclipse.gmf.tests.runtime.emf.type.core.employee.Employee;
import org.eclipse.gmf.tests.runtime.emf.type.core.employee.EmployeePackage;
import org.eclipse.gmf.tests.runtime.emf.type.core.employee.HighSchoolStudent;
import org.eclipse.gmf.tests.runtime.emf.type.core.employee.Office;
import org.eclipse.gmf.tests.runtime.emf.type.core.employee.Student;
import org.eclipse.gmf.tests.runtime.emf.type.core.internal.EmployeeType;
import org.eclipse.gmf.tests.runtime.emf.type.core.internal.ExecutiveEditHelperAdvice;
import org.eclipse.gmf.tests.runtime.emf.type.core.internal.FinanceEditHelperAdvice;
import org.eclipse.gmf.tests.runtime.emf.type.core.internal.ManagerEditHelperAdvice;
import org.eclipse.gmf.tests.runtime.emf.type.core.internal.NotInheritedEditHelperAdvice;
import org.eclipse.gmf.tests.runtime.emf.type.core.internal.SecurityClearedElementTypeFactory;
/**
* @author ldamus
*/
public class ElementTypeRegistryTest
extends AbstractEMFTypeTest {
private class MySpecializationAdvice extends AbstractEditHelperAdvice {
public MySpecializationAdvice() {
super();
}
protected ICommand getBeforeCreateCommand(CreateElementRequest request) {
return super.getBeforeCreateCommand(request);
}
}
private class MyAdvice extends AbstractEditHelperAdvice {
public MyAdvice() {
super();
}
protected ICommand getBeforeCreateCommand(CreateElementRequest request) {
return super.getBeforeCreateCommand(request);
}
}
private class MyAdviceBindingDescriptor extends AbstractAdviceBindingDescriptor {
public MyAdviceBindingDescriptor(String id, String typeID) {
super(id, typeID, AdviceBindingInheritance.ALL, new MyAdvice());
}
public IElementMatcher getMatcher() {
return null;
}
public IContainerDescriptor getContainerDescriptor() {
return null;
}
}
private ElementTypeRegistry fixture = null;
private IClientContext clientContext;
private IClientContext unboundClientContext;
// Model elements
private Department department;
private Department executiveDepartment;
private Department financeDepartment;
private Employee employee;
private Employee financeEmployee;
private Employee financeManager;
private Student student;
private HighSchoolStudent highSchoolStudent;
private Office employeeOffice;
private Office studentOffice;
private Employee manager;
private Office managerOffice;
private Employee executive;
private Office executiveOffice;
// Model elements in resource with context
private Department cDepartment;
private Department cExecutiveDepartment;
private Department cFinanceDepartment;
private Employee cEmployee;
private Employee cFinanceEmployee;
private Employee cFinanceManager;
private Student cStudent;
private Office cEmployeeOffice;
private Office cStudentOffice;
private Employee cManager;
private Office cManagerOffice;
private Employee cExecutive;
private Office cExecutiveOffice;
/**
* Constructor for CreateDiagramCommandTest.
*
* @param name
*/
public ElementTypeRegistryTest(String name) {
super(name);
}
public static void main(String[] args) {
TestRunner.run(suite());
}
public static Test suite() {
return new TestSuite(ElementTypeRegistryTest.class);
}
protected void doModelSetup(Resource resource) {
setFixture(ElementTypeRegistry.getInstance());
department = (Department) getEmployeeFactory().create(getEmployeePackage()
.getDepartment());
department.setName("Department"); //$NON-NLS-1$
resource.getContents().add(department);
executiveDepartment = (Department) getEmployeeFactory().create(getEmployeePackage()
.getDepartment());
executiveDepartment.setName("ExecutiveDepartment"); //$NON-NLS-1$
resource.getContents().add(executiveDepartment);
financeDepartment = (Department) getEmployeeFactory().create(getEmployeePackage()
.getDepartment());
financeDepartment.setName("Finance"); //$NON-NLS-1$
resource.getContents().add(financeDepartment);
employee = (Employee) getEmployeeFactory().create(getEmployeePackage().getEmployee());
employee.setNumber(1);
department.getMembers().add(employee);
employeeOffice = (Office) getEmployeeFactory().create(getEmployeePackage()
.getOffice());
employee.setOffice(employeeOffice);
financeEmployee = (Employee) getEmployeeFactory().create(getEmployeePackage()
.getEmployee());
financeEmployee.setDepartment(financeDepartment);
financeManager = (Employee) getEmployeeFactory().create(getEmployeePackage()
.getEmployee());
financeDepartment.setManager(financeManager);
Office financeManagerOffice = (Office) getEmployeeFactory()
.create(getEmployeePackage().getOffice());
financeManagerOffice.setNumberOfWindows(1);
financeManagerOffice.setHasDoor(false);
financeManager.setOffice(financeManagerOffice);
student = (Student) getEmployeeFactory().create(getEmployeePackage().getStudent());
student.setNumber(2);
department.getMembers().add(student);
studentOffice = (Office) getEmployeeFactory()
.create(getEmployeePackage().getOffice());
student.setOffice(studentOffice);
manager = (Employee) getEmployeeFactory().create(getEmployeePackage().getEmployee());
department.setManager(manager);
managerOffice = (Office) getEmployeeFactory()
.create(getEmployeePackage().getOffice());
managerOffice.setNumberOfWindows(1);
managerOffice.setHasDoor(false);
manager.setOffice(managerOffice);
executive = (Employee) getEmployeeFactory()
.create(getEmployeePackage().getEmployee());
executiveDepartment.setManager(executive);
executiveOffice = (Office) getEmployeeFactory().create(getEmployeePackage()
.getOffice());
executiveOffice.setNumberOfWindows(1);
executiveOffice.setHasDoor(true);
executive.setOffice(executiveOffice);
highSchoolStudent = (HighSchoolStudent) getEmployeeFactory().create(
getEmployeePackage().getHighSchoolStudent());
}
protected void doModelSetupWithContext(Resource resource) {
setFixture(ElementTypeRegistry.getInstance());
cDepartment = (Department) getEmployeeFactory().create(getEmployeePackage()
.getDepartment());
cDepartment.setName("DepartmentWithContext"); //$NON-NLS-1$
resource.getContents().add(cDepartment);
cExecutiveDepartment = (Department) getEmployeeFactory().create(getEmployeePackage()
.getDepartment());
cExecutiveDepartment.setName("ExecutiveDepartmentWithContext"); //$NON-NLS-1$
resource.getContents().add(cExecutiveDepartment);
cFinanceDepartment = (Department) getEmployeeFactory().create(getEmployeePackage()
.getDepartment());
cFinanceDepartment.setName("FinanceWithContext"); //$NON-NLS-1$
resource.getContents().add(cFinanceDepartment);
cEmployee = (Employee) getEmployeeFactory().create(getEmployeePackage().getEmployee());
cEmployee.setNumber(1);
cDepartment.getMembers().add(cEmployee);
cEmployeeOffice = (Office) getEmployeeFactory().create(getEmployeePackage()
.getOffice());
cEmployee.setOffice(cEmployeeOffice);
cFinanceEmployee = (Employee) getEmployeeFactory().create(getEmployeePackage()
.getEmployee());
cFinanceEmployee.setDepartment(cFinanceDepartment);
cFinanceManager = (Employee) getEmployeeFactory().create(getEmployeePackage()
.getEmployee());
cFinanceDepartment.setManager(cFinanceManager);
Office financeManagerOffice = (Office) getEmployeeFactory()
.create(getEmployeePackage().getOffice());
financeManagerOffice.setNumberOfWindows(1);
financeManagerOffice.setHasDoor(false);
cFinanceManager.setOffice(financeManagerOffice);
cStudent = (Student) getEmployeeFactory().create(getEmployeePackage().getStudent());
cStudent.setNumber(2);
cDepartment.getMembers().add(cStudent);
cStudentOffice = (Office) getEmployeeFactory()
.create(getEmployeePackage().getOffice());
cStudent.setOffice(cStudentOffice);
cManager = (Employee) getEmployeeFactory().create(getEmployeePackage().getEmployee());
cDepartment.setManager(cManager);
cManagerOffice = (Office) getEmployeeFactory()
.create(getEmployeePackage().getOffice());
cManagerOffice.setNumberOfWindows(1);
cManagerOffice.setHasDoor(false);
cManager.setOffice(cManagerOffice);
cExecutive = (Employee) getEmployeeFactory()
.create(getEmployeePackage().getEmployee());
cExecutiveDepartment.setManager(cExecutive);
cExecutiveOffice = (Office) getEmployeeFactory().create(getEmployeePackage()
.getOffice());
cExecutiveOffice.setNumberOfWindows(1);
cExecutiveOffice.setHasDoor(true);
cExecutive.setOffice(cExecutiveOffice);
}
protected ElementTypeRegistry getFixture() {
return fixture;
}
protected void setFixture(ElementTypeRegistry fixture) {
this.fixture = fixture;
}
protected IClientContext getClientContext() {
if (clientContext == null) {
clientContext = ClientContextManager
.getInstance()
.getClientContext(
"org.eclipse.gmf.tests.runtime.emf.type.core.ClientContext1"); //$NON-NLS-1$
}
return clientContext;
}
protected IClientContext getUnboundClientContext() {
if (unboundClientContext == null) {
unboundClientContext = ClientContextManager
.getInstance()
.getClientContext(
"org.eclipse.gmf.tests.runtime.emf.type.core.UnboundClientContext"); //$NON-NLS-1$
}
return unboundClientContext;
}
/**
* Verifies that the #getSpecializationsOf API returns the correct
* specializations.
*/
public void test_getSpecializationsOf_151097() {
ISpecializationType[] specializations = ElementTypeRegistry
.getInstance().getSpecializationsOf(
"org.eclipse.gmf.tests.runtime.emf.type.core.employee"); //$NON-NLS-1$
assertEquals(4, specializations.length);
for (int i = 0; i < specializations.length; i++) {
if (specializations[i].getId().equals("org.eclipse.gmf.tests.runtime.emf.type.core.manager") //$NON-NLS-1$
&& specializations[i].getClass().equals("org.eclipse.gmf.tests.runtime.emf.type.core.topSecret") //$NON-NLS-1$
&& specializations[i].getClass().equals("org.eclipse.gmf.tests.runtime.emf.type.core.executive")) { //$NON-NLS-1$
fail("expected manager, top-secret and executive specializations"); //$NON-NLS-1$
}
}
}
public void test_getAllTypesMatching_eObject_metamodel() {
IElementType[] officeMatches = getFixture().getAllTypesMatching(
employeeOffice);
assertTrue(officeMatches.length == 1);
assertTrue(officeMatches[0] == EmployeeType.OFFICE);
}
public void test_getAllTypesMatching_eObject_metamodel_withContext() {
// context inferred
IElementType[] officeMatches = getFixture().getAllTypesMatching(
cEmployeeOffice);
assertTrue(officeMatches.length == 1);
assertTrue(officeMatches[0] == EmployeeType.CONTEXT_OFFICE);
// context explicit
officeMatches = getFixture().getAllTypesMatching(
cEmployeeOffice, getClientContext());
assertTrue(officeMatches.length == 1);
assertTrue(officeMatches[0] == EmployeeType.CONTEXT_OFFICE);
}
public void test_getAllTypesMatching_eObject_metamodel_unboundContext() {
IElementType[] officeMatches = getFixture().getAllTypesMatching(
cEmployeeOffice, getUnboundClientContext());
assertTrue(officeMatches.length == 1);
assertTrue(officeMatches[0] == DefaultMetamodelType.getInstance());
}
public void test_getAllTypesMatching_eObject_metamodelAndSpecializations() {
IElementType[] managerMatches = getFixture().getAllTypesMatching(
manager);
assertEquals(4, managerMatches.length);
List managerMatchList = Arrays.asList(managerMatches);
assertTrue(managerMatchList.contains(EmployeeType.MANAGER));
assertTrue(managerMatchList.contains(EmployeeType.TOP_SECRET));
// The metamodel type should be last.
// assertEquals(EmployeeType.EMPLOYEE, managerMatches[2]);
}
public void test_getAllTypesMatching_eObject_metamodelAndSpecializations_withContext() {
// context inferred
IElementType[] managerMatches = getFixture().getAllTypesMatching(
cManager);
assertEquals(3, managerMatches.length);
List managerMatchList = Arrays.asList(managerMatches);
assertTrue(managerMatchList.contains(EmployeeType.CONTEXT_MANAGER));
assertTrue(managerMatchList.contains(EmployeeType.CONTEXT_TOP_SECRET));
// The metamodel type should be last.
assertEquals(EmployeeType.CONTEXT_EMPLOYEE, managerMatches[2]);
// context explicit
managerMatches = getFixture().getAllTypesMatching(
cManager, getClientContext());
assertEquals(3, managerMatches.length);
managerMatchList = Arrays.asList(managerMatches);
assertTrue(managerMatchList.contains(EmployeeType.CONTEXT_MANAGER));
assertTrue(managerMatchList.contains(EmployeeType.CONTEXT_TOP_SECRET));
// The metamodel type should be last.
assertEquals(EmployeeType.CONTEXT_EMPLOYEE, managerMatches[2]);
}
public void test_getAllTypesMatching_eObject_metamodelAndSpecializations_unboundContext() {
IElementType[] managerMatches = getFixture().getAllTypesMatching(
cManager, getUnboundClientContext());
assertEquals(1, managerMatches.length);
assertTrue(managerMatches[0] == DefaultMetamodelType.getInstance());
}
public void test_getElementType_eObject_eClass() {
MetamodelType eClassType = new MetamodelType(
"dynamic.org.eclipse.gmf.tests.runtime.emf.type.core.eclass", null, null, //$NON-NLS-1$
EcorePackage.eINSTANCE.getEClass(), null);
IClientContext context = ClientContextManager.getInstance()
.getClientContext(
"org.eclipse.gmf.tests.runtime.emf.type.core.ClientContext2"); //$NON-NLS-1$
// EClass type conflicts with the one in the ECore example editor
context.bindId(
"dynamic.org.eclipse.gmf.tests.runtime.emf.type.core.eclass"); //$NON-NLS-1$
boolean wasRegistered = getFixture().register(eClassType);
EObject myEClassInstance = EcoreFactory.eINSTANCE.createEClass();
IElementType metamodelType = getFixture().getElementType(
myEClassInstance, context);
assertNotNull(metamodelType);
if (wasRegistered) {
assertSame(eClassType, metamodelType);
}
}
/**
* Verifies that the metamodel types bound to a specified context can be
* retrieved from the registry.
*/
public void test_getMetamodelTypes_155601() {
IMetamodelType[] metamodelTypes = ElementTypeRegistry.getInstance()
.getMetamodelTypes(getClientContext());
assertEquals(EmployeeType.METAMODEL_TYPES_WITH_CONTEXT.length,
metamodelTypes.length);
for (int i = 0; i < metamodelTypes.length; i++) {
boolean match = false;
for (int j = 0; j < EmployeeType.METAMODEL_TYPES_WITH_CONTEXT.length; j++) {
if (metamodelTypes[i] == EmployeeType.METAMODEL_TYPES_WITH_CONTEXT[j]) {
match = true;
break;
}
}
assertTrue("missing metamodel type", match); //$NON-NLS-1$
}
}
/**
* Verifies that the specialization types bound to a specified context can be
* retrieved from the registry.
*/
public void test_getSpecializationTypes_155601() {
ISpecializationType[] specializationTypes = ElementTypeRegistry
.getInstance().getSpecializationTypes(getClientContext());
assertEquals(EmployeeType.SPECIALIZATION_TYPES_WITH_CONTEXT.length,
specializationTypes.length);
for (int i = 0; i < specializationTypes.length; i++) {
boolean match = false;
for (int j = 0; j < EmployeeType.SPECIALIZATION_TYPES_WITH_CONTEXT.length; j++) {
if (specializationTypes[i] == EmployeeType.SPECIALIZATION_TYPES_WITH_CONTEXT[j]) {
match = true;
break;
}
}
assertTrue("missing specialization type", match); //$NON-NLS-1$
}
}
/**
* Verifies that the element types bound to a specified context can be
* retrieved from the registry.
*/
public void test_getElementTypes_155601() {
IElementType[] elementTypes = ElementTypeRegistry.getInstance()
.getElementTypes(getClientContext());
assertEquals(EmployeeType.METAMODEL_TYPES_WITH_CONTEXT.length
+ EmployeeType.SPECIALIZATION_TYPES_WITH_CONTEXT.length,
elementTypes.length);
for (int i = 0; i < elementTypes.length; i++) {
boolean match = false;
for (int j = 0; j < EmployeeType.METAMODEL_TYPES_WITH_CONTEXT.length; j++) {
if (elementTypes[i] == EmployeeType.METAMODEL_TYPES_WITH_CONTEXT[j]) {
match = true;
break;
}
}
if (!match) {
for (int j = 0; j < EmployeeType.SPECIALIZATION_TYPES_WITH_CONTEXT.length; j++) {
if (elementTypes[i] == EmployeeType.SPECIALIZATION_TYPES_WITH_CONTEXT[j]) {
match = true;
break;
}
}
}
assertTrue("missing element type", match); //$NON-NLS-1$
}
}
public void test_getContainedTypes_metamodel() {
IElementType[] officeMatches = getFixture().getContainedTypes(employee,
EmployeePackage.eINSTANCE.getEmployee_Office());
assertEquals(1, officeMatches.length);
List officeMatchList = Arrays.asList(officeMatches);
assertTrue(officeMatchList.contains(EmployeeType.OFFICE));
}
public void test_getContainedTypes_metamodel_withContext() {
// context inferred
IElementType[] officeMatches = getFixture().getContainedTypes(cEmployee,
EmployeePackage.eINSTANCE.getEmployee_Office());
assertEquals(1, officeMatches.length);
List officeMatchList = Arrays.asList(officeMatches);
assertTrue(officeMatchList.contains(EmployeeType.CONTEXT_OFFICE));
// context explicit
officeMatches = getFixture().getContainedTypes(cEmployee,
EmployeePackage.eINSTANCE.getEmployee_Office(), getClientContext());
assertEquals(1, officeMatches.length);
officeMatchList = Arrays.asList(officeMatches);
assertTrue(officeMatchList.contains(EmployeeType.CONTEXT_OFFICE));
}
public void test_getContainedTypes_metamodel_unboundContext() {
IElementType[] officeMatches = getFixture().getContainedTypes(cEmployee,
EmployeePackage.eINSTANCE.getEmployee_Office(), getUnboundClientContext());
assertEquals(0, officeMatches.length);
}
public void test_getContainedTypes_metamodelAndSpecializations_departmentMembers() {
IElementType[] memberMatches = getFixture().getContainedTypes(
department, EmployeePackage.eINSTANCE.getDepartment_Members());
List memberMatchList = Arrays.asList(memberMatches);
List expected = Arrays.asList(new Object[] {EmployeeType.EMPLOYEE,
EmployeeType.STUDENT, EmployeeType.HIGH_SCHOOL_STUDENT, EmployeeType.TOP_SECRET});
assertEquals(expected.size() + 1, memberMatches.length);
assertTrue(memberMatchList.containsAll(expected));
}
public void test_getContainedTypes_metamodelAndSpecializations_departmentMembers_withContext() {
// context inferred
IElementType[] memberMatches = getFixture().getContainedTypes(
cDepartment, EmployeePackage.eINSTANCE.getDepartment_Members());
List memberMatchList = Arrays.asList(memberMatches);
List expected = Arrays.asList(new Object[] {EmployeeType.CONTEXT_EMPLOYEE,
EmployeeType.CONTEXT_STUDENT, EmployeeType.CONTEXT_TOP_SECRET});
assertEquals(expected.size(), memberMatches.length);
assertTrue(memberMatchList.containsAll(expected));
// context explicit
memberMatches = getFixture().getContainedTypes(
cDepartment, EmployeePackage.eINSTANCE.getDepartment_Members(), getClientContext());
memberMatchList = Arrays.asList(memberMatches);
expected = Arrays.asList(new Object[] {EmployeeType.CONTEXT_EMPLOYEE,
EmployeeType.CONTEXT_STUDENT, EmployeeType.CONTEXT_TOP_SECRET});
assertEquals(expected.size(), memberMatches.length);
assertTrue(memberMatchList.containsAll(expected));
}
public void test_getContainedTypes_metamodelAndSpecializations_departmentMembers_unboundContext() {
IElementType[] memberMatches = getFixture().getContainedTypes(
cDepartment, EmployeePackage.eINSTANCE.getDepartment_Members(), getUnboundClientContext());
assertEquals(0, memberMatches.length);
}
public void test_getContainedTypes_metamodelAndSpecializations_departmentManager() {
IElementType[] managerMatches = getFixture().getContainedTypes(
department, EmployeePackage.eINSTANCE.getDepartment_Manager());
List managerMatchList = Arrays.asList(managerMatches);
List expected = Arrays.asList(new Object[] {EmployeeType.EMPLOYEE,
EmployeeType.STUDENT, EmployeeType.HIGH_SCHOOL_STUDENT, EmployeeType.MANAGER, EmployeeType.EXECUTIVE,
EmployeeType.TOP_SECRET});
assertEquals(expected.size() + 1, managerMatches.length);
assertTrue(managerMatchList.containsAll(expected));
}
public void test_getContainedTypes_metamodelAndSpecializations_departmentManager_withContext() {
// context inferred
IElementType[] managerMatches = getFixture().getContainedTypes(
cDepartment, EmployeePackage.eINSTANCE.getDepartment_Manager());
List managerMatchList = Arrays.asList(managerMatches);
List expected = Arrays.asList(new Object[] {EmployeeType.CONTEXT_EMPLOYEE,
EmployeeType.CONTEXT_STUDENT, EmployeeType.CONTEXT_MANAGER, EmployeeType.CONTEXT_EXECUTIVE,
EmployeeType.CONTEXT_TOP_SECRET});
assertEquals(expected.size(), managerMatches.length);
assertTrue(managerMatchList.containsAll(expected));
// context explicit
managerMatches = getFixture().getContainedTypes(
cDepartment, EmployeePackage.eINSTANCE.getDepartment_Manager(), getClientContext());
managerMatchList = Arrays.asList(managerMatches);
expected = Arrays.asList(new Object[] {EmployeeType.CONTEXT_EMPLOYEE,
EmployeeType.CONTEXT_STUDENT, EmployeeType.CONTEXT_MANAGER, EmployeeType.CONTEXT_EXECUTIVE,
EmployeeType.CONTEXT_TOP_SECRET});
assertEquals(expected.size(), managerMatches.length);
assertTrue(managerMatchList.containsAll(expected));
}
public void test_getContainedTypes_metamodelAndSpecializations_departmentManager_unboundContext() {
IElementType[] managerMatches = getFixture().getContainedTypes(
cDepartment, EmployeePackage.eINSTANCE.getDepartment_Manager(), getUnboundClientContext());
assertEquals(0, managerMatches.length);
}
public void test_getEditHelperAdvice_noAdvice() {
IEditHelperAdvice[] advice = getNonWildcardAdvice(studentOffice);
assertEquals(0, advice.length);
}
public void test_getEditHelperAdvice_noAdvice_withContext() {
// context inferred
IEditHelperAdvice[] advice = getNonWildcardAdvice(cStudentOffice);
assertEquals(0, advice.length);
// context explicit
advice = getNonWildcardAdvice(cStudentOffice, getClientContext());
assertEquals(0, advice.length);
}
public void test_getEditHelperAdvice_noAdvice_unboundContext() {
IEditHelperAdvice[] advice = getNonWildcardAdvice(cStudentOffice, getUnboundClientContext());
assertEquals(0, advice.length);
}
public void test_getEditHelperAdvice_eObject_directAdvice() {
IEditHelperAdvice[] advice = getNonWildcardAdvice(financeEmployee);
assertEquals(3, advice.length);
//for (int i = 0; i < advice.length; i++) {
// if (advice[i].getClass() != FinanceEditHelperAdvice.class
// && advice[i].getClass() != NotInheritedEditHelperAdvice.class) {
// fail("expected finance and not inherited helper advice"); //$NON-NLS-1$
// }
//}
}
public void test_getEditHelperAdvice_eObject_directAdvice_withContext() {
// context inferred
IEditHelperAdvice[] advice = getNonWildcardAdvice(cFinanceEmployee);
assertEquals(2, advice.length);
for (int i = 0; i < advice.length; i++) {
if (advice[i].getClass() != FinanceEditHelperAdvice.class
&& advice[i].getClass() != NotInheritedEditHelperAdvice.class) {
fail("expected finance and not inherited helper advice"); //$NON-NLS-1$
}
}
// context explicit
advice = getNonWildcardAdvice(cFinanceEmployee, getClientContext());
assertEquals(2, advice.length);
for (int i = 0; i < advice.length; i++) {
if (advice[i].getClass() != FinanceEditHelperAdvice.class
&& advice[i].getClass() != NotInheritedEditHelperAdvice.class) {
fail("expected finance and not inherited helper advice"); //$NON-NLS-1$
}
}
}
public void test_getEditHelperAdvice_eObject_directAdvice_unboundContext() {
IEditHelperAdvice[] advice = getNonWildcardAdvice(cFinanceEmployee, getUnboundClientContext());
assertEquals(0, advice.length);
}
public void test_getEditHelperAdvice_eObject_indirectAdvice() {
IEditHelperAdvice[] advice = getNonWildcardAdvice(financeManager);
assertEquals(4, advice.length);
//for (int i = 0; i < advice.length; i++) {
// if (advice[i].getClass() != FinanceEditHelperAdvice.class
// && advice[i].getClass() != ManagerEditHelperAdvice.class
// && advice[i].getClass() != NotInheritedEditHelperAdvice.class) {
// fail("expected finance, manager and not inherited edit helper advice"); //$NON-NLS-1$
// }
//}
}
public void test_getEditHelperAdvice_eObject_indirectAdvice_withContext() {
// context inferred
IEditHelperAdvice[] advice = getNonWildcardAdvice(cFinanceManager);
assertEquals(3, advice.length);
for (int i = 0; i < advice.length; i++) {
if (advice[i].getClass() != FinanceEditHelperAdvice.class
&& advice[i].getClass() != ManagerEditHelperAdvice.class
&& advice[i].getClass() != NotInheritedEditHelperAdvice.class) {
fail("expected finance, manager and not inherited edit helper advice"); //$NON-NLS-1$
}
}
// context explicit
advice = getNonWildcardAdvice(cFinanceManager, getClientContext());
assertEquals(3, advice.length);
for (int i = 0; i < advice.length; i++) {
if (advice[i].getClass() != FinanceEditHelperAdvice.class
&& advice[i].getClass() != ManagerEditHelperAdvice.class
&& advice[i].getClass() != NotInheritedEditHelperAdvice.class) {
fail("expected finance, manager and not inherited edit helper advice"); //$NON-NLS-1$
}
}
}
public void test_getEditHelperAdvice_eObject_indirectAdvice_unboundContext() {
IEditHelperAdvice[] advice = getNonWildcardAdvice(cFinanceManager, getUnboundClientContext());
assertEquals(0, advice.length);
}
public void test_getEditHelperAdvice_elementType_directMatch() {
IEditHelperAdvice[] advice = getNonWildcardAdvice(EmployeeType.EMPLOYEE);
assertEquals(2, advice.length);
for (int i = 0; i < advice.length; i++) {
if (advice[i].getClass() != FinanceEditHelperAdvice.class
&& advice[i].getClass() != NotInheritedEditHelperAdvice.class) {
fail("expected finance and notInherited edit helper advice"); //$NON-NLS-1$
}
}
}
public void test_getEditHelperAdvice_elementType_directMatch_withContext() {
// context inferred
IEditHelperAdvice[] advice = getNonWildcardAdvice(EmployeeType.CONTEXT_EMPLOYEE);
assertEquals(2, advice.length);
for (int i = 0; i < advice.length; i++) {
if (advice[i].getClass() != FinanceEditHelperAdvice.class
&& advice[i].getClass() != NotInheritedEditHelperAdvice.class) {
fail("expected finance and notInherited edit helper advice"); //$NON-NLS-1$
}
}
// context explicit
advice = getNonWildcardAdvice(EmployeeType.CONTEXT_EMPLOYEE, getClientContext());
assertEquals(2, advice.length);
for (int i = 0; i < advice.length; i++) {
if (advice[i].getClass() != FinanceEditHelperAdvice.class
&& advice[i].getClass() != NotInheritedEditHelperAdvice.class) {
fail("expected finance and notInherited edit helper advice"); //$NON-NLS-1$
}
}
}
public void test_getEditHelperAdvice_elementType_directMatch_unboundContext() {
IEditHelperAdvice[] advice = getNonWildcardAdvice(EmployeeType.CONTEXT_EMPLOYEE, getUnboundClientContext());
assertEquals(0, advice.length);
}
public void test_getEditHelperAdvice_elementType_inheritedMatches() {
IEditHelperAdvice[] advice = getNonWildcardAdvice(EmployeeType.EXECUTIVE);
assertEquals(4, advice.length);
for (int i = 0; i < advice.length; i++) {
if (advice[i].getClass() != FinanceEditHelperAdvice.class
&& advice[i].getClass() != ManagerEditHelperAdvice.class
&& advice[i].getClass() != ExecutiveEditHelperAdvice.class
&& advice[i].getClass() != NotInheritedEditHelperAdvice.class) {
fail("expected finance, manager, executive and not-inherited edit helper advice"); //$NON-NLS-1$
}
}
}
public void test_getEditHelperAdvice_elementType_inheritedMatches_withContext() {
// context inferred
IEditHelperAdvice[] advice = getNonWildcardAdvice(EmployeeType.CONTEXT_EXECUTIVE);
assertEquals(4, advice.length);
for (int i = 0; i < advice.length; i++) {
if (advice[i].getClass() != FinanceEditHelperAdvice.class
&& advice[i].getClass() != ManagerEditHelperAdvice.class
&& advice[i].getClass() != ExecutiveEditHelperAdvice.class
&& advice[i].getClass() != NotInheritedEditHelperAdvice.class) {
fail("expected finance, manager, executive and not-inherited edit helper advice"); //$NON-NLS-1$
}
}
// context explicit
advice = getNonWildcardAdvice(EmployeeType.CONTEXT_EXECUTIVE, getClientContext());
assertEquals(4, advice.length);
for (int i = 0; i < advice.length; i++) {
if (advice[i].getClass() != FinanceEditHelperAdvice.class
&& advice[i].getClass() != ManagerEditHelperAdvice.class
&& advice[i].getClass() != ExecutiveEditHelperAdvice.class
&& advice[i].getClass() != NotInheritedEditHelperAdvice.class) {
fail("expected finance, manager, executive and not-inherited edit helper advice"); //$NON-NLS-1$
}
}
}
public void test_getEditHelperAdvice_elementType_inheritedMatches_unboundContext() {
IEditHelperAdvice[] advice = getNonWildcardAdvice(EmployeeType.CONTEXT_EXECUTIVE, getUnboundClientContext());
assertEquals(0, advice.length);
}
public void test_getEditHelperAdvice_elementType_noInheritedMatches() {
IEditHelperAdvice[] advice = getNonWildcardAdvice(EmployeeType.STUDENT);
assertEquals(1, advice.length);
for (int i = 0; i < advice.length; i++) {
if (advice[i].getClass() != FinanceEditHelperAdvice.class) {
fail("expected finance edit helper advice"); //$NON-NLS-1$
}
}
}
public void test_getEditHelperAdvice_elementType_noInheritedMatches_withContext() {
// context inferred
IEditHelperAdvice[] advice = getNonWildcardAdvice(EmployeeType.CONTEXT_STUDENT);
assertEquals(1, advice.length);
for (int i = 0; i < advice.length; i++) {
if (advice[i].getClass() != FinanceEditHelperAdvice.class) {
fail("expected finance edit helper advice"); //$NON-NLS-1$
}
}
// context explicit
advice = getNonWildcardAdvice(EmployeeType.CONTEXT_STUDENT, getClientContext());
assertEquals(1, advice.length);
for (int i = 0; i < advice.length; i++) {
if (advice[i].getClass() != FinanceEditHelperAdvice.class) {
fail("expected finance edit helper advice"); //$NON-NLS-1$
}
}
}
public void test_getEditHelperAdvice_elementType_noInheritedMatches_unboundContext() {
IEditHelperAdvice[] advice = getNonWildcardAdvice(EmployeeType.CONTEXT_STUDENT, getUnboundClientContext());
assertEquals(0, advice.length);
}
public void test_getEditHelperAdvice_editHelperContext_withEObject() {
IEditHelperContext context = new EditHelperContext(cFinanceManager,
getClientContext());
IEditHelperAdvice[] advice = getNonWildcardAdvice(context);
assertEquals(3, advice.length);
for (int i = 0; i < advice.length; i++) {
if (advice[i].getClass() != FinanceEditHelperAdvice.class
&& advice[i].getClass() != ManagerEditHelperAdvice.class
&& advice[i].getClass() != NotInheritedEditHelperAdvice.class) {
fail("expected finance, manager and not inherited edit helper advice"); //$NON-NLS-1$
}
}
}
public void test_getEditHelperAdvice_editHelperContext_withElementType() {
IEditHelperContext context = new EditHelperContext(
EmployeeType.CONTEXT_EXECUTIVE, getClientContext());
IEditHelperAdvice[] advice = getNonWildcardAdvice(context);
assertEquals(4, advice.length);
for (int i = 0; i < advice.length; i++) {
if (advice[i].getClass() != FinanceEditHelperAdvice.class
&& advice[i].getClass() != ManagerEditHelperAdvice.class
&& advice[i].getClass() != ExecutiveEditHelperAdvice.class
&& advice[i].getClass() != NotInheritedEditHelperAdvice.class) {
fail("expected finance, manager, executive and not-inherited edit helper advice"); //$NON-NLS-1$
}
}
}
public void test_getEditHelperAdvice_editHelperContext_noClientContext() {
IEditHelperContext context = new EditHelperContext(
EmployeeType.CONTEXT_EXECUTIVE, null);
IEditHelperAdvice[] advice = getNonWildcardAdvice(context);
assertEquals(4, advice.length);
for (int i = 0; i < advice.length; i++) {
if (advice[i].getClass() != FinanceEditHelperAdvice.class
&& advice[i].getClass() != ManagerEditHelperAdvice.class
&& advice[i].getClass() != ExecutiveEditHelperAdvice.class
&& advice[i].getClass() != NotInheritedEditHelperAdvice.class) {
fail("expected finance, manager, executive and not-inherited edit helper advice"); //$NON-NLS-1$
}
}
}
public void test_getElementTypeFactory_none() {
IElementTypeFactory factory = getFixture().getElementTypeFactory(
"noName"); //$NON-NLS-1$
assertNull(factory);
}
public void test_getElementTypeFactory_default() {
IElementTypeFactory factory = getFixture().getElementTypeFactory(
"org.eclipse.gmf.runtime.emf.type.core.IElementType"); //$NON-NLS-1$
assertNotNull(factory);
assertEquals(DefaultElementTypeFactory.class, factory.getClass());
}
public void test_getElementTypeFactory_custom() {
IElementTypeFactory factory = getFixture().getElementTypeFactory(
"org.eclipse.gmf.tests.runtime.emf.type.core.internal.ISecurityCleared"); //$NON-NLS-1$
assertNotNull(factory);
assertEquals(SecurityClearedElementTypeFactory.class, factory
.getClass());
}
public void test_getElementType_eClass() {
IElementType metamodelType = getFixture().getElementType(
getEmployeePackage().getDepartment());
assertNotNull(metamodelType);
assertEquals(EmployeeType.DEPARTMENT, metamodelType);
}
public void test_getElementType_eClass_withContext() {
// context explicit
IElementType metamodelType = getFixture().getElementType(
getEmployeePackage().getDepartment(), getClientContext());
assertNotNull(metamodelType);
assertEquals(EmployeeType.CONTEXT_DEPARTMENT, metamodelType);
}
public void test_getElementType_eClass_unboundContext() {
IElementType metamodelType = getFixture().getElementType(
getEmployeePackage().getDepartment(), getUnboundClientContext());
assertSame(DefaultMetamodelType.getInstance(), metamodelType);
}
public void test_getElementType_eObject() {
IElementType metamodelType = getFixture().getElementType(
financeManager);
assertNotNull(metamodelType);
assertEquals(EmployeeType.EMPLOYEE, metamodelType);
}
public void test_getElementType_eObject_withContext() {
// context inferred
IElementType metamodelType = getFixture().getElementType(
cFinanceManager);
assertNotNull(metamodelType);
assertEquals(EmployeeType.CONTEXT_EMPLOYEE, metamodelType);
// context explicit
metamodelType = getFixture().getElementType(
cFinanceManager, getClientContext());
assertNotNull(metamodelType);
assertEquals(EmployeeType.CONTEXT_EMPLOYEE, metamodelType);
}
public void test_getElementType_eObject_unboundContext() {
IElementType metamodelType = getFixture().getElementType(
cFinanceManager, getUnboundClientContext());
assertSame(DefaultMetamodelType.getInstance(), metamodelType);
}
public void test_getElementType_overridesEditHelper() {
IElementType elementType = getFixture().getElementType(
EmployeeType.TOP_SECRET);
assertNotNull(elementType);
assertEquals(EmployeeType.TOP_SECRET, elementType);
assertTrue(elementType.getEditHelper() instanceof SecurityClearedElementTypeFactory.SecurityClearedEditHelper);
}
public void test_getElementType_overridesEditHelper_withContext() {
IElementType elementType = getFixture().getElementType(
EmployeeType.CONTEXT_TOP_SECRET);
assertNotNull(elementType);
assertEquals(EmployeeType.CONTEXT_TOP_SECRET, elementType);
assertTrue(elementType.getEditHelper() instanceof SecurityClearedElementTypeFactory.SecurityClearedEditHelper);
}
public void test_getElementType_metamodelType() {
IElementType metamodelType = getFixture().getElementType(EmployeeType.STUDENT);
assertNotNull(metamodelType);
assertEquals(EmployeeType.STUDENT, metamodelType);
}
public void test_getElementType_metamodelType_withContext() {
IElementType metamodelType = getFixture().getElementType(EmployeeType.CONTEXT_STUDENT);
assertNotNull(metamodelType);
assertEquals(EmployeeType.CONTEXT_STUDENT, metamodelType);
}
public void test_getElementType_specializationType() {
IElementType specializationType = getFixture()
.getElementType(EmployeeType.MANAGER);
assertNotNull(specializationType);
assertEquals(EmployeeType.MANAGER, specializationType);
}
public void test_getElementType_specializationType_withContext() {
IElementType specializationType = getFixture()
.getElementType(EmployeeType.CONTEXT_MANAGER);
assertNotNull(specializationType);
assertEquals(EmployeeType.CONTEXT_MANAGER, specializationType);
}
public void test_getElementType_editHelperContext_withEObject() {
IEditHelperContext context = new EditHelperContext(cFinanceManager,
getClientContext());
IElementType type = getFixture().getElementType(context);
assertNotNull(type);
assertEquals(EmployeeType.CONTEXT_EMPLOYEE, type);
}
/**
* Verifies that the element type in the IEditHelperContext will be used
* regardless of the client context specified in the IEditHelperContext.
*/
public void test_getElementType_editHelperContext_withElementType() {
IEditHelperContext context = new EditHelperContext(
EmployeeType.CONTEXT_STUDENT, ClientContextManager.getDefaultClientContext());
IElementType type = getFixture().getElementType(context);
assertNotNull(type);
assertEquals(EmployeeType.CONTEXT_STUDENT, type);
}
public void test_getElementType_editHelperContext_noClientContext() {
IEditHelperContext context = new EditHelperContext(financeManager, null);
IElementType type = getFixture().getElementType(context);
assertNotNull(type);
assertEquals(EmployeeType.EMPLOYEE, type);
}
public void test_getType_metamodel() {
IElementType studentType = getFixture().getType(
EmployeeType.STUDENT.getId());
assertNotNull(studentType);
assertEquals(EmployeeType.STUDENT.getId(), studentType.getId());
}
public void test_getType_specialization() {
IElementType managerType = getFixture().getType(
EmployeeType.MANAGER.getId());
assertNotNull(managerType);
assertEquals(EmployeeType.MANAGER.getId(), managerType.getId());
}
public void test_duplicateId_notRegistered() {
IElementType employeeType = getFixture().getType(
"org.eclipse.gmf.tests.runtime.emf.type.core.employee"); //$NON-NLS-1$
assertFalse(employeeType.getDisplayName().equals("DuplicateEmployee")); //$NON-NLS-1$
}
public void test_duplicateEClass_notRegistered() {
IElementType employeeType = getFixture().getType(
"org.eclipse.gmf.tests.runtime.emf.type.ui.employee2"); //$NON-NLS-1$
assertNull(employeeType);
}
public void test_multipleMetatmodelTypes_notRegistered() {
IElementType employeeType = getFixture().getType(
"org.eclipse.gmf.tests.runtime.emf.type.ui.multipleMetamodelTypes"); //$NON-NLS-1$
assertNull(employeeType);
}
public void test_noSuchType_notRegistered() {
IElementType employeeType = getFixture().getType(
"org.eclipse.gmf.tests.runtime.emf.type.ui.SpecializesNoSuchType"); //$NON-NLS-1$
assertNull(employeeType);
}
public void test_invalidMetatmodel_notRegistered() {
IElementType employeeType = getFixture().getType(
"org.eclipse.gmf.tests.runtime.emf.type.ui.noMetamodel"); //$NON-NLS-1$
assertNull(employeeType);
}
public void test_register_specializationType() {
IEditHelperAdvice specialAdvice = new MySpecializationAdvice();
String id = "dynamic.specialization.type"; //$NON-NLS-1$
final ISpecializationType dynamicSpecializationType = new SpecializationType(id, null, id,
new IElementType[] {EmployeeType.EMPLOYEE}, null, null, specialAdvice);
final boolean[] listenerNotified = new boolean[] {false};
IElementTypeRegistryListener listener = new IElementTypeRegistryListener() {
public void elementTypeAdded(
ElementTypeAddedEvent elementTypeAddedEvent) {
listenerNotified[0] = true;
assertEquals(dynamicSpecializationType.getId(), elementTypeAddedEvent
.getElementTypeId());
}
};
boolean result;
ElementTypeRegistry.getInstance().addElementTypeRegistryListener(listener);
try {
result = ElementTypeRegistry.getInstance().register(dynamicSpecializationType);
} finally {
ElementTypeRegistry.getInstance().removeElementTypeRegistryListener(listener);
}
// Check that the element type was registered
assertTrue(result);
assertTrue(listenerNotified[0]);
assertSame(dynamicSpecializationType, getFixture().getType(id));
// Check that the advice can be retrieved
IEditHelperAdvice[] advice = getFixture().getEditHelperAdvice(
dynamicSpecializationType);
assertTrue(Arrays.asList(advice).contains(specialAdvice));
}
public void test_register_metamodelType() {
String id = "dynamic.metamodel.type"; //$NON-NLS-1$
final IMetamodelType dynamicMetamodelType = new MetamodelType(id, null, id, EmployeePackage.eINSTANCE.getLocation(), null);
final boolean[] listenerNotified = new boolean[] {false};
IElementTypeRegistryListener listener = new IElementTypeRegistryListener() {
public void elementTypeAdded(
ElementTypeAddedEvent elementTypeAddedEvent) {
listenerNotified[0] = true;
assertEquals(dynamicMetamodelType.getId(), elementTypeAddedEvent
.getElementTypeId());
}
};
boolean result;
ElementTypeRegistry.getInstance().addElementTypeRegistryListener(listener);
try {
result = ElementTypeRegistry.getInstance().register(dynamicMetamodelType);
} finally {
ElementTypeRegistry.getInstance().removeElementTypeRegistryListener(listener);
}
assertTrue(result);
assertTrue(listenerNotified[0]);
assertSame(dynamicMetamodelType, ElementTypeRegistry.getInstance().getType(id));
}
public void test_nullElementType_specialization() {
IElementType nullSpecialization = getFixture().getType(
"org.eclipse.gmf.tests.runtime.emf.type.core.nullSpecialization"); //$NON-NLS-1$
assertNotNull(nullSpecialization);
RecordingCommand recordingCommand = new RecordingCommand(getEditingDomain()) {
protected void doExecute() {
department.setManager(null);
};
};
try {
((TransactionalCommandStack) getEditingDomain().getCommandStack()).execute(recordingCommand,
null);
} catch (RollbackException re) {
fail("setUp() failed:" + re.getLocalizedMessage()); //$NON-NLS-1$
} catch (InterruptedException ie) {
fail("setUp() failed:" + ie.getLocalizedMessage()); //$NON-NLS-1$
}
assertNull(department.getManager());
CreateElementRequest createRequest = new CreateElementRequest(getEditingDomain(),
department, nullSpecialization);
createRequest.setParameter("MANAGER", manager); //$NON-NLS-1$
IElementType elementType = ElementTypeRegistry.getInstance()
.getElementType(createRequest.getEditHelperContext());
ICommand command = elementType.getEditCommand(createRequest);
assertNotNull(command);
assertTrue(command.canExecute());
try {
command.execute(new NullProgressMonitor(), null);
} catch (ExecutionException e) {
fail(e.getLocalizedMessage());
}
assertSame(manager, department.getManager());
assertNull(command.getCommandResult().getReturnValue());
}
/**
* Verifies that the original metamodel type array is not reversed by the
* #getAllTypesMatching method.
*/
public void test_getAllTypesMatching_146097() {
IElementType[] superTypes = EmployeeType.HIGH_SCHOOL_STUDENT
.getAllSuperTypes();
assertEquals(2, superTypes.length);
assertEquals(superTypes[0], EmployeeType.EMPLOYEE);
assertEquals(superTypes[1], EmployeeType.STUDENT);
IElementType[] highSchoolStudentMatches = getFixture()
.getAllTypesMatching(highSchoolStudent);
assertTrue(highSchoolStudentMatches.length == 3);
assertTrue(highSchoolStudentMatches[0] == EmployeeType.HIGH_SCHOOL_STUDENT);
assertTrue(highSchoolStudentMatches[1] == EmployeeType.STUDENT);
assertTrue(highSchoolStudentMatches[2] == EmployeeType.EMPLOYEE);
// check that the super types array was not reversed by the call to
// #getAllSuperTypes
assertEquals(superTypes[0], EmployeeType.EMPLOYEE);
assertEquals(superTypes[1], EmployeeType.STUDENT);
}
/**
* Tests that when finding the nearest metamodel type that matches a given
* model object (when there is no type registered specifically against its
* EClass in current client context), the ElementTypeRegistry finds the type
* for the nearest supertype EClass in the current client context.
*/
public void test_getMetamodelType_157788() {
final Resource r = getEditingDomain()
.getResourceSet()
.createResource(
URI
.createURI("null://org.eclipse.gmf.tests.runtime.emf.type.core.157788")); //$NON-NLS-1$
final Student[] s = new Student[1];
RecordingCommand command = new RecordingCommand(getEditingDomain()) {
protected void doExecute() {
Department d = (Department) getEmployeeFactory().create(
getEmployeePackage().getDepartment());
d.setName("Department_157788"); //$NON-NLS-1$
r.getContents().add(d);
s[0] = (Student) getEmployeeFactory().create(
getEmployeePackage().getStudent());
s[0].setNumber(157788);
d.getMembers().add(s[0]);
};
};
try {
((TransactionalCommandStack) getEditingDomain().getCommandStack()).execute(command,
null);
} catch (RollbackException re) {
fail("test_getMetamodelType_157788 setup failed:" + re.getLocalizedMessage()); //$NON-NLS-1$
} catch (InterruptedException ie) {
fail("test_getMetamodelType_157788 setup failed:" + ie.getLocalizedMessage()); //$NON-NLS-1$
}
IElementType type = ElementTypeRegistry.getInstance().getElementType(s[0]);
assertNotNull(type);
assertEquals(
"org.eclipse.gmf.tests.runtime.emf.type.core.157788.employee", type.getId()); //$NON-NLS-1$
}
/**
* Tests that dynamically-added metamodel types can be removed from the
* registry.
*
* @see https://bugs.eclipse.org/bugs/show_bug.cgi?id=457888
*/
public void test_deregister_metamodelType_457888() {
String id = "dynamic.metamodel.typeToBeRemoved"; //$NON-NLS-1$
final IMetamodelType dynamicMetamodelType = new MetamodelType(id, null, id,
EmployeePackage.eINSTANCE.getLocation(), null);
// Register the type now
getFixture().register(dynamicMetamodelType);
final boolean[] listenerNotified = new boolean[] { false };
IElementTypeRegistryListener2 listener = new ElementTypeRegistryAdapter() {
@Override
public void elementTypeRemoved(ElementTypeRemovedEvent event) {
listenerNotified[0] = true;
assertEquals(dynamicMetamodelType.getId(), event.getElementTypeId());
assertSame(dynamicMetamodelType, event.getElementType());
}
};
boolean result;
getFixture().addElementTypeRegistryListener(listener);
try {
result = getFixture().deregister(dynamicMetamodelType);
} finally {
getFixture().removeElementTypeRegistryListener(listener);
}
assertTrue(result);
assertTrue(listenerNotified[0]);
assertNull(getFixture().getType(id));
}
/**
* Tests that dynamically-added specialization types can be removed from the
* registry.
*
* @see https://bugs.eclipse.org/bugs/show_bug.cgi?id=457888
*/
public void test_deregister_specializationType_457888() {
IEditHelperAdvice specialAdvice = new MySpecializationAdvice();
String id = "dynamic.specialization.typeToBeRemoved"; //$NON-NLS-1$
final ISpecializationType dynamicSpecializationType = new SpecializationType(id, null, id,
new IElementType[] { EmployeeType.EMPLOYEE }, null, null, specialAdvice);
// Register the type now
getFixture().register(dynamicSpecializationType);
final boolean[] listenerNotified = new boolean[] { false };
IElementTypeRegistryListener2 listener = new ElementTypeRegistryAdapter() {
@Override
public void elementTypeRemoved(ElementTypeRemovedEvent event) {
listenerNotified[0] = true;
assertEquals(dynamicSpecializationType.getId(), event.getElementTypeId());
assertSame(dynamicSpecializationType, event.getElementType());
}
};
boolean result;
getFixture().addElementTypeRegistryListener(listener);
try {
result = getFixture().deregister(dynamicSpecializationType);
} finally {
getFixture().removeElementTypeRegistryListener(listener);
}
// Check that the element type was deregistered
assertTrue(result);
assertTrue(listenerNotified[0]);
assertNull(getFixture().getType(id));
// Check that the advice can no longer be retrieved
IEditHelperAdvice[] advice = getFixture().getEditHelperAdvice(dynamicSpecializationType);
assertFalse(Arrays.asList(advice).contains(advice));
// And the removed type's supertype has forgotten the subtype
assertFalse(Arrays.asList(getFixture().getSpecializationsOf(EmployeeType.EMPLOYEE.getId())).contains(
dynamicSpecializationType));
}
/**
* Tests that statically-registered metamodel types from the extension point
* cannot be removed from the registry (except by unloading the contributing
* plug-in, which is not tested here).
*
* @see https://bugs.eclipse.org/bugs/show_bug.cgi?id=457888
*/
public void test_deregister_static_metamodelType_457888() {
String id = "org.eclipse.gmf.tests.runtime.emf.type.core.department"; //$NON-NLS-1$
final IMetamodelType staticMetamodelType = (IMetamodelType) getFixture().getType(id);
final boolean[] listenerNotified = new boolean[] { false };
IElementTypeRegistryListener2 listener = new ElementTypeRegistryAdapter() {
@Override
public void elementTypeRemoved(ElementTypeRemovedEvent event) {
listenerNotified[0] = true;
}
};
boolean result;
getFixture().addElementTypeRegistryListener(listener);
try {
result = getFixture().deregister(staticMetamodelType);
} finally {
getFixture().removeElementTypeRegistryListener(listener);
}
assertFalse(result);
assertFalse(listenerNotified[0]);
assertSame(staticMetamodelType, getFixture().getType(id));
}
/**
* Tests that statically-registered specialization types from the extension
* point cannot be removed from the registry (except by unloading the
* contributing plug-in, which is not tested here).
*
* @see https://bugs.eclipse.org/bugs/show_bug.cgi?id=457888
*/
public void test_deregister_static_specializationType_457888() {
String id = "org.eclipse.gmf.tests.runtime.emf.type.core.secretDepartment"; //$NON-NLS-1$
final ISpecializationType staticSpecializationType = (ISpecializationType) getFixture().getType(id);
final boolean[] listenerNotified = new boolean[] { false };
IElementTypeRegistryListener2 listener = new ElementTypeRegistryAdapter() {
@Override
public void elementTypeRemoved(ElementTypeRemovedEvent event) {
listenerNotified[0] = true;
}
};
boolean result;
getFixture().addElementTypeRegistryListener(listener);
try {
result = getFixture().deregister(staticSpecializationType);
} finally {
getFixture().removeElementTypeRegistryListener(listener);
}
assertFalse(result);
assertFalse(listenerNotified[0]);
assertSame(staticSpecializationType, getFixture().getType(id));
}
/**
* Tests that when a metamodel type is removed that has specializations
* (sub-types) extant, it cannot be removed because the subtypes depend on
* it, but it can be removed after its subtypes are removed.
*
* @see https://bugs.eclipse.org/bugs/show_bug.cgi?id=457888
*/
public void test_deregister_metamodelType_extantSpecializations_457888() {
String id = "dynamic.metamodel.typeToBeRemoved"; //$NON-NLS-1$
final IMetamodelType dynamicMetamodelType = new MetamodelType(id, null, id,
EmployeePackage.eINSTANCE.getLocation(), null);
String subID = "dynamic.specialization.typeToBeRemoved"; //$NON-NLS-1$
final ISpecializationType dynamicSpecializationType = new SpecializationType(subID, null, subID,
new IElementType[] { dynamicMetamodelType }, null, null, new MySpecializationAdvice());
final Set<IElementType> bothTypes = new HashSet<IElementType>(Arrays.asList(dynamicMetamodelType,
dynamicSpecializationType));
// Register the types now
getFixture().register(dynamicMetamodelType);
getFixture().register(dynamicSpecializationType);
final int[] listenerNotified = new int[] { 0 };
final Set<IElementType> removed = new HashSet<IElementType>();
IElementTypeRegistryListener2 listener = new ElementTypeRegistryAdapter() {
@Override
public void elementTypeRemoved(ElementTypeRemovedEvent event) {
listenerNotified[0]++;
removed.add(event.getElementType());
}
};
boolean result;
getFixture().addElementTypeRegistryListener(listener);
try {
result = getFixture().deregister(dynamicMetamodelType);
// Assert that nothing was removed
assertFalse(result);
assertEquals(0, listenerNotified[0]);
assertEquals(Collections.EMPTY_SET, removed);
// Now try removing the subtype and then the supertype
result = getFixture().deregister(dynamicSpecializationType);
result = result && getFixture().deregister(dynamicMetamodelType);
// Check both element types were deregistered
assertTrue(result);
assertEquals(2, listenerNotified[0]);
assertEquals(bothTypes, removed);
assertNull(getFixture().getType(id));
assertNull(getFixture().getType(subID));
// And the removed type's supertype has forgotten the subtype
assertFalse(Arrays.asList(getFixture().getSpecializationsOf(id)).contains(dynamicSpecializationType));
} finally {
getFixture().removeElementTypeRegistryListener(listener);
}
}
/**
* Tests that when a specialization type is removed that has specializations
* (sub-types) of its own, it cannot be removed because the subtypes depend
* on it, but it can be removed after its subtypes are removed.
*
* @see https://bugs.eclipse.org/bugs/show_bug.cgi?id=457888
*/
public void test_deregister_specializationType_extantSubtypes_457888() {
String id = "dynamic.specialization.typeToBeRemoved"; //$NON-NLS-1$
final ISpecializationType dynamicSpecializationType = new SpecializationType(id, null, id,
new IElementType[] { EmployeeType.EMPLOYEE }, null, null, new MySpecializationAdvice());
String subID = "dynamic.specialization.typeToBeRemoved.sub"; //$NON-NLS-1$
final ISpecializationType dynamicSpecializationTypeSubtype = new SpecializationType(subID, null, subID,
new IElementType[] { dynamicSpecializationType, EmployeeType.CLIENT }, null, null,
new MySpecializationAdvice());
final Set<IElementType> bothTypes = new HashSet<IElementType>(Arrays.asList(dynamicSpecializationType,
dynamicSpecializationTypeSubtype));
// Register the types now
getFixture().register(dynamicSpecializationType);
getFixture().register(dynamicSpecializationTypeSubtype);
final int[] listenerNotified = new int[] { 0 };
final Set<IElementType> removed = new HashSet<IElementType>();
IElementTypeRegistryListener2 listener = new ElementTypeRegistryAdapter() {
@Override
public void elementTypeRemoved(ElementTypeRemovedEvent event) {
listenerNotified[0]++;
removed.add(event.getElementType());
}
};
boolean result;
getFixture().addElementTypeRegistryListener(listener);
try {
result = getFixture().deregister(dynamicSpecializationType);
// Assert that nothing was removed
assertFalse(result);
assertEquals(0, listenerNotified[0]);
assertEquals(Collections.EMPTY_SET, removed);
// Now try removing the subtype and then the supertype
result = getFixture().deregister(dynamicSpecializationTypeSubtype);
result = result && getFixture().deregister(dynamicSpecializationType);
// Check both element types were deregistered
assertTrue(result);
assertEquals(2, listenerNotified[0]);
assertEquals(bothTypes, removed);
assertNull(getFixture().getType(id));
assertNull(getFixture().getType(subID));
// And the removed type's supertype has forgotten the subtype
assertFalse(Arrays.asList(getFixture().getSpecializationsOf(id)).contains(dynamicSpecializationTypeSubtype));
} finally {
getFixture().removeElementTypeRegistryListener(listener);
}
}
/**
* Tests that advice bindings can be dynamically added and removed from the
* registry.
*
* @see https://bugs.eclipse.org/bugs/show_bug.cgi?id=457888
*/
public void test_register_deregister_adviceBinding_457888() {
String id = "dynamic.advice.toBeRemoved"; //$NON-NLS-1$
final IAdviceBindingDescriptor advice = new MyAdviceBindingDescriptor(id, EmployeeType.EMPLOYEE.getId());
final boolean[] listenerNotifiedAdd = new boolean[] { false };
final boolean[] listenerNotifiedRemove = new boolean[] { false };
IElementTypeRegistryListener2 listener = new ElementTypeRegistryAdapter() {
public void adviceBindingAdded(AdviceBindingAddedEvent event) {
listenerNotifiedAdd[0] = true;
assertSame(advice, event.getAdviceBinding());
}
@Override
public void adviceBindingRemoved(AdviceBindingRemovedEvent event) {
listenerNotifiedRemove[0] = true;
assertSame(advice, event.getAdviceBinding());
}
};
boolean result;
getFixture().addElementTypeRegistryListener(listener);
try {
result = getFixture().registerAdvice(advice);
result = result && getFixture().deregisterAdvice(advice);
} finally {
getFixture().removeElementTypeRegistryListener(listener);
}
// Check that the element type was deregistered
assertTrue(result);
assertTrue(listenerNotifiedAdd[0]);
assertTrue(listenerNotifiedRemove[0]);
// Check that the advice can no longer be retrieved
IEditHelperAdvice boundAdvice = null;
for (IEditHelperAdvice next : Arrays.asList(getFixture().getEditHelperAdvice(EmployeeType.EMPLOYEE))) {
if (next instanceof MyAdvice) {
boundAdvice = next;
break;
}
}
assertNull(boundAdvice);
}
/**
* Tests that statically-registered advice bindings from the extension point
* cannot be removed from the registry (except by unloading the contributing
* plug-in, which is not tested here).
*
* @see https://bugs.eclipse.org/bugs/show_bug.cgi?id=457888
*/
public void test_deregister_static_adviceBinding_457888() {
String id = "org.eclipse.gmf.tests.runtime.emf.type.core.financeEmployee"; //$NON-NLS-1$
// Fake up a descriptor to try to remove the static advice
final IAdviceBindingDescriptor advice = new MyAdviceBindingDescriptor(id, EmployeeType.EMPLOYEE.getId());
final boolean[] listenerNotifiedRemove = new boolean[] { false };
IElementTypeRegistryListener2 listener = new ElementTypeRegistryAdapter() {
@Override
public void adviceBindingRemoved(AdviceBindingRemovedEvent event) {
listenerNotifiedRemove[0] = true;
assertSame(advice, event.getAdviceBinding());
}
};
boolean result;
getFixture().addElementTypeRegistryListener(listener);
try {
result = getFixture().deregisterAdvice(advice);
} finally {
getFixture().removeElementTypeRegistryListener(listener);
}
assertFalse(result);
assertFalse(listenerNotifiedRemove[0]);
}
}
| 62,997
|
Java
|
.java
| 1,379
| 41.933285
| 125
| 0.776006
|
Samsung/gmf-runtime
| 4
| 5
| 0
|
EPL-1.0
|
9/4/2024, 11:09:04 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 62,997
|
4,412,455
|
IteratorEnumeration.java
|
JOM3C4_nHCFSource/src/org/apache/commons/collections4/iterators/IteratorEnumeration.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.commons.collections4.iterators;
import java.util.Enumeration;
import java.util.Iterator;
/**
* Adapter to make an {@link Iterator Iterator} instance appear to be an
* {@link Enumeration Enumeration} instance.
*
* @since 1.0
* @version $Id: IteratorEnumeration.java 1543728 2013-11-20 07:51:32Z ebourg $
*/
public class IteratorEnumeration<E> implements Enumeration<E> {
/** The iterator being decorated. */
private Iterator<? extends E> iterator;
/**
* Constructs a new <code>IteratorEnumeration</code> that will not function
* until {@link #setIterator(Iterator) setIterator} is invoked.
*/
public IteratorEnumeration() {
}
/**
* Constructs a new <code>IteratorEnumeration</code> that will use the given
* iterator.
*
* @param iterator the iterator to use
*/
public IteratorEnumeration(final Iterator<? extends E> iterator) {
this.iterator = iterator;
}
// Iterator interface
// -------------------------------------------------------------------------
/**
* Returns true if the underlying iterator has more elements.
*
* @return true if the underlying iterator has more elements
*/
public boolean hasMoreElements() {
return iterator.hasNext();
}
/**
* Returns the next element from the underlying iterator.
*
* @return the next element from the underlying iterator.
* @throws java.util.NoSuchElementException if the underlying iterator has no
* more elements
*/
public E nextElement() {
return iterator.next();
}
// Properties
// -------------------------------------------------------------------------
/**
* Returns the underlying iterator.
*
* @return the underlying iterator
*/
public Iterator<? extends E> getIterator() {
return iterator;
}
/**
* Sets the underlying iterator.
*
* @param iterator the new underlying iterator
*/
public void setIterator(final Iterator<? extends E> iterator) {
this.iterator = iterator;
}
}
| 2,796
|
Java
|
.java
| 83
| 31.253012
| 79
| 0.694928
|
JOM3C4/nHCFSource
| 2
| 0
| 0
|
GPL-3.0
|
9/5/2024, 12:12:08 AM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 2,796
|
4,949,914
|
ShoppingApplication.java
|
cockroachzl_JavaWebService/jaxrs2/ex10_2/src/main/java/com/restfully/shop/services/ShoppingApplication.java
|
package com.restfully.shop.services;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
@ApplicationPath("/services")
public class ShoppingApplication extends Application
{
private Set<Object> singletons = new HashSet<Object>();
public ShoppingApplication()
{
singletons.add(new CustomerResource());
singletons.add(new OrderResource());
singletons.add(new StoreResource());
}
@Override
public Set<Object> getSingletons()
{
return singletons;
}
}
| 568
|
Java
|
.java
| 21
| 23.571429
| 58
| 0.753223
|
cockroachzl/JavaWebService
| 1
| 0
| 0
|
GPL-3.0
|
9/5/2024, 12:36:54 AM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 568
|
1,320,623
|
A.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameMethodInInterface/test3/in/A.java
|
//renaming I.m to k
package p;
class B {
public void m(){};
}
class A extends B implements I{
}
interface I {
void m();
}
| 125
|
Java
|
.java
| 10
| 11.2
| 31
| 0.672414
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 125
|
1,316,753
|
A.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test32/out/A.java
|
package p1;
public class A {
public int foo() {
class P {
public void m() {
}
};
class O {
};
return 0;
}
}
| 130
|
Java
|
.java
| 12
| 8
| 20
| 0.543103
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 130
|
1,316,936
|
A.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/PushDown/test22/out/A.java
|
package p;
class A {
}
class B extends A {
private int x;
private int bar;
public void fred(){
}
}
| 105
|
Java
|
.java
| 9
| 10
| 20
| 0.702128
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 105
|
1,315,300
|
A_test45_in.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTemp/canRename/A_test45_in.java
|
package p;
class A{
void m(){
int xx;
}
}
| 45
|
Java
|
.java
| 6
| 6
| 10
| 0.6
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 45
|
1,497,327
|
L2AttackableAI.java
|
L2jBrasil_L2jBrasil/L2JBrasil_CORE/java/com/it/br/gameserver/ai/L2AttackableAI.java
|
/*
* 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, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* http://www.gnu.org/copyleft/gpl.html
*/
package com.it.br.gameserver.ai;
import static com.it.br.gameserver.ai.CtrlIntention.AI_INTENTION_ACTIVE;
import static com.it.br.gameserver.ai.CtrlIntention.AI_INTENTION_ATTACK;
import static com.it.br.gameserver.ai.CtrlIntention.AI_INTENTION_IDLE;
import java.util.concurrent.Future;
import com.it.br.Config;
import com.it.br.gameserver.GameTimeController;
import com.it.br.gameserver.GeoData;
import com.it.br.gameserver.ThreadPoolManager;
import com.it.br.gameserver.datatables.xml.TerritoryTable;
import com.it.br.gameserver.instancemanager.DimensionalRiftManager;
import com.it.br.gameserver.model.L2Attackable;
import com.it.br.gameserver.model.L2CharPosition;
import com.it.br.gameserver.model.L2Character;
import com.it.br.gameserver.model.L2Effect;
import com.it.br.gameserver.model.L2Object;
import com.it.br.gameserver.model.L2Skill;
import com.it.br.gameserver.model.L2Summon;
import com.it.br.gameserver.model.actor.instance.L2ChestInstance;
import com.it.br.gameserver.model.actor.instance.L2DoorInstance;
import com.it.br.gameserver.model.actor.instance.L2FestivalMonsterInstance;
import com.it.br.gameserver.model.actor.instance.L2FolkInstance;
import com.it.br.gameserver.model.actor.instance.L2FriendlyMobInstance;
import com.it.br.gameserver.model.actor.instance.L2GrandBossInstance;
import com.it.br.gameserver.model.actor.instance.L2GuardInstance;
import com.it.br.gameserver.model.actor.instance.L2MinionInstance;
import com.it.br.gameserver.model.actor.instance.L2MonsterInstance;
import com.it.br.gameserver.model.actor.instance.L2NpcInstance;
import com.it.br.gameserver.model.actor.instance.L2PcInstance;
import com.it.br.gameserver.model.actor.instance.L2PenaltyMonsterInstance;
import com.it.br.gameserver.model.actor.instance.L2RaidBossInstance;
import com.it.br.gameserver.model.actor.instance.L2RiftInvaderInstance;
import com.it.br.gameserver.model.quest.Quest;
import com.it.br.gameserver.templates.L2Weapon;
import com.it.br.gameserver.templates.L2WeaponType;
import com.it.br.util.Rnd;
/**
* This class manages AI of L2Attackable.<BR>
* <BR>
*/
public class L2AttackableAI extends L2CharacterAI implements Runnable
{
//protected static final Logger _log = Logger.getLogger(L2AttackableAI.class.getName());
private static final int RANDOM_WALK_RATE = 30; // confirmed
// private static final int MAX_DRIFT_RANGE = 300;
private static final int MAX_ATTACK_TIMEOUT = 300; // int ticks, i.e. 30 seconds
/** The L2Attackable AI task executed every 1s (call onEvtThink method) */
private Future<?> _aiTask;
/** The delay after wich the attacked is stopped */
private int _attackTimeout;
/** The L2Attackable aggro counter */
private int _globalAggro;
/** The flag used to indicate that a thinking action is in progress */
private boolean _thinking; // to prevent recursive thinking
/**
* Constructor of L2AttackableAI.<BR>
* <BR>
*
* @param accessor The AI accessor of the L2Character
*/
public L2AttackableAI(L2Character.AIAccessor accessor)
{
super(accessor);
_attackTimeout = Integer.MAX_VALUE;
_globalAggro = -10; // 10 seconds timeout of ATTACK after respawn
}
public void run()
{
// Launch actions corresponding to the Event Think
onEvtThink();
}
/**
* Return True if the target is autoattackable (depends on the actor type).<BR>
* <BR>
* <B><U> Actor is a L2GuardInstance</U> :</B><BR>
* <BR>
* <li>The target isn't a Folk or a Door</li> <li>The target isn't dead, isn't invulnerable, isn't in silent moving
* mode AND too far (>100)</li> <li>The target is in the actor Aggro range and is at the same height</li> <li>The
* L2PcInstance target has karma (=PK)</li> <li>The L2MonsterInstance target is aggressive</li><BR>
* <BR>
* <B><U> Actor is a L2SiegeGuardInstance</U> :</B><BR>
* <BR>
* <li>The target isn't a Folk or a Door</li> <li>The target isn't dead, isn't invulnerable, isn't in silent moving
* mode AND too far (>100)</li> <li>The target is in the actor Aggro range and is at the same height</li> <li>A
* siege is in progress</li> <li>The L2PcInstance target isn't a Defender</li><BR>
* <BR>
* <B><U> Actor is a L2FriendlyMobInstance</U> :</B><BR>
* <BR>
* <li>The target isn't a Folk, a Door or another L2NpcInstance</li> <li>The target isn't dead, isn't invulnerable,
* isn't in silent moving mode AND too far (>100)</li> <li>The target is in the actor Aggro range and is at the same
* height</li> <li>The L2PcInstance target has karma (=PK)</li><BR>
* <BR>
* <B><U> Actor is a L2MonsterInstance</U> :</B><BR>
* <BR>
* <li>The target isn't a Folk, a Door or another L2NpcInstance</li> <li>The target isn't dead, isn't invulnerable,
* isn't in silent moving mode AND too far (>100)</li> <li>The target is in the actor Aggro range and is at the same
* height</li> <li>The actor is Aggressive</li><BR>
* <BR>
*
* @param target The targeted L2Object
*/
private boolean autoAttackCondition(L2Character target)
{
if(target == null || !(_actor instanceof L2Attackable))
return false;
L2Attackable me = (L2Attackable) _actor;
// Check if the target isn't invulnerable
if(target.isInvul())
{
// However EffectInvincible requires to check GMs specially
if(target instanceof L2PcInstance && ((L2PcInstance) target).isGM())
return false;
if(target instanceof L2Summon && ((L2Summon) target).getOwner().isGM())
return false;
}
// Check if the target isn't a Folk or a Door
if(target instanceof L2FolkInstance || target instanceof L2DoorInstance)
return false;
// Check if the target isn't dead, is in the Aggro range and is at the same height
if(target.isAlikeDead() || !me.isInsideRadius(target, me.getAggroRange(), false, false) || Math.abs(_actor.getZ() - target.getZ()) > 300)
return false;
// Check if the target is a L2PcInstance
if(target instanceof L2PcInstance)
{
// Check if the AI isn't a Raid Boss and the target isn't in silent move mode
if(!(me instanceof L2RaidBossInstance) && ((L2PcInstance) target).isSilentMoving())
return false;
// Check if player is an ally //TODO! [Nemesiss] it should be rather boolean or smth like that
// Comparing String isn't good idea!
if(me.getFactionId() == "varka" && ((L2PcInstance) target).isAlliedWithVarka())
return false;
if(me.getFactionId() == "ketra" && ((L2PcInstance) target).isAlliedWithKetra())
return false;
// check if the target is within the grace period for JUST getting up from fake death
if(((L2PcInstance) target).isRecentFakeDeath())
return false;
// check player is in away mod
if(((L2PcInstance) target).isAway() && !Config.AWAY_PLAYER_TAKE_AGGRO)
return false;
if(target.isInParty() && target.getParty().isInDimensionalRift())
{
byte riftType = target.getParty().getDimensionalRift().getType();
byte riftRoom = target.getParty().getDimensionalRift().getCurrentRoom();
if(me instanceof L2RiftInvaderInstance && !DimensionalRiftManager.getInstance().getRoom(riftType, riftRoom).checkIfInZone(me.getX(), me.getY(), me.getZ()))
return false;
}
}
// Check if the actor is a L2GuardInstance
if(_actor instanceof L2GuardInstance)
{
// Check if the L2PcInstance target has karma (=PK)
if(target instanceof L2PcInstance && ((L2PcInstance) target).getKarma() > 0)
// Los Check
return GeoData.getInstance().canSeeTarget(me, target);
//if (target instanceof L2Summon)
// return ((L2Summon)target).getKarma() > 0;
// Check if the L2MonsterInstance target is aggressive
if(target instanceof L2MonsterInstance)
return ((L2MonsterInstance) target).isAggressive() && GeoData.getInstance().canSeeTarget(me, target);
return false;
}
else if(_actor instanceof L2FriendlyMobInstance)
{
// the actor is a L2FriendlyMobInstance
// Check if the target isn't another L2NpcInstance
if(target instanceof L2NpcInstance)
return false;
// Check if the L2PcInstance target has karma (=PK)
if(target instanceof L2PcInstance && ((L2PcInstance) target).getKarma() > 0)
// Los Check
return GeoData.getInstance().canSeeTarget(me, target);
return false;
}
else
{
//The actor is a L2MonsterInstance
// Check if the target isn't another L2NpcInstance
if(target instanceof L2NpcInstance)
return false;
// depending on config, do not allow mobs to attack _new_ players in peacezones,
// unless they are already following those players from outside the peacezone.
if(!Config.ALT_MOB_AGRO_IN_PEACEZONE && target.isInsideZone(L2Character.ZONE_PEACE))
return false;
// Check if the actor is Aggressive
return me.isAggressive() && GeoData.getInstance().canSeeTarget(me, target);
}
}
public void startAITask()
{
// If not idle - create an AI task (schedule onEvtThink repeatedly)
if(_aiTask == null)
{
_aiTask = ThreadPoolManager.getInstance().scheduleAiAtFixedRate(this, 1000, 1000);
}
}
public void stopAITask()
{
if(_aiTask != null)
{
_aiTask.cancel(false);
_aiTask = null;
}
}
@Override
protected void onEvtDead()
{
stopAITask();
super.onEvtDead();
}
/**
* Set the Intention of this L2CharacterAI and create an AI Task executed every 1s (call onEvtThink method) for this
* L2Attackable.<BR>
* <BR>
* <FONT COLOR=#FF0000><B> <U>Caution</U> : If actor _knowPlayer isn't EMPTY, AI_INTENTION_IDLE will be change in
* AI_INTENTION_ACTIVE</B></FONT><BR>
* <BR>
*
* @param intention The new Intention to set to the AI
* @param arg0 The first parameter of the Intention
* @param arg1 The second parameter of the Intention
*/
@Override
synchronized void changeIntention(CtrlIntention intention, Object arg0, Object arg1)
{
if(intention == AI_INTENTION_IDLE || intention == AI_INTENTION_ACTIVE)
{
// Check if actor is not dead
if(!_actor.isAlikeDead())
{
L2Attackable npc = (L2Attackable) _actor;
// If its _knownPlayer isn't empty set the Intention to AI_INTENTION_ACTIVE
if(npc.getKnownList().getKnownPlayers().size() > 0)
{
intention = AI_INTENTION_ACTIVE;
}
npc = null;
}
if(intention == AI_INTENTION_IDLE)
{
// Set the Intention of this L2AttackableAI to AI_INTENTION_IDLE
super.changeIntention(AI_INTENTION_IDLE, null, null);
// Stop AI task and detach AI from NPC
if(_aiTask != null)
{
_aiTask.cancel(true);
_aiTask = null;
}
// Cancel the AI
_accessor.detachAI();
return;
}
}
// Set the Intention of this L2AttackableAI to intention
super.changeIntention(intention, arg0, arg1);
// If not idle - create an AI task (schedule onEvtThink repeatedly)
startAITask();
}
/**
* Manage the Attack Intention : Stop current Attack (if necessary), Calculate attack timeout, Start a new Attack
* and Launch Think Event.<BR>
* <BR>
*
* @param target The L2Character to attack
*/
@Override
protected void onIntentionAttack(L2Character target)
{
// Calculate the attack timeout
_attackTimeout = MAX_ATTACK_TIMEOUT + GameTimeController.getGameTicks();
// Manage the Attack Intention : Stop current Attack (if necessary), Start a new Attack and Launch Think Event
super.onIntentionAttack(target);
}
/**
* Manage AI standard thinks of a L2Attackable (called by onEvtThink).<BR>
* <BR>
* <B><U> Actions</U> :</B><BR>
* <BR>
* <li>Update every 1s the _globalAggro counter to come close to 0</li> <li>If the actor is Aggressive and can
* attack, add all autoAttackable L2Character in its Aggro Range to its _aggroList, chose a target and order to
* attack it</li> <li>If the actor is a L2GuardInstance that can't attack, order to it to return to its home
* location</li> <li>If the actor is a L2MonsterInstance that can't attack, order to it to random walk (1/100)</li><BR>
* <BR>
*/
@SuppressWarnings("unused")
private void thinkActive()
{
L2Attackable npc = (L2Attackable) _actor;
// Update every 1s the _globalAggro counter to come close to 0
if(_globalAggro != 0)
{
if(_globalAggro < 0)
{
_globalAggro++;
}
else
{
_globalAggro--;
}
}
// Add all autoAttackable L2Character in L2Attackable Aggro Range to its _aggroList with 0 damage and 1 hate
// A L2Attackable isn't aggressive during 10s after its spawn because _globalAggro is set to -10
if(_globalAggro >= 0)
{
// Get all visible objects inside its Aggro Range
//L2Object[] objects = L2World.getInstance().getVisibleObjects(_actor, ((L2NpcInstance)_actor).getAggroRange());
// Go through visible objects
for(L2Object obj : npc.getKnownList().getKnownObjects().values())
{
if(obj == null || !(obj instanceof L2Character))
{
continue;
}
L2Character target = (L2Character) obj;
/*
* Check to see if this is a festival mob spawn.
* If it is, then check to see if the aggro trigger
* is a festival participant...if so, move to attack it.
*/
if(_actor instanceof L2FestivalMonsterInstance && obj instanceof L2PcInstance)
{
L2PcInstance targetPlayer = (L2PcInstance) obj;
if(!targetPlayer.isFestivalParticipant())
{
continue;
}
targetPlayer = null;
}
if(obj instanceof L2PcInstance || obj instanceof L2Summon)
{
if(!((L2Character) obj).isAlikeDead() && !npc.isInsideRadius(obj, npc.getAggroRange(), true, false))
{
L2PcInstance targetPlayer = obj instanceof L2PcInstance ? (L2PcInstance) obj : ((L2Summon) obj).getOwner();
}
}
// For each L2Character check if the target is autoattackable
if(autoAttackCondition(target)) // check aggression
{
// Get the hate level of the L2Attackable against this L2Character target contained in _aggroList
int hating = npc.getHating(target);
// Add the attacker to the L2Attackable _aggroList with 0 damage and 1 hate
if(hating == 0)
{
npc.addDamageHate(target, 0, 1);
}
}
target = null;
}
// Chose a target from its aggroList
L2Character hated;
// Force mobs to attak anybody if confused
if(_actor.isConfused())
{
hated = getAttackTarget();
}
else
{
hated = npc.getMostHated();
}
// Order to the L2Attackable to attack the target
if(hated != null)
{
// Get the hate level of the L2Attackable against this L2Character target contained in _aggroList
int aggro = npc.getHating(hated);
if(aggro + _globalAggro > 0)
{
// Set the L2Character movement type to run and send Server->Client packet ChangeMoveType to all others L2PcInstance
if(!_actor.isRunning())
{
_actor.setRunning();
}
// Set the AI Intention to AI_INTENTION_ATTACK
setIntention(CtrlIntention.AI_INTENTION_ATTACK, hated);
}
return;
}
}
// Check if the actor is a L2GuardInstance
if(_actor instanceof L2GuardInstance)
{
// Order to the L2GuardInstance to return to its home location because there's no target to attack
((L2GuardInstance) _actor).returnHome();
}
// If this is a festival monster, then it remains in the same location.
if(_actor instanceof L2FestivalMonsterInstance)
return;
// Minions following leader
if(_actor instanceof L2MinionInstance && ((L2MinionInstance) _actor).getLeader() != null)
{
int offset;
// for Raids - need correction
if(_actor.isRaid())
{
offset = 500;
}
else
{
// for normal minions - need correction :)
offset = 200;
}
if(((L2MinionInstance) _actor).getLeader().isRunning())
{
_actor.setRunning();
}
else
{
_actor.setWalking();
}
if(_actor.getPlanDistanceSq(((L2MinionInstance) _actor).getLeader()) > offset * offset)
{
int x1, y1, z1;
x1 = ((L2MinionInstance) _actor).getLeader().getX() + Rnd.nextInt((offset - 30) * 2) - (offset - 30);
y1 = ((L2MinionInstance) _actor).getLeader().getY() + Rnd.nextInt((offset - 30) * 2) - (offset - 30);
z1 = ((L2MinionInstance) _actor).getLeader().getZ();
// Move the actor to Location (x,y,z) server side AND client side by sending Server->Client packet CharMoveToLocation (broadcast)
return;
}
}
// Order to the L2MonsterInstance to random walk (1/100)
else if (npc.getSpawn() != null && Rnd.nextInt(RANDOM_WALK_RATE) == 0 && !(_actor instanceof L2MinionInstance || _actor instanceof L2ChestInstance))
{
int x1, y1, z1;
// If NPC with random coord in territory
if(npc.getSpawn().getLocx() == 0 && npc.getSpawn().getLocy() == 0)
{
// If NPC with random fixed coord, don't move
if(TerritoryTable.getInstance().getProcMax(npc.getSpawn().getLocation()) > 0)
return;
// Calculate a destination point in the spawn area
int p[] = TerritoryTable.getInstance().getRandomPoint(npc.getSpawn().getLocation());
x1 = p[0];
y1 = p[1];
z1 = p[2];
// Calculate the distance between the current position of the L2Character and the target (x,y)
double distance2 = _actor.getPlanDistanceSq(x1, y1);
if(distance2 > Config.MAX_DRIFT_RANGE * Config.MAX_DRIFT_RANGE)
{
npc.setisReturningToSpawnPoint(true);
float delay = (float) Math.sqrt(distance2) / Config.MAX_DRIFT_RANGE;
x1 = _actor.getX() + (int) ((x1 - _actor.getX()) / delay);
y1 = _actor.getY() + (int) ((y1 - _actor.getY()) / delay);
}
else
npc.setisReturningToSpawnPoint(false);
}
//_log.config("Curent pos ("+getX()+", "+getY()+"), moving to ("+x1+", "+y1+").");
// Move the actor to Location (x,y,z) server side AND client side by sending Server->Client packet CharMoveToLocation (broadcast)
}
npc = null;
return;
}
/**
* Manage AI attack thinks of a L2Attackable (called by onEvtThink).<BR>
* <BR>
* <B><U> Actions</U> :</B><BR>
* <BR>
* <li>Update the attack timeout if actor is running</li> <li>If target is dead or timeout is expired, stop this
* attack and set the Intention to AI_INTENTION_ACTIVE</li> <li>Call all L2Object of its Faction inside the Faction
* Range</li> <li>Chose a target and order to attack it with magic skill or physical attack</li><BR>
* <BR>
* TODO: Manage casting rules to healer mobs (like Ant Nurses)
*/
private void thinkAttack()
{
if(_attackTimeout < GameTimeController.getGameTicks())
{
// Check if the actor is running
if(_actor.isRunning())
{
// Set the actor movement type to walk and send Server->Client packet ChangeMoveType to all others L2PcInstance
_actor.setWalking();
// Calculate a new attack timeout
_attackTimeout = MAX_ATTACK_TIMEOUT + GameTimeController.getGameTicks();
}
}
// Check if target is dead or if timeout is expired to stop this attack
if(getAttackTarget() == null || getAttackTarget().isAlikeDead() || _attackTimeout < GameTimeController.getGameTicks())
{
// Stop hating this target after the attack timeout or if target is dead
if(getAttackTarget() != null)
{
L2Attackable npc = (L2Attackable) _actor;
npc.stopHating(getAttackTarget());
npc = null;
}
// Set the AI Intention to AI_INTENTION_ACTIVE
setIntention(AI_INTENTION_ACTIVE);
_actor.setWalking();
return;
}
// Call all L2Object of its Faction inside the Faction Range
if(((L2NpcInstance) _actor).getFactionId() != null)
{
// Go through all L2Object that belong to its faction
for(L2Object obj : _actor.getKnownList().getKnownObjects().values())
{
if(obj instanceof L2NpcInstance)
{
L2NpcInstance npc = (L2NpcInstance) obj;
String faction_id = ((L2NpcInstance) _actor).getFactionId();
if(getAttackTarget() == null || faction_id != npc.getFactionId())
continue;
// Check if the L2Object is inside the Faction Range of the actor
if(_actor.isInsideRadius(npc, npc.getFactionRange(), true, false) && _actor != null && npc.getAI() != null && GeoData.getInstance().canSeeTarget(_actor, npc) && Math.abs(getAttackTarget().getZ() - npc.getZ()) < 600 && _actor.getAttackByList().contains(getAttackTarget()) && (npc.getAI()._intention == CtrlIntention.AI_INTENTION_IDLE || npc.getAI()._intention == CtrlIntention.AI_INTENTION_ACTIVE))
{
if(getAttackTarget() instanceof L2PcInstance && getAttackTarget().isInParty() && getAttackTarget().getParty().isInDimensionalRift())
{
byte riftType = getAttackTarget().getParty().getDimensionalRift().getType();
byte riftRoom = getAttackTarget().getParty().getDimensionalRift().getCurrentRoom();
if(_actor instanceof L2RiftInvaderInstance && !DimensionalRiftManager.getInstance().getRoom(riftType, riftRoom).checkIfInZone(npc.getX(), npc.getY(), npc.getZ()))
continue;
}
// Notify the L2Object AI with EVT_AGGRESSION
npc.getAI().notifyEvent(CtrlEvent.EVT_AGGRESSION, getAttackTarget(), 1);
int chance = 4;
if (_actor instanceof L2MinionInstance)
// minions support boss
if (((L2MinionInstance) _actor).getLeader() == npc)
chance = 6;
else
chance = 3;
// XXX All the ai system needs to be recoded..
if (npc instanceof L2GrandBossInstance)
chance = 6;
if (chance >= Rnd.get(100)) // chance
continue;
if (!GeoData.getInstance().canSeeTarget(_actor, npc))
break;
if (getAttackTarget() instanceof L2PcInstance || getAttackTarget() instanceof L2Summon)
{
L2PcInstance player = getAttackTarget() instanceof L2PcInstance ? (L2PcInstance) getAttackTarget() : ((L2Summon) getAttackTarget()).getOwner();
if (npc.getTemplate().getEventQuests(Quest.QuestEventType.ON_FACTION_CALL) != null)
for (Quest quest : npc.getTemplate().getEventQuests(Quest.QuestEventType.ON_FACTION_CALL))
quest.notifyFactionCall(npc, (L2NpcInstance) _actor, player, (getAttackTarget() instanceof L2Summon));
}
}
}
}
}
if(_actor.isAttackingDisabled())
return;
// Get all information needed to chose between physical or magical attack
L2Skill[] skills = null;
double dist2 = 0;
int range = 0;
try
{
_actor.setTarget(getAttackTarget());
skills = _actor.getAllSkills();
dist2 = _actor.getPlanDistanceSq(getAttackTarget().getX(), getAttackTarget().getY());
range = _actor.getPhysicalAttackRange() + _actor.getTemplate().collisionRadius + getAttackTarget().getTemplate().collisionRadius;
}
catch(NullPointerException e)
{
//_log.warning("AttackableAI: Attack target is NULL.");
setIntention(AI_INTENTION_ACTIVE);
return;
}
L2Weapon weapon = _actor.getActiveWeaponItem();
if(weapon != null && weapon.getItemType() == L2WeaponType.BOW)
{
// Micht: kepping this one otherwise we should do 2 sqrt
double distance2 = _actor.getPlanDistanceSq(getAttackTarget().getX(), getAttackTarget().getY());
if(distance2 <= 10000)
{
int chance = 5;
if(chance >= Rnd.get(100))
{
int posX = _actor.getX();
int posY = _actor.getY();
int posZ = _actor.getZ();
double distance = Math.sqrt(distance2); // This way, we only do the sqrt if we need it
int signx = -1;
int signy = -1;
if(_actor.getX() > getAttackTarget().getX())
{
signx = 1;
}
if(_actor.getY() > getAttackTarget().getY())
{
signy = 1;
}
posX += Math.round((float) (signx * (range / 2 + Rnd.get(range)) - distance));
posY += Math.round((float) (signy * (range / 2 + Rnd.get(range)) - distance));
setIntention(CtrlIntention.AI_INTENTION_MOVE_TO, new L2CharPosition(posX, posY, posZ, 0));
return;
}
}
}
weapon = null;
// Force mobs to attack anybody if confused
L2Character hated;
if(_actor.isConfused())
{
hated = getAttackTarget();
}
else
{
hated = ((L2Attackable) _actor).getMostHated();
}
if(hated == null)
{
setIntention(AI_INTENTION_ACTIVE);
return;
}
if(hated != getAttackTarget())
{
setAttackTarget(hated);
}
// We should calculate new distance cuz mob can have changed the target
dist2 = _actor.getPlanDistanceSq(hated.getX(), hated.getY());
if(hated.isMoving())
{
range += 50;
}
// Check if the actor isn't far from target
if(dist2 > range * range)
{
// check for long ranged skills and heal/buff skills
if(!_actor.isMuted() && (!Config.ALT_GAME_MOB_ATTACK_AI || _actor instanceof L2MonsterInstance && Rnd.nextInt(100) <= 5))
{
for(L2Skill sk : skills)
{
int castRange = sk.getCastRange();
if((sk.getSkillType() == L2Skill.SkillType.BUFF || sk.getSkillType() == L2Skill.SkillType.HEAL || dist2 >= castRange * castRange / 9.0 && dist2 <= castRange * castRange && castRange > 70) && !_actor.isSkillDisabled(sk.getId()) && _actor.getCurrentMp() >= _actor.getStat().getMpConsume(sk) && !sk.isPassive() && Rnd.nextInt(100) <= 5)
{
if(sk.getSkillType() == L2Skill.SkillType.BUFF || sk.getSkillType() == L2Skill.SkillType.HEAL)
{
boolean useSkillSelf = true;
if(sk.getSkillType() == L2Skill.SkillType.HEAL && _actor.getCurrentHp() > (int) (_actor.getMaxHp() / 1.5))
{
useSkillSelf = false;
break;
}
if(sk.getSkillType() == L2Skill.SkillType.BUFF)
{
L2Effect[] effects = _actor.getAllEffects();
for(int i = 0; effects != null && i < effects.length; i++)
{
L2Effect effect = effects[i];
if(effect.getSkill() == sk)
{
useSkillSelf = false;
break;
}
}
effects = null;
}
if(useSkillSelf)
{
_actor.setTarget(_actor);
}
}
L2Object OldTarget = _actor.getTarget();
clientStopMoving(null);
_accessor.doCast(sk);
_actor.setTarget(OldTarget);
OldTarget = null;
return;
}
}
}
// Move the actor to Pawn server side AND client side by sending Server->Client packet MoveToPawn (broadcast)
if(hated.isMoving())
{
range -= 100;
}
if(range < 5)
{
range = 5;
}
moveToPawn(getAttackTarget(), range);
return;
}
// Else, if this is close enough to attack
_attackTimeout = MAX_ATTACK_TIMEOUT + GameTimeController.getGameTicks();
// check for close combat skills && heal/buff skills
if(!_actor.isMuted() /*&& _rnd.nextInt(100) <= 5*/)
{
boolean useSkillSelf = true;
for(L2Skill sk : skills)
{
if(/*sk.getCastRange() >= dist && sk.getCastRange() <= 70 && */!sk.isPassive() && _actor.getCurrentMp() >= _actor.getStat().getMpConsume(sk) && !_actor.isSkillDisabled(sk.getId()) && (Rnd.nextInt(100) <= 8 || _actor instanceof L2PenaltyMonsterInstance && Rnd.nextInt(100) <= 20))
{
if(sk.getSkillType() == L2Skill.SkillType.BUFF || sk.getSkillType() == L2Skill.SkillType.HEAL)
{
useSkillSelf = true;
if(sk.getSkillType() == L2Skill.SkillType.HEAL && _actor.getCurrentHp() > (int) (_actor.getMaxHp() / 1.5))
{
useSkillSelf = false;
break;
}
if(sk.getSkillType() == L2Skill.SkillType.BUFF)
{
L2Effect[] effects = _actor.getAllEffects();
for(int i = 0; effects != null && i < effects.length; i++)
{
L2Effect effect = effects[i];
if(effect.getSkill() == sk)
{
useSkillSelf = false;
break;
}
}
effects = null;
}
if(useSkillSelf)
{
_actor.setTarget(_actor);
}
}
// GeoData Los Check here
if(!useSkillSelf && !GeoData.getInstance().canSeeTarget(_actor, _actor.getTarget()))
return;
L2Object OldTarget = _actor.getTarget();
clientStopMoving(null);
_accessor.doCast(sk);
_actor.setTarget(OldTarget);
OldTarget = null;
return;
}
}
}
// Finally, physical attacks
clientStopMoving(null);
_accessor.doAttack(hated);
skills = null;
hated = null;
}
/**
* Manage AI thinking actions of a L2Attackable.<BR>
* <BR>
*/
@Override
protected void onEvtThink()
{
// Check if the actor can't use skills and if a thinking action isn't already in progress
if(_thinking || _actor.isAllSkillsDisabled())
return;
// Start thinking action
_thinking = true;
try
{
// Manage AI thinks of a L2Attackable
if(getIntention() == AI_INTENTION_ACTIVE)
{
thinkActive();
}
else if(getIntention() == AI_INTENTION_ATTACK)
{
thinkAttack();
}
}
finally
{
// Stop thinking action
_thinking = false;
}
}
/**
* Launch actions corresponding to the Event Attacked.<BR>
* <BR>
* <B><U> Actions</U> :</B><BR>
* <BR>
* <li>Init the attack : Calculate the attack timeout, Set the _globalAggro to 0, Add the attacker to the actor
* _aggroList</li> <li>Set the L2Character movement type to run and send Server->Client packet ChangeMoveType to all
* others L2PcInstance</li> <li>Set the Intention to AI_INTENTION_ATTACK</li><BR>
* <BR>
*
* @param attacker The L2Character that attacks the actor
*/
@Override
protected void onEvtAttacked(L2Character attacker)
{
// Calculate the attack timeout
_attackTimeout = MAX_ATTACK_TIMEOUT + GameTimeController.getGameTicks();
// Set the _globalAggro to 0 to permit attack even just after spawn
if(_globalAggro < 0)
{
_globalAggro = 0;
}
// Add the attacker to the _aggroList of the actor
((L2Attackable) _actor).addDamageHate(attacker, 0, 1);
// Set the L2Character movement type to run and send Server->Client packet ChangeMoveType to all others L2PcInstance
if(!_actor.isRunning())
{
_actor.setRunning();
}
// Set the Intention to AI_INTENTION_ATTACK
if(getIntention() != AI_INTENTION_ATTACK)
{
setIntention(CtrlIntention.AI_INTENTION_ATTACK, attacker);
}
else if(((L2Attackable) _actor).getMostHated() != getAttackTarget())
{
setIntention(CtrlIntention.AI_INTENTION_ATTACK, attacker);
}
super.onEvtAttacked(attacker);
}
/**
* Launch actions corresponding to the Event Aggression.<BR>
* <BR>
* <B><U> Actions</U> :</B><BR>
* <BR>
* <li>Add the target to the actor _aggroList or update hate if already present</li> <li>Set the actor Intention to
* AI_INTENTION_ATTACK (if actor is L2GuardInstance check if it isn't too far from its home location)</li><BR>
* <BR>
*
* @param The L2Character that attacks
* @param aggro The value of hate to add to the actor against the target
*/
@Override
protected void onEvtAggression(L2Character target, int aggro)
{
L2Attackable me = (L2Attackable) _actor;
if(target != null)
{
// Add the target to the actor _aggroList or update hate if already present
me.addDamageHate(target, 0, aggro);
// Set the actor AI Intention to AI_INTENTION_ATTACK
if(getIntention() != CtrlIntention.AI_INTENTION_ATTACK)
{
// Set the L2Character movement type to run and send Server->Client packet ChangeMoveType to all others L2PcInstance
if(!_actor.isRunning())
{
_actor.setRunning();
}
setIntention(CtrlIntention.AI_INTENTION_ATTACK, target);
}
}
me = null;
}
@Override
protected void onIntentionActive()
{
// Cancel attack timeout
_attackTimeout = Integer.MAX_VALUE;
super.onIntentionActive();
}
public void setGlobalAggro(int value)
{
_globalAggro = value;
}
}
| 32,119
|
Java
|
.java
| 861
| 32.933798
| 402
| 0.691764
|
L2jBrasil/L2jBrasil
| 26
| 16
| 31
|
GPL-3.0
|
9/4/2024, 7:54:02 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| true
| false
| true
| 32,119
|
434,921
|
BoolExprAnd.java
|
Retera_WarsmashModEngine/core/src/com/etheller/warsmash/parsers/jass/triggers/BoolExprAnd.java
|
package com.etheller.warsmash.parsers.jass.triggers;
import com.etheller.interpreter.ast.scope.GlobalScope;
import com.etheller.interpreter.ast.scope.TriggerExecutionScope;
import com.etheller.interpreter.ast.scope.trigger.TriggerBooleanExpression;
public class BoolExprAnd implements TriggerBooleanExpression {
private final TriggerBooleanExpression operandA;
private final TriggerBooleanExpression operandB;
public BoolExprAnd(final TriggerBooleanExpression operandA, final TriggerBooleanExpression operandB) {
this.operandA = operandA;
this.operandB = operandB;
}
@Override
public boolean evaluate(final GlobalScope globalScope, final TriggerExecutionScope triggerScope) {
return this.operandA.evaluate(globalScope, triggerScope) && this.operandB.evaluate(globalScope, triggerScope);
}
}
| 809
|
Java
|
.java
| 16
| 48.4375
| 112
| 0.859137
|
Retera/WarsmashModEngine
| 224
| 39
| 25
|
AGPL-3.0
|
9/4/2024, 7:07:11 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 809
|
4,948,039
|
AccountsReceivableReportServiceImpl.java
|
ua-eas_ua-kfs-5_3/work/src/org/kuali/kfs/module/ar/report/service/impl/AccountsReceivableReportServiceImpl.java
|
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2014 The Kuali Foundation
*
* 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 <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.module.ar.report.service.impl;
import java.io.File;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.kuali.kfs.coa.businessobject.Organization;
import org.kuali.kfs.coa.service.OrganizationService;
import org.kuali.kfs.module.ar.ArConstants;
import org.kuali.kfs.module.ar.businessobject.AppliedPayment;
import org.kuali.kfs.module.ar.businessobject.Customer;
import org.kuali.kfs.module.ar.businessobject.CustomerAddress;
import org.kuali.kfs.module.ar.businessobject.CustomerBillingStatement;
import org.kuali.kfs.module.ar.businessobject.CustomerCreditMemoDetail;
import org.kuali.kfs.module.ar.businessobject.CustomerInvoiceDetail;
import org.kuali.kfs.module.ar.businessobject.InvoicePaidApplied;
import org.kuali.kfs.module.ar.businessobject.OrganizationOptions;
import org.kuali.kfs.module.ar.businessobject.SystemInformation;
import org.kuali.kfs.module.ar.businessobject.defaultvalue.InstitutionNameValueFinder;
import org.kuali.kfs.module.ar.document.CustomerCreditMemoDocument;
import org.kuali.kfs.module.ar.document.CustomerInvoiceDocument;
import org.kuali.kfs.module.ar.document.CustomerInvoiceWriteoffDocument;
import org.kuali.kfs.module.ar.document.PaymentApplicationDocument;
import org.kuali.kfs.module.ar.document.service.CustomerAddressService;
import org.kuali.kfs.module.ar.document.service.CustomerCreditMemoDocumentService;
import org.kuali.kfs.module.ar.document.service.CustomerInvoiceDetailService;
import org.kuali.kfs.module.ar.document.service.CustomerInvoiceDocumentService;
import org.kuali.kfs.module.ar.document.service.CustomerInvoiceWriteoffDocumentService;
import org.kuali.kfs.module.ar.document.service.CustomerService;
import org.kuali.kfs.module.ar.document.service.InvoicePaidAppliedService;
import org.kuali.kfs.module.ar.report.service.AccountsReceivableReportService;
import org.kuali.kfs.module.ar.report.service.CustomerAgingReportService;
import org.kuali.kfs.module.ar.report.service.CustomerCreditMemoReportService;
import org.kuali.kfs.module.ar.report.service.CustomerInvoiceReportService;
import org.kuali.kfs.module.ar.report.service.CustomerStatementReportService;
import org.kuali.kfs.module.ar.report.service.OCRLineService;
import org.kuali.kfs.module.ar.report.util.CustomerAgingReportDataHolder;
import org.kuali.kfs.module.ar.report.util.CustomerCreditMemoDetailReportDataHolder;
import org.kuali.kfs.module.ar.report.util.CustomerCreditMemoReportDataHolder;
import org.kuali.kfs.module.ar.report.util.CustomerInvoiceReportDataHolder;
import org.kuali.kfs.module.ar.report.util.CustomerStatementDetailReportDataHolder;
import org.kuali.kfs.module.ar.report.util.CustomerStatementReportDataHolder;
import org.kuali.kfs.module.ar.report.util.CustomerStatementResultHolder;
import org.kuali.kfs.module.ar.report.util.SortTransaction;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.service.UniversityDateService;
import org.kuali.rice.core.api.datetime.DateTimeService;
import org.kuali.rice.core.api.util.type.KualiDecimal;
import org.kuali.rice.core.web.format.CurrencyFormatter;
import org.kuali.rice.core.web.format.PhoneNumberFormatter;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.kew.api.WorkflowDocument;
import org.kuali.rice.kew.api.exception.WorkflowException;
import org.kuali.rice.kim.api.identity.entity.Entity;
import org.kuali.rice.kim.api.services.KimApiServiceLocator;
import org.kuali.rice.krad.document.Document;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krad.service.DocumentService;
import org.kuali.rice.krad.util.ObjectUtils;
import org.kuali.rice.location.api.country.Country;
import org.kuali.rice.location.api.country.CountryService;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class AccountsReceivableReportServiceImpl implements AccountsReceivableReportService {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(AccountsReceivableReportServiceImpl.class);
private DateTimeService dateTimeService;
private DocumentService documentService;
private ParameterService parameterService;
private PhoneNumberFormatter phoneNumberFormatter = new PhoneNumberFormatter();
private CurrencyFormatter currencyFormatter = new CurrencyFormatter();
/**
* @see org.kuali.kfs.module.ar.report.service.AccountsReceivableReportService#generateCreditMemo(org.kuali.kfs.module.ar.document.CustomerCreditMemoDocument)
*/
@Override
public File generateCreditMemo(CustomerCreditMemoDocument creditMemo) throws WorkflowException {
CustomerCreditMemoReportDataHolder reportDataHolder = new CustomerCreditMemoReportDataHolder();
String invoiceNumber = creditMemo.getFinancialDocumentReferenceInvoiceNumber();
CustomerInvoiceDocument invoice = (CustomerInvoiceDocument) documentService.getByDocumentHeaderId(invoiceNumber);
String custID = invoice.getAccountsReceivableDocumentHeader().getCustomerNumber();
CustomerAddressService addrService = SpringContext.getBean(CustomerAddressService.class);
Map<String, String> creditMemoMap = new HashMap<String, String>();
creditMemoMap.put("docNumber", creditMemo.getDocumentNumber());
creditMemoMap.put("refDocNumber", invoice.getDocumentNumber());
Date date = creditMemo.getFinancialSystemDocumentHeader().getDocumentFinalDate();
if (ObjectUtils.isNotNull(date)) {
creditMemoMap.put("createDate", dateTimeService.toDateString(date));
}
reportDataHolder.setCreditmemo(creditMemoMap);
Map<String, String> customerMap = new HashMap<String, String>();
customerMap.put("id", custID);
customerMap.put("billToName", invoice.getBillingAddressName());
customerMap.put("billToStreetAddressLine1", invoice.getBillingLine1StreetAddress());
customerMap.put("billToStreetAddressLine2", invoice.getBillingLine2StreetAddress());
String billCityStateZip = "";
if (KFSConstants.COUNTRY_CODE_UNITED_STATES.equals(invoice.getBillingCountryCode())) {
billCityStateZip = generateCityStateZipLine(invoice.getBillingCityName(), invoice.getBillingStateCode(), invoice.getBillingZipCode());
}
else {
billCityStateZip = generateCityStateZipLine(invoice.getBillingCityName(), invoice.getBillingAddressInternationalProvinceName(), invoice.getBillingInternationalMailCode());
if ( StringUtils.isNotBlank(invoice.getBillingCountryCode())) {
Country country = SpringContext.getBean(CountryService.class).getCountry(invoice.getBillingCountryCode());
if (ObjectUtils.isNotNull(country)) {
customerMap.put("billToCountry", country.getName());
}
}
}
customerMap.put("billToCityStateZip", billCityStateZip);
reportDataHolder.setCustomer(customerMap);
Map<String, String> invoiceMap = new HashMap<String, String>();
if (ObjectUtils.isNotNull(invoice.getCustomerPurchaseOrderNumber())) {
invoiceMap.put("poNumber", invoice.getCustomerPurchaseOrderNumber());
}
if (invoice.getCustomerPurchaseOrderDate() != null) {
invoiceMap.put("poDate", dateTimeService.toDateString(invoice.getCustomerPurchaseOrderDate()));
}
String initiatorID = invoice.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId();
Entity user = KimApiServiceLocator.getIdentityService().getEntityByPrincipalId(initiatorID);
if (user == null) {
throw new RuntimeException("User '" + initiatorID + "' could not be retrieved.");
}
invoiceMap.put("invoicePreparer", user.getDefaultName().getFirstName() + " " + user.getDefaultName().getLastName());
invoiceMap.put("headerField", (ObjectUtils.isNull(invoice.getInvoiceHeaderText()) ? "" : invoice.getInvoiceHeaderText()));
invoiceMap.put("billingOrgName", invoice.getBilledByOrganization().getOrganizationName());
invoiceMap.put("pretaxAmount", invoice.getInvoiceItemPreTaxAmountTotal().toString());
boolean salesTaxInd = SpringContext.getBean(ParameterService.class).getParameterValueAsBoolean("KFS-AR", "Document", ArConstants.ENABLE_SALES_TAX_IND);
if (salesTaxInd) {
invoiceMap.put("taxAmount", invoice.getInvoiceItemTaxAmountTotal().toString());
// KualiDecimal taxPercentage = invoice.getStateTaxPercent().add(invoice.getLocalTaxPercent());
KualiDecimal taxPercentage = new KualiDecimal(6.85);
invoiceMap.put("taxPercentage", "*** " + taxPercentage.toString() + "%");
}
invoiceMap.put("invoiceAmountDue", invoice.getSourceTotal().toString());
invoiceMap.put("ocrLine", "");
reportDataHolder.setInvoice(invoiceMap);
Map<String, String> sysinfoMap = new HashMap<String, String>();
InstitutionNameValueFinder finder = new InstitutionNameValueFinder();
Organization billingOrg = invoice.getBilledByOrganization();
String chart = billingOrg.getChartOfAccountsCode();
String org = billingOrg.getOrganizationCode();
Map<String, String> criteria = new HashMap<String, String>();
criteria.put("chartOfAccountsCode", chart);
criteria.put("organizationCode", org);
OrganizationOptions orgOptions = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(OrganizationOptions.class, criteria);
BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
String fiscalYear = SpringContext.getBean(UniversityDateService.class).getCurrentFiscalYear().toString();
criteria = new HashMap<String, String>();
Organization processingOrg = invoice.getAccountsReceivableDocumentHeader().getProcessingOrganization();
criteria.put("universityFiscalYear", fiscalYear);
criteria.put("processingChartOfAccountCode", processingOrg.getChartOfAccountsCode());
criteria.put("processingOrganizationCode", processingOrg.getOrganizationCode());
SystemInformation sysinfo = businessObjectService.findByPrimaryKey(SystemInformation.class, criteria);
sysinfoMap.put("univName", StringUtils.upperCase(finder.getValue()));
String univAddr = processingOrg.getOrganizationCityName() + ", " + processingOrg.getOrganizationStateCode() + " " + processingOrg.getOrganizationZipCode();
sysinfoMap.put("univAddr", univAddr);
if (sysinfo != null) {
sysinfoMap.put("FEIN", "FED ID #" + sysinfo.getUniversityFederalEmployerIdentificationNumber());
}
reportDataHolder.setSysinfo(sysinfoMap);
invoiceMap.put("billingOrgFax", (String) phoneNumberFormatter.format(phoneNumberFormatter.convertFromPresentationFormat(orgOptions.getOrganizationFaxNumber())));
invoiceMap.put("billingOrgPhone", (String) phoneNumberFormatter.format(phoneNumberFormatter.convertFromPresentationFormat(orgOptions.getOrganizationPhoneNumber())));
creditMemo.populateCustomerCreditMemoDetailsAfterLoad();
List<CustomerCreditMemoDetail> detailsList = creditMemo.getCreditMemoDetails();
List<CustomerCreditMemoDetailReportDataHolder> details = new ArrayList<CustomerCreditMemoDetailReportDataHolder>();
CustomerCreditMemoDetailReportDataHolder detailDataHolder;
for (CustomerCreditMemoDetail detail : detailsList) {
if (detail.getCreditMemoLineTotalAmount().isGreaterThan(KualiDecimal.ZERO)) {
detailDataHolder = new CustomerCreditMemoDetailReportDataHolder(detail, detail.getCustomerInvoiceDetail());
details.add(detailDataHolder);
}
}
reportDataHolder.setDetails(details);
Date runDate = dateTimeService.getCurrentSqlDate();
CustomerCreditMemoReportService service = SpringContext.getBean(CustomerCreditMemoReportService.class);
File report = service.generateReport(reportDataHolder, runDate);
return report;
}
/**
* @see org.kuali.kfs.module.ar.report.service.AccountsReceivableReportService#generateInvoice(org.kuali.kfs.module.ar.document.CustomerInvoiceDocument)
*/
@Override
public File generateInvoice(CustomerInvoiceDocument invoice) {
CustomerInvoiceReportDataHolder reportDataHolder = new CustomerInvoiceReportDataHolder();
String custID = invoice.getAccountsReceivableDocumentHeader().getCustomerNumber();
CustomerService custService = SpringContext.getBean(CustomerService.class);
Customer cust = custService.getByPrimaryKey(custID);
Integer customerBillToAddressIdentifier = invoice.getCustomerBillToAddressIdentifier();
Integer customerShipToAddressIdentifier = invoice.getCustomerShipToAddressIdentifier();
CustomerAddressService addrService = SpringContext.getBean(CustomerAddressService.class);
CustomerAddress billToAddr = addrService.getByPrimaryKey(custID, customerBillToAddressIdentifier);
CustomerAddress shipToAddr = addrService.getByPrimaryKey(custID, customerShipToAddressIdentifier);
Map<String, String> customerMap = new HashMap<String, String>();
customerMap.put("id", custID);
if (billToAddr != null) {
customerMap.put("billToName", billToAddr.getCustomerAddressName());
customerMap.put("billToStreetAddressLine1", billToAddr.getCustomerLine1StreetAddress());
customerMap.put("billToStreetAddressLine2", billToAddr.getCustomerLine2StreetAddress());
String billCityStateZip = "";
if (billToAddr.getCustomerCountryCode().equals("US")) {
billCityStateZip = generateCityStateZipLine(billToAddr.getCustomerCityName(), billToAddr.getCustomerStateCode(), billToAddr.getCustomerZipCode());
}
else {
billCityStateZip = generateCityStateZipLine(billToAddr.getCustomerCityName(), billToAddr.getCustomerAddressInternationalProvinceName(), billToAddr.getCustomerInternationalMailCode());
customerMap.put("billToCountry", billToAddr.getCustomerCountry().getName());
}
customerMap.put("billToCityStateZip", billCityStateZip);
}
if (shipToAddr != null) {
customerMap.put("shipToName", shipToAddr.getCustomerAddressName());
customerMap.put("shipToStreetAddressLine1", shipToAddr.getCustomerLine1StreetAddress());
customerMap.put("shipToStreetAddressLine2", shipToAddr.getCustomerLine2StreetAddress());
String shipCityStateZip = "";
if (shipToAddr.getCustomerCountryCode().equals("US")) {
shipCityStateZip = generateCityStateZipLine(shipToAddr.getCustomerCityName(), shipToAddr.getCustomerStateCode(), shipToAddr.getCustomerZipCode());
}
else {
shipCityStateZip = generateCityStateZipLine(shipToAddr.getCustomerCityName(), shipToAddr.getCustomerAddressInternationalProvinceName(), shipToAddr.getCustomerInternationalMailCode());
customerMap.put("shipToCountry", shipToAddr.getCustomerCountry().getName());
}
customerMap.put("shipToCityStateZip", shipCityStateZip);
}
reportDataHolder.setCustomer(customerMap);
Map<String, String> invoiceMap = new HashMap<String, String>();
invoiceMap.put("poNumber", invoice.getCustomerPurchaseOrderNumber());
if (invoice.getCustomerPurchaseOrderDate() != null) {
invoiceMap.put("poDate", dateTimeService.toDateString(invoice.getCustomerPurchaseOrderDate()));
}
String initiatorID = invoice.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId();
Entity user = KimApiServiceLocator.getIdentityService().getEntityByPrincipalId(initiatorID);
if (user == null) {
throw new RuntimeException("User '" + initiatorID + "' could not be retrieved.");
}
invoiceMap.put("invoicePreparer", user.getDefaultName().getFirstName() + " " + user.getDefaultName().getLastName());
invoiceMap.put("headerField", invoice.getInvoiceHeaderText());
invoiceMap.put("customerOrg", invoice.getBilledByOrganizationCode());
invoiceMap.put("docNumber", invoice.getDocumentNumber());
invoiceMap.put("invoiceDueDate", dateTimeService.toDateString(invoice.getInvoiceDueDate()));
invoiceMap.put("createDate", dateTimeService.toDateString(invoice.getDocumentHeader().getWorkflowDocument().getDateCreated().toDate()));
invoiceMap.put("invoiceAttentionLineText", StringUtils.upperCase(invoice.getInvoiceAttentionLineText()));
invoiceMap.put("billingOrgName", invoice.getBilledByOrganization().getOrganizationName());
invoiceMap.put("pretaxAmount", currencyFormatter.format(invoice.getInvoiceItemPreTaxAmountTotal()).toString());
boolean salesTaxInd = SpringContext.getBean(ParameterService.class).getParameterValueAsBoolean("KFS-AR", "Document", ArConstants.ENABLE_SALES_TAX_IND);
if (salesTaxInd) {
invoiceMap.put("taxAmount", currencyFormatter.format(invoice.getInvoiceItemTaxAmountTotal()).toString());
invoiceMap.put("taxPercentage", ""); // suppressing this as its useless ... see KULAR-415
}
invoiceMap.put("invoiceAmountDue", currencyFormatter.format(invoice.getSourceTotal()).toString());
invoiceMap.put("invoiceTermsText", invoice.getInvoiceTermsText());
OCRLineService ocrService = SpringContext.getBean(OCRLineService.class);
String ocrLine = ocrService.generateOCRLine(invoice.getSourceTotal(), custID, invoice.getDocumentNumber());
invoiceMap.put("ocrLine", ocrLine);
CustomerInvoiceDetailService invoiceDetailService = SpringContext.getBean(CustomerInvoiceDetailService.class);
List<CustomerInvoiceDetail> detailsList = (List<CustomerInvoiceDetail>) invoiceDetailService.getCustomerInvoiceDetailsForInvoice(invoice);
CustomerInvoiceDetail firstDetail = detailsList.get(0);
String firstChartCode = firstDetail.getChartOfAccountsCode();
String firstAccount = firstDetail.getAccountNumber();
invoiceMap.put("chartAndAccountOfFirstItem", firstChartCode + firstAccount);
Map<String, String> sysinfoMap = new HashMap<String, String>();
Organization billingOrg = invoice.getBilledByOrganization();
String chart = billingOrg.getChartOfAccountsCode();
String org = billingOrg.getOrganizationCode();
Map<String, String> criteria = new HashMap<String, String>();
criteria.put("chartOfAccountsCode", chart);
criteria.put("organizationCode", org);
OrganizationOptions orgOptions = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(OrganizationOptions.class, criteria);
BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
String fiscalYear = SpringContext.getBean(UniversityDateService.class).getCurrentFiscalYear().toString();
criteria = new HashMap<String, String>();
Organization processingOrg = invoice.getAccountsReceivableDocumentHeader().getProcessingOrganization();
criteria.put("universityFiscalYear", fiscalYear);
criteria.put("processingChartOfAccountCode", processingOrg.getChartOfAccountsCode());
criteria.put("processingOrganizationCode", processingOrg.getOrganizationCode());
SystemInformation sysinfo = businessObjectService.findByPrimaryKey(SystemInformation.class, criteria);
sysinfoMap.put("univName", StringUtils.upperCase(sysinfo.getOrganizationCheckPayableToName()));
sysinfoMap.put("univAddr", generateCityStateZipLine(processingOrg.getOrganizationCityName(), processingOrg.getOrganizationStateCode(), processingOrg.getOrganizationZipCode()));
if (sysinfo != null) {
sysinfoMap.put("FEIN", "FED ID #" + sysinfo.getUniversityFederalEmployerIdentificationNumber());
}
sysinfoMap.put("checkPayableTo", orgOptions.getOrganizationCheckPayableToName());
sysinfoMap.put("remitToName", orgOptions.getOrganizationRemitToAddressName());
sysinfoMap.put("remitToAddressLine1", orgOptions.getOrganizationRemitToLine1StreetAddress());
sysinfoMap.put("remitToAddressLine2", orgOptions.getOrganizationRemitToLine2StreetAddress());
sysinfoMap.put("remitToCityStateZip", generateCityStateZipLine(orgOptions.getOrganizationRemitToCityName(), orgOptions.getOrganizationRemitToStateCode(), orgOptions.getOrganizationRemitToZipCode()));
invoiceMap.put("billingOrgFax", (String) phoneNumberFormatter.format(phoneNumberFormatter.convertFromPresentationFormat(orgOptions.getOrganizationFaxNumber())));
invoiceMap.put("billingOrgPhone", (String) phoneNumberFormatter.format(phoneNumberFormatter.convertFromPresentationFormat(orgOptions.getOrganizationPhoneNumber())));
invoiceMap.put("orgOptionsMessageText", orgOptions.getOrganizationMessageText());
reportDataHolder.setSysinfo(sysinfoMap);
reportDataHolder.setDetails(detailsList);
reportDataHolder.setInvoice(invoiceMap);
Date runDate = dateTimeService.getCurrentSqlDate();
CustomerInvoiceReportService service = SpringContext.getBean(CustomerInvoiceReportService.class);
File report = service.generateReport(reportDataHolder, runDate);
invoice.setPrintDate(runDate);
documentService.updateDocument(invoice);
return report;
}
/**
* Constructs the data holder to be used for
*
* @param billingChartCode
* @param billingOrgCode
* @param customerNumber
* @param details
* @return
*/
public File createStatement(String billingChartCode, String billingOrgCode, String customerNumber, Organization processingOrg, List<CustomerStatementDetailReportDataHolder> details, String statementFormat, String zeroBalance, CustomerStatementResultHolder customerStatementResultHolder) {
CustomerStatementReportDataHolder reportDataHolder = new CustomerStatementReportDataHolder();
CustomerAddressService addrService = SpringContext.getBean(CustomerAddressService.class);
CustomerAddress billToAddr = addrService.getPrimaryAddress(customerNumber);
Map<String, String> customerMap = new HashMap<String, String>();
customerMap.put("id", customerNumber);
if (billToAddr != null) {
customerMap.put("billToName", billToAddr.getCustomerAddressName());
customerMap.put("billToStreetAddressLine1", billToAddr.getCustomerLine1StreetAddress());
customerMap.put("billToStreetAddressLine2", billToAddr.getCustomerLine2StreetAddress());
String billCityStateZip = "";
if (billToAddr.getCustomerCountryCode().equals("US")) {
billCityStateZip = generateCityStateZipLine(billToAddr.getCustomerCityName(), billToAddr.getCustomerStateCode(), billToAddr.getCustomerZipCode());
}
else {
billCityStateZip = generateCityStateZipLine(billToAddr.getCustomerCityName(), billToAddr.getCustomerAddressInternationalProvinceName(), billToAddr.getCustomerInternationalMailCode());
customerMap.put("billToCountry", billToAddr.getCustomerCountry().getName());
}
customerMap.put("billToCityStateZip", billCityStateZip);
}
reportDataHolder.setCustomer(customerMap);
Map<String, String> invoiceMap = new HashMap<String, String>();
invoiceMap.clear();
invoiceMap.put("createDate", dateTimeService.toDateString(dateTimeService.getCurrentDate()));
invoiceMap.put("customerOrg", billingOrgCode);
Organization billingOrg = SpringContext.getBean(OrganizationService.class).getByPrimaryId(billingChartCode, billingOrgCode);
invoiceMap.put("billingOrgName", billingOrg.getOrganizationName());
KualiDecimal amountDue = KualiDecimal.ZERO;
KualiDecimal previousBalance = KualiDecimal.ZERO;
String lastReportedDate = "";
CustomerBillingStatement customerBillingStatement = getCustomerBillingStatement(customerNumber);
if (ObjectUtils.isNotNull(customerBillingStatement)) {
previousBalance = customerBillingStatement.getPreviouslyBilledAmount();
if (statementFormat.equals(ArConstants.STATEMENT_FORMAT_DETAIL)) {
amountDue = previousBalance;
lastReportedDate = dateTimeService.toDateString(customerBillingStatement.getReportedDate());
}
}
invoiceMap.put("previousBalance", currencyFormatter.format(previousBalance).toString());
invoiceMap.put("lastReportedDate", lastReportedDate);
for (CustomerStatementDetailReportDataHolder data : details) {
if (data.getFinancialDocumentTotalAmountCharge() != null) {
amountDue = amountDue.add(data.getFinancialDocumentTotalAmountCharge());
}
if (data.getFinancialDocumentTotalAmountCredit() != null) {
amountDue = amountDue.subtract(data.getFinancialDocumentTotalAmountCredit());
}
}
// This customer has a zero balance and so we do not need to generate the report if the include zero balance is "No."
if (amountDue.equals(KualiDecimal.ZERO) && zeroBalance.equals(ArConstants.INCLUDE_ZERO_BALANCE_NO)) {
return null;
}
customerStatementResultHolder.setCurrentBilledAmount(amountDue);
invoiceMap.put("amountDue", currencyFormatter.format(amountDue).toString());
invoiceMap.put("dueDate", calculateDueDate());
String ocrLine = SpringContext.getBean(OCRLineService.class).generateOCRLine(amountDue, customerNumber, null);
invoiceMap.put("ocrLine", ocrLine);
Map<String, String> sysinfoMap = new HashMap<String, String>();
Map<String, String> criteria = new HashMap<String, String>();
criteria.put("chartOfAccountsCode", billingChartCode);
criteria.put("organizationCode", billingOrgCode);
OrganizationOptions orgOptions = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(OrganizationOptions.class, criteria);
sysinfoMap.put("checkPayableTo", orgOptions.getOrganizationCheckPayableToName());
sysinfoMap.put("remitToName", orgOptions.getOrganizationRemitToAddressName());
sysinfoMap.put("remitToAddressLine1", orgOptions.getOrganizationRemitToLine1StreetAddress());
sysinfoMap.put("remitToAddressLine2", orgOptions.getOrganizationRemitToLine2StreetAddress());
sysinfoMap.put("remitToCityStateZip", generateCityStateZipLine(orgOptions.getOrganizationRemitToCityName(), orgOptions.getOrganizationRemitToStateCode(), orgOptions.getOrganizationRemitToZipCode()));
invoiceMap.put("billingOrgFax", (String) phoneNumberFormatter.format(phoneNumberFormatter.convertFromPresentationFormat(orgOptions.getOrganizationFaxNumber())));
invoiceMap.put("billingOrgPhone", (String) phoneNumberFormatter.format(phoneNumberFormatter.convertFromPresentationFormat(orgOptions.getOrganizationPhoneNumber())));
BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
String fiscalYear = SpringContext.getBean(UniversityDateService.class).getCurrentFiscalYear().toString();
criteria.clear();
criteria.put("universityFiscalYear", fiscalYear);
criteria.put("processingChartOfAccountCode", processingOrg.getChartOfAccountsCode());
criteria.put("processingOrganizationCode", processingOrg.getOrganizationCode());
SystemInformation sysinfo = businessObjectService.findByPrimaryKey(SystemInformation.class, criteria);
sysinfoMap.put("univName", StringUtils.upperCase(sysinfo.getOrganizationCheckPayableToName()));
sysinfoMap.put("univAddr", generateCityStateZipLine(processingOrg.getOrganizationCityName(), processingOrg.getOrganizationStateCode(), processingOrg.getOrganizationZipCode()));
if (sysinfo != null) {
sysinfoMap.put("FEIN", "FED ID #" + sysinfo.getUniversityFederalEmployerIdentificationNumber());
}
KualiDecimal bal = (statementFormat.equals(ArConstants.STATEMENT_FORMAT_DETAIL)) ? previousBalance : KualiDecimal.ZERO;
calculateAgingAmounts(details, invoiceMap, bal);
reportDataHolder.setSysinfo(sysinfoMap);
reportDataHolder.setDetails(details);
reportDataHolder.setInvoice(invoiceMap);
Date runDate = dateTimeService.getCurrentSqlDate();
CustomerStatementReportService service = SpringContext.getBean(CustomerStatementReportService.class);
File f = service.generateReport(reportDataHolder, runDate, statementFormat);
return f;
}
/**
* @see org.kuali.kfs.module.ar.report.service.AccountsReceivableReportService#generateInvoicesByBillingOrg(java.lang.String,
* java.lang.String, java.sql.Date)
*/
@Override
public List<File> generateInvoicesByBillingOrg(String chartCode, String orgCode, Date date) {
CustomerInvoiceDocumentService invoiceDocService = SpringContext.getBean(CustomerInvoiceDocumentService.class);
List<CustomerInvoiceDocument> invoices = invoiceDocService.getPrintableCustomerInvoiceDocumentsByBillingChartAndOrg(chartCode, orgCode);
List<File> reports = new ArrayList<File>();
for (CustomerInvoiceDocument doc : invoices) {
if (date == null) {
reports.add(generateInvoice(doc));
}
else if (dateTimeService.toDateString(doc.getDocumentHeader().getWorkflowDocument().getDateCreated().toDate()) != null) {
if (dateTimeService.toDateString(doc.getDocumentHeader().getWorkflowDocument().getDateCreated().toDate()).equals(dateTimeService.toDateString(date))) {
reports.add(generateInvoice(doc));
}
}
}
return reports;
}
/**
* @see org.kuali.kfs.module.ar.report.service.AccountsReceivableReportService#generateInvoicesByProcessingOrg(java.lang.String,
* java.lang.String, java.sql.Date)
*/
@Override
public List<File> generateInvoicesByProcessingOrg(String chartCode, String orgCode, Date date) {
CustomerInvoiceDocumentService invoiceDocService = SpringContext.getBean(CustomerInvoiceDocumentService.class);
List<CustomerInvoiceDocument> invoices = invoiceDocService.getPrintableCustomerInvoiceDocumentsByProcessingChartAndOrg(chartCode, orgCode);
List<File> reports = new ArrayList<File>();
for (CustomerInvoiceDocument doc : invoices) {
if (date == null) {
reports.add(generateInvoice(doc));
}
else if (dateTimeService.toDateString(doc.getDocumentHeader().getWorkflowDocument().getDateCreated().toDate()) != null) {
if (dateTimeService.toDateString(doc.getDocumentHeader().getWorkflowDocument().getDateCreated().toDate()).equals(dateTimeService.toDateString(date))) {
reports.add(generateInvoice(doc));
}
}
}
return reports;
}
/**
* @see org.kuali.kfs.module.ar.report.service.AccountsReceivableReportService#generateInvoicesByInitiator(java.lang.String)
*/
@Override
public List<File> generateInvoicesByInitiator(String initiator, java.sql.Date date) {
List<File> reports = new ArrayList<File>();
CustomerInvoiceDocumentService invoiceDocService = SpringContext.getBean(CustomerInvoiceDocumentService.class);
Collection<CustomerInvoiceDocument> invoices = invoiceDocService.getPrintableCustomerInvoiceDocumentsByInitiatorPrincipalName(initiator);
for (CustomerInvoiceDocument invoice : invoices) {
if (date == null) {
reports.add(generateInvoice(invoice));
}
else if (dateTimeService.toDateString(invoice.getDocumentHeader().getWorkflowDocument().getDateCreated().toDate()) != null) {
if (dateTimeService.toDateString(invoice.getDocumentHeader().getWorkflowDocument().getDateCreated().toDate()).equals(dateTimeService.toDateString(date))) {
reports.add(generateInvoice(invoice));
}
}
}
return reports;
}
/**
* Generates detail statement reports
*
* @param invoiceList
* @param creditMemoList
* @param paymentList
* @param writeoffList
* @return CustomerStatementResultHolder
*/
protected List<CustomerStatementResultHolder> generateStatementReports(Collection<CustomerInvoiceDocument> invoices, String statementFormat, String incldueZeroBalanceCustomers) {
List<CustomerInvoiceDocument> invoiceList = new ArrayList<CustomerInvoiceDocument>(invoices);
Collections.sort(invoiceList);
Map<String, Map<String, Map<String, List<CustomerStatementDetailReportDataHolder>>>> statementDetailsSorted = sortCustomerStatementData(invoiceList, statementFormat, incldueZeroBalanceCustomers);
Set<String> processingOrgKeys = statementDetailsSorted.keySet();
//List<File> reports = new ArrayList<File>();
List<CustomerStatementResultHolder> result = new ArrayList<CustomerStatementResultHolder>();
for (String processingChartAndOrg : processingOrgKeys) {
String processingChartCode = processingChartAndOrg.substring(0, 2);
String processingOrgCode = processingChartAndOrg.substring(2);
Organization processingOrg = SpringContext.getBean(OrganizationService.class).getByPrimaryId(processingChartCode, processingOrgCode);
// sort by organization
Map<String, Map<String, List<CustomerStatementDetailReportDataHolder>>> statementDetailsByProcessingOrg = statementDetailsSorted.get(processingChartAndOrg);
Set<String> billingOrgKeys = statementDetailsByProcessingOrg.keySet();
for (String billingChartAndOrg : billingOrgKeys) {
String billingChartCode = billingChartAndOrg.substring(0, 2);
String billingOrgCode = billingChartAndOrg.substring(2);
Map<String, List<CustomerStatementDetailReportDataHolder>> statementDetailsByBillingOrg = statementDetailsByProcessingOrg.get(billingChartAndOrg);
Set<String> customerKeys = statementDetailsByBillingOrg.keySet();
for (String customerId : customerKeys) {
List<CustomerStatementDetailReportDataHolder> statementDetailsByCustomer = statementDetailsByBillingOrg.get(customerId);
CustomerStatementResultHolder customerStatementResultHolder = new CustomerStatementResultHolder();
customerStatementResultHolder.setCustomerNumber(customerId);
File file = createStatement(billingChartCode, billingOrgCode, customerId, processingOrg, statementDetailsByCustomer, statementFormat, incldueZeroBalanceCustomers, customerStatementResultHolder);
if (file != null) {
customerStatementResultHolder.setFile(file);
if (statementFormat.equalsIgnoreCase(ArConstants.STATEMENT_FORMAT_DETAIL)) {
List<String> invoiceNumbers = new ArrayList<String>();
for (CustomerStatementDetailReportDataHolder c : statementDetailsByCustomer) {
if (c.getDocType().equalsIgnoreCase(ArConstants.INVOICE_DOC_TYPE)) {
invoiceNumbers.add(c.getDocumentNumber());
}
}
customerStatementResultHolder.setInvoiceNumbers(invoiceNumbers);
}
result.add(customerStatementResultHolder);
}
}
}
}
return result;
}
/**
* @see org.kuali.kfs.module.ar.report.service.AccountsReceivableReportService#generateStatementByBillingOrg(java.lang.String,
* java.lang.String)
*/
@Override
public List<CustomerStatementResultHolder> generateStatementByBillingOrg(String chartCode, String orgCode, String statementFormat, String incldueZeroBalanceCustomers) {
return generateStatementReports(SpringContext.getBean(CustomerInvoiceDocumentService.class).getPrintableCustomerInvoiceDocumentsForBillingStatementByBillingChartAndOrg(chartCode, orgCode), statementFormat, incldueZeroBalanceCustomers);
}
/**
* @see org.kuali.kfs.module.ar.report.service.AccountsReceivableReportService#generateStatementByAccount(java.lang.String)
*/
@Override
public List<CustomerStatementResultHolder> generateStatementByAccount(String accountNumber, String statementFormat, String incldueZeroBalanceCustomers) {
return generateStatementReports(SpringContext.getBean(CustomerInvoiceDocumentService.class).getCustomerInvoiceDocumentsByAccountNumber(accountNumber), statementFormat, incldueZeroBalanceCustomers);
}
/**
* @see org.kuali.kfs.module.ar.report.service.AccountsReceivableReportService#generateStatementByCustomer(java.lang.String)
*/
@Override
public List<CustomerStatementResultHolder> generateStatementByCustomer(String customerNumber, String statementFormat, String incldueZeroBalanceCustomers) {
if(StringUtils.equals(statementFormat, ArConstants.STATEMENT_FORMAT_SUMMARY)){
return generateStatementReports(SpringContext.getBean(CustomerInvoiceDocumentService.class).getOpenInvoiceDocumentsByCustomerNumber(customerNumber), statementFormat, incldueZeroBalanceCustomers);
} else {
return generateStatementReports(SpringContext.getBean(CustomerInvoiceDocumentService.class).getCustomerInvoiceDocumentsByCustomerNumber(customerNumber), statementFormat, incldueZeroBalanceCustomers);
}
}
protected KualiDecimal creditTotalInList(Collection<CustomerStatementDetailReportDataHolder> holderList) {
KualiDecimal totalCredit = KualiDecimal.ZERO;
for (CustomerStatementDetailReportDataHolder holder : holderList) {
totalCredit = totalCredit.add(holder.getFinancialDocumentTotalAmountCredit());
}
return totalCredit;
}
protected Collection<CustomerStatementDetailReportDataHolder> creditMemosForInvoice(CustomerInvoiceDocument invoice) {
// credit memo
List<CustomerStatementDetailReportDataHolder> returnList = new ArrayList<CustomerStatementDetailReportDataHolder>();
CustomerCreditMemoDocumentService creditMemoService = SpringContext.getBean(CustomerCreditMemoDocumentService.class);
Collection<CustomerCreditMemoDocument> creditMemos = creditMemoService.getCustomerCreditMemoDocumentByInvoiceDocument(invoice.getDocumentNumber());
for (CustomerCreditMemoDocument doc : creditMemos) {
try {
doc.populateCustomerCreditMemoDetailsAfterLoad();
WorkflowDocument workflowDoc = doc.getDocumentHeader().getWorkflowDocument();
if (workflowDoc.isFinal() || workflowDoc.isProcessed()) {
CustomerCreditMemoDocument creditMemoDoc = (CustomerCreditMemoDocument)documentService.getByDocumentHeaderId(doc.getDocumentNumber());
CustomerStatementDetailReportDataHolder detail = new CustomerStatementDetailReportDataHolder(creditMemoDoc.getFinancialSystemDocumentHeader(),
invoice.getAccountsReceivableDocumentHeader().getProcessingOrganization(),
ArConstants.CREDIT_MEMO_DOC_TYPE,doc.getTotalDollarAmount());
returnList.add(detail);
}
} catch(Exception ex) {
LOG.error(ex);
}
}
return returnList;
}
protected Collection<CustomerStatementDetailReportDataHolder> paymentsForInvoice(CustomerInvoiceDocument invoice) {
List<CustomerStatementDetailReportDataHolder> returnList = new ArrayList<CustomerStatementDetailReportDataHolder>();
// payment
InvoicePaidAppliedService<AppliedPayment> paymentService = SpringContext.getBean(InvoicePaidAppliedService.class);
Collection<InvoicePaidApplied> payments = paymentService.getInvoicePaidAppliedsForInvoice(invoice);
for (InvoicePaidApplied doc : payments) {
try {
Document payAppDoc = documentService.getByDocumentHeaderId(doc.getDocumentNumber());
if (payAppDoc instanceof PaymentApplicationDocument ){
WorkflowDocument workflowDoc = doc.getDocumentHeader().getWorkflowDocument();
if (workflowDoc.isFinal() || workflowDoc.isProcessed()) {
PaymentApplicationDocument paymentApplicationDoc = (PaymentApplicationDocument)payAppDoc;
CustomerStatementDetailReportDataHolder detail = new CustomerStatementDetailReportDataHolder(paymentApplicationDoc.getFinancialSystemDocumentHeader(),
invoice.getAccountsReceivableDocumentHeader().getProcessingOrganization(),
ArConstants.PAYMENT_DOC_TYPE, doc.getInvoiceItemAppliedAmount());
returnList.add(detail);
}
}
} catch(Exception ex) {
LOG.error(ex);
}
}
return returnList;
}
/**
* This method groups invoices according to processingOrg, billedByOrg, customerNumber
*
* @param invoiceList
* @return
*/
protected Map<String, Map<String, Map<String, List<CustomerStatementDetailReportDataHolder>>>> sortCustomerStatementData(List<CustomerInvoiceDocument> invoiceList, String statementFormat, String incldueZeroBalanceCustomers) {
// To group - Map<processingOrg, map<billedByOrg, map<customerNumber, List<CustomerStatementDetailReportDataHolder>
Map<String, Map<String, Map<String, List<CustomerStatementDetailReportDataHolder>>>> customerStatementDetailsSorted = new HashMap<String, Map<String, Map<String, List<CustomerStatementDetailReportDataHolder>>>>();
// This is where all the magic will begin
for (CustomerInvoiceDocument invoice : invoiceList) {
if (invoice.getFinancialSystemDocumentHeader().getFinancialDocumentStatusCode().equals(KFSConstants.DocumentStatusCodes.APPROVED)) {
if (invoice.isOpenInvoiceIndicator()) {
// if it is detailed report, take only invoices that have not reported yet
if (statementFormat.equalsIgnoreCase(ArConstants.STATEMENT_FORMAT_DETAIL) && ObjectUtils.isNotNull(invoice.getReportedDate())) {
continue;
}
// Break down list into a map based on processing org
Organization processingOrg = invoice.getAccountsReceivableDocumentHeader().getProcessingOrganization();
// Retrieve the collection of invoices that already exist for the processing org provided
Map<String, Map<String, List<CustomerStatementDetailReportDataHolder>>> statementDetailsForGivenProcessingOrg = customerStatementDetailsSorted.get(getChartAndOrgCodesCombined(processingOrg));
if (statementDetailsForGivenProcessingOrg == null) {
statementDetailsForGivenProcessingOrg = new HashMap<String, Map<String, List<CustomerStatementDetailReportDataHolder>>>();
}
// Then break down that list for billing chart and org codes
Organization billedByOrg = invoice.getBilledByOrganization();
Map<String, List<CustomerStatementDetailReportDataHolder>> statementDetailsForGivenBillingOrg = statementDetailsForGivenProcessingOrg.get(getChartAndOrgCodesCombined(billedByOrg));
if (statementDetailsForGivenBillingOrg == null) {
statementDetailsForGivenBillingOrg = new HashMap<String, List<CustomerStatementDetailReportDataHolder>>();
}
// Then break down that list by customer
String customerNumber = invoice.getCustomer().getCustomerNumber();
List<CustomerStatementDetailReportDataHolder> statementDetailsByCustomer = statementDetailsForGivenBillingOrg.get(customerNumber);
if (ObjectUtils.isNull(statementDetailsByCustomer)) {
statementDetailsByCustomer = new ArrayList<CustomerStatementDetailReportDataHolder>();
}
// for detail only
if (ArConstants.STATEMENT_FORMAT_DETAIL.equals(statementFormat)) {
// add credit memo
statementDetailsByCustomer.addAll( creditMemosForInvoice(invoice));
// add payment
statementDetailsByCustomer.addAll( paymentsForInvoice(invoice));
// add writeoff
CustomerInvoiceWriteoffDocumentService writeoffService = SpringContext.getBean(CustomerInvoiceWriteoffDocumentService.class);
Collection<CustomerInvoiceWriteoffDocument> writeoffs = writeoffService.getCustomerCreditMemoDocumentByInvoiceDocument(invoice.getDocumentNumber());
for (CustomerInvoiceWriteoffDocument doc : writeoffs) {
try {
WorkflowDocument workflowDoc = doc.getDocumentHeader().getWorkflowDocument();
if (workflowDoc.isFinal() || workflowDoc.isProcessed()) {
CustomerStatementDetailReportDataHolder detail = new CustomerStatementDetailReportDataHolder(doc.getFinancialSystemDocumentHeader(),
invoice.getAccountsReceivableDocumentHeader().getProcessingOrganization(),
ArConstants.WRITEOFF_DOC_TYPE, doc.getTotalDollarAmount());
statementDetailsByCustomer.add(detail);
}
} catch(Exception ex) {
LOG.error(ex);
}
}
}
// add invoice
CustomerStatementDetailReportDataHolder detail = new CustomerStatementDetailReportDataHolder(invoice.getFinancialSystemDocumentHeader(), invoice.getAccountsReceivableDocumentHeader().getProcessingOrganization(), ArConstants.INVOICE_DOC_TYPE, invoice.getTotalDollarAmount());
if (detail != null) {
if (!statementFormat.equalsIgnoreCase(ArConstants.STATEMENT_FORMAT_DETAIL)) {
KualiDecimal totalInvoiceCredit = KualiDecimal.ZERO;
totalInvoiceCredit = totalInvoiceCredit.add(creditTotalInList(creditMemosForInvoice(invoice)));
totalInvoiceCredit = totalInvoiceCredit.add(creditTotalInList(paymentsForInvoice(invoice)));
detail.setFinancialDocumentTotalAmountCredit(totalInvoiceCredit);
}
statementDetailsByCustomer.add(detail);
statementDetailsForGivenBillingOrg.put(customerNumber, statementDetailsByCustomer);
statementDetailsForGivenProcessingOrg.put(getChartAndOrgCodesCombined(billedByOrg), statementDetailsForGivenBillingOrg);
customerStatementDetailsSorted.put(getChartAndOrgCodesCombined(processingOrg), statementDetailsForGivenProcessingOrg);
}
}
}
}
// sort
if (ArConstants.STATEMENT_FORMAT_DETAIL.equals(statementFormat)) {
// To group - Map<processingOrg, map<billedByOrg, map<customerNumber, List<CustomerStatementDetailReportDataHolder>
Set<String> ProcessingOrgKeys = customerStatementDetailsSorted.keySet();
for (String processingOrg : ProcessingOrgKeys) {
Map<String, Map<String, List<CustomerStatementDetailReportDataHolder>>> billedByOrgs = customerStatementDetailsSorted.get(processingOrg);
Set<String> billedByOrgKeys = billedByOrgs.keySet();
for (String billedOrg : billedByOrgKeys) {
Map<String, List<CustomerStatementDetailReportDataHolder>> customerNumbers = billedByOrgs.get(billedOrg);
Set<String> customerNumberKeys = customerNumbers.keySet();
for (String customerNumber : customerNumberKeys) {
List<CustomerStatementDetailReportDataHolder> transactions = customerNumbers.get(customerNumber);
if (ObjectUtils.isNotNull(transactions)) {
Collections.sort(transactions, new SortTransaction());
}
}
}
}
}
return customerStatementDetailsSorted;
}
/**
* This method...
*
* @param city
* @param state
* @param zipCode
* @return
*/
protected String generateCityStateZipLine(String city, String state, String zipCode) {
StringBuffer cityStateZip = new StringBuffer(city);
cityStateZip.append(", ").append(state);
cityStateZip.append(" ").append(zipCode);
return cityStateZip.toString();
}
/**
* This method calculates the total aging amounts for a given statement. This will often be a collection of totals from multiple
* invoices and/or credit memos.
*
* @param details
* @param invoiceMap
*/
protected void calculateAgingAmounts(List<CustomerStatementDetailReportDataHolder> details, Map<String, String> invoiceMap,KualiDecimal previousBalance) {
for (CustomerStatementDetailReportDataHolder csdrdh : details) {
if (csdrdh.getDocType().equals(ArConstants.INVOICE_DOC_TYPE)) {
CustomerInvoiceDocumentService customerInvoiceDocumentService = SpringContext.getBean(CustomerInvoiceDocumentService.class);
CustomerInvoiceDocument ci = customerInvoiceDocumentService.getInvoiceByInvoiceDocumentNumber(csdrdh.getDocumentNumber());
Collection<CustomerInvoiceDetail> invoiceDetails = customerInvoiceDocumentService.getCustomerInvoiceDetailsForCustomerInvoiceDocument(ci);
java.util.Date reportRunDate = dateTimeService.getCurrentDate();
CustomerAgingReportDataHolder agingData = SpringContext.getBean(CustomerAgingReportService.class).calculateAgingReportAmounts(invoiceDetails, reportRunDate);
// add previous balance to 30 days and total amount due
addAgingAmountToInvoiceMap(ArConstants.CustomerAgingReportFields.TOTAL_0_TO_30, agingData.getTotal0to30().add(previousBalance), invoiceMap);
addAgingAmountToInvoiceMap(ArConstants.CustomerAgingReportFields.TOTAL_31_TO_60, agingData.getTotal31to60(), invoiceMap);
addAgingAmountToInvoiceMap(ArConstants.CustomerAgingReportFields.TOTAL_61_TO_90, agingData.getTotal61to90(), invoiceMap);
addAgingAmountToInvoiceMap(ArConstants.CustomerAgingReportFields.TOTAL_91_TO_SYSPR, agingData.getTotal91toSYSPR(), invoiceMap);
// it's not necessary to display an extra bucket on the statement, so I'm rolling up the amounts over 90 days into a single bucket for display
addAgingAmountToInvoiceMap(ArConstants.CustomerAgingReportFields.TOTAL_91_TO_SYSPR, agingData.getTotalSYSPRplus1orMore(), invoiceMap);
addAgingAmountToInvoiceMap(ArConstants.CustomerAgingReportFields.TOTAL_AMOUNT_DUE, agingData.getTotalAmountDue().add(previousBalance), invoiceMap);
}
}
}
/**
* This method...
*
* @param mapKey
* @param amountToAdd
* @param invoiceMap
*/
protected void addAgingAmountToInvoiceMap(String mapKey, KualiDecimal amountToAdd, Map<String, String> invoiceMap) {
BigDecimal amount = BigDecimal.ZERO;
String currentAmount = invoiceMap.get(mapKey);
if (StringUtils.isNotEmpty(currentAmount)) {
try {
amount = new BigDecimal(StringUtils.remove(currentAmount, ','));
}
catch (NumberFormatException nfe) {
LOG.error(currentAmount + " is an invalid amount.", nfe);
}
}
if (ObjectUtils.isNull(amountToAdd)) {
amountToAdd = KualiDecimal.ZERO;
}
KualiDecimal newAmount = new KualiDecimal(amount.add(amountToAdd.bigDecimalValue()));
invoiceMap.put(mapKey, currencyFormatter.format(newAmount).toString());
}
/**
* Gets a CustomerBillingStatement
* @param customerNumber
* @return
*/
protected CustomerBillingStatement getCustomerBillingStatement(String customerNumber) {
Map<String, String> criteria = new HashMap<String, String>();
criteria.put("customerNumber", customerNumber);
BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
return businessObjectService.findByPrimaryKey(CustomerBillingStatement.class, criteria);
}
protected String calculateDueDate() {
String parameterValue = getParameterService().getParameterValueAsString(CustomerBillingStatement.class, ArConstants.DUE_DATE_DAYS);
Calendar cal = Calendar.getInstance();
cal.setTime(dateTimeService.getCurrentDate());
cal.add(Calendar.DATE, Integer.parseInt(parameterValue));
Date dueDate = null;
try {
dueDate = dateTimeService.convertToSqlDate(new Timestamp(cal.getTime().getTime()));
}
catch (ParseException e) {
// TODO: throw an error here, but don't die
}
return dateTimeService.toDateString(dueDate);
}
/**
* This method...
*
* @param org
* @return
*/
protected String getChartAndOrgCodesCombined(Organization org) {
if (org == null) {
return null;
}
StringBuffer chartAndOrg = new StringBuffer(6);
chartAndOrg.append(org.getChartOfAccountsCode()).append(org.getOrganizationCode());
return chartAndOrg.toString();
}
/**
* This method...
*
* @return
*/
public DateTimeService getDateTimeService() {
if (dateTimeService == null) {
dateTimeService = SpringContext.getBean(DateTimeService.class);
}
return dateTimeService;
}
/**
* This method...
*
* @param dateTimeService
*/
public void setDateTimeService(DateTimeService dateTimeService) {
this.dateTimeService = dateTimeService;
}
public void setDocumentService(DocumentService documentService) {
this.documentService = documentService;
}
/**
* @return the parameterService
*/
public ParameterService getParameterService() {
if (parameterService == null) {
parameterService = SpringContext.getBean(ParameterService.class);
}
return parameterService;
}
/**
* @param parameterService the parameterService to set
*/
public void setParameterService(ParameterService parameterService) {
this.parameterService = parameterService;
}
}
| 58,166
|
Java
|
.java
| 853
| 56.400938
| 295
| 0.718004
|
ua-eas/ua-kfs-5.3
| 1
| 0
| 0
|
AGPL-3.0
|
9/5/2024, 12:36:54 AM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 58,166
|
1,316,112
|
B.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface/test77/out/B.java
|
package p;
public class B {
B(int t, I a){
a.amount();
}
}
| 64
|
Java
|
.java
| 6
| 8.833333
| 16
| 0.596491
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 64
|
4,534,509
|
IMarker.java
|
vitelabs_vite-wallet-android/MPChartLib/src/main/java/com/github/mikephil/charting/components/IMarker.java
|
package com.github.mikephil.charting.components;
import android.graphics.Canvas;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.utils.MPPointF;
public interface IMarker {
/**
* @return The desired (general) offset you wish the IMarker to have on the x- and y-axis.
* By returning x: -(width / 2) you will center the IMarker horizontally.
* By returning y: -(height / 2) you will center the IMarker vertically.
*/
MPPointF getOffset();
/**
* @param posX This is the X position at which the marker wants to be drawn.
* You can adjust the offset conditionally based on this argument.
* @param posY This is the X position at which the marker wants to be drawn.
* You can adjust the offset conditionally based on this argument.
* @return The offset for drawing at the specific `point`. This allows conditional adjusting of the Marker position.
* If you have no adjustments to make, return getOffset().
*/
MPPointF getOffsetForDrawingAtPoint(float posX, float posY);
/**
* This method enables a specified custom IMarker to update it's content every time the IMarker is redrawn.
*
* @param e The Entry the IMarker belongs to. This can also be any subclass of Entry, like BarEntry or
* CandleEntry, simply cast it at runtime.
* @param highlight The highlight object contains information about the highlighted value such as it's dataset-index, the
* selected range or stack-index (only stacked bar entries).
*/
void refreshContent(Entry e, Highlight highlight);
/**
* Draws the IMarker on the given position on the screen with the given Canvas object.
*
* @param canvas
* @param posX
* @param posY
*/
void draw(Canvas canvas, float posX, float posY);
}
| 1,963
|
Java
|
.java
| 39
| 45.25641
| 125
| 0.697444
|
vitelabs/vite-wallet-android
| 2
| 0
| 0
|
GPL-3.0
|
9/5/2024, 12:16:26 AM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 1,963
|
1,319,625
|
A_test565.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/locals_out/A_test565.java
|
package locals_out;
public class A_test565 {
void f(byte bytes) {
String s= "k";
extracted(bytes, s);
}
protected void extracted(byte bytes, String s) {
/*[*/System.out.println(s + " " + bytes); /*]*/
}
}
| 217
|
Java
|
.java
| 10
| 19.5
| 49
| 0.643902
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 217
|
2,293,925
|
KeyConfigurationEvent.java
|
dadler64_Logisim/src/main/java/com/cburch/logisim/tools/key/KeyConfigurationEvent.java
|
/* Copyright (c) 2010, Carl Burch. License information is located in the
* com.cburch.logisim.Main source code and at www.cburch.com/logisim/. */
package com.cburch.logisim.tools.key;
import com.cburch.logisim.data.AttributeSet;
import java.awt.event.KeyEvent;
public class KeyConfigurationEvent {
public static final int KEY_PRESSED = 0;
public static final int KEY_RELEASED = 1;
public static final int KEY_TYPED = 2;
private final int type;
private final AttributeSet attrs;
private final KeyEvent event;
private final Object data;
private boolean consumed;
public KeyConfigurationEvent(int type, AttributeSet attrs, KeyEvent event, Object data) {
this.type = type;
this.attrs = attrs;
this.event = event;
this.data = data;
this.consumed = false;
}
public int getType() {
return type;
}
public KeyEvent getKeyEvent() {
return event;
}
public AttributeSet getAttributeSet() {
return attrs;
}
public void consume() {
consumed = true;
}
public boolean isConsumed() {
return consumed;
}
public Object getData() {
return data;
}
}
| 1,218
|
Java
|
.java
| 40
| 24.725
| 93
| 0.676672
|
dadler64/Logisim
| 9
| 3
| 3
|
GPL-3.0
|
9/4/2024, 8:53:06 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| true
| true
| true
| 1,218
|
696,815
|
DeadDetector.java
|
mathgladiator_adama-lang/overlord/src/main/java/org/adamalang/overlord/roles/DeadDetector.java
|
/*
* Adama Platform and Language
* Copyright (C) 2021 - 2024 by Adama Platform Engineering, LLC
*
* 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.adamalang.overlord.roles;
import org.adamalang.common.NamedRunnable;
import org.adamalang.common.SimpleExecutor;
import org.adamalang.mysql.DataBase;
import org.adamalang.mysql.model.Sentinel;
import org.adamalang.overlord.OverlordMetrics;
import java.util.concurrent.atomic.AtomicBoolean;
// The dead detector will periodically scan the database to find tasks which haven't self reported in 15 minutes.
// This will raise a flag for the alarm system to pick up on
public class DeadDetector {
public static void kickOff(OverlordMetrics metrics, DataBase dataBase, AtomicBoolean alive) {
SimpleExecutor executor = SimpleExecutor.create("dead-detector");
executor.schedule(new NamedRunnable("dead-detector") {
@Override
public void execute() throws Exception {
if (alive.get()) {
try {
metrics.sentinel_behind.set(Sentinel.countBehind(dataBase, System.currentTimeMillis() - 15 * 60 * 1000));
Sentinel.ping(dataBase, "dead-detector", System.currentTimeMillis());
} finally {
executor.schedule(this, (int) (30000 + Math.random() * 30000));
}
}
}
}, 1000);
}
}
| 1,947
|
Java
|
.java
| 44
| 40.477273
| 117
| 0.744211
|
mathgladiator/adama-lang
| 107
| 15
| 14
|
AGPL-3.0
|
9/4/2024, 7:08:19 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 1,947
|
1,316,511
|
A_testRenameReorder26_out.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testRenameReorder26_out.java
|
package p;
class A{
/**
* @deprecated Use {@link #m(int,boolean)} instead
*/
private void m(boolean y, int a){
m(a, y);
}
private void m(int bb, boolean zzz){
m(bb, zzz);
}
}
| 198
|
Java
|
.java
| 12
| 13.583333
| 51
| 0.589189
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 198
|
1,773,141
|
ExportProperties.java
|
radiskis_ephesoft/dcma-export/src/main/java/com/ephesoft/dcma/export/ExportProperties.java
|
/*********************************************************************************
* Ephesoft is a Intelligent Document Capture and Mailroom Automation program
* developed by Ephesoft, Inc. Copyright (C) 2010-2012 Ephesoft Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY EPHESOFT, EPHESOFT DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact Ephesoft, Inc. headquarters at 111 Academy Way,
* Irvine, CA 92617, USA. or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Ephesoft" logo.
* If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by Ephesoft".
********************************************************************************/
package com.ephesoft.dcma.export;
import com.ephesoft.dcma.core.common.PluginProperty;
/**
* This enum contains all the properties required for this plug in from properties file.
*
* @author Ephesoft
* @version 1.0
* @see com.ephesoft.dcma.export.service.ExportServiceImpl
*/
public enum ExportProperties implements PluginProperty {
/**
* batch export to folder property.
*/
EXPORT_FOLDER("batch.export_to_folder"),
/**
* batch export to folder switch property.
*/
EXPORT_TO_FOLDER_SWITCH("batch.export_to_folder_switch"),
/**
* batch folder name.
*/
FOLDER_NAME("batch.folder_name"),
/**
* batch file name.
*/
FILE_NAME("batch.file_name"),
/**
* batch xml export folder.
*/
BATCH_XML_EXPORT_FOLDER("batch.batch_xml_export_folder");
/**
* The property key.
*/
String key;
ExportProperties(String key) {
this.key = key;
}
@Override
public String getPropertyKey() {
return key;
}
}
| 2,917
|
Java
|
.java
| 76
| 36.171053
| 88
| 0.716402
|
radiskis/ephesoft
| 10
| 20
| 0
|
AGPL-3.0
|
9/4/2024, 8:18:08 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 2,917
|
1,315,851
|
ATest.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots2/in/srcTest/p/p/ATest.java
|
package p.p;
import p.p.*; //myself
public class ATest {
A aFromOtherPackageFragment;
p.p.A aQualifiedFromNamesake;
public void test1() {
TestHelper.log("x");
}
}
| 173
|
Java
|
.java
| 9
| 17.111111
| 30
| 0.74375
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 173
|
11,692
|
package-info.java
|
junit-team_junit4/src/main/java/org/junit/internal/requests/package-info.java
|
/**
* Provides implementations of {@link org.junit.runner.Request}.
*
* @since 4.0
*/
package org.junit.internal.requests;
| 126
|
Java
|
.java
| 6
| 19.5
| 64
| 0.727273
|
junit-team/junit4
| 8,517
| 3,254
| 125
|
EPL-1.0
|
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 126
|
2,943,046
|
SharedListSet.java
|
MIT-PAC_obj-sens-soot/src/soot/jimple/spark/sets/SharedListSet.java
|
package soot.jimple.spark.sets;
import soot.Type;
import soot.jimple.spark.pag.Node;
import soot.jimple.spark.pag.PAG;
import soot.util.BitVector;
/*
* Reference counting was amazingly difficult to get right, for the number of lines of
* code it makes up.
* Reference counting keeps track of how many things are pointing to a ListNode. When
* it has no more things pointing to it, it needs to be deleted from the HashMap.
*
* I think I finally got the correct algorithm for when to increase and when to decrease
* a node's reference count. It is:
* -When a new node is created (in makeNode), its "next" pointer will have an extra thing
* pointing at it, so increase its reference count.
* -When a new top-level pointer (a "SharedListSet.data member) is assigned to a node, it
* has one extra thing pointing at it, so increase its reference count.
* -Reference count decreases when a chain is detached. Detachment is bit of a complicated
* process; it should be described in my thesis.
*
*/
//Can't use java.lang.ref.WeakReferences instead because:
//The HashMap will now map WeakReferences (containing
//Pairs) to ListNodes, so its object will be null. But will it then hash to the same
//value after its object has become null?
//And it still seems like I'd have to remove the WeakReferences from the HashMap whose references
//have become null.
/*
* Ideas to speed things up:
* -For contains(), first check the index of all nodes to see whether the node exists
* in *any* points-to set.
* -I don't think this one will be very fast because if 2 lists are similar but differ in an
* element at the end of them, they can't be shared.
*/
/*
List is sorted.
Therefore:
contains: O(n)
add: O(n), and might add things to other lists too
*/
/** Implementation of a points-to set as a sorted list of elements,
* but where similar lists share parts of their data.
*/
public class SharedListSet extends PointsToSetInternal
{
public SharedListSet(Type type, PAG pag)
{
super( type );
this.pag = pag;
}
// Ripped from the other points-to sets - returns a factory that can be
// used to construct SharedHybridSets
public final static P2SetFactory getFactory() {
return new P2SetFactory() {
public final PointsToSetInternal newSet(Type type, PAG pag) {
return new SharedListSet(type, pag);
}
};
}
public boolean contains(Node n)
{
for (ListNode i = data; i != null; i = i.next)
{
if (i.elem == n) return true;
}
return false;
}
public boolean isEmpty()
{
return data == null;
}
public boolean forall(P2SetVisitor v)
{
for (ListNode i = data; i != null; i = i.next)
{
v.visit(i.elem);
}
return v.getReturnValue();
}
private ListNode advanceExclude(ListNode exclude, ListNode other)
{
//If exclude's node is less than other's first node, then there
//are elements to exclude that aren't in other, so keep advancing exclude
final int otherNum = other.elem.getNumber();
while(exclude != null && exclude.elem.getNumber() < otherNum)
{
exclude = exclude.next;
}
return exclude;
}
private boolean excluded(ListNode exclude, ListNode other, BitVector mask)
{
return (exclude != null && other.elem == exclude.elem)
|| (mask != null && (!(mask.get(other.elem.getNumber()))));
}
private ListNode union(ListNode first, ListNode other, ListNode exclude, BitVector mask
, boolean detachChildren)
{
//This algorithm must be recursive because we don't know whether to detach until
//we know the rest of the list.
if (first == null)
{
if (other == null) return null;
//Normally, we could just return other in this case.
//But the problem is that there might be elements to exclude from other.
//We also can't modify other and remove elements from it, because that would
//remove elements from the points-to set whose elements are being added to this
//one.
//So we have to create a new list from scratch of the copies of the elements
//of other.
if (exclude == null && mask == null)
{
return makeNode(other.elem, other.next);
//Can't just do:
//return other;
//because of the reference counting going on. (makeNode might increment
//the reference count.)
}
else
{
exclude = advanceExclude(exclude, other);
if (excluded(exclude, other, mask))
//If the first element of other is to be excluded
{
return union(first, other.next, exclude, mask, detachChildren);
}
else
{
return makeNode(other.elem, union(first, other.next, exclude, mask, detachChildren));
}
}
}
else if (other == null)
{
return first;
}
else if (first == other)
{
//We've found sharing - don't need to add any more
return first; //Doesn't matter what's being excluded, since it's all in first
}
else
{
ListNode retVal;
if (first.elem.getNumber() > other.elem.getNumber())
{
//Adding a new node, other.elem. But we might not have to add it if
//it's to be excluded.
exclude = advanceExclude(exclude, other);
if (excluded(exclude, other, mask))
//If the first element of other is to be excluded
{
retVal = union(first, other.next, exclude, mask, detachChildren);
}
else
{
retVal = makeNode(other.elem, union(first, other.next, exclude, mask, detachChildren));
}
}
else
{
if (first.refCount > 1)
{
//if we're dealing with a shared node, stop detaching.
detachChildren = false;
}
//Doesn't matter whether it's being excluded; just add it once and advance
//both lists to the next node
if (first.elem == other.elem)
{
//if both lists contain the element being added, only add it once
other = other.next;
}
retVal = makeNode(first.elem, union(first.next, other, exclude, mask, detachChildren));
if (detachChildren && first != retVal && first.next != null)
{
first.next.decRefCount(); //When we advance "first" and copy its node into the
//output list, the old "first" will eventually be thrown away (unless other
//stuff points to it).
}
}
return retVal;
}
}
//Common function to prevent repeated code in add and addAll
private boolean addOrAddAll(ListNode first, ListNode other, ListNode exclude, BitVector mask)
{
ListNode result = union(first, other, exclude, mask, true);
if (result == data)
{
return false;
}
else
{
//result is about to have an extra thing pointing at it, and data is about to
//have one less thing pointing at it, so adjust the reference counts.
result.incRefCount();
if (data != null) data.decRefCount();
data = result;
return true;
}
}
public boolean add(Node n)
{
//Prevent repeated code by saying add() is just a union() with one element in the
//set being merged in. add isn't called frequently anyway.
//However, we have to call makeNode() to get the node, in case it was already there
//and because union() assumes "other" is an existing node in another set. So we
//create the node for the duration of the call to addOrAddAll(), after which we
//delete it unless it was already there
ListNode other = makeNode(n, null);
other.incRefCount();
boolean added = addOrAddAll(data, other, null, null);
other.decRefCount(); //undo its creation
return added;
}
public boolean addAll(PointsToSetInternal other, PointsToSetInternal exclude)
{
if (other == null) return false;
if ((!(other instanceof SharedListSet))
|| (exclude != null && !(exclude instanceof SharedListSet)))
{
return super.addAll(other, exclude);
}
else
{
SharedListSet realOther = (SharedListSet) other,
realExclude = (SharedListSet) exclude;
BitVector mask = getBitMask(realOther, pag);
ListNode excludeData = (realExclude == null)? null : realExclude.data;
return addOrAddAll(data, realOther.data, excludeData, mask);
}
}
//Holds pairs of (Node, ListNode)
public class Pair
{
public Node first;
public ListNode second;
public Pair(Node first, ListNode second)
{
this.first = first;
this.second = second;
}
public int hashCode() {
//I don't think the Node will ever be null
if (second == null) return first.hashCode();
else return first.hashCode() + second.hashCode();
}
public boolean equals(Object other)
{
if (! (other instanceof Pair)) return false;
Pair o = (Pair)other;
return ((first == null && o.first == null) || first == o.first)
&& ((second == null && o.second == null) || second == o.second);
}
}
//It's a bit confusing because there are nodes in the list and nodes in the PAG.
//Node means a node in the PAG, ListNode is for nodes in the list (each of which
//contains a Node as its data)
public class ListNode
{
private Node elem;
private ListNode next = null;
public long refCount;
public ListNode(Node elem, ListNode next)
{
this.elem = elem;
this.next = next;
refCount = 0; //When it's first created, it's being used exactly once
}
public void incRefCount()
{
++refCount;
//Get an idea of how much sharing is taking place
// System.out.println(refCount);
}
public void decRefCount()
{
if (--refCount == 0)
//if it's not being shared
{
//Remove the list from the HashMap if it's no longer used; otherwise
//the sharing won't really gain us memory.
AllSharedListNodes.v().allNodes.remove(new Pair(elem, next));
}
}
}
//I wanted to make this a static method of ListNode, but it
//wasn't working for some reason
private ListNode makeNode(Node elem, ListNode next)
{
Pair p = new Pair(elem, next);
ListNode retVal = (AllSharedListNodes.v().allNodes.get(p));
if (retVal == null)
//if it's not an existing node
{
retVal = new ListNode(elem, next);
if (next != null) next.incRefCount(); //next now has an extra
//thing pointing at it (the newly created node)
AllSharedListNodes.v().allNodes.put(p, retVal);
}
return retVal;
}
//private final Map allNodes = AllSharedListNodes.v().allNodes;
//private static Map allNodes = new HashMap();
private PAG pag; // I think this is needed to get the size of the bit
// vector and the mask for casting
private ListNode data = null;
}
| 10,286
|
Java
|
.java
| 309
| 29.802589
| 97
| 0.703166
|
MIT-PAC/obj-sens-soot
| 5
| 1
| 0
|
LGPL-2.1
|
9/4/2024, 10:36:36 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 10,286
|
1,317,489
|
A_test4_out.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/InlineTemp/canInline/A_test4_out.java
|
package p;
class A{
int m(int i){
return (i + 1) * (i + 1) + m(m(i));
}
}
| 77
|
Java
|
.java
| 6
| 11.333333
| 37
| 0.486111
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 77
|
4,947,987
|
CustomerInvoiceDetailDao.java
|
ua-eas_ua-kfs-5_3/work/src/org/kuali/kfs/module/ar/document/dataaccess/CustomerInvoiceDetailDao.java
|
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2014 The Kuali Foundation
*
* 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 <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.module.ar.document.dataaccess;
import java.util.Collection;
import java.util.List;
public interface CustomerInvoiceDetailDao {
/**
* This method retrieves all CustomerInvoiceDetail objects for the accountNumber if invoiceNumber is from the invoiceNumberList
* @return CustomerInvoiceDetail objects
*/
public Collection getCustomerInvoiceDetailsByAccountNumberByInvoiceDocumentNumbers(String accountNumber,List documentNumbers);
}
| 1,335
|
Java
|
.java
| 28
| 43.857143
| 134
| 0.772064
|
ua-eas/ua-kfs-5.3
| 1
| 0
| 0
|
AGPL-3.0
|
9/5/2024, 12:36:54 AM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 1,335
|
1,320,693
|
A.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameMethodInInterface/test44/in/A.java
|
//renaming I.m to k
package p;
interface I {
void m();
}
interface J{
void m();
}
interface J2 extends J{
void m();
}
class A{
public void m(){};
}
class C extends A implements I, J{
public void m(){};
}
class Test{
void k(){
}
}
| 239
|
Java
|
.java
| 21
| 9.952381
| 34
| 0.662037
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 239
|
2,660,514
|
PodcastOpenHelper.java
|
jimmc_HapiPodcastJ/src/info/xuluan/podcast/provider/PodcastOpenHelper.java
|
package info.xuluan.podcast.provider;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import info.xuluan.podcast.utils.Log;
public class PodcastOpenHelper extends SQLiteOpenHelper {
private final Log log = Log.getLog(getClass());
//Version 12: inherited from original HapiPodcast
//Version 13: add KEEP column to items table
//Version 14: add SUSPENDED column to subscriptions table
private final static int DBVERSION = 14;
private boolean downgradeEnabled = false; //for debugging
public PodcastOpenHelper(Context context) {
super(context, "podcast.db", null, DBVERSION);
}
//For debugging, allow opening the database using an older version number
public PodcastOpenHelper(Context context, int version) {
super(context, "podcast.db", null, version);
downgradeEnabled = true;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SubscriptionColumns.sql_create_table(DBVERSION));
db.execSQL(SubscriptionColumns.sql_index_subs_url);
db.execSQL(SubscriptionColumns.sql_index_last_update);
db.execSQL(ItemColumns.sql_create_table);
db.execSQL(ItemColumns.sql_index_item_res);
db.execSQL(ItemColumns.sql_index_item_created);
db.execSQL(SubscriptionColumns.sql_insert_default);
db.execSQL(SubscriptionColumns.sql_insert_default1);
db.execSQL(SubscriptionColumns.sql_insert_default2);
//db.execSQL(SubscriptionColumns.sql_insert_default3);
//db.execSQL(SubscriptionColumns.sql_insert_default4);
}
@SuppressLint("NewApi")
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion>=newVersion) {
if ((newVersion < oldVersion) && downgradeEnabled) {
onDowngrade(db, oldVersion, newVersion);
}
return;
}
if (oldVersion < 12) {
log.debug("Database is version "+oldVersion+", drop and recreate");
db.execSQL("DROP TABLE " + ItemColumns.TABLE_NAME);
db.execSQL("DROP TABLE " + SubscriptionColumns.TABLE_NAME);
onCreate(db);
return;
}
log.debug("Upgrading database from version "+oldVersion+" to "+newVersion);
if (oldVersion<=12) {
//Add the KEEP column to the items table,
//use that rather than the old KEEP status
log.debug("executing sql: "+ItemColumns.sql_upgrade_table_add_keep_column);
db.execSQL(ItemColumns.sql_upgrade_table_add_keep_column);
log.debug("executing sql: "+ItemColumns.sql_populate_keep_from_status);
db.execSQL(ItemColumns.sql_populate_keep_from_status);
log.debug("executing sql: "+ItemColumns.sql_change_keep_status_to_played);
db.execSQL(ItemColumns.sql_change_keep_status_to_played);
log.debug("Done upgrading database");
}
if (oldVersion<=13) {
//Add the SUSPENDED column to the subscriptions table
log.debug("executing sql: "+SubscriptionColumns.sql_upgrade_subscriptions_add_suspended_column);
db.execSQL(SubscriptionColumns.sql_upgrade_subscriptions_add_suspended_column);
}
}
//For debugging, allow downgrading the database.
//Before API 11, this method did not exist in the API, and onUpgrade would be called whenever
//oldVersion!=newVersion, even when oldVersion>newVersion.
//Starting with API 11, the default behavior is to throw an exception if
//oldVersion>newVersion and there is no onDowngrade. By defining our own onDowngrade
//and putting code in onUpgrade to call us when oldVersion>newVersion, we end up
//executing this method on a downgrade for any API version.
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion<=newVersion)
return;
if (newVersion<14 && oldVersion>=14) {
//Remove the stuff added in version 14
dropTableColumn(db, SubscriptionColumns.TABLE_NAME, SubscriptionColumns.SUSPENDED,
SubscriptionColumns.sql_create_table(13));
}
if (newVersion<13 && oldVersion>=13) {
//Remove stuff added in version 13
//TODO - for each item marked in the KEEP columns of the items table,
// if the status is played, change it to keep.
//TODO - remove the KEEP column from the items table
}
}
private void dropTableColumn(SQLiteDatabase db, String table, String dropColumn,
String createTableSql) {
List<String> columnList = tableColumns(db, table, dropColumn);
String columnNames = TextUtils.join(",", columnList);
String oldTable = table + "_old";
db.execSQL("ALTER TABLE "+table+" RENAME TO "+oldTable+";");
db.execSQL(createTableSql);
db.execSQL("INSERT INTO "+table+" SELECT "+columnNames+" FROM "+oldTable+";");
db.execSQL("DROP TABLE "+oldTable+";");
}
private List<String> tableColumns(SQLiteDatabase db, String tableName, String excludingColumn) {
ArrayList<String> columns = new ArrayList<String>();
String columnsCommand = "PRAGMA TABLE_INFO(" + tableName + ");";
Cursor columnsCursor = db.rawQuery(columnsCommand, null);
int nameColIndex = columnsCursor.getColumnIndex("name");
while (columnsCursor.moveToNext()) {
String column = columnsCursor.getString(nameColIndex);
if (!column.equals(excludingColumn))
columns.add(column);
}
columnsCursor.close();
return columns;
}
}
| 5,440
|
Java
|
.java
| 119
| 41.378151
| 100
| 0.749953
|
jimmc/HapiPodcastJ
| 6
| 18
| 0
|
GPL-2.0
|
9/4/2024, 10:01:50 PM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 5,440
|
990,327
|
LongProperty.java
|
ac2cz_FoxTelem/lib/mysql-connector-java-8.0.29/src/main/core-impl/java/com/mysql/cj/conf/LongProperty.java
|
/*
* Copyright (c) 2015, 2020, Oracle and/or its affiliates.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 2.0, as published by the
* Free Software Foundation.
*
* This program is also distributed with certain software (including but not
* limited to OpenSSL) that is licensed under separate terms, as designated in a
* particular file or component or in included license documentation. The
* authors of MySQL hereby grant you an additional permission to link the
* program and your derivative works with the separately licensed software that
* they have included with MySQL.
*
* Without limiting anything contained in the foregoing, this file, which is
* part of MySQL Connector/J, is also subject to the Universal FOSS Exception,
* version 1.0, a copy of which can be found at
* http://oss.oracle.com/licenses/universal-foss-exception.
*
* 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, version 2.0,
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.mysql.cj.conf;
import com.mysql.cj.exceptions.ExceptionFactory;
import com.mysql.cj.exceptions.ExceptionInterceptor;
import com.mysql.cj.exceptions.WrongArgumentException;
public class LongProperty extends AbstractRuntimeProperty<Long> {
private static final long serialVersionUID = 1814429804634837665L;
protected LongProperty(PropertyDefinition<Long> propertyDefinition) {
super(propertyDefinition);
}
@Override
protected void checkRange(Long val, String valueAsString, ExceptionInterceptor exceptionInterceptor) {
if ((val.longValue() < getPropertyDefinition().getLowerBound()) || (val.longValue() > getPropertyDefinition().getUpperBound())) {
throw ExceptionFactory.createException(WrongArgumentException.class,
"The connection property '" + getPropertyDefinition().getName() + "' only accepts long integer values in the range of "
+ getPropertyDefinition().getLowerBound() + " - " + getPropertyDefinition().getUpperBound() + ", the value '"
+ (valueAsString == null ? val.longValue() : valueAsString) + "' exceeds this range.",
exceptionInterceptor);
}
}
}
| 2,660
|
Java
|
.java
| 48
| 50.479167
| 139
| 0.74175
|
ac2cz/FoxTelem
| 52
| 17
| 62
|
GPL-3.0
|
9/4/2024, 7:10:22 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 2,660
|
4,060,508
|
LocalAgentReport.java
|
heniancheng_FRODO/src/frodo2/daemon/LocalAgentReport.java
|
/*
FRODO: a FRamework for Open/Distributed Optimization
Copyright (C) 2008-2013 Thomas Leaute, Brammert Ottens & Radoslaw Szymanek
FRODO 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.
FRODO 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/>.
How to contact the authors:
<http://frodo2.sourceforge.net/>
*/
package frodo2.daemon;
import frodo2.algorithms.AgentInterface;
import frodo2.communication.MessageWith3Payloads;
import frodo2.communication.sharedMemory.QueueIOPipe;
/** A message that an agent sends to its local white pages to report
* @author Thomas Leaute
*/
public class LocalAgentReport extends MessageWith3Payloads<String, Integer, QueueIOPipe> {
/** Empty constructor used for externalization */
public LocalAgentReport () { }
/** Constructor
* @param agentID the agent's ID
* @param port the port the agent listens on
* @param localPipe the agent's local I/O pipe
*/
public LocalAgentReport (String agentID, Integer port, QueueIOPipe localPipe) {
super (AgentInterface.LOCAL_AGENT_REPORTING, agentID, port, localPipe);
}
/** @return the agent's ID */
public String getAgentID () {
return super.getPayload1();
}
/** @return the port the agent listens on */
public Integer getPort () {
return super.getPayload2();
}
/** @return the agent's local I/O pipe */
public QueueIOPipe getLocalPipe () {
return super.getPayload3();
}
}
| 1,906
|
Java
|
.java
| 47
| 38.446809
| 90
| 0.778924
|
heniancheng/FRODO
| 2
| 0
| 0
|
AGPL-3.0
|
9/5/2024, 12:01:34 AM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 1,906
|
1,316,418
|
A_testVararg01_out.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testVararg01_out.java
|
package p;
class A {
public void m(int i, String... strings) {
for (String name : strings) {
System.out.println(name);
}
}
}
class B extends A {
public void m(int i, String[] strings) {
for (String name : strings) {
System.out.println(name);
}
}
}
class C extends B {
public void m(int i, String... strings) {
System.out.println(strings[i]);
strings= new String[0];
}
}
class Client {
{
new A().m(0);
new B().m(1, new String[] {"X"});
new C().m(2, new String[] {"X", "Y"});
new C().m(2, "X", "Y", "Z");
}
}
| 544
|
Java
|
.java
| 29
| 16.482759
| 42
| 0.597656
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 544
|
3,696,512
|
ImageBasedLight.java
|
thsa_fxmolviewer/src/main/java/org/sunflow/core/light/ImageBasedLight.java
|
package org.sunflow.core.light;
import org.sunflow.SunflowAPI;
import org.sunflow.core.Instance;
import org.sunflow.core.IntersectionState;
import org.sunflow.core.LightSample;
import org.sunflow.core.LightSource;
import org.sunflow.core.ParameterList;
import org.sunflow.core.PrimitiveList;
import org.sunflow.core.Ray;
import org.sunflow.core.Shader;
import org.sunflow.core.ShadingState;
import org.sunflow.core.Texture;
import org.sunflow.core.TextureCache;
import org.sunflow.image.Bitmap;
import org.sunflow.image.Color;
import org.sunflow.math.BoundingBox;
import org.sunflow.math.Matrix4;
import org.sunflow.math.OrthoNormalBasis;
import org.sunflow.math.Point3;
import org.sunflow.math.QMC;
import org.sunflow.math.Vector3;
public class ImageBasedLight implements PrimitiveList, LightSource, Shader {
private Texture texture;
private OrthoNormalBasis basis;
private int numSamples;
private int numLowSamples;
private float jacobian;
private float[] colHistogram;
private float[][] imageHistogram;
private Vector3[] samples;
private Vector3[] lowSamples;
private Color[] colors;
private Color[] lowColors;
public ImageBasedLight() {
texture = null;
updateBasis(new Vector3(0, 0, -1), new Vector3(0, 1, 0));
numSamples = 64;
numLowSamples = 8;
}
private void updateBasis(Vector3 center, Vector3 up) {
if (center != null && up != null) {
basis = OrthoNormalBasis.makeFromWV(center, up);
basis.swapWU();
basis.flipV();
}
}
public boolean update(ParameterList pl, SunflowAPI api) {
updateBasis(pl.getVector("center", null), pl.getVector("up", null));
numSamples = pl.getInt("samples", numSamples);
numLowSamples = pl.getInt("lowsamples", numLowSamples);
String filename = pl.getString("texture", null);
if (filename != null)
texture = TextureCache.getTexture(api.resolveTextureFilename(filename), false);
// no texture provided
if (texture == null)
return false;
Bitmap b = texture.getBitmap();
if (b == null)
return false;
// rebuild histograms if this is a new texture
if (filename != null) {
imageHistogram = new float[b.getWidth()][b.getHeight()];
colHistogram = new float[b.getWidth()];
float du = 1.0f / b.getWidth();
float dv = 1.0f / b.getHeight();
for (int x = 0; x < b.getWidth(); x++) {
for (int y = 0; y < b.getHeight(); y++) {
float u = (x + 0.5f) * du;
float v = (y + 0.5f) * dv;
Color c = texture.getPixel(u, v);
imageHistogram[x][y] = c.getLuminance() * (float) Math.sin(Math.PI * v);
if (y > 0)
imageHistogram[x][y] += imageHistogram[x][y - 1];
}
colHistogram[x] = imageHistogram[x][b.getHeight() - 1];
if (x > 0)
colHistogram[x] += colHistogram[x - 1];
for (int y = 0; y < b.getHeight(); y++)
imageHistogram[x][y] /= imageHistogram[x][b.getHeight() - 1];
}
for (int x = 0; x < b.getWidth(); x++)
colHistogram[x] /= colHistogram[b.getWidth() - 1];
jacobian = (float) (2 * Math.PI * Math.PI) / (b.getWidth() * b.getHeight());
}
// take fixed samples
if (pl.getBoolean("fixed", samples != null)) {
// high density samples
samples = new Vector3[numSamples];
colors = new Color[numSamples];
generateFixedSamples(samples, colors);
// low density samples
lowSamples = new Vector3[numLowSamples];
lowColors = new Color[numLowSamples];
generateFixedSamples(lowSamples, lowColors);
} else {
// turn off
samples = lowSamples = null;
colors = lowColors = null;
}
return true;
}
private void generateFixedSamples(Vector3[] samples, Color[] colors) {
for (int i = 0; i < samples.length; i++) {
double randX = (double) i / (double) samples.length;
double randY = QMC.halton(0, i);
int x = 0;
while (randX >= colHistogram[x] && x < colHistogram.length - 1)
x++;
float[] rowHistogram = imageHistogram[x];
int y = 0;
while (randY >= rowHistogram[y] && y < rowHistogram.length - 1)
y++;
// sample from (x, y)
float u = (float) ((x == 0) ? (randX / colHistogram[0]) : ((randX - colHistogram[x - 1]) / (colHistogram[x] - colHistogram[x - 1])));
float v = (float) ((y == 0) ? (randY / rowHistogram[0]) : ((randY - rowHistogram[y - 1]) / (rowHistogram[y] - rowHistogram[y - 1])));
float px = ((x == 0) ? colHistogram[0] : (colHistogram[x] - colHistogram[x - 1]));
float py = ((y == 0) ? rowHistogram[0] : (rowHistogram[y] - rowHistogram[y - 1]));
float su = (x + u) / colHistogram.length;
float sv = (y + v) / rowHistogram.length;
float invP = (float) Math.sin(sv * Math.PI) * jacobian / (numSamples * px * py);
samples[i] = getDirection(su, sv);
basis.transform(samples[i]);
colors[i] = texture.getPixel(su, sv).mul(invP);
}
}
public void prepareShadingState(ShadingState state) {
if (state.includeLights())
state.setShader(this);
}
public void intersectPrimitive(Ray r, int primID, IntersectionState state) {
if (r.getMax() == Float.POSITIVE_INFINITY)
state.setIntersection(0);
}
public int getNumPrimitives() {
return 1;
}
public float getPrimitiveBound(int primID, int i) {
return 0;
}
public BoundingBox getWorldBounds(Matrix4 o2w) {
return null;
}
public PrimitiveList getBakingPrimitives() {
return null;
}
public int getNumSamples() {
return numSamples;
}
public void getSamples(ShadingState state) {
if (samples == null) {
int n = state.getDiffuseDepth() > 0 ? 1 : numSamples;
for (int i = 0; i < n; i++) {
// random offset on unit square, we use the infinite version of
// getRandom because the light sampling is adaptive
double randX = state.getRandom(i, 0, n);
double randY = state.getRandom(i, 1, n);
int x = 0;
while (randX >= colHistogram[x] && x < colHistogram.length - 1)
x++;
float[] rowHistogram = imageHistogram[x];
int y = 0;
while (randY >= rowHistogram[y] && y < rowHistogram.length - 1)
y++;
// sample from (x, y)
float u = (float) ((x == 0) ? (randX / colHistogram[0]) : ((randX - colHistogram[x - 1]) / (colHistogram[x] - colHistogram[x - 1])));
float v = (float) ((y == 0) ? (randY / rowHistogram[0]) : ((randY - rowHistogram[y - 1]) / (rowHistogram[y] - rowHistogram[y - 1])));
float px = ((x == 0) ? colHistogram[0] : (colHistogram[x] - colHistogram[x - 1]));
float py = ((y == 0) ? rowHistogram[0] : (rowHistogram[y] - rowHistogram[y - 1]));
float su = (x + u) / colHistogram.length;
float sv = (y + v) / rowHistogram.length;
float invP = (float) Math.sin(sv * Math.PI) * jacobian / (n * px * py);
Vector3 dir = getDirection(su, sv);
basis.transform(dir);
if (Vector3.dot(dir, state.getGeoNormal()) > 0) {
LightSample dest = new LightSample();
dest.setShadowRay(new Ray(state.getPoint(), dir));
dest.getShadowRay().setMax(Float.MAX_VALUE);
Color radiance = texture.getPixel(su, sv);
dest.setRadiance(radiance, radiance);
dest.getDiffuseRadiance().mul(invP);
dest.getSpecularRadiance().mul(invP);
dest.traceShadow(state);
state.addSample(dest);
}
}
} else {
if (state.getDiffuseDepth() > 0) {
for (int i = 0; i < numLowSamples; i++) {
if (Vector3.dot(lowSamples[i], state.getGeoNormal()) > 0 && Vector3.dot(lowSamples[i], state.getNormal()) > 0) {
LightSample dest = new LightSample();
dest.setShadowRay(new Ray(state.getPoint(), lowSamples[i]));
dest.getShadowRay().setMax(Float.MAX_VALUE);
dest.setRadiance(lowColors[i], lowColors[i]);
dest.traceShadow(state);
state.addSample(dest);
}
}
} else {
for (int i = 0; i < numSamples; i++) {
if (Vector3.dot(samples[i], state.getGeoNormal()) > 0 && Vector3.dot(samples[i], state.getNormal()) > 0) {
LightSample dest = new LightSample();
dest.setShadowRay(new Ray(state.getPoint(), samples[i]));
dest.getShadowRay().setMax(Float.MAX_VALUE);
dest.setRadiance(colors[i], colors[i]);
dest.traceShadow(state);
state.addSample(dest);
}
}
}
}
}
public void getPhoton(double randX1, double randY1, double randX2, double randY2, Point3 p, Vector3 dir, Color power) {
}
public Color getRadiance(ShadingState state) {
// lookup texture based on ray direction
return state.includeLights() ? getColor(basis.untransform(state.getRay().getDirection(), new Vector3())) : Color.BLACK;
}
private Color getColor(Vector3 dir) {
float u, v;
// assume lon/lat format
double phi = 0, theta = 0;
phi = Math.acos(dir.y);
theta = Math.atan2(dir.z, dir.x);
u = (float) (0.5 - 0.5 * theta / Math.PI);
v = (float) (phi / Math.PI);
return texture.getPixel(u, v);
}
private Vector3 getDirection(float u, float v) {
Vector3 dest = new Vector3();
double phi = 0, theta = 0;
theta = u * 2 * Math.PI;
phi = v * Math.PI;
double sin_phi = Math.sin(phi);
dest.x = (float) (-sin_phi * Math.cos(theta));
dest.y = (float) Math.cos(phi);
dest.z = (float) (sin_phi * Math.sin(theta));
return dest;
}
public void scatterPhoton(ShadingState state, Color power) {
}
public float getPower() {
return 0;
}
public Instance createInstance() {
return Instance.createTemporary(this, null, this);
}
}
| 11,359
|
Java
|
.java
| 247
| 33.502024
| 150
| 0.538663
|
thsa/fxmolviewer
| 3
| 3
| 5
|
GPL-3.0
|
9/4/2024, 11:38:49 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 11,359
|
1,314,874
|
Foo.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceIndirection/test17_33/out/Foo.java
|
package p;
class C {
}
interface I {
}
public class Foo<T extends C & I> {
/**
* @param <T>
* @param <U>
* @param foo
* @return
*/
public static <T extends C & I, U extends C & I> Foo<U> getX(Foo<T> foo) {
return foo.getX();
}
<U extends C & I> Foo<U> getX() {
return null;
}
Foo<?> f2 = Foo.getX(this);
}
| 347
|
Java
|
.java
| 20
| 14.3
| 75
| 0.559748
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 347
|
1,317,270
|
ThirdClass.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameType/testSimilarElements20/out/ThirdClass.java
|
package p;
public class ThirdClass extends OtherClass {
public ThirdClass getThirdClass() {
return null;
}
}
| 117
|
Java
|
.java
| 6
| 17.166667
| 44
| 0.794393
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 117
|
1,317,938
|
A_test6_out.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractTemp/canExtract/A_test6_out.java
|
package p;
class A{
int m(int i){
final int temp= 1 + 2;
int x= temp;
return temp;
}
}
| 94
|
Java
|
.java
| 8
| 9.875
| 24
| 0.62069
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 94
|
1,318,893
|
A_test621.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/expression_out/A_test621.java
|
package expression_out;
public class A_test621 {
public A_test621() {
this(extracted());
}
protected static int extracted() {
return /*[*/5 + 6/*]*/;
}
public A_test621(int i) {
}
}
| 193
|
Java
|
.java
| 11
| 15.545455
| 35
| 0.657459
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 193
|
1,316,060
|
SwitchCase.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractClass/testSwitchCase/in/SwitchCase.java
|
/*******************************************************************************
* Copyright (c) 2007 IBM Corporation and others.
*
* 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 p;
public class SwitchCase {
private static final int TEST2 = 6;
public final int TEST = TEST2;
public void foo(){
int test=5;
switch (test) {
case TEST:
break;
default:
break;
}
}
}
| 763
|
Java
|
.java
| 27
| 26.074074
| 81
| 0.572011
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 763
|
1,315,918
|
Klass.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/InlineConstant/canInline/test2/out/Klass.java
|
// 10, 22 -> 10, 30 replaceAll == false
package p;
class Klass {
static final Klass KONSTANT= new Klass() ;
static void f() {
Klass klass= new Klass();
}
Klass klass=KONSTANT;
}
| 208
|
Java
|
.java
| 9
| 20.555556
| 56
| 0.625
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 208
|
48,275
|
Ambient.java
|
Bukkit_Bukkit/src/main/java/org/bukkit/entity/Ambient.java
|
package org.bukkit.entity;
/**
* Represents an ambient mob
*/
public interface Ambient extends LivingEntity {}
| 114
|
Java
|
.java
| 5
| 21.2
| 48
| 0.787037
|
Bukkit/Bukkit
| 2,394
| 1,051
| 70
|
GPL-3.0
|
9/4/2024, 7:04:55 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 114
|
1,316,173
|
C.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface/test102/in/C.java
|
package p;
public class C<S, T extends String> {
public void foo () {}
}
| 83
|
Java
|
.java
| 4
| 17.25
| 37
| 0.685714
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 83
|
1,316,459
|
A_test14_in.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_test14_in.java
|
package p;
class A{
private int m(int i, int j){
return m(m(1, 2), 3);
}
}
| 78
|
Java
|
.java
| 6
| 11.5
| 29
| 0.60274
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 78
|
4,060,520
|
Test2_DateTimeTest.java
|
brianwoo_Programming-Mobile-Applications-for-Android-Handheld-Systems/Week4/UserInterface/SourceFiles/TestCases/UILabsTest/src/course/labs/todomanager/test/Test2_DateTimeTest.java
|
package course.labs.todomanager.test;
import android.test.ActivityInstrumentationTestCase2;
import com.robotium.solo.Solo;
import course.labs.todomanager.ToDoManagerActivity;
public class Test2_DateTimeTest extends ActivityInstrumentationTestCase2<ToDoManagerActivity> {
private Solo solo;
public Test2_DateTimeTest() {
super(ToDoManagerActivity.class);
}
protected void setUp() throws Exception {
solo = new Solo(getInstrumentation());
getActivity();
}
protected void tearDown() throws Exception {
solo.finishOpenedActivities();
}
// Executes DateTimeTest
public void testRun() {
// ============== Section One ================
// Wait for activity: 'course.labs.todomanager.ToDoManagerActivity'
assertTrue("DateTimeTest failed:" +
"Section One:" +
"ToDoManagerActivity did not correctly load.",
solo.waitForActivity(
course.labs.todomanager.ToDoManagerActivity.class, 2000));
// Click on action bar item to delete all items
solo.clickOnActionBarItem(0x1);
// Click on Add New ToDo Item
solo.clickOnView(solo.getView(course.labs.todomanager.R.id.footerView));
// Wait for activity: 'course.labs.todomanager.AddToDoActivity'
assertTrue("DateTimeTest failed:" +
"Section One:" +
"AddToDoActivity did not correctly load.",
solo.waitForActivity(course.labs.todomanager.AddToDoActivity.class));
// Hide the soft keyboard
solo.hideSoftKeyboard();
// Enter the text: 't1'
solo.clearEditText((android.widget.EditText) solo
.getView(course.labs.todomanager.R.id.title));
solo.enterText((android.widget.EditText) solo
.getView(course.labs.todomanager.R.id.title), "t1");
// Hide the soft keyboard
solo.hideSoftKeyboard();
// Click on Done:
solo.clickOnView(solo.getView(course.labs.todomanager.R.id.statusDone));
// Click on Low
solo.clickOnView(solo.getView(course.labs.todomanager.R.id.lowPriority));
// Click on Choose Date
solo.clickOnView(solo
.getView(course.labs.todomanager.R.id.date_picker_button));
// Wait for dialog
solo.waitForDialogToOpen(10000);
// Enter the text: 'Feb'
solo.clearEditText((android.widget.EditText) solo
.getView("numberpicker_input"));
solo.enterText(
(android.widget.EditText) solo.getView("numberpicker_input"),
"Feb");
// Enter the text: '28'
solo.clearEditText((android.widget.EditText) solo.getView(
"numberpicker_input", 1));
solo.enterText(
(android.widget.EditText) solo.getView("numberpicker_input", 1),
"28");
// Enter the text: '2014'
solo.clearEditText((android.widget.EditText) solo.getView(
"numberpicker_input", 2));
solo.enterText(
(android.widget.EditText) solo.getView("numberpicker_input", 2),
"2014");
// Really set the date
solo.setDatePicker(0, 2014, 1, 28);
// Click on Done
solo.clickOnView(solo.getView(android.R.id.button1));
// Click on Choose Time
solo.clickOnView(solo
.getView(course.labs.todomanager.R.id.time_picker_button));
// Wait for dialog
solo.waitForDialogToOpen(10000);
// Enter the text: '9'
solo.clearEditText((android.widget.EditText) solo
.getView("numberpicker_input"));
solo.enterText(
(android.widget.EditText) solo.getView("numberpicker_input"),
"9");
// Enter the text: '19'
solo.clearEditText((android.widget.EditText) solo.getView(
"numberpicker_input", 1));
solo.enterText(
(android.widget.EditText) solo.getView("numberpicker_input", 1),
"19");
// Really set the time
solo.setTimePicker(0, 9, 19);
// Click on Done
solo.clickOnView(solo.getView(android.R.id.button1));
// Click on Submit
solo.clickOnView(solo
.getView(course.labs.todomanager.R.id.submitButton));
// Wait for activity: 'course.labs.todomanager.ToDoManagerActivity'
assertTrue("DateTimeTest failed:" +
"Section One:" +
"ToDoManagerActivity did not load correctly",
solo.waitForActivity(
course.labs.todomanager.ToDoManagerActivity.class, 2000));
// ============== Section Two =============
// Makes sure the title was changed correctly
assertTrue("DateTimeTest failed:" +
"Section Two:" +
"Did not modify title correctly",solo.searchText("t1"));
// Checks to see if the status was changed correctly
assertTrue("DateTimeTest failed:" +
"Section Two:" +
"Did not change status correctly",solo.isCheckBoxChecked(0));
// Checks to make sure the priority was correctly set
assertTrue("DateTimeTest failed:" +
"Section Two:" +
"Did not correctly set priority",solo.searchText("LOW"));
// Checks to make sure the Date was correctly set
assertTrue("DateTimeTest failed:" +
"Section Two:" +
"Did not correctly set the date",solo.searchText("2014-02-28"));
// Checks to make sure the Time was correctly set
assertTrue("DateTimeTest failed:" +
"Section Two:" +
"Did not correctly set the time",solo.searchText("09:19:00"));
}
}
| 4,933
|
Java
|
.java
| 127
| 34.897638
| 95
| 0.728421
|
brianwoo/Programming-Mobile-Applications-for-Android-Handheld-Systems
| 2
| 2
| 0
|
GPL-2.0
|
9/5/2024, 12:01:34 AM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 4,933
|
1,852,023
|
CppCompiler.java
|
catofmrlu_Reer/gradle/wrapper/gradle-3.3/src/platform-native/org/gradle/nativeplatform/toolchain/internal/gcc/CppCompiler.java
|
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.nativeplatform.toolchain.internal.gcc;
import org.gradle.internal.Transformers;
import org.gradle.internal.operations.BuildOperationProcessor;
import org.gradle.nativeplatform.toolchain.internal.CommandLineToolContext;
import org.gradle.nativeplatform.toolchain.internal.CommandLineToolInvocationWorker;
import org.gradle.nativeplatform.toolchain.internal.compilespec.CppCompileSpec;
class CppCompiler extends GccCompatibleNativeCompiler<CppCompileSpec> {
CppCompiler(BuildOperationProcessor buildOperationProcessor, CommandLineToolInvocationWorker commandLineToolInvocationWorker, CommandLineToolContext invocationContext, String objectFileExtension, boolean useCommandFile) {
super(buildOperationProcessor, commandLineToolInvocationWorker, invocationContext, new CppCompileArgsTransformer(), Transformers.<CppCompileSpec>noOpTransformer(), objectFileExtension, useCommandFile);
}
private static class CppCompileArgsTransformer extends GccCompilerArgsTransformer<CppCompileSpec> {
@Override
protected String getLanguage() {
return "c++";
}
}
}
| 1,746
|
Java
|
.java
| 32
| 51.09375
| 225
| 0.812756
|
catofmrlu/Reer
| 18
| 4
| 1
|
GPL-3.0
|
9/4/2024, 8:20:57 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 1,746
|
4,296,330
|
readInTest.java
|
vineet1992_tetrad-vineet/tetrad-lib/src/main/java/edu/pitt/csb/HBA/readInTest.java
|
package edu.pitt.csb.HBA;
import edu.cmu.tetrad.data.DataSet;
import edu.pitt.csb.mgm.MixedUtils;
/**
* Created by vinee_000 on 9/20/2018.
*/
public class readInTest {
public static void main(String [] args) throws Exception
{
DataSet temp = MixedUtils.loadDataSet2("DataSet_50_300_301_CGS_M.txt",5);
System.out.println(temp.isMixed());
System.out.println(temp);
}
}
| 407
|
Java
|
.java
| 14
| 25.214286
| 81
| 0.69821
|
vineet1992/tetrad-vineet
| 2
| 1
| 4
|
GPL-2.0
|
9/5/2024, 12:08:25 AM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 407
|
5,112,420
|
DoublePercentageProgressBar.java
|
jtux270_translate/ovirt/3.6_source/frontend/webadmin/modules/userportal-gwtp/src/main/java/org/ovirt/engine/ui/userportal/widget/DoublePercentageProgressBar.java
|
package org.ovirt.engine.ui.userportal.widget;
import org.ovirt.engine.ui.common.idhandler.HasElementId;
import org.ovirt.engine.ui.common.widget.tooltip.WidgetTooltip;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.IsEditor;
import com.google.gwt.editor.client.adapters.TakesValueEditor;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.TakesValue;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
public class DoublePercentageProgressBar extends Composite implements IsEditor<TakesValueEditor<Object>>, TakesValue<Object>, HasElementId {
private static final String ZERO = "0%"; //$NON-NLS-1$
private static final int FULL_WIDTH = 99;
private static final int MINIMUM_SIZE_TO_SHOW_TEXT = 10;
protected WidgetTooltip tooltip;
interface WidgetUiBinder extends UiBinder<Widget, DoublePercentageProgressBar> {
WidgetUiBinder uiBinder = GWT.create(WidgetUiBinder.class);
}
public DoublePercentageProgressBar() {
initWidget(WidgetUiBinder.uiBinder.createAndBindUi(this));
this.tooltip = new WidgetTooltip(this);
}
private Integer valueA;
private Integer valueB;
@UiField
WidgetStyle style;
@UiField
Label percentageLabelA;
@UiField
Label percentageLabelB;
@UiField
FlowPanel percentageBarA;
@UiField
FlowPanel percentageBarB;
private SafeHtml tooltipText;
@Override
public void setValue(Object value) {
assert value instanceof Integer : "Only integer values are accepted"; //$NON-NLS-1$
}
@Override
public Object getValue() {
return valueB;
}
public void setValueA(Integer value) {
this.valueA = value;
}
public void setValueB(Integer value) {
this.valueB = value;
}
public void setZeroValue() {
percentageBarB.setVisible(false);
percentageBarB.setWidth("0px"); //$NON-NLS-1$
percentageBarA.setVisible(true);
tooltip.setHtml(tooltipText);
tooltip.reconfigure();
percentageBarA.setStyleName(style.empty());
percentageBarA.setWidth(FULL_WIDTH + "%"); //$NON-NLS-1$
percentageLabelA.setText(ZERO);
percentageLabelA.setStyleName(style.percentageLabelBlack());
}
public void setBars() {
if (valueA != null && valueB != null) {
int fakeA = valueA;
int fakeB = valueB;
if (valueA + valueB >= FULL_WIDTH) {
double factor = (double) (FULL_WIDTH - 1) / (valueA + valueB);
fakeA = (int) Math.round(factor * valueA);
fakeB = (int) Math.round(factor * valueB);
fakeA = (fakeB == 0 ? FULL_WIDTH : fakeA);
fakeB = (fakeA == 0 ? FULL_WIDTH : fakeB);
}
setBar(percentageBarA, percentageLabelA, valueA, fakeA, style.percentageLabelBlack());
setBar(percentageBarB, percentageLabelB, valueB, fakeB, style.percentageLabel());
}
}
private void setBar(FlowPanel percentageBar, Label percentageLabel, Integer value, int fakeValue, String style){
if (value != null) {
String percentage = value + "%"; //$NON-NLS-1$
String fakePercentage = fakeValue + "%"; //$NON-NLS-1$
percentageLabel.setText(value < MINIMUM_SIZE_TO_SHOW_TEXT ? "" : percentage); //$NON-NLS-1$
percentageLabel.setStyleName(style);
percentageBar.setWidth(fakePercentage);
percentageBar.setVisible(value != 0);
}
}
public Object getValueA() {
return valueA;
}
public Object getValueB() {
return valueB;
}
@Override
public TakesValueEditor<Object> asEditor() {
return TakesValueEditor.of(this);
}
@Override
public void setElementId(String elementId) {
// Set percentage label element ID
percentageLabelB.getElement().setId(elementId);
}
interface WidgetStyle extends CssResource {
String percentageBarUnlimited();
String percentageBarExceeded();
String empty();
String percentageBarA();
String percentageLabelBlack();
String percentageLabel();
}
public void setTooltipText(SafeHtml tooltipText) {
this.tooltipText = tooltipText;
}
}
| 4,631
|
Java
|
.java
| 117
| 32.444444
| 140
| 0.682143
|
jtux270/translate
| 1
| 0
| 23
|
GPL-3.0
|
9/5/2024, 12:41:44 AM (Europe/Amsterdam)
| true
| true
| true
| true
| true
| true
| true
| true
| 4,631
|
1,534,587
|
CommandRespawn.java
|
VenixPLL_LightProxynetty/src/main/java/pl/venixpll/system/command/impl/CommandRespawn.java
|
/*
* LightProxy
* Copyright (C) 2021. VenixPLL
*
* 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 pl.venixpll.system.command.impl;
import pl.venixpll.mc.objects.Player;
import pl.venixpll.mc.packet.impl.client.play.ClientStatusPacket;
import pl.venixpll.system.command.Command;
public class CommandRespawn extends Command {
public CommandRespawn() {
super(",respawn","Respawning all bots!","");
}
@Override
public void onExecute(String cmd, Player sender) throws Exception {
if(!sender.getBots().isEmpty()){
sender.getBots().forEach(b -> {
if(b.getConnection().isConnected()) b.getConnection().sendPacket(new ClientStatusPacket(0));
});
sender.sendChatMessage("&aRespawned!");
}else{
sender.sendChatMessage("&cYou do not have any bots!");
}
}
}
| 1,501
|
Java
|
.java
| 37
| 35.864865
| 108
| 0.710761
|
VenixPLL/LightProxynetty
| 23
| 6
| 1
|
AGPL-3.0
|
9/4/2024, 7:57:39 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| true
| true
| 1,501
|
1,317,814
|
A_test97_out.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractTemp/canExtract/A_test97_out.java
|
package p; //10, 32, 10, 47
import java.util.Enumeration;
import java.util.Vector;
class A {
void m(Vector v) {
Enumeration e= v.elements();
while (e.hasMoreElements()) {
Object temp= e.nextElement();
System.out.println(temp);
}
}
}
| 250
|
Java
|
.java
| 12
| 18.416667
| 32
| 0.690678
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 250
|
3,601,345
|
Taxi.java
|
flashboss_wildfly-book/business-components/injection/src/main/java/it/vige/businesscomponents/injection/inject/spi/Taxi.java
|
package it.vige.businesscomponents.injection.inject.spi;
import javax.inject.Named;
@Named
public class Taxi {
}
| 116
|
Java
|
.java
| 5
| 21.6
| 56
| 0.842593
|
flashboss/wildfly-book
| 3
| 6
| 0
|
GPL-3.0
|
9/4/2024, 11:34:56 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 116
|
1,315,598
|
Outer.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/UseSupertypeWherePossible/test67/in/Outer.java
|
package p;
public class Outer{
public static class Implementor implements Inter{
public void work(A a) {}
}
Implementor implementor;
void f(){
A a= new A();
implementor.work(a);
}
}
| 195
|
Java
|
.java
| 11
| 15.545455
| 51
| 0.717391
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 195
|
3,693,158
|
BaseReceiver.java
|
ellisontan_Shopwt-Android/shopwt/src/main/java/top/yokey/shopwt/base/BaseReceiver.java
|
package top.yokey.shopwt.base;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import cn.jpush.android.api.JPushInterface;
/**
* 基础Receiver
*
* @author MapleStory
* @ qq 1002285057
* @ project https://gitee.com/MapStory/Shopwt-Android
*/
@SuppressWarnings("ALL")
public class BaseReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (BaseApplication.get().isPush()) {
String alert = intent.getStringExtra(JPushInterface.EXTRA_ALERT);
String extra = intent.getStringExtra(JPushInterface.EXTRA_EXTRA);
String message = intent.getStringExtra(JPushInterface.EXTRA_MESSAGE);
}
}
}
| 768
|
Java
|
.java
| 23
| 28.826087
| 81
| 0.74352
|
ellisontan/Shopwt-Android
| 3
| 7
| 1
|
GPL-3.0
|
9/4/2024, 11:38:49 PM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| false
| true
| true
| 764
|
1,317,022
|
A.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/PushDown/testGenerics10/out/A.java
|
package p;
class A<T>{
}
class B<T> extends A<T>{
/**
* comment
*/
public void m() {}
}
class B1 extends B<String>{
}
class C extends A<String>{
/**
* comment
*/
public void m() {}
}
| 196
|
Java
|
.java
| 17
| 9.764706
| 27
| 0.606742
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 196
|
4,381,704
|
BenchmarkTest01239.java
|
tranmyabs_OWASPBenchmark/src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01239.java
|
/**
* OWASP Benchmark Project v1.2
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The OWASP Benchmark 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, version 2.
*
* The OWASP Benchmark 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.
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(value="/pathtraver-01/BenchmarkTest01239")
public class BenchmarkTest01239 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String param = request.getParameter("BenchmarkTest01239");
if (param == null) param = "";
String bar = new Test().doSomething(request, param);
String fileName = null;
java.io.FileOutputStream fos = null;
try {
// Create the file first so the test won't throw an exception if it doesn't exist.
// Note: Don't actually do this because this method signature could cause a tool to find THIS file constructor
// as a vuln, rather than the File signature we are trying to actually test.
// If necessary, just run the benchmark twice. The 1st run should create all the necessary files.
//new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir + bar).createNewFile();
fileName = org.owasp.benchmark.helpers.Utils.testfileDir + bar;
java.io.FileInputStream fileInputStream = new java.io.FileInputStream(fileName);
java.io.FileDescriptor fd = fileInputStream.getFD();
fos = new java.io.FileOutputStream(fd);
response.getWriter().println(
"Now ready to write to file: " + org.owasp.esapi.ESAPI.encoder().encodeForHTML(fileName)
);
} catch (Exception e) {
System.out.println("Couldn't open FileOutputStream on file: '" + fileName + "'");
// System.out.println("File exception caught and swallowed: " + e.getMessage());
} finally {
if (fos != null) {
try {
fos.close();
fos = null;
} catch (Exception e) {
// we tried...
}
}
}
} // end doPost
private class Test {
public String doSomething(HttpServletRequest request, String param) throws ServletException, IOException {
String bar = "alsosafe";
if (param != null) {
java.util.List<String> valuesList = new java.util.ArrayList<String>( );
valuesList.add("safe");
valuesList.add( param );
valuesList.add( "moresafe" );
valuesList.remove(0); // remove the 1st safe value
bar = valuesList.get(1); // get the last 'safe' value
}
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| 3,654
|
Java
|
.java
| 81
| 41.17284
| 116
| 0.740164
|
tranmyabs/OWASPBenchmark
| 2
| 1
| 0
|
GPL-2.0
|
9/5/2024, 12:11:05 AM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| true
| false
| true
| 3,654
|
3,299,376
|
QWechatReplyClick.java
|
chenbo19867758_jeecmsX1_2/jeecms-component/src/main/java/com/jeecms/wechat/domain/querydsl/QWechatReplyClick.java
|
package com.jeecms.wechat.domain.querydsl;
import static com.querydsl.core.types.PathMetadataFactory.*;
import com.jeecms.wechat.domain.WechatReplyClick;
import com.querydsl.core.types.dsl.*;
import com.querydsl.core.types.PathMetadata;
import javax.annotation.Generated;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.dsl.PathInits;
/**
* QWechatReplyClick is a Querydsl query type for WechatReplyClick
*/
@Generated("com.querydsl.codegen.EntitySerializer")
public class QWechatReplyClick extends EntityPathBase<WechatReplyClick> {
private static final long serialVersionUID = -1353296792L;
private static final PathInits INITS = PathInits.DIRECT2;
public static final QWechatReplyClick wechatReplyClick = new QWechatReplyClick("wechatReplyClick");
public final com.jeecms.common.base.domain.querydsl.QAbstractDomain _super = new com.jeecms.common.base.domain.querydsl.QAbstractDomain(this);
public final StringPath appId = createString("appId");
//inherited
public final DateTimePath<java.util.Date> createTime = _super.createTime;
//inherited
public final StringPath createUser = _super.createUser;
//inherited
public final BooleanPath hasDeleted = _super.hasDeleted;
public final NumberPath<Integer> id = createNumber("id", Integer.class);
public final NumberPath<Integer> replyContentId = createNumber("replyContentId", Integer.class);
public final NumberPath<Integer> replyType = createNumber("replyType", Integer.class);
//inherited
public final DateTimePath<java.util.Date> updateTime = _super.updateTime;
//inherited
public final StringPath updateUser = _super.updateUser;
public final QWechatReplyContent wechatReplyContent;
public QWechatReplyClick(String variable) {
this(WechatReplyClick.class, forVariable(variable), INITS);
}
public QWechatReplyClick(Path<? extends WechatReplyClick> path) {
this(path.getType(), path.getMetadata(), PathInits.getFor(path.getMetadata(), INITS));
}
public QWechatReplyClick(PathMetadata metadata) {
this(metadata, PathInits.getFor(metadata, INITS));
}
public QWechatReplyClick(PathMetadata metadata, PathInits inits) {
this(WechatReplyClick.class, metadata, inits);
}
public QWechatReplyClick(Class<? extends WechatReplyClick> type, PathMetadata metadata, PathInits inits) {
super(type, metadata, inits);
this.wechatReplyContent = inits.isInitialized("wechatReplyContent") ? new QWechatReplyContent(forProperty("wechatReplyContent"), inits.get("wechatReplyContent")) : null;
}
}
| 2,640
|
Java
|
.java
| 49
| 48.938776
| 177
| 0.778081
|
chenbo19867758/jeecmsX1.2
| 4
| 7
| 11
|
GPL-3.0
|
9/4/2024, 11:11:18 PM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| true
| true
| true
| 2,640
|
4,948,744
|
TaxNumberService.java
|
ua-eas_ua-kfs-5_3/work/src/org/kuali/kfs/vnd/service/TaxNumberService.java
|
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2014 The Kuali Foundation
*
* 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 <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.vnd.service;
import org.kuali.rice.core.web.format.FormatException;
public interface TaxNumberService {
public String formatToDefaultFormat(String taxNbr) throws FormatException;
public boolean isStringAllNumbers(String field);
public boolean isStringEmpty(String field);
public boolean isValidTaxNumber(String taxNbr, String taxType);
public boolean isAllowedTaxNumber(String taxNbr);
public String[] parseSSNFormats();
public String[] parseFEINFormats();
public String[] parseNotAllowedTaxNumbers();
}
| 1,435
|
Java
|
.java
| 30
| 43.333333
| 97
| 0.765004
|
ua-eas/ua-kfs-5.3
| 1
| 0
| 0
|
AGPL-3.0
|
9/5/2024, 12:36:54 AM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| true
| true
| 1,435
|
1,317,094
|
AA.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/RenameType/test31/in/AA.java
|
package p;
class AA{
Object a = new A(){
};
}
| 63
|
Java
|
.java
| 5
| 8.2
| 22
| 0.448276
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 63
|
1,317,801
|
A_test54_out.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractTemp/canExtract/A_test54_out.java
|
// 6, 37 -> 6, 43
package p;
class A {
void foob() {
int temp= 2+2* 4;
int e= (2 + 2) * (27 + 2 * (temp+1*2));
int c= 3 * (2 + 1) + temp + 28;
}
}
| 158
|
Java
|
.java
| 9
| 15.333333
| 41
| 0.452055
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 158
|
1,316,603
|
A_testAll38_in.java
|
eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testAll38_in.java
|
package p;
//to protected
class A{
int m(int iii, boolean j){
return m(m(iii, j), false);
}
}
class B extends A{
public int m(int iii, boolean j){
return m(m(iii, j), false);
}
}
| 186
|
Java
|
.java
| 12
| 13.916667
| 34
| 0.657143
|
eclipse-jdt/eclipse.jdt.ui
| 35
| 86
| 242
|
EPL-2.0
|
9/4/2024, 7:34:16 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 186
|
4,280,563
|
SetImageByFileChooserAction.java
|
snapcraft-docs_freeplane/freeplane/src/main/java/org/freeplane/features/text/mindmapmode/SetImageByFileChooserAction.java
|
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev
*
* This file is modified by Dimitry Polivaev in 2008.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.features.text.mindmapmode;
import java.awt.event.ActionEvent;
import org.freeplane.core.ui.AFreeplaneAction;
import org.freeplane.features.mode.Controller;
import org.freeplane.features.text.TextController;
class SetImageByFileChooserAction extends AFreeplaneAction {
/**
*
*/
private static final long serialVersionUID = 1L;
public SetImageByFileChooserAction() {
super("SetImageByFileChooserAction");
}
public void actionPerformed(final ActionEvent e) {
((MTextController) TextController.getController()).setImageByFileChooser();
Controller.getCurrentController().getMapViewManager().obtainFocusForSelected();
}
}
| 1,506
|
Java
|
.java
| 37
| 38.621622
| 89
| 0.784153
|
snapcraft-docs/freeplane
| 2
| 4
| 0
|
GPL-2.0
|
9/5/2024, 12:07:57 AM (Europe/Amsterdam)
| false
| false
| true
| true
| false
| true
| false
| true
| 1,506
|
4,256,060
|
ReactorClientHttpRequest.java
|
rockleeprc_sourcecode/spring-framework/spring-web/src/main/java/org/springframework/http/client/reactive/ReactorClientHttpRequest.java
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.client.reactive;
import java.net.URI;
import java.nio.file.Path;
import java.util.Collection;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.cookie.DefaultCookie;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.NettyOutbound;
import reactor.netty.http.client.HttpClientRequest;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.ZeroCopyHttpOutputMessage;
/**
* {@link ClientHttpRequest} implementation for the Reactor-Netty HTTP client.
*
* @author Brian Clozel
* @since 5.0
* @see reactor.netty.http.client.HttpClient
*/
class ReactorClientHttpRequest extends AbstractClientHttpRequest implements ZeroCopyHttpOutputMessage {
private final HttpMethod httpMethod;
private final URI uri;
private final HttpClientRequest request;
private final NettyOutbound outbound;
private final NettyDataBufferFactory bufferFactory;
public ReactorClientHttpRequest(HttpMethod method, URI uri, HttpClientRequest request, NettyOutbound outbound) {
this.httpMethod = method;
this.uri = uri;
this.request = request;
this.outbound = outbound;
this.bufferFactory = new NettyDataBufferFactory(outbound.alloc());
}
@Override
public DataBufferFactory bufferFactory() {
return this.bufferFactory;
}
@Override
public HttpMethod getMethod() {
return this.httpMethod;
}
@Override
public URI getURI() {
return this.uri;
}
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
return doCommit(() -> {
Flux<ByteBuf> byteBufFlux = Flux.from(body).map(NettyDataBufferFactory::toByteBuf);
return this.outbound.send(byteBufFlux).then();
});
}
@Override
public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) {
Publisher<Publisher<ByteBuf>> byteBufs = Flux.from(body).map(ReactorClientHttpRequest::toByteBufs);
return doCommit(() -> this.outbound.sendGroups(byteBufs).then());
}
private static Publisher<ByteBuf> toByteBufs(Publisher<? extends DataBuffer> dataBuffers) {
return Flux.from(dataBuffers).map(NettyDataBufferFactory::toByteBuf);
}
@Override
public Mono<Void> writeWith(Path file, long position, long count) {
return doCommit(() -> this.outbound.sendFile(file, position, count).then());
}
@Override
public Mono<Void> setComplete() {
return doCommit(this.outbound::then);
}
@Override
protected void applyHeaders() {
getHeaders().forEach((key, value) -> this.request.requestHeaders().set(key, value));
}
@Override
protected void applyCookies() {
getCookies().values().stream().flatMap(Collection::stream)
.map(cookie -> new DefaultCookie(cookie.getName(), cookie.getValue()))
.forEach(this.request::addCookie);
}
}
| 3,629
|
Java
|
.java
| 97
| 35.092784
| 113
| 0.790479
|
rockleeprc/sourcecode
| 2
| 2
| 0
|
GPL-3.0
|
9/5/2024, 12:07:03 AM (Europe/Amsterdam)
| false
| false
| false
| true
| true
| true
| true
| true
| 3,629
|
2,188,492
|
EcoreBuilder.java
|
eclipse-emf_org_eclipse_emf/plugins/org.eclipse.emf.ecore.xmi/src/org/eclipse/emf/ecore/xmi/EcoreBuilder.java
|
/**
* Copyright (c) 2005-2006 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v20.html
*
* Contributors:
* IBM - Initial API and implementation
*/
package org.eclipse.emf.ecore.xmi;
import java.util.Collection;
import java.util.Map;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.ExtendedMetaData;
/**
* The interface describes an XML Schema to Ecore builder.
*/
public interface EcoreBuilder
{
/**
* Given an XML schema location URI this method creates corresponding Ecore model(s)
* @param uri - location of the XML Schema files.
* @return Collection of resources containing the generated models.
* @see org.eclipse.emf.common.util.URI
*/
public Collection<? extends Resource> generate(URI uri) throws Exception;
/**
* Given XML Schema location URIs this method creates corresponding Ecore model(s)
* @param uris - locations of the XML Schema files.
* @return Collection of resources containing the generated models.
* @see org.eclipse.emf.common.util.URI
*/
public Collection<? extends Resource> generate(Collection<URI> uris) throws Exception;
/**
* Given a map of XML Schema targetNamespaces (String) to XML Schema location URIs, this method
* generates corresponding Ecore model(s).
* @param targetNamespaceToURI - a map of XML Schema targetNamespaces to XML Schema location URIs
* @return Collection of resources containing the generated models.
* @see org.eclipse.emf.common.util.URI
*/
public Collection<? extends Resource> generate(Map<String, URI> targetNamespaceToURI) throws Exception;
/**
* Sets extended meta data to register generated Ecore models.
* Note the same extended meta data should be used for loading/saving an instance document.
*/
public void setExtendedMetaData(ExtendedMetaData extendedMetaData);
}
| 2,117
|
Java
|
.java
| 49
| 40.244898
| 105
| 0.768109
|
eclipse-emf/org.eclipse.emf
| 10
| 13
| 1
|
EPL-2.0
|
9/4/2024, 8:31:57 PM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 2,117
|
659,400
|
TiffDirectoryType.java
|
KnIfER_PlainDictionaryAPP/PLOD/src/main/java/org/apache/commons/imaging/formats/tiff/constants/TiffDirectoryType.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.commons.imaging.formats.tiff.constants;
public enum TiffDirectoryType {
TIFF_DIRECTORY_IFD0(
true, TiffDirectoryConstants.DIRECTORY_TYPE_DIR_0, "IFD0"),
TIFF_DIRECTORY_IFD1(
true, TiffDirectoryConstants.DIRECTORY_TYPE_DIR_1, "IFD1"),
TIFF_DIRECTORY_IFD2(
true, TiffDirectoryConstants.DIRECTORY_TYPE_DIR_2, "IFD2"),
TIFF_DIRECTORY_IFD3(
true, TiffDirectoryConstants.DIRECTORY_TYPE_DIR_3, "IFD3"),
EXIF_DIRECTORY_INTEROP_IFD(
false, TiffDirectoryConstants.DIRECTORY_TYPE_INTEROPERABILITY, "Interop IFD"),
EXIF_DIRECTORY_MAKER_NOTES(
false, TiffDirectoryConstants.DIRECTORY_TYPE_MAKER_NOTES, "Maker Notes"),
EXIF_DIRECTORY_EXIF_IFD(
false, TiffDirectoryConstants.DIRECTORY_TYPE_EXIF, "Exif IFD"),
EXIF_DIRECTORY_GPS(
false, TiffDirectoryConstants.DIRECTORY_TYPE_GPS, "GPS IFD");
private final boolean isImageDirectory;
public final int directoryType;
public final String name;
TiffDirectoryType(final boolean isImageDirectory, final int directoryType, final String name) {
this.isImageDirectory = isImageDirectory;
this.directoryType = directoryType;
this.name = name;
}
public boolean isImageDirectory() {
return isImageDirectory;
}
public static TiffDirectoryType getExifDirectoryType(final int type) {
for (final TiffDirectoryType tiffDirectoryType : values()) {
if (tiffDirectoryType.directoryType == type) {
return tiffDirectoryType;
}
}
return TiffDirectoryType.EXIF_DIRECTORY_UNKNOWN;
}
public static final TiffDirectoryType EXIF_DIRECTORY_IFD0 = TIFF_DIRECTORY_IFD0;
public static final TiffDirectoryType TIFF_DIRECTORY_ROOT = TIFF_DIRECTORY_IFD0;
public static final TiffDirectoryType EXIF_DIRECTORY_IFD1 = TIFF_DIRECTORY_IFD1;
public static final TiffDirectoryType EXIF_DIRECTORY_IFD2 = TIFF_DIRECTORY_IFD2;
public static final TiffDirectoryType EXIF_DIRECTORY_IFD3 = TIFF_DIRECTORY_IFD3;
public static final TiffDirectoryType EXIF_DIRECTORY_SUB_IFD = TIFF_DIRECTORY_IFD1;
public static final TiffDirectoryType EXIF_DIRECTORY_SUB_IFD1 = TIFF_DIRECTORY_IFD2;
public static final TiffDirectoryType EXIF_DIRECTORY_SUB_IFD2 = TIFF_DIRECTORY_IFD3;
public static final TiffDirectoryType EXIF_DIRECTORY_UNKNOWN = null;
}
| 3,250
|
Java
|
.java
| 63
| 45.47619
| 99
| 0.743703
|
KnIfER/PlainDictionaryAPP
| 114
| 18
| 4
|
GPL-3.0
|
9/4/2024, 7:08:18 PM (Europe/Amsterdam)
| false
| true
| true
| true
| true
| true
| true
| true
| 3,250
|
4,571,688
|
Item.java
|
NikolayKostadinov_Java-OOP/ExamPreparation/06 Java OOP Exam - 12 Dec 2020/P03UnitTesting/BankSafe/src/bankSafe/Item.java
|
package bankSafe;
public class Item {
private String owner;
private String itemId;
public Item(String owner, String itemId)
{
this.setOwner(owner);
this.setItemId(itemId);
}
public String getOwner() {
return owner;
}
private void setOwner(String owner) {
this.owner = owner;
}
public String getItemId() {
return itemId;
}
private void setItemId(String itemId) {
this.itemId = itemId;
}
}
| 494
|
Java
|
.java
| 22
| 16.636364
| 44
| 0.626609
|
NikolayKostadinov/Java-OOP
| 2
| 0
| 0
|
GPL-3.0
|
9/5/2024, 12:17:49 AM (Europe/Amsterdam)
| false
| false
| true
| true
| true
| true
| true
| true
| 494
|
4,400,781
|
V_Code.java
|
Sensrdt_Vote-Now/Frontend/app/src/main/java/com/example/votenow/V_Code.java
|
package com.example.votenow;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.method.HideReturnsTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class V_Code extends AppCompatActivity {
EditText input;
ImageButton next;
ImageView imageView;
String phnNo;
private String phoneVerificationId;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks verificationCallbacks;
private PhoneAuthProvider.ForceResendingToken resendingToken;
private FirebaseAuth mAuth;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name);
input = findViewById(R.id.inputText);
next = findViewById(R.id.next);
imageView = findViewById(R.id.imageView);
input.setHint("Verification Code");
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
imageView.setImageResource(R.drawable.codes);
phnNo=getIntent().getStringExtra("phnNo");
Toast.makeText(this,phnNo,Toast.LENGTH_SHORT).show();
progressDialog=new ProgressDialog(this);
progressDialog.setTitle("Sending OTP");
progressDialog.setMessage("Please Wait While We Send The OTP");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
sendCode("+91"+phnNo);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
verifyCode();
}
});
}
private void verifyCode() {
String code = input.getText().toString();
if (code.isEmpty()) {
Toast.makeText(this, "Code Is Empty", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this,"k"+code,Toast.LENGTH_LONG).show();
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(phoneVerificationId, code);
signWithPhoneAuthCredential(phoneAuthCredential);
}
}
private void sendCode(String phnNo) {
setUpVerificationCallback();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phnNo,
60,
TimeUnit.SECONDS,
this,
verificationCallbacks
);
}
private void setUpVerificationCallback() {
verificationCallbacks=
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
signWithPhoneAuthCredential(phoneAuthCredential);
}
@Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(getApplicationContext(),e.getMessage().toString(),Toast.LENGTH_LONG).show();
}
@Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
phoneVerificationId=s;
resendingToken=forceResendingToken;
progressDialog.dismiss();
}
};
}
private void signWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
mAuth=FirebaseAuth.getInstance();
mAuth.signInWithCredential(phoneAuthCredential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"Verification Done",Toast.LENGTH_LONG).show();
FirebaseUser user = task.getResult().getUser();
Intent intent = new Intent(V_Code.this,Password.class);
intent.putExtra("phnNo",phnNo);
startActivity(intent);
}else {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"Wrong Code",Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public void onBackPressed() {
Intent intent = new Intent(V_Code.this,Phone.class);
startActivity(intent);
finish();
}
}
| 5,622
|
Java
|
.java
| 127
| 33.055118
| 115
| 0.651188
|
Sensrdt/Vote-Now
| 2
| 1
| 12
|
GPL-3.0
|
9/5/2024, 12:11:47 AM (Europe/Amsterdam)
| false
| false
| false
| true
| false
| false
| false
| true
| 5,622
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.