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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
258,475 | TestChar.java | openjdk-mirror_jdk7u-jdk/test/java/beans/XMLDecoder/spec/TestChar.java | /*
* Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @summary Tests <char> element
* @author Sergey Malenkov
*/
import java.beans.XMLDecoder;
public final class TestChar extends AbstractTest {
public static final String XML
= "<java>\n"
+ " <char>X</char>\n"
+ " <char code=\"#20\"/>\n"
+ "</java>";
public static void main(String[] args) {
new TestChar().test(true);
}
@Override
protected void validate(XMLDecoder decoder) {
if (!decoder.readObject().equals(Character.valueOf('X'))) {
throw new Error("unexpected character");
}
if (!decoder.readObject().equals(Character.valueOf((char) 0x20))) {
throw new Error("unexpected character code");
}
}
}
| 1,805 | Java | .java | 47 | 33.87234 | 76 | 0.691386 | openjdk-mirror/jdk7u-jdk | 525 | 429 | 6 | GPL-2.0 | 9/4/2024, 7:05:59 PM (Europe/Amsterdam) | true | true | true | false | true | true | true | true | 1,805 |
4,133,266 | ParticleMaster.java | MrManiacc_3d-Engine/src/main/java/engine/particles/ParticleMaster.java | package engine.particles;
import engine.entities.Camera;
import org.lwjgl.util.vector.Matrix4f;
import engine.renderEngine.Loader;
import java.util.*;
/**
* Created by Vtboy on 1/9/2016.
*/
public class ParticleMaster {
private static Map<ParticleTexture, List<Particle>> particles = new HashMap<ParticleTexture, List<Particle>>();
private static ParticleRenderer renderer;
public static void init(Loader loader, Matrix4f projectionMatrix) {
renderer = new ParticleRenderer(loader, projectionMatrix);
}
public static void update(Camera camera) {
Iterator<Map.Entry<ParticleTexture, List<Particle>>> mapIterator = particles.entrySet().iterator();
while (mapIterator.hasNext()) {
Map.Entry<ParticleTexture, List<Particle>> entry = mapIterator.next();
List<Particle> list = entry.getValue();
Iterator<Particle> iterator = list.iterator();
while (iterator.hasNext()) {
Particle p = iterator.next();
boolean stillAlive = p.update(camera);
if (!stillAlive) {
iterator.remove();
if (list.isEmpty()) mapIterator.remove();
}
}
if (!entry.getKey().isAdditive())
InsertionSort.sortHighToLow(list);
}
}
public static void render(Camera camera) {
renderer.render(particles, camera);
}
public static void cleanUp() {
renderer.cleanUp();
}
public static void addParticle(Particle particle) {
List<Particle> list = particles.get(particle.getTexture());
if (list == null) {
list = new ArrayList<Particle>();
particles.put(particle.getTexture(), list);
}
list.add(particle);
}
public static int getAliveParticles() {
int total = 0;
for (ParticleTexture texture : particles.keySet()) {
total += particles.get(texture).size();
}
return total;
}
}
| 2,037 | Java | .java | 54 | 29.12963 | 115 | 0.624556 | MrManiacc/3d-Engine | 2 | 1 | 0 | GPL-2.0 | 9/5/2024, 12:04:01 AM (Europe/Amsterdam) | false | false | true | false | false | true | false | true | 2,037 |
1,314,633 | WorkspaceScopeTest.java | eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/search/WorkspaceScopeTest.java | /*******************************************************************************
* Copyright (c) 2000, 2020 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.ui.tests.search;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.internal.ui.search.JavaSearchScopeFactory;
public class WorkspaceScopeTest {
private IJavaProject fProject1;
private IJavaProject fProject2;
private IJavaProject fProject3;
private IJavaProject fProject4;
private ICompilationUnit fCompilationUnit;
@Before
public void setUp() throws Exception {
fProject1= createStandardProject("Test", "test"); //$NON-NLS-1$ //$NON-NLS-2$
IPackageFragment pkg= fProject1.findPackageFragment(new Path("/Test/src/test")); //$NON-NLS-1$
fCompilationUnit= pkg.createCompilationUnit("Test.java", getSource(), true, null); //$NON-NLS-1$
fProject2= createStandardProject("Test2", "test2"); //$NON-NLS-1$//$NON-NLS-2$
JavaProjectHelper.addRequiredProject(fProject2, fProject1);
fProject3= createStandardProject("Test3", "test3"); //$NON-NLS-1$ //$NON-NLS-2$
fProject4= createStandardProject("Test4", "test4", false); //$NON-NLS-1$//$NON-NLS-2$
}
private IJavaProject createStandardProject(String name, String pkgName) throws CoreException, JavaModelException {
return createStandardProject(name, pkgName, true);
}
private IJavaProject createStandardProject(String name, String pkgName, boolean includeJRE) throws CoreException, JavaModelException {
IJavaProject project= JavaProjectHelper.createJavaProject(name, "bin"); //$NON-NLS-1$
IPackageFragmentRoot root= JavaProjectHelper.addSourceContainer(project, "src"); //$NON-NLS-1$
root.createPackageFragment(pkgName, true, null);
if (includeJRE) {
IClasspathEntry jreLib= JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")); //$NON-NLS-1$
JavaProjectHelper.addToClasspath(project, jreLib);
}
return project;
}
private String getSource() {
return """
package test;
public class Test {
public void publicMethod() {
}
\t
private void privateMethod() {
}
\t
protected void protectedMethod() {
}
\t
void defaultMethod() {
}
}
""";
}
@Test
public void testPrivateScope() throws JavaModelException {
IType type= fCompilationUnit.findPrimaryType();
type.getMethod("privateMethod", new String[0]); //$NON-NLS-1$
IJavaSearchScope scope= createWorkspaceScope(true);
assertTrue(scope.encloses(fCompilationUnit));
for (IPackageFragmentRoot root : fProject1.getAllPackageFragmentRoots()) {
for (IJavaElement fragment : root.getChildren()) {
assertFalse(scope.encloses(fragment));
}
}
checkNoRoots(scope, fProject2);
checkNoRoots(scope, fProject3);
}
private IJavaSearchScope createWorkspaceScope(boolean includeJRE) {
return JavaSearchScopeFactory.getInstance().createWorkspaceScope(includeJRE);
}
@Test
public void testDefaultScope() throws JavaModelException {
IType type= fCompilationUnit.findPrimaryType();
type.getMethod("defaultMethod", new String[0]); //$NON-NLS-1$
IJavaSearchScope scope= createWorkspaceScope(true);
assertTrue(scope.encloses(fCompilationUnit.getParent()));
for (IPackageFragmentRoot root : fProject1.getAllPackageFragmentRoots()) {
for (IJavaElement fragment : root.getChildren()) {
if (!fragment.equals(fCompilationUnit.getParent())) {
assertFalse(scope.encloses(fragment));
}
}
}
checkNoRoots(scope, fProject2);
checkNoRoots(scope, fProject3);
}
@Test
public void testPublicMethod() throws JavaModelException {
IType type= fCompilationUnit.findPrimaryType();
type.getMethod("publicMethod", new String[0]); //$NON-NLS-1$
IJavaSearchScope scope= createWorkspaceScope(true);
checkNoJreRoots(scope, fProject1);
checkNoJreRoots(scope, fProject2);
checkNoRoots(scope, fProject3);
}
@Test
public void testProtectedMethod() throws JavaModelException {
IType type= fCompilationUnit.findPrimaryType();
type.getMethod("protectedMethod", new String[0]); //$NON-NLS-1$
IJavaSearchScope scope= createWorkspaceScope(true);
checkNoJreRoots(scope, fProject1);
checkNoJreRoots(scope, fProject2);
checkNoRoots(scope, fProject3);
}
private void checkNoJreRoots(IJavaSearchScope scope, IJavaProject project) throws JavaModelException {
for (IPackageFragmentRoot root : project.getAllPackageFragmentRoots()) {
if (scope.encloses(root)) {
assertFalse(root.isExternal());
} else {
assertTrue(root.isExternal());
}
}
}
private void checkJreRoots(IJavaSearchScope scope, IJavaProject project) throws JavaModelException {
for (IPackageFragmentRoot root : project.getAllPackageFragmentRoots()) {
if (scope.encloses(root)) {
assertTrue(root.isExternal());
} else {
assertFalse(root.isExternal());
}
}
}
private void checkNoRoots(IJavaSearchScope scope, IJavaProject project) throws JavaModelException {
for (IPackageFragmentRoot root : project.getAllPackageFragmentRoots()) {
assertFalse(scope.encloses(root));
}
}
private void checkAllRoots(IJavaSearchScope scope, IJavaProject project) throws JavaModelException {
for (IPackageFragmentRoot root : project.getAllPackageFragmentRoots()) {
assertTrue(scope.encloses(root));
}
}
@Test
public void testJREProtected() throws JavaModelException {
IType object= fProject1.findType("java.lang.Object"); //$NON-NLS-1$
object.getMethod("clone", new String [0]); //$NON-NLS-1$
IJavaSearchScope scope= createWorkspaceScope(true);
checkAllRoots(scope, fProject1);
checkAllRoots(scope, fProject2);
checkJreRoots(scope, fProject3);
checkNoRoots(scope, fProject4);
}
}
| 6,755 | Java | .java | 169 | 37.005917 | 135 | 0.759579 | eclipse-jdt/eclipse.jdt.ui | 35 | 86 | 242 | EPL-2.0 | 9/4/2024, 7:34:16 PM (Europe/Amsterdam) | false | false | false | false | false | true | true | true | 6,755 |
1,313,172 | JavaHoverMessages.java | eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavaHoverMessages.java | /*******************************************************************************
* Copyright (c) 2000, 2019 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.internal.ui.text.java.hover;
import org.eclipse.osgi.util.NLS;
/**
* Helper class to get NLSed messages.
*/
public final class JavaHoverMessages extends NLS {
private static final String BUNDLE_NAME= JavaHoverMessages.class.getName();
private JavaHoverMessages() {
// Do not instantiate
}
public static String AbstractAnnotationHover_action_configureAnnotationPreferences;
public static String AbstractAnnotationHover_message_singleQuickFix;
public static String AbstractAnnotationHover_message_multipleQuickFix;
public static String AbstractAnnotationHover_multifix_variable_description;
public static String JavadocHover_back;
public static String JavadocHover_back_toElement_toolTip;
public static String JavadocHover_constantValue_hexValue;
public static String JavadocHover_fallback_warning;
public static String JavadocHover_forward;
public static String JavadocHover_forward_toElement_toolTip;
public static String JavadocHover_forward_toolTip;
public static String JavadocHover_openDeclaration;
public static String JavadocHover_showInJavadoc;
public static String JavaSourceHover_skippedLines;
public static String JavaSourceHover_skippedLinesSymbol;
public static String JavaTextHover_createTextHover;
public static String NoBreakpointAnnotation_addBreakpoint;
public static String NLSStringHover_NLSStringHover_missingKeyWarning;
public static String NLSStringHover_NLSStringHover_PropertiesFileCouldNotBeReadWarning;
public static String NLSStringHover_NLSStringHover_PropertiesFileNotDetectedWarning;
public static String NLSStringHover_open_in_properties_file;
public static String ProblemHover_action_configureProblemSeverity;
public static String ProblemHover_chooseSettingsTypeDialog_button_project;
public static String ProblemHover_chooseSettingsTypeDialog_button_workspace;
public static String ProblemHover_chooseSettingsTypeDialog_checkBox_dontShowAgain;
public static String ProblemHover_chooseSettingsTypeDialog_message;
public static String ProblemHover_chooseSettingsTypeDialog_title;
public static String ProblemHover_chooseCompilerSettingsTypeDialog_message;
public static String ProblemHover_chooseCompilerSettingsTypeDialog_title;
static {
NLS.initializeMessages(BUNDLE_NAME, JavaHoverMessages.class);
}
}
| 2,870 | Java | .java | 56 | 49.107143 | 88 | 0.807637 | eclipse-jdt/eclipse.jdt.ui | 35 | 86 | 242 | EPL-2.0 | 9/4/2024, 7:34:16 PM (Europe/Amsterdam) | false | true | false | false | false | true | true | true | 2,870 |
5,014,551 | ApplicationTest.java | flooose_gpxkept/app/src/androidTest/java/com/flooose/gpxkeeper/ApplicationTest.java | package com.flooose.gpxkeeper;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | 352 | Java | .java | 11 | 29.272727 | 93 | 0.776471 | flooose/gpxkept | 1 | 0 | 0 | GPL-3.0 | 9/5/2024, 12:39:03 AM (Europe/Amsterdam) | false | true | true | false | false | true | true | true | 352 |
47,793 | GameModeTest.java | Bukkit_Bukkit/src/test/java/org/bukkit/GameModeTest.java | package org.bukkit;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
public class GameModeTest {
@Test
public void getByValue() {
for (GameMode gameMode : GameMode.values()) {
assertThat(GameMode.getByValue(gameMode.getValue()), is(gameMode));
}
}
}
| 354 | Java | .java | 12 | 24.916667 | 79 | 0.710914 | 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 | 354 |
1,405,875 | ExOlympiadMode.java | oonym_l2InterludeServer/L2J_Server/java/net/sf/l2j/gameserver/serverpackets/ExOlympiadMode.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;
/**
* This class ...
* @version $Revision: 1.4.2.1.2.3 $ $Date: 2005/03/27 15:29:57 $
* @author godson
*/
public class ExOlympiadMode extends L2GameServerPacket
{
// chc
private static final String _S__FE_2B_OLYMPIADMODE = "[S] FE:2B ExOlympiadMode";
private static int _mode;
/**
* @param mode (0 = return, 3 = spectate)
*/
public ExOlympiadMode(int mode)
{
_mode = mode;
}
@Override
protected final void writeImpl()
{
writeC(0xfe);
writeH(0x2b);
writeC(_mode);
}
@Override
public String getType()
{
return _S__FE_2B_OLYMPIADMODE;
}
}
| 1,426 | Java | .java | 49 | 25.857143 | 82 | 0.702782 | 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 | 1,426 |
3,151,304 | MainActivity.java | r4jiv007_GetLocation/src/my/app/location/MainActivity.java | package my.app.location;
import my.app.location.utils.Location;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText etInput;
private TextView tvOutput;
private Button bSearch;
private final int REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
initView();
}
private void initView() {
etInput = (EditText) findViewById(R.id.etInput);
tvOutput = (TextView) findViewById(R.id.tvOutput);
bSearch = (Button) findViewById(R.id.bSearch);
setListener();
}
private void setListener() {
bSearch.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String input = etInput.getText().toString();
Intent intent = new Intent(MainActivity.this, MapActivity.class);
intent.putExtra("input", input);
startActivityForResult(intent, REQUEST_CODE);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (REQUEST_CODE): {
if (resultCode == Activity.RESULT_OK) {
String result = data.getStringExtra(MapActivity.RESULT);
tvOutput.setText(result);
}
break;
}
}
}
}
| 1,553 | Java | .java | 52 | 27.057692 | 77 | 0.770624 | r4jiv007/GetLocation | 4 | 3 | 0 | GPL-2.0 | 9/4/2024, 11:01:18 PM (Europe/Amsterdam) | false | false | true | false | false | true | false | true | 1,553 |
3,387,532 | zaat.java | FzArnob_Covidease/sources/com/google/android/gms/common/api/internal/zaat.java | package com.google.android.gms.common.api.internal;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.signin.internal.zad;
final class zaat implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private final /* synthetic */ zaak zagj;
private zaat(zaak zaak) {
this.zagj = zaak;
}
public final void onConnected(Bundle bundle) {
zad zad;
zad zad2;
Bundle bundle2 = bundle;
if (this.zagj.zaet.isSignInClientDisconnectFixEnabled()) {
this.zagj.zaeo.lock();
try {
if (this.zagj.zagb == null) {
this.zagj.zaeo.unlock();
return;
}
new zaar(this.zagj);
this.zagj.zagb.zaa(zad2);
this.zagj.zaeo.unlock();
} catch (Throwable th) {
Throwable th2 = th;
this.zagj.zaeo.unlock();
throw th2;
}
} else {
new zaar(this.zagj);
this.zagj.zagb.zaa(zad);
}
}
public final void onConnectionSuspended(int i) {
}
public final void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
ConnectionResult connectionResult2 = connectionResult;
this.zagj.zaeo.lock();
try {
if (this.zagj.zad(connectionResult2)) {
this.zagj.zaar();
this.zagj.zaap();
} else {
this.zagj.zae(connectionResult2);
}
this.zagj.zaeo.unlock();
} catch (Throwable th) {
Throwable th2 = th;
this.zagj.zaeo.unlock();
throw th2;
}
}
/* JADX INFO: this call moved to the top of the method (can break code semantics) */
/* synthetic */ zaat(zaak zaak, zaal zaal) {
this(zaak);
zaal zaal2 = zaal;
}
}
| 2,093 | Java | .java | 60 | 24.9 | 109 | 0.578973 | FzArnob/Covidease | 4 | 0 | 0 | GPL-3.0 | 9/4/2024, 11:17:41 PM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 2,093 |
706,568 | InventoryAccessory.java | Arakne_Araknemu/src/main/java/fr/quatrevieux/araknemu/game/player/inventory/accessory/InventoryAccessory.java | /*
* This file is part of Araknemu.
*
* Araknemu 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.
*
* Araknemu 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 Araknemu. If not, see <https://www.gnu.org/licenses/>.
*
* Copyright (c) 2017-2019 Vincent Quatrevieux
*/
package fr.quatrevieux.araknemu.game.player.inventory.accessory;
import fr.quatrevieux.araknemu.game.item.inventory.ItemEntry;
import fr.quatrevieux.araknemu.game.world.creature.accessory.Accessory;
import fr.quatrevieux.araknemu.game.world.creature.accessory.AccessoryType;
/**
* Adapt inventory entry to accessory
*/
public final class InventoryAccessory implements Accessory {
private final ItemEntry entry;
public InventoryAccessory(ItemEntry entry) {
this.entry = entry;
}
@Override
public AccessoryType type() {
return AccessoryType.bySlot(entry.position());
}
@Override
public int appearance() {
return entry.templateId();
}
@Override
public String toString() {
return Integer.toHexString(appearance());
}
}
| 1,554 | Java | .java | 43 | 32.674419 | 78 | 0.753324 | Arakne/Araknemu | 105 | 28 | 24 | LGPL-3.0 | 9/4/2024, 7:08:19 PM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 1,554 |
3,206,206 | CommandInvoke.java | FlameBoss20_DungeonRealms-1/game/src/main/java/net/dungeonrealms/game/commands/CommandInvoke.java | package net.dungeonrealms.game.commands;
import net.dungeonrealms.common.game.commands.BasicCommand;
import net.dungeonrealms.common.game.database.player.rank.Rank;
import net.dungeonrealms.game.affair.Affair;
import net.dungeonrealms.game.mechanic.DungeonManager;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Nick on 10/20/2015.
*/
public class CommandInvoke extends BasicCommand {
public CommandInvoke(String command, String usage, String description) {
super(command, usage, description);
}
@Override
public boolean onCommand(CommandSender s, Command cmd, String string, String[] args) {
if (s instanceof ConsoleCommandSender) return false;
Player player = (Player) s;
if (!Rank.isGM(player)) {
return false;
}
if (args.length > 0) {
if (DungeonManager.getInstance().canCreateInstance()) {
switch (args[0].toLowerCase()) {
case "bandittrove":
case "t1dungeon":
if (Affair.getInstance().isInParty(player)) {
Map<Player, Boolean> partyList = new HashMap<>();
for (Player player1 : Affair.getInstance().getParty(player).get().getMembers()) {
if (player1.getLocation().distanceSquared(player.getLocation()) <= 200) {
partyList.put(player1, true);
} else {
partyList.put(player1, false);
}
}
partyList.put(player, true);
DungeonManager.getInstance().createNewInstance(DungeonManager.DungeonType.BANDIT_TROVE, partyList, "T1Dungeon");
} else {
Affair.getInstance().createParty(player);
Map<Player, Boolean> partyList = new HashMap<>();
for (Player player1 : Affair.getInstance().getParty(player).get().getMembers()) {
if (player1.getLocation().distanceSquared(player.getLocation()) <= 200) {
partyList.put(player1, true);
} else {
partyList.put(player1, false);
}
}
partyList.put(player, true);
DungeonManager.getInstance().createNewInstance(DungeonManager.DungeonType.BANDIT_TROVE, partyList, "T1Dungeon");
}
break;
case "varenglade":
case "dodungeon":
if (Affair.getInstance().isInParty(player)) {
Map<Player, Boolean> partyList = new HashMap<>();
for (Player player1 : Affair.getInstance().getParty(player).get().getMembers()) {
if (player1.getLocation().distanceSquared(player.getLocation()) <= 200) {
partyList.put(player1, true);
} else {
partyList.put(player1, false);
}
}
partyList.put(player, true);
DungeonManager.getInstance().createNewInstance(DungeonManager.DungeonType.VARENGLADE, partyList, "DODungeon");
} else {
Affair.getInstance().createParty(player);
Map<Player, Boolean> partyList = new HashMap<>();
for (Player player1 : Affair.getInstance().getParty(player).get().getMembers()) {
if (player1.getLocation().distanceSquared(player.getLocation()) <= 200) {
partyList.put(player1, true);
} else {
partyList.put(player1, false);
}
}
partyList.put(player, true);
DungeonManager.getInstance().createNewInstance(DungeonManager.DungeonType.VARENGLADE, partyList, "DODungeon");
}
break;
case "infernal_abyss":
case "infernalabyss":
case "fireydungeon":
if (Affair.getInstance().isInParty(player)) {
Map<Player, Boolean> partyList = new HashMap<>();
for (Player player1 : Affair.getInstance().getParty(player).get().getMembers()) {
if (player1.getLocation().distanceSquared(player.getLocation()) <= 400) {
partyList.put(player1, true);
} else {
partyList.put(player1, false);
}
}
partyList.put(player, true);
DungeonManager.getInstance().createNewInstance(DungeonManager.DungeonType.THE_INFERNAL_ABYSS, partyList, "fireydungeon");
} else {
Affair.getInstance().createParty(player);
Map<Player, Boolean> partyList = new HashMap<>();
for (Player player1 : Affair.getInstance().getParty(player).get().getMembers()) {
if (player1.getLocation().distanceSquared(player.getLocation()) <= 400) {
partyList.put(player1, true);
} else {
partyList.put(player1, false);
}
}
partyList.put(player, true);
DungeonManager.getInstance().createNewInstance(DungeonManager.DungeonType.THE_INFERNAL_ABYSS, partyList, "fireydungeon");
}
break;
default:
player.sendMessage(ChatColor.RED + "Unknown instance " + args[0] + "!");
break;
}
} else {
player.sendMessage(ChatColor.RED + "There are no dungeons available at this time.");
}
}
return false;
}
}
| 6,861 | Java | .java | 122 | 33.786885 | 149 | 0.479352 | FlameBoss20/DungeonRealms-1 | 4 | 8 | 0 | GPL-3.0 | 9/4/2024, 11:05:06 PM (Europe/Amsterdam) | false | false | true | false | false | true | false | true | 6,861 |
1,481,164 | EmptyImmutableSortedSet.java | s-store_s-store/src/frontend/com/google_voltpatches/common/collect/EmptyImmutableSortedSet.java | /*
* Copyright (C) 2008 The Guava 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 com.google_voltpatches.common.collect;
import com.google_voltpatches.common.annotations.GwtCompatible;
import com.google_voltpatches.common.annotations.GwtIncompatible;
import java.util.Collection;
import java.util.Comparator;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation_voltpatches.Nullable;
/**
* An empty immutable sorted set.
*
* @author Jared Levy
*/
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
class EmptyImmutableSortedSet<E> extends ImmutableSortedSet<E> {
EmptyImmutableSortedSet(Comparator<? super E> comparator) {
super(comparator);
}
@Override
public int size() {
return 0;
}
@Override public boolean isEmpty() {
return true;
}
@Override public boolean contains(@Nullable Object target) {
return false;
}
@Override public boolean containsAll(Collection<?> targets) {
return targets.isEmpty();
}
@Override public UnmodifiableIterator<E> iterator() {
return Iterators.emptyIterator();
}
@GwtIncompatible("NavigableSet")
@Override public UnmodifiableIterator<E> descendingIterator() {
return Iterators.emptyIterator();
}
@Override boolean isPartialView() {
return false;
}
@Override public ImmutableList<E> asList() {
return ImmutableList.of();
}
@Override
int copyIntoArray(Object[] dst, int offset) {
return offset;
}
@Override public boolean equals(@Nullable Object object) {
if (object instanceof Set) {
Set<?> that = (Set<?>) object;
return that.isEmpty();
}
return false;
}
@Override public int hashCode() {
return 0;
}
@Override public String toString() {
return "[]";
}
@Override
public E first() {
throw new NoSuchElementException();
}
@Override
public E last() {
throw new NoSuchElementException();
}
@Override
ImmutableSortedSet<E> headSetImpl(E toElement, boolean inclusive) {
return this;
}
@Override
ImmutableSortedSet<E> subSetImpl(
E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
return this;
}
@Override
ImmutableSortedSet<E> tailSetImpl(E fromElement, boolean inclusive) {
return this;
}
@Override int indexOf(@Nullable Object target) {
return -1;
}
@Override
ImmutableSortedSet<E> createDescendingSet() {
return new EmptyImmutableSortedSet<E>(Ordering.from(comparator).reverse());
}
}
| 3,110 | Java | .java | 106 | 26.018868 | 79 | 0.741611 | s-store/s-store | 22 | 8 | 1 | GPL-3.0 | 9/4/2024, 7:53:28 PM (Europe/Amsterdam) | false | true | true | false | false | true | true | true | 3,110 |
4,211,354 | Chrome.java | lighthouse64_Random-Dungeon/src/com/lh64/randomdungeon/Chrome.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.lh64.randomdungeon;
import com.lh64.noosa.NinePatch;
public class Chrome {
public enum Type {
TOAST,
TOAST_TR,
WINDOW,
BUTTON,
TAG,
SCROLL,
TAB_SET,
TAB_SELECTED,
TAB_UNSELECTED
};
public static NinePatch get( Type type ) {
switch (type) {
case WINDOW:
return new NinePatch( Assets.CHROME, 0, 0, 22, 22, 7 );
case TOAST:
return new NinePatch( Assets.CHROME, 22, 0, 18, 18, 5 );
case TOAST_TR:
return new NinePatch( Assets.CHROME, 40, 0, 18, 18, 5 );
case BUTTON:
return new NinePatch( Assets.CHROME, 58, 0, 6, 6, 2 );
case TAG:
return new NinePatch( Assets.CHROME, 22, 18, 16, 14, 3 );
case SCROLL:
return new NinePatch( Assets.CHROME, 32, 32, 32, 32, 5, 11, 5, 11 );
case TAB_SET:
return new NinePatch( Assets.CHROME, 64, 0, 22, 22, 7, 7, 7, 7 );
case TAB_SELECTED:
return new NinePatch( Assets.CHROME, 64, 22, 10, 14, 4, 7, 4, 6 );
case TAB_UNSELECTED:
return new NinePatch( Assets.CHROME, 74, 22, 10, 14, 4, 7, 4, 6 );
default:
return null;
}
}
}
| 1,754 | Java | .java | 56 | 28.589286 | 71 | 0.701713 | lighthouse64/Random-Dungeon | 2 | 3 | 1 | GPL-3.0 | 9/5/2024, 12:05:57 AM (Europe/Amsterdam) | false | false | true | false | false | true | true | true | 1,754 |
4,945,766 | LogicContainer.java | ua-eas_ua-kfs-5_3/work/src/org/kuali/kfs/module/purap/document/service/LogicContainer.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.purap.document.service;
/**
* Used for containing logic that must be run... usually when faking a user session
*/
public abstract interface LogicContainer {
public abstract Object runLogic(Object[] objects) throws Exception;
}
| 1,118 | Java | .java | 25 | 41.4 | 97 | 0.75437 | ua-eas/ua-kfs-5.3 | 1 | 0 | 0 | AGPL-3.0 | 9/5/2024, 12:36:54 AM (Europe/Amsterdam) | true | true | true | true | false | true | true | true | 1,118 |
4,039,822 | ItemMunny20.java | Wehavecookies56_Kingdom-Keys-1_7-8/java/wehavecookies56/kk/item/ItemMunny20.java | package wehavecookies56.kk.item;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import wehavecookies56.kk.KingdomKeys;
import wehavecookies56.kk.core.packet.MunnyPacket;
import wehavecookies56.kk.lib.Strings;
public class ItemMunny20 extends ItemKingdomKeys{
public ItemMunny20() {
super();
this.setUnlocalizedName(Strings.Munny20);
}
@Override
public ItemStack onItemRightClick(ItemStack item, World world, EntityPlayer entity) {
IMessage packet = new MunnyPacket(new ItemStack(AddedItems.Munny20), 20);
KingdomKeys.network.sendToServer(packet);
entity.playSound("random.orb", 1, 1);
return super.onItemRightClick(item, world, entity);
}
} | 838 | Java | .java | 21 | 36.142857 | 86 | 0.793572 | Wehavecookies56/Kingdom-Keys-1.7-8 | 2 | 3 | 0 | LGPL-3.0 | 9/5/2024, 12:00:55 AM (Europe/Amsterdam) | false | false | false | false | false | true | true | true | 838 |
996,101 | GFOp_SC_stroke.java | veraPDF_veraPDF-validation/validation-model/src/main/java/org/verapdf/gf/model/impl/operator/color/GFOp_SC_stroke.java | /**
* This file is part of veraPDF Validation, a module of the veraPDF project.
* Copyright (c) 2015-2024, veraPDF Consortium <info@verapdf.org>
* All rights reserved.
*
* veraPDF Validation is free software: you can redistribute it and/or modify
* it under the terms of either:
*
* The GNU General public license GPLv3+.
* You should have received a copy of the GNU General Public License
* along with veraPDF Validation as the LICENSE.GPL file in the root of the source
* tree. If not, see http://www.gnu.org/licenses/ or
* https://www.gnu.org/licenses/gpl-3.0.en.html.
*
* The Mozilla Public License MPLv2+.
* You should have received a copy of the Mozilla Public License along with
* veraPDF Validation as the LICENSE.MPL file in the root of the source tree.
* If a copy of the MPL was not distributed with this file, you can obtain one at
* http://mozilla.org/MPL/2.0/.
*/
package org.verapdf.gf.model.impl.operator.color;
import org.verapdf.cos.COSBase;
import org.verapdf.model.operator.Op_SC_stroke;
import java.util.List;
/**
* @author Maxim Plushchov
*/
public class GFOp_SC_stroke extends GFOpSetColor implements Op_SC_stroke {
public static final String OP_SC_STROKE_TYPE = "Op_SC_stroke";
public GFOp_SC_stroke(List<COSBase> arguments) {
super(arguments, OP_SC_STROKE_TYPE);
}
}
| 1,340 | Java | .java | 33 | 38.181818 | 82 | 0.749424 | veraPDF/veraPDF-validation | 52 | 25 | 1 | GPL-3.0 | 9/4/2024, 7:10:22 PM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 1,340 |
4,519,462 | AutorDTO.java | netomantonio_orange/FASE_3/desafio_Casa_do_Codigo/code/main/java/br/com/zupacademy/neto/casadocodigo/autor/AutorDTO.java | package br.com.zupacademy.neto.casadocodigo.autor;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import br.com.zupacademy.neto.casadocodigo.validacoes.Unique;
public class AutorDTO {
@NotBlank(message = "Nome obrigatoio")
private String nome;
@NotBlank(message = "Ja foi avisado que tem que preencher tudo zé oreia")
@Email(message = "Bota o email cabeça de bagre")
@Unique(domainClass = Autor.class, fieldName = "email")
private String email;
@NotBlank
@Size(max = 400, min = 20)
private String descricao;
public AutorDTO(@NotBlank(message = "Nome obrigatório") String nome, @NotBlank @Email String email, @NotBlank @Size(max = 400) String descricao) {
super();
this.nome = nome;
this.email = email;
this.descricao = descricao;
}
public Autor toModel() {
return new Autor(this.nome, this.email, this.descricao);
}
}
| 974 | Java | .java | 25 | 35.08 | 148 | 0.751351 | netomantonio/orange | 2 | 0 | 0 | GPL-3.0 | 9/5/2024, 12:15:50 AM (Europe/Amsterdam) | false | false | false | true | true | false | true | true | 971 |
1,316,478 | A_testVararg05_out.java | eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testVararg05_out.java | package p;
class A {
/**
* @see #use(Object, String[])
* @deprecated Use {@link #use(Object)} instead
*/
public void use(Object first, String... args) {
use(first);
}
/**
* @see #use(Object)
*/
public void use(Object arg) {
System.out.println(arg);
}
public void call() {
use(null);
use(null);
use(null);
use(null);
use(null);
use(null);
use(null);
}
} | 392 | Java | .java | 25 | 13.12 | 48 | 0.612637 | 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 |
4,504,902 | TooManyCommunitiesActivity.java | iwondev_iwon-Android/TMessagesProj/src/main/java/org/telegram/ui/TooManyCommunitiesActivity.java | package org.telegram.ui;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import org.telegram.androidx.recyclerview.widget.LinearLayoutManager;
import org.telegram.androidx.recyclerview.widget.RecyclerView;
import org.telegram.messenger.AndroidUtilities;
import org.telegram.messenger.ChatObject;
import org.telegram.messenger.LocaleController;
import org.telegram.messenger.R;
import org.telegram.messenger.Utilities;
import org.telegram.tgnet.TLRPC;
import org.telegram.ui.ActionBar.ActionBar;
import org.telegram.ui.ActionBar.ActionBarMenu;
import org.telegram.ui.ActionBar.ActionBarMenuItem;
import org.telegram.ui.ActionBar.BaseFragment;
import org.telegram.ui.ActionBar.Theme;
import org.telegram.ui.ActionBar.ThemeDescription;
import org.telegram.ui.Cells.EmptyCell;
import org.telegram.ui.Cells.GroupCreateUserCell;
import org.telegram.ui.Cells.HeaderCell;
import org.telegram.ui.Cells.ShadowSectionCell;
import org.telegram.ui.Cells.TooManyCommunitiesHintCell;
import org.telegram.ui.Components.CombinedDrawable;
import org.telegram.ui.Components.EmptyTextProgressView;
import org.telegram.ui.Components.LayoutHelper;
import org.telegram.ui.Components.RadialProgressView;
import org.telegram.ui.Components.RecyclerListView;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
public class TooManyCommunitiesActivity extends BaseFragment {
public static final int TYPE_JOIN = 0;
public static final int TYPE_EDIT = 1;
public static final int TYPE_CREATE = 2;
private RecyclerListView listView;
private RecyclerListView searchListView;
private TextView buttonTextView;
private Adapter adapter;
private SearchAdapter searchAdapter;
private ArrayList<TLRPC.Chat> inactiveChats = new ArrayList<>();
private ArrayList<String> inactiveChatsSignatures = new ArrayList<>();
private FrameLayout buttonLayout;
private EmptyTextProgressView emptyView;
private FrameLayout searchViewContainer;
private int buttonAnimation;
private Set<Integer> selectedIds = new HashSet<>();
private TooManyCommunitiesHintCell hintCell;
private ValueAnimator enterAnimator;
private float enterProgress;
protected RadialProgressView progressBar;
int type;
private int buttonHeight = AndroidUtilities.dp(64);
Runnable showProgressRunnable = new Runnable() {
@Override
public void run() {
progressBar.setVisibility(View.VISIBLE);
progressBar.setAlpha(0);
progressBar.animate().alpha(1f).start();
}
};
RecyclerListView.OnItemClickListener onItemClickListener = (view, position) -> {
if (view instanceof GroupCreateUserCell) {
TLRPC.Chat chat = (TLRPC.Chat) ((GroupCreateUserCell) view).getObject();
if (selectedIds.contains(chat.id)) {
selectedIds.remove(chat.id);
((GroupCreateUserCell) view).setChecked(false, true);
} else {
selectedIds.add(chat.id);
((GroupCreateUserCell) view).setChecked(true, true);
}
onSelectedCountChange();
if (!selectedIds.isEmpty()) {
RecyclerListView list = searchViewContainer.getVisibility() == View.VISIBLE ? searchListView : listView;
int bottom = list.getHeight() - view.getBottom();
if (bottom < buttonHeight) {
list.smoothScrollBy(0, buttonHeight - bottom);
}
}
}
};
RecyclerListView.OnItemLongClickListener onItemLongClickListener = (view, position) -> {
onItemClickListener.onItemClick(view, position);
return true;
};
public TooManyCommunitiesActivity(int type) {
super();
Bundle bundle = new Bundle();
bundle.putInt("type", type);
arguments = bundle;
}
@Override
public View createView(Context context) {
type = arguments.getInt("type", TYPE_JOIN);
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAllowOverlayTitle(true);
actionBar.setTitle(LocaleController.getString("LimitReached", R.string.LimitReached));
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
finishFragment();
}
}
});
ActionBarMenu menu = actionBar.createMenu();
ActionBarMenuItem searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {
boolean expanded = false;
@Override
public void onSearchCollapse() {
super.onSearchCollapse();
if (listView.getVisibility() != View.VISIBLE) {
listView.setVisibility(View.VISIBLE);
listView.setAlpha(0);
}
emptyView.setVisibility(View.GONE);
adapter.notifyDataSetChanged();
listView.animate().alpha(1f).setDuration(150).setListener(null).start();
searchViewContainer.animate().alpha(0f).setDuration(150).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
searchViewContainer.setVisibility(View.GONE);
}
}).start();
expanded = false;
}
@Override
public void onTextChanged(EditText editText) {
String query = editText.getText().toString();
searchAdapter.search(query);
if (!expanded && !TextUtils.isEmpty(query)) {
if (searchViewContainer.getVisibility() != View.VISIBLE) {
searchViewContainer.setVisibility(View.VISIBLE);
searchViewContainer.setAlpha(0);
}
listView.animate().alpha(0).setDuration(150).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
listView.setVisibility(View.GONE);
}
}).start();
searchAdapter.searchResultsSignatures.clear();
searchAdapter.searchResults.clear();
searchAdapter.notifyDataSetChanged();
searchViewContainer.animate().setListener(null).alpha(1f).setDuration(150).start();
expanded = true;
} else if (expanded && TextUtils.isEmpty(query)) {
onSearchCollapse();
}
}
});
searchItem.setContentDescription(LocaleController.getString("Search", R.string.Search));
searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search));
FrameLayout contentView = new FrameLayout(context);
fragmentView = contentView;
listView = new RecyclerListView(context);
listView.setLayoutManager(new LinearLayoutManager(context));
listView.setAdapter(adapter = new Adapter());
listView.setClipToPadding(false);
listView.setOnItemClickListener(onItemClickListener);
listView.setOnItemLongClickListener(onItemLongClickListener);
searchListView = new RecyclerListView(context);
searchListView.setLayoutManager(new LinearLayoutManager(context));
searchListView.setAdapter(searchAdapter = new SearchAdapter());
searchListView.setOnItemClickListener(onItemClickListener);
searchListView.setOnItemLongClickListener(onItemLongClickListener);
searchListView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
}
}
});
emptyView = new EmptyTextProgressView(context);
emptyView.setShowAtCenter(true);
emptyView.setText(LocaleController.getString("NoResult", R.string.NoResult));
emptyView.showTextView();
progressBar = new RadialProgressView(context);
contentView.addView(progressBar, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));
adapter.updateRows();
progressBar.setVisibility(View.GONE);
contentView.addView(listView);
searchViewContainer = new FrameLayout(context);
searchViewContainer.addView(searchListView);
searchViewContainer.addView(emptyView);
searchViewContainer.setVisibility(View.GONE);
contentView.addView(searchViewContainer);
loadInactiveChannels();
fragmentView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
buttonLayout = new FrameLayout(context) {
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(0, 0, getMeasuredWidth(), 1, Theme.dividerPaint);
}
};
buttonLayout.setWillNotDraw(false);
buttonTextView = new TextView(context);
buttonTextView.setTextColor(Theme.getColor(Theme.key_featuredStickers_buttonText));
buttonTextView.setGravity(Gravity.CENTER);
buttonTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
buttonTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
buttonTextView.setBackground(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), Theme.getColor(Theme.key_featuredStickers_addButton), Theme.getColor(Theme.key_featuredStickers_addButtonPressed)));
contentView.addView(buttonLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 64, Gravity.BOTTOM));
buttonLayout.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
buttonLayout.addView(buttonTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 0, 16, 12, 16, 12));
buttonLayout.setVisibility(View.GONE);
buttonTextView.setOnClickListener(v -> {
if (selectedIds.isEmpty()) {
return;
}
TLRPC.User currentUser = getMessagesController().getUser(getUserConfig().getClientUserId());
ArrayList<TLRPC.Chat> chats = new ArrayList<>();
for (int i = 0; i < inactiveChats.size(); i++) {
if (selectedIds.contains(inactiveChats.get(i).id)) {
chats.add(inactiveChats.get(i));
}
}
for (int i = 0; i < chats.size(); i++) {
TLRPC.Chat chat = chats.get(i);
getMessagesController().putChat(chat, false);
getMessagesController().deleteUserFromChat(chat.id, currentUser, null);
}
finishFragment();
});
return fragmentView;
}
private void onSelectedCountChange() {
if (selectedIds.isEmpty() && buttonAnimation != -1 && buttonLayout.getVisibility() == View.VISIBLE) {
buttonAnimation = -1;
buttonLayout.animate().setListener(null).cancel();
buttonLayout.animate().translationY(buttonHeight).setDuration(200).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
buttonAnimation = 0;
buttonLayout.setVisibility(View.GONE);
}
}).start();
RecyclerListView list = searchViewContainer.getVisibility() == View.VISIBLE ? searchListView : listView;
list.hideSelector(false);
int last = ((LinearLayoutManager) list.getLayoutManager()).findLastVisibleItemPosition();
if (last == list.getAdapter().getItemCount() - 1 || (last == list.getAdapter().getItemCount() - 2 && list == listView)) {
RecyclerView.ViewHolder holder = list.findViewHolderForAdapterPosition(last);
if (holder != null) {
int bottom = holder.itemView.getBottom();
if (last == adapter.getItemCount() - 2) {
bottom += AndroidUtilities.dp(12);
}
if (list.getMeasuredHeight() - bottom <= buttonHeight) {
int dy = -(list.getMeasuredHeight() - bottom);
list.setTranslationY(dy);
list.animate().translationY(0).setDuration(200).start();
}
}
}
listView.setPadding(0, 0, 0, 0);
searchListView.setPadding(0, 0, 0, 0);
}
if (!selectedIds.isEmpty() && buttonLayout.getVisibility() == View.GONE && buttonAnimation != 1) {
buttonAnimation = 1;
buttonLayout.setVisibility(View.VISIBLE);
buttonLayout.setTranslationY(buttonHeight);
buttonLayout.animate().setListener(null).cancel();
buttonLayout.animate().translationY(0).setDuration(200).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
buttonAnimation = 0;
}
}).start();
listView.setPadding(0, 0, 0, buttonHeight - AndroidUtilities.dp(12));
searchListView.setPadding(0, 0, 0, buttonHeight);
}
if (!selectedIds.isEmpty()) {
buttonTextView.setText(LocaleController.formatString("LeaveChats", R.string.LeaveChats, LocaleController.formatPluralString("Chats", selectedIds.size())));
}
}
private void loadInactiveChannels() {
adapter.notifyDataSetChanged();
enterProgress = 0f;
AndroidUtilities.runOnUIThread(showProgressRunnable, 500);
TLRPC.TL_channels_getInactiveChannels inactiveChannelsRequest = new TLRPC.TL_channels_getInactiveChannels();
getConnectionsManager().sendRequest(inactiveChannelsRequest, ((response, error) -> {
if (error == null) {
final TLRPC.TL_messages_inactiveChats chats = (TLRPC.TL_messages_inactiveChats) response;
final ArrayList<String> signatures = new ArrayList<>();
for (int i = 0; i < chats.chats.size(); i++) {
TLRPC.Chat chat = chats.chats.get(i);
int currentDate = getConnectionsManager().getCurrentTime();
int date = chats.dates.get(i);
int daysDif = (currentDate - date) / 86400;
String dateFormat;
if (daysDif < 30) {
dateFormat = LocaleController.formatPluralString("Days", daysDif);
} else if (daysDif < 365) {
dateFormat = LocaleController.formatPluralString("Months", daysDif / 30);
} else {
dateFormat = LocaleController.formatPluralString("Years", daysDif / 365);
}
if (ChatObject.isMegagroup(chat)) {
String members = LocaleController.formatPluralString("Members", chat.participants_count);
signatures.add(LocaleController.formatString("InactiveChatSignature", R.string.InactiveChatSignature, members, dateFormat));
} else if (ChatObject.isChannel(chat)) {
signatures.add(LocaleController.formatString("InactiveChannelSignature", R.string.InactiveChannelSignature, dateFormat));
} else {
String members = LocaleController.formatPluralString("Members", chat.participants_count);
signatures.add(LocaleController.formatString("InactiveChatSignature", R.string.InactiveChatSignature, members, dateFormat));
}
}
AndroidUtilities.runOnUIThread(() -> {
inactiveChatsSignatures.clear();
inactiveChats.clear();
inactiveChatsSignatures.addAll(signatures);
inactiveChats.addAll(chats.chats);
adapter.notifyDataSetChanged();
if (listView.getMeasuredHeight() > 0) {
enterAnimator = ValueAnimator.ofFloat(0, 1f);
enterAnimator.addUpdateListener(animation -> {
enterProgress = (float) animation.getAnimatedValue();
int n = listView.getChildCount();
for (int i = 0; i < n; i++) {
if (listView.getChildAdapterPosition(listView.getChildAt(i)) >= adapter.headerPosition && adapter.headerPosition > 0) {
listView.getChildAt(i).setAlpha(enterProgress);
} else {
listView.getChildAt(i).setAlpha(1f);
}
}
});
enterAnimator.setDuration(100);
enterAnimator.start();
} else {
enterProgress = 1f;
}
AndroidUtilities.cancelRunOnUIThread(showProgressRunnable);
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.animate().alpha(0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
progressBar.setVisibility(View.GONE);
}
}).start();
}
});
}
}));
}
class Adapter extends RecyclerListView.SelectionAdapter {
int rowCount;
int hintPosition;
int shadowPosition;
int headerPosition;
int inactiveChatsStartRow;
int inactiveChatsEndRow;
int endPaddingPosition;
@Override
public void notifyDataSetChanged() {
updateRows();
super.notifyDataSetChanged();
}
public void updateRows() {
hintPosition = -1;
shadowPosition = -1;
headerPosition = -1;
inactiveChatsStartRow = -1;
inactiveChatsEndRow = -1;
endPaddingPosition = -1;
rowCount = 0;
hintPosition = rowCount++;
shadowPosition = rowCount++;
if (!inactiveChats.isEmpty()) {
headerPosition = rowCount++;
inactiveChatsStartRow = rowCount++;
rowCount += inactiveChats.size() - 1;
inactiveChatsEndRow = rowCount;
endPaddingPosition = rowCount++;
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case 1:
hintCell = new TooManyCommunitiesHintCell(parent.getContext());
view = hintCell;
String message;
if (type == TYPE_JOIN) {
message = LocaleController.getString("TooManyCommunitiesHintJoin", R.string.TooManyCommunitiesHintJoin);
} else if (type == TYPE_EDIT) {
message = LocaleController.getString("TooManyCommunitiesHintEdit", R.string.TooManyCommunitiesHintEdit);
} else {
message = LocaleController.getString("TooManyCommunitiesHintCreate", R.string.TooManyCommunitiesHintCreate);
}
hintCell.setMessageText(message);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.bottomMargin = AndroidUtilities.dp(16);
lp.topMargin = AndroidUtilities.dp(23);
hintCell.setLayoutParams(lp);
break;
case 2:
view = new ShadowSectionCell(parent.getContext());
Drawable drawable = Theme.getThemedDrawable(parent.getContext(), R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow);
CombinedDrawable combinedDrawable = new CombinedDrawable(new ColorDrawable(Theme.getColor(Theme.key_windowBackgroundGray)), drawable);
combinedDrawable.setFullsize(true);
view.setBackground(combinedDrawable);
break;
case 3:
HeaderCell header = new HeaderCell(parent.getContext(), Theme.key_windowBackgroundWhiteBlueHeader, 21, 8, false);
view = header;
header.setHeight(54);
header.setText(LocaleController.getString("InactiveChats", R.string.InactiveChats));
break;
case 5:
view = new EmptyCell(parent.getContext(), AndroidUtilities.dp(12));
break;
case 4:
default:
view = new GroupCreateUserCell(parent.getContext(), true, 0, false);
break;
}
return new RecyclerListView.Holder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if (position >= headerPosition && headerPosition > 0) {
holder.itemView.setAlpha(enterProgress);
} else {
holder.itemView.setAlpha(1f);
}
if (getItemViewType(position) == 4) {
GroupCreateUserCell cell = (GroupCreateUserCell) holder.itemView;
TLRPC.Chat chat = inactiveChats.get(position - inactiveChatsStartRow);
String signature = inactiveChatsSignatures.get(position - inactiveChatsStartRow);
cell.setObject(chat, chat.title, signature, position != inactiveChatsEndRow - 1);
cell.setChecked(selectedIds.contains(chat.id), false);
}
}
@Override
public int getItemViewType(int position) {
if (position == hintPosition) {
return 1;
} else if (position == shadowPosition) {
return 2;
} else if (position == headerPosition) {
return 3;
} else if (position == endPaddingPosition) {
return 5;
}
return 4;
}
@Override
public int getItemCount() {
return rowCount;
}
@Override
public boolean isEnabled(RecyclerView.ViewHolder holder) {
if (holder.getAdapterPosition() >= inactiveChatsStartRow && holder.getAdapterPosition() < inactiveChatsEndRow) {
return true;
}
return false;
}
}
class SearchAdapter extends RecyclerListView.SelectionAdapter {
ArrayList<TLRPC.Chat> searchResults = new ArrayList<>();
ArrayList<String> searchResultsSignatures = new ArrayList<>();
private Runnable searchRunnable;
private int lastSearchId;
@Override
public boolean isEnabled(RecyclerView.ViewHolder holder) {
return true;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new RecyclerListView.Holder(new GroupCreateUserCell(parent.getContext(), true, 0, false));
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
TLRPC.Chat chat = searchResults.get(position);
String signature = searchResultsSignatures.get(position);
GroupCreateUserCell cell = ((GroupCreateUserCell) holder.itemView);
cell.setObject(chat, chat.title, signature, position != searchResults.size() - 1);
cell.setChecked(selectedIds.contains(chat.id), false);
}
@Override
public int getItemCount() {
return searchResults.size();
}
public void search(final String query) {
if (searchRunnable != null) {
Utilities.searchQueue.cancelRunnable(searchRunnable);
searchRunnable = null;
}
if (TextUtils.isEmpty(query)) {
searchResults.clear();
searchResultsSignatures.clear();
notifyDataSetChanged();
emptyView.setVisibility(View.GONE);
} else {
int searchId = ++lastSearchId;
Utilities.searchQueue.postRunnable(searchRunnable = () -> processSearch(query, searchId), 300);
}
}
public void processSearch(String query, int id) {
Utilities.searchQueue.postRunnable(() -> {
String search1 = query.trim().toLowerCase();
if (search1.length() == 0) {
updateSearchResults(null, null, id);
return;
}
String search2 = LocaleController.getInstance().getTranslitString(search1);
if (search1.equals(search2) || search2.length() == 0) {
search2 = null;
}
String[] search = new String[1 + (search2 != null ? 1 : 0)];
search[0] = search1;
if (search2 != null) {
search[1] = search2;
}
ArrayList<TLRPC.Chat> resultArray = new ArrayList<>();
ArrayList<String> resultArraySignatures = new ArrayList<>();
for (int a = 0; a < inactiveChats.size(); a++) {
TLRPC.Chat chat = inactiveChats.get(a);
boolean found = false;
for (int i = 0; i < 2; i++) {
String name = i == 0 ? chat.title : chat.username;
if (name == null) {
continue;
}
name = name.toLowerCase();
for (String q : search) {
if ((name.startsWith(q) || name.contains(" " + q))) {
found = true;
break;
}
}
if (found) {
resultArray.add(chat);
resultArraySignatures.add(inactiveChatsSignatures.get(a));
break;
}
}
}
updateSearchResults(resultArray, resultArraySignatures, id);
});
}
private void updateSearchResults(ArrayList<TLRPC.Chat> chats, ArrayList<String> signatures, int searchId) {
AndroidUtilities.runOnUIThread(() -> {
if (searchId != lastSearchId) {
return;
}
searchResults.clear();
searchResultsSignatures.clear();
if (chats != null) {
searchResults.addAll(chats);
searchResultsSignatures.addAll(signatures);
}
notifyDataSetChanged();
if (searchResults.isEmpty()) {
emptyView.setVisibility(View.VISIBLE);
} else {
emptyView.setVisibility(View.GONE);
}
});
}
}
public ArrayList<ThemeDescription> getThemeDescriptions() {
ArrayList<ThemeDescription> themeDescriptions = new ArrayList<>();ThemeDescription.ThemeDescriptionDelegate cellDelegate = () -> {
if (listView != null) {
int count = listView.getChildCount();
for (int a = 0; a < count; a++) {
View child = listView.getChildAt(a);
if (child instanceof GroupCreateUserCell) {
((GroupCreateUserCell) child).update(0);
}
}
}
if (searchListView != null) {
int count = searchListView.getChildCount();
for (int a = 0; a < count; a++) {
View child = searchListView.getChildAt(a);
if (child instanceof GroupCreateUserCell) {
((GroupCreateUserCell) child).update(0);
}
}
}
buttonTextView.setBackground(Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(4), Theme.getColor(Theme.key_featuredStickers_addButton), Theme.getColor(Theme.key_featuredStickers_addButtonPressed)));
progressBar.setProgressColor(Theme.getColor(Theme.key_progressCircle));
};
themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_actionBarDefault));
themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_ITEMSCOLOR, null, null, null, null, Theme.key_actionBarDefaultIcon));
themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SELECTORCOLOR, null, null, null, null, Theme.key_actionBarDefaultSelector));
themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_ITEMSCOLOR, null, null, null, null, Theme.key_actionBarDefaultIcon));
themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SEARCH, null, null, null, null, Theme.key_actionBarDefaultSearch));
themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_SEARCHPLACEHOLDER, null, null, null, null, Theme.key_actionBarDefaultSearchPlaceholder));
themeDescriptions.add(new ThemeDescription(actionBar, ThemeDescription.FLAG_AB_TITLECOLOR, null, null, null, null, Theme.key_actionBarDefaultTitle));
themeDescriptions.add(new ThemeDescription(hintCell, 0, new Class[]{TooManyCommunitiesHintCell.class}, new String[]{"imageView"}, null, null, null, Theme.key_chats_nameMessage_threeLines));
themeDescriptions.add(new ThemeDescription(hintCell, 0, new Class[]{TooManyCommunitiesHintCell.class}, new String[]{"headerTextView"}, null, null, null, Theme.key_chats_nameMessage_threeLines));
themeDescriptions.add(new ThemeDescription(hintCell, 0, new Class[]{TooManyCommunitiesHintCell.class}, new String[]{"messageTextView"}, null, null, null, Theme.key_chats_message));
themeDescriptions.add(new ThemeDescription(fragmentView, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_windowBackgroundWhite));
themeDescriptions.add(new ThemeDescription(buttonLayout, ThemeDescription.FLAG_BACKGROUND, null, null, null, null, Theme.key_windowBackgroundWhite));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_BACKGROUNDFILTER, new Class[]{ShadowSectionCell.class}, null, null, null, Theme.key_windowBackgroundGrayShadow));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_BACKGROUNDFILTER | ThemeDescription.FLAG_CELLBACKGROUNDCOLOR, new Class[]{ShadowSectionCell.class}, null, null, null, Theme.key_windowBackgroundGray));
themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{HeaderCell.class}, new String[]{"textView"}, null, null, null, Theme.key_windowBackgroundWhiteBlueHeader));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{GroupCreateUserCell.class}, new String[]{"textView"}, null, null, null, Theme.key_groupcreate_sectionText));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{GroupCreateUserCell.class}, new String[]{"checkBox"}, null, null, null, Theme.key_checkbox));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{GroupCreateUserCell.class}, new String[]{"checkBox"}, null, null, null, Theme.key_checkboxDisabled));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{GroupCreateUserCell.class}, new String[]{"checkBox"}, null, null, null, Theme.key_checkboxCheck));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{GroupCreateUserCell.class}, new String[]{"nameTextView"}, null, null, null, Theme.key_windowBackgroundWhiteBlackText));
themeDescriptions.add(new ThemeDescription(listView, ThemeDescription.FLAG_TEXTCOLOR | ThemeDescription.FLAG_CHECKTAG, new Class[]{GroupCreateUserCell.class}, new String[]{"statusTextView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText));
themeDescriptions.add(new ThemeDescription(listView, 0, new Class[]{GroupCreateUserCell.class}, null, Theme.avatarDrawables, null, Theme.key_avatar_text));
themeDescriptions.add(new ThemeDescription(searchListView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{GroupCreateUserCell.class}, new String[]{"textView"}, null, null, null, Theme.key_groupcreate_sectionText));
themeDescriptions.add(new ThemeDescription(searchListView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{GroupCreateUserCell.class}, new String[]{"checkBox"}, null, null, null, Theme.key_checkbox));
themeDescriptions.add(new ThemeDescription(searchListView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{GroupCreateUserCell.class}, new String[]{"checkBox"}, null, null, null, Theme.key_checkboxDisabled));
themeDescriptions.add(new ThemeDescription(searchListView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{GroupCreateUserCell.class}, new String[]{"checkBox"}, null, null, null, Theme.key_checkboxCheck));
themeDescriptions.add(new ThemeDescription(searchListView, ThemeDescription.FLAG_TEXTCOLOR, new Class[]{GroupCreateUserCell.class}, new String[]{"nameTextView"}, null, null, null, Theme.key_windowBackgroundWhiteBlackText));
themeDescriptions.add(new ThemeDescription(searchListView, ThemeDescription.FLAG_TEXTCOLOR | ThemeDescription.FLAG_CHECKTAG, new Class[]{GroupCreateUserCell.class}, new String[]{"statusTextView"}, null, null, null, Theme.key_windowBackgroundWhiteGrayText));
themeDescriptions.add(new ThemeDescription(searchListView, 0, new Class[]{GroupCreateUserCell.class}, null, Theme.avatarDrawables, null, Theme.key_avatar_text));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundRed));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundOrange));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundViolet));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundGreen));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundCyan));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundBlue));
themeDescriptions.add(new ThemeDescription(null, 0, null, null, null, cellDelegate, Theme.key_avatar_backgroundPink));
themeDescriptions.add(new ThemeDescription(emptyView, ThemeDescription.FLAG_TEXTCOLOR, null, null, null, null, Theme.key_emptyListPlaceholder));
themeDescriptions.add(new ThemeDescription(buttonTextView, 0, null, null, null, cellDelegate, Theme.key_featuredStickers_addButton));
themeDescriptions.add(new ThemeDescription(buttonTextView, 0, null, null, null, cellDelegate, Theme.key_featuredStickers_addButtonPressed));
themeDescriptions.add(new ThemeDescription(progressBar, 0, null, null, null, cellDelegate, Theme.key_featuredStickers_addButtonPressed));
themeDescriptions.add(new ThemeDescription(hintCell, 0, new Class[]{TooManyCommunitiesHintCell.class}, new String[]{"imageLayout"}, null, null, null, Theme.key_dialogRedIcon));
return themeDescriptions;
}
}
| 37,508 | Java | .java | 647 | 44.100464 | 265 | 0.6328 | iwondev/iwon-Android | 2 | 2 | 1 | GPL-2.0 | 9/5/2024, 12:15:15 AM (Europe/Amsterdam) | false | false | false | false | false | true | true | true | 37,508 |
969,312 | MD4.java | pquiring_javaforce/src/javaforce/MD4.java | package javaforce;
/**
* MD4
*
*/
import java.security.MessageDigest;
public final class MD4 extends MessageDigest implements Cloneable {
/**
* The size in bytes of the input block to the transformation algorithm.
*/
private static final int BLOCK_LENGTH = 64; // = 512 / 8;
/**
* 4 32-bit words (interim result)
*/
private int[] context = new int[4];
/**
* Number of bytes processed so far mod. 2 power of 64.
*/
private long count;
/**
* 512 bits input buffer = 16 x 32-bit words holds until reaches 512 bits.
*/
private byte[] buffer = new byte[BLOCK_LENGTH];
/**
* 512 bits work buffer = 16 x 32-bit words
*/
private int[] X = new int[16];
public MD4 () {
super("MD4");
engineReset();
}
/**
* This constructor is here to implement clone ability of this class.
*/
private MD4 (MD4 md) {
this();
context = (int[])md.context.clone();
buffer = (byte[])md.buffer.clone();
count = md.count;
}
// Cloneable method implementation
//...........................................................................
/**
* Returns a copy of this MD object.
*/
public Object clone() { return new MD4(this); }
// JCE methods
//...........................................................................
/**
* Resets this object disregarding any temporary data present at the
* time of the invocation of this call.
*/
public void engineReset () {
// initial values of MD4 i.e. A, B, C, D
// as per rfc-1320; they are low-order byte first
context[0] = 0x67452301;
context[1] = 0xEFCDAB89;
context[2] = 0x98BADCFE;
context[3] = 0x10325476;
count = 0L;
for (int i = 0; i < BLOCK_LENGTH; i++)
buffer[i] = 0;
}
/**
* Continues an MD4 message digest using the input byte.
*/
public void engineUpdate (byte b) {
// compute number of bytes still unhashed; ie. present in buffer
int i = (int)(count % BLOCK_LENGTH);
count++; // update number of bytes
buffer[i] = b;
if (i == BLOCK_LENGTH - 1)
transform(buffer, 0);
}
/**
* MD4 block update operation.
* <p>
* Continues an MD4 message digest operation, by filling the buffer,
* transform(ing) data in 512-bit message block(s), updating the variables
* context and count, and leaving (buffering) the remaining bytes in buffer
* for the next update or finish.
*
* @param input input block
* @param offset start of meaningful bytes in input
* @param len count of bytes in input block to consider
*/
public void engineUpdate (byte[] input, int offset, int len) {
// make sure we don't exceed input's allocated size/length
if (offset < 0 || len < 0 || (long)offset + len > input.length)
throw new ArrayIndexOutOfBoundsException();
// compute number of bytes still unhashed; ie. present in buffer
int bufferNdx = (int)(count % BLOCK_LENGTH);
count += len; // update number of bytes
int partLen = BLOCK_LENGTH - bufferNdx;
int i = 0;
if (len >= partLen) {
System.arraycopy(input, offset, buffer, bufferNdx, partLen);
transform(buffer, 0);
for (i = partLen; i + BLOCK_LENGTH - 1 < len; i+= BLOCK_LENGTH)
transform(input, offset + i);
bufferNdx = 0;
}
// buffer remaining input
if (i < len)
System.arraycopy(input, offset + i, buffer, bufferNdx, len - i);
}
/**
* Completes the hash computation by performing final operations such
* as padding. At the return of this engineDigest, the MD engine is
* reset.
*
* @return the array of bytes for the resulting hash value.
*/
public byte[] engineDigest () {
// pad output to 56 mod 64; as RFC1320 puts it: congruent to 448 mod 512
int bufferNdx = (int)(count % BLOCK_LENGTH);
int padLen = (bufferNdx < 56) ? (56 - bufferNdx) : (120 - bufferNdx);
// padding is alwas binary 1 followed by binary 0s
byte[] tail = new byte[padLen + 8];
tail[0] = (byte)0x80;
// append length before final transform:
// save number of bits, casting the long to an array of 8 bytes
// save low-order byte first.
for (int i = 0; i < 8; i++)
tail[padLen + i] = (byte)((count * 8) >>> (8 * i));
engineUpdate(tail, 0, tail.length);
byte[] result = new byte[16];
// cast this MD4's context (array of 4 ints) into an array of 16 bytes.
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
result[i * 4 + j] = (byte)(context[i] >>> (8 * j));
// reset the engine
engineReset();
return result;
}
// own methods
//...........................................................................
/**
* MD4 basic transformation.
* <p>
* Transforms context based on 512 bits from input block starting
* from the offset'th byte.
*
* @param block input sub-array.
* @param offset starting position of sub-array.
*/
private void transform (byte[] block, int offset) {
// encodes 64 bytes from input block into an array of 16 32-bit
// entities. Use A as a temp var.
for (int i = 0; i < 16; i++)
X[i] = (block[offset++] & 0xFF) |
(block[offset++] & 0xFF) << 8 |
(block[offset++] & 0xFF) << 16 |
(block[offset++] & 0xFF) << 24;
int A = context[0];
int B = context[1];
int C = context[2];
int D = context[3];
A = FF(A, B, C, D, X[ 0], 3);
D = FF(D, A, B, C, X[ 1], 7);
C = FF(C, D, A, B, X[ 2], 11);
B = FF(B, C, D, A, X[ 3], 19);
A = FF(A, B, C, D, X[ 4], 3);
D = FF(D, A, B, C, X[ 5], 7);
C = FF(C, D, A, B, X[ 6], 11);
B = FF(B, C, D, A, X[ 7], 19);
A = FF(A, B, C, D, X[ 8], 3);
D = FF(D, A, B, C, X[ 9], 7);
C = FF(C, D, A, B, X[10], 11);
B = FF(B, C, D, A, X[11], 19);
A = FF(A, B, C, D, X[12], 3);
D = FF(D, A, B, C, X[13], 7);
C = FF(C, D, A, B, X[14], 11);
B = FF(B, C, D, A, X[15], 19);
A = GG(A, B, C, D, X[ 0], 3);
D = GG(D, A, B, C, X[ 4], 5);
C = GG(C, D, A, B, X[ 8], 9);
B = GG(B, C, D, A, X[12], 13);
A = GG(A, B, C, D, X[ 1], 3);
D = GG(D, A, B, C, X[ 5], 5);
C = GG(C, D, A, B, X[ 9], 9);
B = GG(B, C, D, A, X[13], 13);
A = GG(A, B, C, D, X[ 2], 3);
D = GG(D, A, B, C, X[ 6], 5);
C = GG(C, D, A, B, X[10], 9);
B = GG(B, C, D, A, X[14], 13);
A = GG(A, B, C, D, X[ 3], 3);
D = GG(D, A, B, C, X[ 7], 5);
C = GG(C, D, A, B, X[11], 9);
B = GG(B, C, D, A, X[15], 13);
A = HH(A, B, C, D, X[ 0], 3);
D = HH(D, A, B, C, X[ 8], 9);
C = HH(C, D, A, B, X[ 4], 11);
B = HH(B, C, D, A, X[12], 15);
A = HH(A, B, C, D, X[ 2], 3);
D = HH(D, A, B, C, X[10], 9);
C = HH(C, D, A, B, X[ 6], 11);
B = HH(B, C, D, A, X[14], 15);
A = HH(A, B, C, D, X[ 1], 3);
D = HH(D, A, B, C, X[ 9], 9);
C = HH(C, D, A, B, X[ 5], 11);
B = HH(B, C, D, A, X[13], 15);
A = HH(A, B, C, D, X[ 3], 3);
D = HH(D, A, B, C, X[11], 9);
C = HH(C, D, A, B, X[ 7], 11);
B = HH(B, C, D, A, X[15], 15);
context[0] += A;
context[1] += B;
context[2] += C;
context[3] += D;
}
// The basic MD4 atomic functions.
private int FF (int a, int b, int c, int d, int x, int s) {
int t = a + ((b & c) | (~b & d)) + x;
return t << s | t >>> (32 - s);
}
private int GG (int a, int b, int c, int d, int x, int s) {
int t = a + ((b & (c | d)) | (c & d)) + x + 0x5A827999;
return t << s | t >>> (32 - s);
}
private int HH (int a, int b, int c, int d, int x, int s) {
int t = a + (b ^ c ^ d) + x + 0x6ED9EBA1;
return t << s | t >>> (32 - s);
}
}
| 7,687 | Java | .java | 225 | 29.555556 | 77 | 0.525663 | pquiring/javaforce | 55 | 24 | 0 | LGPL-3.0 | 9/4/2024, 7:10:21 PM (Europe/Amsterdam) | false | false | false | false | false | true | true | true | 7,687 |
4,023,117 | AvailableResourcesNodeMapping.java | liruixpc11_crucian/alevin/src/main/java/vnreal/algorithms/nodemapping/AvailableResourcesNodeMapping.java | /* ***** BEGIN LICENSE BLOCK *****
* Copyright (C) 2010-2011, The VNREAL Project Team.
*
* This work has been funded by the European FP7
* Network of Excellence "Euro-NF" (grant agreement no. 216366)
* through the Specific Joint Developments and Experiments Project
* "Virtual Network Resource Embedding Algorithms" (VNREAL).
*
* The VNREAL Project Team consists of members from:
* - University of Wuerzburg, Germany
* - Universitat Politecnica de Catalunya, Spain
* - University of Passau, Germany
* See the file AUTHORS for details and contact information.
*
* This file is part of ALEVIN (ALgorithms for Embedding VIrtual Networks).
*
* ALEVIN is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License Version 3 or later
* (the "GPL"), or the GNU Lesser General Public License Version 3 or later
* (the "LGPL") as published by the Free Software Foundation.
*
* ALEVIN 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
* or the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License and
* GNU Lesser General Public License along with ALEVIN; see the file
* COPYING. If not, see <http://www.gnu.org/licenses/>.
*
* ***** END LICENSE BLOCK ***** */
package vnreal.algorithms.nodemapping;
/**
* This class implements the node mapping based on a greedy algorithm,
* taking into account the available resources of a node.
*
*
* This node mapping algorithm was proposed in:
*
* - Minlan Yu, Yung Yi, Jennifer Rexford, and Mung Chiang. Rethinking
* virtual network embedding: Substrate support for path splitting and
* migration. ACM SIGCOMM CCR, 38(2):17–29, April 2008.
*
* @author Juan Felipe Botero
* @author Lisset Diaz
* @since 2010-10-15
*/
import vnreal.algorithms.AbstractNodeMapping;
import vnreal.algorithms.utils.NodeLinkAssignation;
import vnreal.demands.AbstractDemand;
import vnreal.demands.CpuDemand;
import vnreal.network.substrate.SubstrateLink;
import vnreal.network.substrate.SubstrateNetwork;
import vnreal.network.substrate.SubstrateNode;
import vnreal.network.virtual.VirtualNetwork;
import vnreal.network.virtual.VirtualNode;
import vnreal.resources.AbstractResource;
import vnreal.resources.BandwidthResource;
import vnreal.resources.CpuResource;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class AvailableResourcesNodeMapping extends AbstractNodeMapping {
int distance;
boolean withDist;
/**
* Constructor of the algorithm
*
* @param sNet substrate Network
* @param distance
* @param withDistance Indicates if the distance will be taken into account to chose
* the candidate substrate nodes
* @param nodesOverload Indicatesif the fact that more that one node in one VNR are
* mapped to the same node in the SN
*/
public AvailableResourcesNodeMapping(SubstrateNetwork sNet, int distance,
boolean withDistance, boolean nodesOverload) {
super(sNet, nodesOverload);
this.distance = distance;
this.withDist = withDistance;
}
/**
* Node mapping method implementation
*/
@Override
protected boolean nodeMapping(VirtualNetwork vNet) {
List<SubstrateNode> unmappedSnodes = super.getUnmappedsNodes();
List<SubstrateNode> allNodes = new LinkedList<SubstrateNode>(sNet
.getVertices());
SubstrateNode mappedSnode = null;
VirtualNode currVnode;
List<SubstrateNode> candidates = new LinkedList<SubstrateNode>();
// Move through the virtual nodes
for (Iterator<VirtualNode> itt = vNet.getVertices().iterator(); itt
.hasNext(); ) {
currVnode = itt.next();
// Find the candidate substrate nodes accomplishing the virtual node
// demands
for (AbstractDemand dem : currVnode) {
if (dem instanceof CpuDemand) {
if (!nodeOverload) {
if (!withDist) {
candidates = findFulfillingNodes(dem,
unmappedSnodes);
} else {
candidates = findFulfillingNodes(currVnode, dem,
unmappedSnodes, distance);
}
} else {
if (!withDist) {
candidates = findFulfillingNodes(dem, allNodes);
} else {
candidates = findFulfillingNodes(currVnode, dem,
allNodes, distance);
}
}
}
// Find the feasible node with greatest available resources
// The available resources are the H value defined in the
// "Rethinking virtual network embedding" paper
mappedSnode = bestAvailableResources(candidates);
if (mappedSnode != null) {
// Realize the node mapping
if (NodeLinkAssignation.vnm(currVnode, mappedSnode)) {
nodeMapping.put(currVnode, mappedSnode);
} else {
// If this exception is thrown, it means that something
// in the code is wrong. The feasibility of nodes is
// checked in findFulfillingNodes
throw new AssertionError("But we checked before!");
}
} else {
// Mapping is not possible, not feasible nodes
return false;
}
}
}
return true;
}
/**
* @param dem virtual node demand
* @param filtratedsNodes set of all nodes to extract the feasible substrate node
* candidates
* @return The set of nodes accomplishing a demand dem
*/
private List<SubstrateNode> findFulfillingNodes(AbstractDemand dem,
List<SubstrateNode> filtratedsNodes) {
List<SubstrateNode> nodes = new LinkedList<SubstrateNode>();
for (SubstrateNode n : filtratedsNodes) {
for (AbstractResource res : n)
if ((res instanceof CpuResource) && res.accepts(dem)
&& res.fulfills(dem)) {
nodes.add(n);
break;
}
}
return nodes;
}
/**
* @param candidates feasible substrate node candidates
* @return substrate node among candidates with the highest available
* resources value
*/
private SubstrateNode bestAvailableResources(List<SubstrateNode> candidates) {
double resCPU = 0;
double resLink = 0;
double greatAr = 0;
SubstrateNode chosenNode = null;
for (Iterator<SubstrateNode> sn = candidates.iterator(); sn.hasNext(); ) {
SubstrateNode tmp = sn.next();
for (AbstractResource res : tmp) {
if (res instanceof CpuResource) {
resCPU = ((CpuResource) res).getAvailableCycles();
resLink = calcLinksRes(tmp);
if (!nodeOverload) {
if ((resCPU * resLink >= greatAr)
&& !nodeMapping.containsValue(tmp)) {
greatAr = resCPU * resLink;
chosenNode = tmp;
}
} else {
if (resCPU * resLink >= greatAr) {
greatAr = resCPU * resLink;
chosenNode = tmp;
}
}
}
}
}
return chosenNode;
}
/**
* @param sn Substrate node
* @return The available resources of the node sn
*/
private double calcLinksRes(SubstrateNode sn) {
SubstrateNode srcSnode = null;
double resBW = 0;
double total_resBW = 0;
for (SubstrateLink sl : sNet.getEdges()) {
srcSnode = sNet.getSource(sl);
// If the processing SubstrateNode is equals to the source of a
// SubstrateLink then add the link
if (sn.equals(srcSnode)) {
for (AbstractResource res : sl) {
if (res instanceof BandwidthResource) {
resBW = ((BandwidthResource) res)
.getAvailableBandwidth();
total_resBW += resBW;
}
}
}
}
return total_resBW;
}
/**
* @param vNode virtual node
* @param dem demand of the virtual node
* @param filtratedsNodes set of all nodes to extract the feasible substrate node
* candidates
* @param dist parameter to assure that the candidate nodes will be separated
* of virtual node by a distance of, at maximum, equal to dist.
* @return The set of substrate nodes accomplishing a demand and a distance
* dist from the vnode
*/
private List<SubstrateNode> findFulfillingNodes(VirtualNode vNode,
AbstractDemand dem, List<SubstrateNode> filtratedsNodes, int dist) {
List<SubstrateNode> nodes = new LinkedList<SubstrateNode>();
for (SubstrateNode n : filtratedsNodes) {
for (AbstractResource res : n)
if ((res instanceof CpuResource) && res.accepts(dem)
&& res.fulfills(dem) && nodeDistance(vNode, n, dist)) {
nodes.add(n);
break;
}
}
return nodes;
}
/**
* @param vNode virtual node
* @param sNode substrate node
* @param distance
* @return true if vNode is separated from sNode by a value lower than
* "distance"
*/
private boolean nodeDistance(VirtualNode vNode, SubstrateNode sNode,
int distance) {
double dis;
dis = Math.pow(sNode.getCoordinateX() - vNode.getCoordinateX(), 2)
+ Math.pow(sNode.getCoordinateY() - vNode.getCoordinateY(), 2);
if (Math.sqrt(dis) <= distance) {
return true;
} else {
return false;
}
}
}
| 10,898 | Java | .java | 257 | 31.237354 | 120 | 0.582431 | liruixpc11/crucian | 2 | 4 | 0 | GPL-3.0 | 9/5/2024, 12:00:16 AM (Europe/Amsterdam) | false | false | true | false | false | true | false | true | 10,898 |
4,953,337 | InstituteServiceImpl.java | kamcpp_edusys/old-src/org.labcrypto.edusys.ws.education/src/main/java/org/labcrypto/edusys/ws/education/services/impl/InstituteServiceImpl.java | package org.labcrypto.edusys.ws.education.services.impl;
import java.util.List;
import org.labcrypto.edusys.domain.pg.entity.education.Institute;
import org.labcrypto.edusys.facade.education.InstituteFacade;
import org.labcrypto.edusys.ws.education.services.InstituteService;
import org.springframework.beans.factory.annotation.Autowired;
public class InstituteServiceImpl implements InstituteService {
@Autowired
private InstituteFacade instituteFacade;
@Override
public Long addEntity(Institute entity) {
return instituteFacade.add(entity);
}
@Override
public void updateEntity(Institute entity) {
instituteFacade.update(entity);
}
@Override
public void deleteEntity(Long id) {
instituteFacade.delete(id);
}
@Override
public Institute getEntityById(Long id) {
return instituteFacade.getById(id);
}
@Override
public List<Institute> getAllEntities() {
return instituteFacade.getAll();
}
}
| 925 | Java | .java | 30 | 28.633333 | 67 | 0.8307 | kamcpp/edusys | 1 | 0 | 0 | GPL-3.0 | 9/5/2024, 12:37:05 AM (Europe/Amsterdam) | false | false | true | false | false | true | true | true | 925 |
4,946,244 | KemidReportGroup.java | ua-eas_ua-kfs-5_3/work/src/org/kuali/kfs/module/endow/businessobject/KemidReportGroup.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.endow.businessobject;
import java.sql.Date;
import java.util.LinkedHashMap;
import org.kuali.kfs.module.endow.EndowPropertyConstants;
import org.kuali.rice.core.api.util.type.KualiInteger;
import org.kuali.rice.krad.bo.PersistableBusinessObjectBase;
/**
* This KemidReportGroup class provides the report group for consolidated reporting to which the KEMID belongs.
*/
public class KemidReportGroup extends PersistableBusinessObjectBase {
private String kemid;
private KualiInteger combineGroupSeq;
private String combineGroupCode;
private Date dateAdded;
private Date dateTerminated;
private KEMID kemidObjRef;
private CombineGroupCode combineGroup;
/**
* @see org.kuali.rice.krad.bo.BusinessObjectBase#toStringMapper()
*/
protected LinkedHashMap toStringMapper_RICE20_REFACTORME() {
LinkedHashMap<String, String> m = new LinkedHashMap<String, String>();
m.put(EndowPropertyConstants.KEMID, this.kemid);
m.put(EndowPropertyConstants.KEMID_REPORT_GRP_SEQ, String.valueOf(combineGroupSeq));
m.put(EndowPropertyConstants.KEMID_REPORT_GRP_CD, combineGroupCode);
return m;
}
/**
* Gets the combineGroup.
*
* @return combineGroup
*/
public CombineGroupCode getCombineGroup() {
return combineGroup;
}
/**
* Sets the combineGroup.
*
* @param combineGroup
*/
public void setCombineGroup(CombineGroupCode combineGroup) {
this.combineGroup = combineGroup;
}
/**
* Gets the combineGroupCode.
*
* @return combineGroupCode
*/
public String getCombineGroupCode() {
return combineGroupCode;
}
/**
* Sets the combineGroupCode.
*
* @param combineGroupCode
*/
public void setCombineGroupCode(String combineGroupCode) {
this.combineGroupCode = combineGroupCode;
}
/**
* Gets the combineGroupSeq.
*
* @return combineGroupSeq
*/
public KualiInteger getCombineGroupSeq() {
return combineGroupSeq;
}
/**
* Sets the combineGroupSeq.
*
* @param combineGroupSeq
*/
public void setCombineGroupSeq(KualiInteger combineGroupSeq) {
this.combineGroupSeq = combineGroupSeq;
}
/**
* Gets the dateAdded.
*
* @return dateAdded
*/
public Date getDateAdded() {
return dateAdded;
}
/**
* Sets the dateAdded.
*
* @param dateAdded
*/
public void setDateAdded(Date dateAdded) {
this.dateAdded = dateAdded;
}
/**
* Gets the dateTerminated.
*
* @return dateTerminated
*/
public Date getDateTerminated() {
return dateTerminated;
}
/**
* Sets the dateTerminated.
*
* @param dateTerminated
*/
public void setDateTerminated(Date dateTerminated) {
this.dateTerminated = dateTerminated;
}
/**
* Gets the kemid.
*
* @return kemid
*/
public String getKemid() {
return kemid;
}
/**
* Sets the kemid.
*
* @param kemid
*/
public void setKemid(String kemid) {
this.kemid = kemid;
}
/**
* Gets the kemidObjRef.
*
* @return kemidObjRef
*/
public KEMID getKemidObjRef() {
return kemidObjRef;
}
/**
* Sets the kemidObjRef.
*
* @param kemidObjRef
*/
public void setKemidObjRef(KEMID kemidObjRef) {
this.kemidObjRef = kemidObjRef;
}
}
| 4,599 | Java | .java | 158 | 22.455696 | 112 | 0.64967 | ua-eas/ua-kfs-5.3 | 1 | 0 | 0 | AGPL-3.0 | 9/5/2024, 12:36:54 AM (Europe/Amsterdam) | false | true | true | true | false | true | false | true | 4,599 |
4,672,352 | SkewedTrafficPairProbabilitiesCreator.java | mostafaei_RIFO/java-code/src/main/java/ch/ethz/systems/netbench/xpt/utility/pairprob/deprecated/SkewedTrafficPairProbabilitiesCreator.java | package ch.ethz.systems.netbench.xpt.utility.pairprob.deprecated;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class SkewedTrafficPairProbabilitiesCreator {
public static void main(String args[]) throws IOException {
// Number of server-carrying nodes
int n = 192;
// The higher, the skewer the pair probabilities
double skewness = 0.321; // 0.95
// Amount of servers per server-carrying node
int serversPerNode = 6;
// Start of the server indexes, the servers will have indexes [start, start + n * serversPerNode - 1]
int serverIndexStart = 192;
// Random shuffle seed for the node probabilities
int shuffleSeed = 289895;
// Out file names
String outNodePairsFileName = "temp/node_pair_probabilities.csv";
String outServerPairsFileName = "temp/server_pair_probabilities.csv";
/* ***************************************
* 1) Calculate node pair probabilities
*/
// Calculate skewed fabricated mass for each node
List<Double> mass = new ArrayList<>();
double defaultMass = 1 / (2.0 * n);
double totalMass = 0.0;
for (int i = 0; i < n; i++) {
double val = skewedExponentialFunction(skewness, i) + defaultMass;
mass.add(val);
totalMass += val;
}
// Calculate probability of a node being involved in a pair
List<Double> nodeProb = new ArrayList<>();
for (int i = 0; i < n; i++) {
nodeProb.add(mass.get(i) / totalMass);
}
double top1percTotalProb = 0.0;
double top5percTotalProb = 0.0;
double top10percTotalProb = 0.0;
for (int i = 0; i < n / 10; i++) {
if (i < n / 100) {
top1percTotalProb += nodeProb.get(i);
}
if (i < n / 20) {
top5percTotalProb += nodeProb.get(i);
}
if (i < n / 10) {
top10percTotalProb += nodeProb.get(i);
}
}
System.out.println("The top 1% nodes hold " + (100 * top1percTotalProb) + "% of all node probability.");
System.out.println("The top 5% nodes hold " + (100 * top5percTotalProb) + "% of all node probability.");
System.out.println("The top 10% nodes hold " + (100 * top10percTotalProb) + "% of all node probability.");
System.out.println("Maximum node probability: " + nodeProb.get(0));
// Shuffle probability list such that there is no guarantee which node
// will become the most probable (as mass is drawn from exponential distribution left-to-right)
Collections.shuffle(nodeProb, new Random(shuffleSeed));
// Calculate all node pair probabilities
List<Integer> nodePairSrc = new ArrayList<>();
List<Integer> nodePairDst = new ArrayList<>();
List<Double> nodePairProb = new ArrayList<>();
double totalProbLeft = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
double prob = i == j ? 0 : nodeProb.get(i) * nodeProb.get(j);
nodePairSrc.add(i);
nodePairDst.add(j);
nodePairProb.add(prob);
totalProbLeft += prob;
}
}
// Normalize again for the missing diagonal
double max = 0.0;
for (int i = 0; i < n * n; i++) {
double val = nodePairProb.get(i) / totalProbLeft;
max = Math.max(max, val);
nodePairProb.set(i, val);
}
System.out.println("Maximum node pair probability: " + max);
// Write away node probabilities
BufferedWriter nodeOutWriter = new BufferedWriter(new FileWriter(outNodePairsFileName));
nodeOutWriter.write("# Skewed traffic node pairs; n=" + n +
", skewness=" + skewness +
", serverStartIdx=" + serverIndexStart +
", serversPerNode=" + serversPerNode +
", shuffleSeed=" + shuffleSeed + "\n"
);
nodeOutWriter.write("#node_pair_id,src,dst,pdf_num_bytes\n");
for (int i = 0; i < n * n; i++) {
if (!nodePairSrc.get(i).equals(nodePairDst.get(i))) {
nodeOutWriter.write(i + "," + nodePairSrc.get(i) + "," + nodePairDst.get(i) + "," + nodePairProb.get(i) + "\n");
}
}
nodeOutWriter.close();
/* ***************************************
* 2) Calculate node pair probabilities
*/
// Open file output stream
BufferedWriter outWriter = new BufferedWriter(new FileWriter(outServerPairsFileName));
// Write header
outWriter.write("# Skewed traffic server pairs; n=" + n +
", skewness=" + skewness +
", serverStartIdx=" + serverIndexStart +
", serversPerNode=" + serversPerNode +
", shuffleSeed=" + shuffleSeed + "\n"
);
outWriter.write("#server_pair_id,src,dst,pdf_num_bytes\n");
// Read in others
int srvPairId = 0;
double totalProb = 0;
for (int i = 0; i < n * n; i++) {
if (!nodePairSrc.get(i).equals(nodePairDst.get(i))) {
// Write away server probability nodes
int srvSrcStartId = serverIndexStart + nodePairSrc.get(i) * serversPerNode;
int srvDstStartId = serverIndexStart + nodePairDst.get(i) * serversPerNode;
double serverProb = nodePairProb.get(i) / (double) (serversPerNode * serversPerNode);
for (int z = srvSrcStartId; z < srvSrcStartId + serversPerNode; z++) {
for (int j = srvDstStartId; j < srvDstStartId + serversPerNode; j++) {
outWriter.write(srvPairId + "," + z + "," + j + "," + serverProb + "\n");
srvPairId++;
totalProb += serverProb;
}
}
}
}
System.out.println("Total server pair probability: " + totalProb);
// Close file streams
outWriter.close();
}
public static double skewedExponentialFunction(double skewness, int x) {
return 2 * Math.exp(-1 * skewness * x);
}
}
| 6,450 | Java | .java | 137 | 36.116788 | 128 | 0.564927 | mostafaei/RIFO | 2 | 0 | 0 | AGPL-3.0 | 9/5/2024, 12:20:59 AM (Europe/Amsterdam) | false | false | false | true | true | false | true | true | 6,450 |
394,431 | ExceptionContextProvider.java | jlizier_jidt/java/source/infodynamics/utils/commonsmath3/exception/util/ExceptionContextProvider.java | /*
* Java Information Dynamics Toolkit (JIDT)
* Copyright (C) 2017, Joseph T. Lizier
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* This class was originally distributed as part of the Apache Commons
* Math3 library (3.6.1), under the Apache License Version 2.0, which is
* copied below. This Apache 2 software is now included as a derivative
* work in the GPLv3 licensed JIDT project, as per:
* http://www.apache.org/licenses/GPL-compatibility.html
*
* The original Apache source code has been modified as follows:
* -- We have modified package names to sit inside the JIDT structure.
*/
/*
* 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 infodynamics.utils.commonsmath3.exception.util;
/**
* Interface for accessing the context data structure stored in Commons Math
* exceptions.
*
*/
public interface ExceptionContextProvider {
/**
* Gets a reference to the "rich context" data structure that allows to
* customize error messages and store key, value pairs in exceptions.
*
* @return a reference to the exception context.
*/
ExceptionContext getContext();
}
| 2,508 | Java | .java | 58 | 40.706897 | 76 | 0.75184 | jlizier/jidt | 258 | 72 | 28 | GPL-3.0 | 9/4/2024, 7:06:52 PM (Europe/Amsterdam) | true | true | true | true | true | true | true | true | 2,508 |
3,136,846 | BrokeredIterator.java | crypto-coder_open-cyclos/src/nl/strohalm/cyclos/controls/members/brokering/BrokeredIterator.java | /*
This file is part of Cyclos (www.cyclos.org).
A project of the Social Trade Organisation (www.socialtrade.org).
Cyclos 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.
Cyclos 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 Cyclos; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package nl.strohalm.cyclos.controls.members.brokering;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import nl.strohalm.cyclos.entities.members.brokerings.Brokering;
import nl.strohalm.cyclos.services.transactions.LoanService;
import nl.strohalm.cyclos.services.transactions.TransactionSummaryVO;
/**
* Iterates over the brokered list, adding loan information
* @author luis
* @author rinke
*/
public class BrokeredIterator implements Iterator<Map<String, Object>> {
private final Iterator<Brokering> iterator;
private final boolean showLoanData;
private final LoanService loanService;
public BrokeredIterator(final Iterator<Brokering> iterator, final LoanService loanService, final boolean showLoanData) {
this.iterator = iterator;
this.showLoanData = showLoanData;
this.loanService = loanService;
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Map<String, Object> next() {
final Brokering brokering = iterator.next();
final Map<String, Object> row = new HashMap<String, Object>();
row.put("brokering", brokering);
if (showLoanData) {
final TransactionSummaryVO loans = loanService.loanSummary(brokering.getBrokered());
row.put("loans", loans);
}
return row;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
| 2,337 | Java | .java | 56 | 36.5 | 124 | 0.728955 | crypto-coder/open-cyclos | 4 | 9 | 0 | GPL-2.0 | 9/4/2024, 10:59:44 PM (Europe/Amsterdam) | false | false | true | true | false | true | false | true | 2,337 |
431,708 | ModeshapeProperty.java | eclipse_vorto/repository/repository-core/src/main/java/org/eclipse/vorto/repository/diagnostics/ModeshapeProperty.java | /**
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* https://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.vorto.repository.diagnostics;
public class ModeshapeProperty {
private String name;
private String value;
public ModeshapeProperty() {
}
public ModeshapeProperty(String name, String value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| 976 | Java | .java | 35 | 23.285714 | 75 | 0.694624 | eclipse/vorto | 225 | 106 | 175 | EPL-2.0 | 9/4/2024, 7:07:11 PM (Europe/Amsterdam) | false | true | false | false | false | true | true | true | 976 |
1,862,795 | KindItemProvider.java | occiware_OCCI-Studio/plugins/org.eclipse.cmf.occi.core.edit/src-gen/org/eclipse/cmf/occi/core/provider/KindItemProvider.java | /**
* Copyright (c) 2017 Inria
*
* 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:
* - Faiez Zalila <faiez.zalila@inria.fr>
*/
package org.eclipse.cmf.occi.core.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.cmf.occi.core.Kind;
import org.eclipse.cmf.occi.core.OCCIPackage;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
/**
* This is the item provider adapter for a {@link org.eclipse.cmf.occi.core.Kind} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class KindItemProvider extends TypeItemProvider {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public KindItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addParentPropertyDescriptor(object);
addEntitiesPropertyDescriptor(object);
addSourcePropertyDescriptor(object);
addTargetPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Parent feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
protected void addParentPropertyDescriptor(Object object) {
final IItemLabelProvider lp = new IItemLabelProvider() {
public String getText(Object object) {
if (object != null) {
return ((Kind) object).getScheme() + ((Kind) object).getTerm();
}
return "";
}
public Object getImage(Object object) {
return null;
}
};
itemPropertyDescriptors
.add(new ItemPropertyDescriptor(((ComposeableAdapterFactory) adapterFactory).getRootAdapterFactory(),
getResourceLocator(), getString("_UI_Kind_parent_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Kind_parent_feature", "_UI_Kind_type"),
OCCIPackage.Literals.KIND__PARENT, true, false, true, null, null, null) {
@Override
public IItemLabelProvider getLabelProvider(Object object) {
if (object instanceof Kind) {
return lp;
}
return super.getLabelProvider(object);
}
});
}
// protected void addParentPropertyDescriptor(Object object) {
// itemPropertyDescriptors.add
// (createItemPropertyDescriptor
// (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
// getResourceLocator(),
// getString("_UI_Kind_parent_feature"),
// getString("_UI_PropertyDescriptor_description", "_UI_Kind_parent_feature", "_UI_Kind_type"),
// OCCIPackage.Literals.KIND__PARENT,
// true,
// false,
// true,
// null,
// null,
// null));
// }
/**
* This adds a property descriptor for the Entities feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addEntitiesPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Kind_entities_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Kind_entities_feature", "_UI_Kind_type"),
OCCIPackage.Literals.KIND__ENTITIES,
false,
false,
false,
null,
null,
null));
}
/**
* This adds a property descriptor for the Source feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addSourcePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Kind_source_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Kind_source_feature", "_UI_Kind_type"),
OCCIPackage.Literals.KIND__SOURCE,
true,
false,
true,
null,
null,
null));
}
/**
* This adds a property descriptor for the Target feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addTargetPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Kind_target_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Kind_target_feature", "_UI_Kind_type"),
OCCIPackage.Literals.KIND__TARGET,
true,
false,
true,
null,
null,
null));
}
/**
* This returns Kind.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/Kind"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((Kind)object).getName();
return label == null || label.length() == 0 ?
getString("_UI_Kind_type") :
getString("_UI_Kind_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
| 6,716 | Java | .java | 212 | 28.334906 | 105 | 0.71107 | occiware/OCCI-Studio | 11 | 2 | 14 | EPL-1.0 | 9/4/2024, 8:21:15 PM (Europe/Amsterdam) | false | false | true | false | false | true | false | true | 6,716 |
1,851,835 | JUnitXmlResultWriter.java | catofmrlu_Reer/gradle/wrapper/gradle-3.3/src/testing-jvm/org/gradle/api/internal/tasks/testing/junit/result/JUnitXmlResultWriter.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.api.internal.tasks.testing.junit.result;
import org.apache.tools.ant.util.DateUtils;
import org.gradle.internal.xml.SimpleXmlWriter;
import org.gradle.api.tasks.testing.TestOutputEvent;
import org.gradle.api.tasks.testing.TestResult;
import org.gradle.internal.UncheckedException;
import java.io.IOException;
import java.io.OutputStream;
public class JUnitXmlResultWriter {
private final String hostName;
private final TestResultsProvider testResultsProvider;
private final TestOutputAssociation outputAssociation;
public JUnitXmlResultWriter(String hostName, TestResultsProvider testResultsProvider, TestOutputAssociation outputAssociation) {
this.hostName = hostName;
this.testResultsProvider = testResultsProvider;
this.outputAssociation = outputAssociation;
}
/**
* @param output The destination, unbuffered
*/
public void write(TestClassResult result, OutputStream output) {
String className = result.getClassName();
long classId = result.getId();
try {
SimpleXmlWriter writer = new SimpleXmlWriter(output, " ");
writer.startElement("testsuite")
.attribute("name", className)
.attribute("tests", String.valueOf(result.getTestsCount()))
.attribute("skipped", String.valueOf(result.getSkippedCount()))
.attribute("failures", String.valueOf(result.getFailuresCount()))
.attribute("errors", "0")
.attribute("timestamp", DateUtils.format(result.getStartTime(), DateUtils.ISO8601_DATETIME_PATTERN))
.attribute("hostname", hostName)
.attribute("time", String.valueOf(result.getDuration() / 1000.0));
writer.startElement("properties");
writer.endElement();
writeTests(writer, result.getResults(), className, classId);
writer.startElement("system-out");
writeOutputs(writer, classId, outputAssociation.equals(TestOutputAssociation.WITH_SUITE), TestOutputEvent.Destination.StdOut);
writer.endElement();
writer.startElement("system-err");
writeOutputs(writer, classId, outputAssociation.equals(TestOutputAssociation.WITH_SUITE), TestOutputEvent.Destination.StdErr);
writer.endElement();
writer.endElement();
} catch (IOException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
}
private void writeOutputs(SimpleXmlWriter writer, long classId, boolean allClassOutput, TestOutputEvent.Destination destination) throws IOException {
writer.startCDATA();
if (allClassOutput) {
testResultsProvider.writeAllOutput(classId, destination, writer);
} else {
testResultsProvider.writeNonTestOutput(classId, destination, writer);
}
writer.endCDATA();
}
private void writeOutputs(SimpleXmlWriter writer, long classId, long testId, TestOutputEvent.Destination destination) throws IOException {
writer.startCDATA();
testResultsProvider.writeTestOutput(classId, testId, destination, writer);
writer.endCDATA();
}
private void writeTests(SimpleXmlWriter writer, Iterable<TestMethodResult> methodResults, String className, long classId) throws IOException {
for (TestMethodResult methodResult : methodResults) {
writer.startElement("testcase")
.attribute("name", methodResult.getName())
.attribute("classname", className)
.attribute("time", String.valueOf(methodResult.getDuration() / 1000.0));
if (methodResult.getResultType() == TestResult.ResultType.SKIPPED) {
writer.startElement("skipped");
writer.endElement();
} else {
for (TestFailure failure : methodResult.getFailures()) {
writer.startElement("failure")
.attribute("message", failure.getMessage())
.attribute("type", failure.getExceptionType());
writer.characters(failure.getStackTrace());
writer.endElement();
}
}
if (outputAssociation.equals(TestOutputAssociation.WITH_TESTCASE)) {
writer.startElement("system-out");
writeOutputs(writer, classId, methodResult.getId(), TestOutputEvent.Destination.StdOut);
writer.endElement();
writer.startElement("system-err");
writeOutputs(writer, classId, methodResult.getId(), TestOutputEvent.Destination.StdErr);
writer.endElement();
}
writer.endElement();
}
}
} | 5,477 | Java | .java | 107 | 40.813084 | 153 | 0.669221 | catofmrlu/Reer | 18 | 4 | 1 | GPL-3.0 | 9/4/2024, 8:20:57 PM (Europe/Amsterdam) | true | true | true | true | true | true | true | true | 5,477 |
3,389,796 | SessionInputBuffer.java | FzArnob_Covidease/sources/org/shaded/apache/http/p007io/SessionInputBuffer.java | package org.shaded.apache.http.p007io;
import java.io.IOException;
import org.shaded.apache.http.util.CharArrayBuffer;
/* renamed from: org.shaded.apache.http.io.SessionInputBuffer */
public interface SessionInputBuffer {
HttpTransportMetrics getMetrics();
boolean isDataAvailable(int i) throws IOException;
int read() throws IOException;
int read(byte[] bArr) throws IOException;
int read(byte[] bArr, int i, int i2) throws IOException;
int readLine(CharArrayBuffer charArrayBuffer) throws IOException;
String readLine() throws IOException;
}
| 580 | Java | .java | 13 | 40.846154 | 69 | 0.788909 | FzArnob/Covidease | 4 | 0 | 0 | GPL-3.0 | 9/4/2024, 11:17:41 PM (Europe/Amsterdam) | false | false | false | false | false | false | true | true | 580 |
2,659,032 | NodeTraversingQueryHits.java | exoplatform_jcr/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/NodeTraversingQueryHits.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.exoplatform.services.jcr.impl.core.query.lucene;
import org.apache.commons.collections.iterators.IteratorChain;
import org.exoplatform.services.jcr.datamodel.NodeData;
import org.exoplatform.services.jcr.impl.core.NodeImpl;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
/**
* <code>NodeTraversingQueryHits</code> implements query hits that traverse
* a node hierarchy.
*/
public class NodeTraversingQueryHits extends AbstractQueryHits
{
private static final Log LOG = ExoLogger.getLogger("exo.jcr.component.core.NodeTraversingQueryHits");
/**
* The nodes to traverse.
*/
private final Iterator<Node> nodes;
private IndexingConfiguration indexConfig;
/**
* Creates query hits that consist of the nodes that are traversed from a
* given <code>start</code> node.
*
* @param start the start node of the traversal.
* @param includeStart whether to include the start node in the result.
*/
public NodeTraversingQueryHits(Node start, boolean includeStart, IndexingConfiguration indexConfig) {
this(start, includeStart, Integer.MAX_VALUE, indexConfig);
}
/**
* Creates query hits that consist of the nodes that are traversed from a
* given <code>start</code> node.
*
* @param start the start node of the traversal.
* @param includeStart whether to include the start node in the result.
* @param maxDepth the maximum depth of nodes to traverse.
*/
public NodeTraversingQueryHits(Node start,
boolean includeStart,
int maxDepth,
IndexingConfiguration indexConfig) {
this.nodes = new TraversingNodeIterator(start, maxDepth);
this.indexConfig = indexConfig;
if (!includeStart) {
nodes.next();
}
}
/**
* {@inheritDoc}
*/
public ScoreNode nextScoreNode() throws IOException {
if (nodes.hasNext()) {
NodeImpl n = (NodeImpl) nodes.next();
return new ScoreNode(n.getData().getIdentifier(), 1.0f);
} else {
return null;
}
}
/**
* Implements a node iterator that traverses a node tree in document
* order.
*/
private class TraversingNodeIterator implements Iterator<Node> {
/**
* The current <code>Node</code>, which acts as the starting point for
* the traversal.
*/
private final Node currentNode;
/**
* The maximum depth of the traversal.
*/
private final int maxDepth;
/**
* The chain of iterators which includes the iterators of the children
* of the current node.
*/
private Iterator<Node> selfAndChildren;
/**
* Creates a <code>TraversingNodeIterator</code>.
*
* @param start the node from where to start the traversal.
* @param maxDepth the maximum depth of nodes to traverse.
*/
TraversingNodeIterator(Node start, int maxDepth) {
if (maxDepth < 0) {
throw new IllegalArgumentException("maxDepth must be >= 0");
}
currentNode = start;
this.maxDepth = maxDepth;
}
/**
* @exception UnsupportedOperationException always.
*/
public void remove() {
throw new UnsupportedOperationException("remove");
}
/**
* {@inheritDoc}
*/
public boolean hasNext() {
init();
return selfAndChildren.hasNext();
}
/**
* {@inheritDoc}
*/
public Node next() {
init();
NodeImpl n = (NodeImpl) selfAndChildren.next();
return n;
}
/**
* Initializes the iterator chain once.
*/
@SuppressWarnings("unchecked")
private void init()
{
if (selfAndChildren == null)
{
List<Iterator<Node>> allIterators = new ArrayList<Iterator<Node>>();
Iterator<Node> current = Collections.singletonList(currentNode).iterator();
allIterators.add(current);
if (maxDepth == 0)
{
// only current node
}
else if (maxDepth == 1)
{
try
{
allIterators.add(currentNode.getNodes());
}
catch (RepositoryException e)
{
if (LOG.isTraceEnabled())
{
LOG.trace("An exception occurred: " + e.getMessage());
}
}
}
else
{
// create new TraversingNodeIterator for each child
try
{
if (indexConfig == null || !indexConfig.isExcluded((NodeData)((NodeImpl)currentNode).getData()))
{
NodeIterator children = currentNode.getNodes();
while (children.hasNext())
{
NodeImpl node = (NodeImpl)children.nextNode();
if (indexConfig == null || !indexConfig.isExcluded((NodeData)node.getData()))
{
allIterators.add(new TraversingNodeIterator(node, maxDepth - 1));
}
}
}
}
catch (RepositoryException e)
{
if (LOG.isTraceEnabled())
{
LOG.trace("An exception occurred: " + e.getMessage());
}
}
}
selfAndChildren = new IteratorChain(allIterators);
}
}
}
}
| 6,990 | Java | .java | 194 | 26.046392 | 114 | 0.583493 | exoplatform/jcr | 6 | 20 | 1 | AGPL-3.0 | 9/4/2024, 10:01:50 PM (Europe/Amsterdam) | false | true | false | true | false | true | true | true | 6,990 |
1,128,261 | PropertyResourceBundle.java | nikita36078_phoneME-android/cdc/src/share/classes/java/util/PropertyResourceBundle.java | /*
*
* @(#)PropertyResourceBundle.java 1.25 06/10/10
*
* Portions Copyright 2000-2008 Sun Microsystems, Inc. All Rights
* Reserved. Use is subject to license terms.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 only, as published by the Free Software Foundation.
*
* This 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 for more details (a copy is
* included at /legal/license.txt).
*
* 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 Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 or visit www.sun.com if you need additional
* information or have any questions.
*/
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
*
* The original version of this source code and documentation
* is copyrighted and owned by Taligent, Inc., a wholly-owned
* subsidiary of IBM. These materials are provided under terms
* of a License Agreement between Taligent and Sun. This technology
* is protected by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*/
package java.util;
import java.io.InputStream;
import java.io.IOException;
/**
* <code>PropertyResourceBundle</code> is a concrete subclass of
* <code>ResourceBundle</code> that manages resources for a locale
* using a set of static strings from a property file. See
* {@link ResourceBundle ResourceBundle} for more information about resource
* bundles. See {@link Properties Properties} for more information
* about properties files, in particular the
* <a href="Properties.html#encoding">information on character encodings</a>.
*
* <p>
* Unlike other types of resource bundle, you don't subclass
* <code>PropertyResourceBundle</code>. Instead, you supply properties
* files containing the resource data. <code>ResourceBundle.getBundle</code>
* will automatically look for the appropriate properties file and create a
* <code>PropertyResourceBundle</code> that refers to it. See
* {@link ResourceBundle#getBundle(java.lang.String, java.util.Locale, java.lang.ClassLoader) ResourceBundle.getBundle}
* for a complete description of the search and instantiation strategy.
*
* <p>
* The following <a name="sample">example</a> shows a member of a resource
* bundle family with the base name "MyResources".
* The text defines the bundle "MyResources_de",
* the German member of the bundle family.
* This member is based on <code>PropertyResourceBundle</code>, and the text
* therefore is the content of the file "MyResources_de.properties"
* (a related <a href="ListResourceBundle.html#sample">example</a> shows
* how you can add bundles to this family that are implemented as subclasses
* of <code>ListResourceBundle</code>).
* The keys in this example are of the form "s1" etc. The actual
* keys are entirely up to your choice, so long as they are the same as
* the keys you use in your program to retrieve the objects from the bundle.
* Keys are case-sensitive.
* <blockquote>
* <pre>
* # MessageFormat pattern
* s1=Die Platte \"{1}\" enthält {0}.
*
* # location of {0} in pattern
* s2=1
*
* # sample disk name
* s3=Meine Platte
*
* # first ChoiceFormat choice
* s4=keine Dateien
*
* # second ChoiceFormat choice
* s5=eine Datei
*
* # third ChoiceFormat choice
* s6={0,number} Dateien
*
* # sample date
* s7=3. März 1996
* </pre>
* </blockquote>
*
* @see ResourceBundle
* @see ListResourceBundle
* @see Properties
* @since JDK1.1
*/
public class PropertyResourceBundle extends ResourceBundle {
/**
* Creates a property resource bundle.
* @param stream property file to read from.
*/
public PropertyResourceBundle (InputStream stream) throws IOException {
Properties properties = new Properties();
properties.load(stream);
lookup = new HashMap(properties);
}
// Implements java.util.ResourceBundle.handleGetObject; inherits javadoc specification.
public Object handleGetObject(String key) {
if (key == null) {
throw new NullPointerException();
}
return lookup.get(key);
}
/**
* Implementation of ResourceBundle.getKeys.
*/
public Enumeration getKeys() {
ResourceBundle parent = this.parent;
return new ResourceBundleEnumeration(lookup.keySet(),
(parent != null) ? parent.getKeys() : null);
}
// ==================privates====================
private Map lookup;
}
| 5,114 | Java | .java | 133 | 35.390977 | 119 | 0.730746 | nikita36078/phoneME-android | 40 | 16 | 1 | GPL-2.0 | 9/4/2024, 7:11:02 PM (Europe/Amsterdam) | false | true | false | true | false | true | true | true | 5,114 |
1,313,471 | TypeParametersCleanUp.java | eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/TypeParametersCleanUp.java | /*******************************************************************************
* Copyright (c) 2014, 2016 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.internal.ui.fix;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.internal.corext.fix.CleanUpConstants;
import org.eclipse.jdt.internal.corext.fix.TypeParametersFixCore;
import org.eclipse.jdt.ui.cleanup.CleanUpRequirements;
import org.eclipse.jdt.ui.cleanup.ICleanUpFix;
import org.eclipse.jdt.ui.text.java.IProblemLocation;
public class TypeParametersCleanUp extends AbstractMultiFix {
private Map<String, String> fOptions;
public TypeParametersCleanUp(Map<String, String> options) {
super(options);
fOptions= options;
}
public TypeParametersCleanUp() {
super();
}
@Override
public CleanUpRequirements getRequirements() {
boolean requireAST= isEnabled(CleanUpConstants.INSERT_INFERRED_TYPE_ARGUMENTS) || isEnabled(CleanUpConstants.REMOVE_REDUNDANT_TYPE_ARGUMENTS);
Map<String, String> requiredOptions= requireAST ? getRequiredOptions() : null;
return new CleanUpRequirements(requireAST, false, false, requiredOptions);
}
private Map<String, String> getRequiredOptions() {
Map<String, String> result= new Hashtable<>();
if (isEnabled(CleanUpConstants.REMOVE_REDUNDANT_TYPE_ARGUMENTS))
result.put(JavaCore.COMPILER_PB_REDUNDANT_TYPE_ARGUMENTS, JavaCore.WARNING);
return result;
}
@Override
protected ICleanUpFix createFix(CompilationUnit compilationUnit) throws CoreException {
if (compilationUnit == null)
return null;
return TypeParametersFixCore.createCleanUp(compilationUnit,
isEnabled(CleanUpConstants.INSERT_INFERRED_TYPE_ARGUMENTS),
isEnabled(CleanUpConstants.REMOVE_REDUNDANT_TYPE_ARGUMENTS));
}
@Override
protected ICleanUpFix createFix(CompilationUnit compilationUnit, IProblemLocation[] problems) throws CoreException {
if (compilationUnit == null)
return null;
return TypeParametersFixCore.createCleanUp(compilationUnit, problems,
isEnabled(CleanUpConstants.INSERT_INFERRED_TYPE_ARGUMENTS),
isEnabled(CleanUpConstants.REMOVE_REDUNDANT_TYPE_ARGUMENTS));
}
@Override
public String[] getStepDescriptions() {
List<String> result= new ArrayList<>();
if (isEnabled(CleanUpConstants.INSERT_INFERRED_TYPE_ARGUMENTS)) {
result.add(MultiFixMessages.TypeParametersCleanUp_InsertInferredTypeArguments_description);
} else if (isEnabled(CleanUpConstants.REMOVE_REDUNDANT_TYPE_ARGUMENTS)) {
result.add(MultiFixMessages.TypeParametersCleanUp_RemoveUnnecessaryTypeArguments_description);
}
return result.toArray(new String[result.size()]);
}
@Override
public boolean canFix(ICompilationUnit compilationUnit, IProblemLocation problem) {
int problemId= problem.getProblemId();
if (problemId == IProblem.RedundantSpecificationOfTypeArguments)
return isEnabled(CleanUpConstants.REMOVE_REDUNDANT_TYPE_ARGUMENTS);
if (problemId == IProblem.DiamondNotBelow17)
return isEnabled(CleanUpConstants.INSERT_INFERRED_TYPE_ARGUMENTS);
return false;
}
@Override
public int computeNumberOfFixes(CompilationUnit compilationUnit) {
if (fOptions == null)
return 0;
int result= 0;
IProblem[] problems= compilationUnit.getProblems();
if (isEnabled(CleanUpConstants.REMOVE_REDUNDANT_TYPE_ARGUMENTS))
result= getNumberOfProblems(problems, IProblem.RedundantSpecificationOfTypeArguments);
else if (isEnabled(CleanUpConstants.INSERT_INFERRED_TYPE_ARGUMENTS))
result= getNumberOfProblems(problems, IProblem.DiamondNotBelow17);
return result;
}
@Override
public String getPreview() {
if (isEnabled(CleanUpConstants.REMOVE_REDUNDANT_TYPE_ARGUMENTS)) {
return "Map<Integer, String> map= new HashMap<>();\n"; //$NON-NLS-1$
}
return "Map<Integer, String> map= new HashMap<Integer, String>();\n"; //$NON-NLS-1$
}
}
| 4,524 | Java | .java | 104 | 40.788462 | 144 | 0.778056 | eclipse-jdt/eclipse.jdt.ui | 35 | 86 | 242 | EPL-2.0 | 9/4/2024, 7:34:16 PM (Europe/Amsterdam) | false | false | false | false | false | true | true | true | 4,524 |
3,851,916 | SubSystemOne.java | cq2021-coder_design-patterns/facade-pattern-stock/src/com/cq/example/sun/SubSystemOne.java | package com.cq.example.sun;
/**
* 子系统一
*
* @author 程崎
* @version 1.0.0
* @since 2022/06/12
*/
public class SubSystemOne {
public void methodOne() {
System.out.println("子系统一方法");
}
}
| 229 | Java | .java | 13 | 13 | 37 | 0.633508 | cq2021-coder/design-patterns | 3 | 0 | 0 | GPL-3.0 | 9/4/2024, 11:45:33 PM (Europe/Amsterdam) | false | false | false | false | false | false | true | true | 205 |
4,570,935 | OAuth2AuthorizationServer.java | AcornPublishing_oauth-2-cookbook/Chapter02/rdbm-server/src/main/java/com/packt/example/rdbmserver/config/OAuth2AuthorizationServer.java | package com.packt.example.rdbmserver.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.JdbcApprovalStore;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import javax.sql.DataSource;
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends
AuthorizationServerConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Bean
public ApprovalStore approvalStore() {
return new JdbcApprovalStore(dataSource);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
//@formatter:off
endpoints
.approvalStore(approvalStore())
.tokenStore(tokenStore());
//@formatter:on
}
@Override
public void configure(ClientDetailsServiceConfigurer clients)
throws Exception {
clients.jdbc(dataSource);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
// the size can be between 4 to 31
return new BCryptPasswordEncoder(4);
}
public static void main(String[] args) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(4);
String clientId = "clientapp";
String clientSecret = "123456";
clientSecret = encoder.encode(clientSecret);
System.out.println(clientId);
System.out.println(clientSecret);
}
}
| 2,713 | Java | .java | 62 | 38.83871 | 116 | 0.8 | AcornPublishing/oauth-2-cookbook | 2 | 0 | 0 | GPL-3.0 | 9/5/2024, 12:17:49 AM (Europe/Amsterdam) | false | false | false | true | true | false | true | true | 2,713 |
4,286,105 | CurrencyNames_ar_AE.java | techsaint_ikvm_openjdk/build/linux-x86_64-normal-server-release/jdk/gensrc/sun/util/resources/ar/CurrencyNames_ar_AE.java | package sun.util.resources.ar;
import java.util.ListResourceBundle;
public final class CurrencyNames_ar_AE extends sun.util.resources.LocaleNamesBundle {
protected final Object[][] getContents() {
return new Object[][] {
{ "AED", "\u062F.\u0625.\u200F" },
};
}
}
| 301 | Java | .java | 9 | 28.222222 | 85 | 0.668966 | techsaint/ikvm_openjdk | 2 | 1 | 0 | GPL-2.0 | 9/5/2024, 12:07:57 AM (Europe/Amsterdam) | false | false | false | false | true | true | true | true | 301 |
2,877,349 | SampleService.java | windup_windup-eclipse-plugin/tests/org.jboss.tools.windup.ui.tests/projects/demo/src/org/windup/examples/migration/SampleService.java | package org.windup.examples.migration;
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("/sampleservice")
public class SampleServlet implements HttpServlet
{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
// noop
}
} | 578 | Java | .java | 17 | 31.058824 | 111 | 0.821942 | windup/windup-eclipse-plugin | 5 | 30 | 1 | EPL-2.0 | 9/4/2024, 10:31:27 PM (Europe/Amsterdam) | false | true | false | false | false | true | true | true | 578 |
4,496,587 | Mymain.java | omoghaoghenemano_cinema-admin/Mymain.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cinemamovies;
/**
*
* @author manoo
*/
public class Mymain {
public static void main(String[] args){
login1 a1 = new login1();
a1.setVisible(true);
}
}
| 397 | Java | .java | 16 | 20.375 | 80 | 0.662198 | omoghaoghenemano/cinema-admin | 2 | 0 | 0 | GPL-3.0 | 9/5/2024, 12:15:04 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 397 |
1,314,245 | MouseScrollTextEditorTest.java | eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/performance/MouseScrollTextEditorTest.java | /*******************************************************************************
* Copyright (c) 2000, 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.text.tests.performance;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.core.runtime.CoreException;
public class MouseScrollTextEditorTest extends MouseScrollEditorTest {
private static final Class<MouseScrollTextEditorTest> THIS= MouseScrollTextEditorTest.class;
private static final String THUMB_SCROLLING_FILE_PREFIX= "/org.eclipse.swt/Eclipse SWT Custom Widgets/common/org/eclipse/swt/custom/StyledText";
private static final String THUMB_SCROLLING_ORIG_FILE= THUMB_SCROLLING_FILE_PREFIX + ".java";
private static final String THUMB_SCROLLING_FILE= THUMB_SCROLLING_FILE_PREFIX + ".txt";
private static final String AUTO_SCROLLING_FILE_PREFIX= "/org.eclipse.swt/Eclipse SWT/win32/org/eclipse/swt/graphics/TextLayout";
private static final String AUTO_SCROLLING_ORIG_FILE= AUTO_SCROLLING_FILE_PREFIX + ".java";
private static final String AUTO_SCROLLING_FILE= AUTO_SCROLLING_FILE_PREFIX + ".txt";
private static final int WARM_UP_RUNS= 3;
private static final int MEASURED_RUNS= 3;
public static Test suite() {
return new PerformanceTestSetup(new TestSuite(THIS));
}
@Override
protected void setUp() throws Exception {
super.setUp();
setWarmUpRuns(WARM_UP_RUNS);
setMeasuredRuns(MEASURED_RUNS);
}
public void testThumbScrollTextEditor1() throws CoreException {
try {
ResourceTestHelper.copy(THUMB_SCROLLING_ORIG_FILE, THUMB_SCROLLING_FILE);
measureScrolling(new ThumbScrollPoster(), ResourceTestHelper.findFile(THUMB_SCROLLING_FILE));
} finally {
ResourceTestHelper.delete(THUMB_SCROLLING_FILE);
}
}
public void testAutoScrollTextEditor1() throws CoreException {
try {
ResourceTestHelper.copy(AUTO_SCROLLING_ORIG_FILE, AUTO_SCROLLING_FILE);
measureScrolling(new AutoScrollPoster(), ResourceTestHelper.findFile(AUTO_SCROLLING_FILE));
} finally {
ResourceTestHelper.delete(AUTO_SCROLLING_FILE);
}
}
}
| 2,490 | Java | .java | 53 | 44.377358 | 145 | 0.744215 | 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 | 2,490 |
4,661,385 | DataSharingPageView.java | xxmustafacooTR_KernelManager/app/src/main/java/com/xxmustafacooTR/kernelmanager/views/recyclerview/datasharing/DataSharingPageView.java | /*
* Copyright (C) 2017 Willi Ye <williye97@gmail.com>
*
* This file is part of Kernel Adiutor.
*
* Kernel Adiutor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Kernel Adiutor 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 Kernel Adiutor. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.xxmustafacooTR.kernelmanager.views.recyclerview.datasharing;
import android.view.View;
import android.widget.TextView;
import com.xxmustafacooTR.kernelmanager.R;
import com.xxmustafacooTR.kernelmanager.views.recyclerview.RecyclerViewItem;
/**
* Created by willi on 22.09.17.
*/
public class DataSharingPageView extends RecyclerViewItem {
public interface DataSharingPageListener {
void onPrevious();
void onNext();
}
private View mPrevious;
private View mNext;
private TextView mPageText;
private boolean mShowPrevious;
private boolean mShowNext;
private int mPage;
private DataSharingPageListener mDataSharingPageListener;
@Override
public int getLayoutRes() {
return R.layout.rv_datasharing_page;
}
@Override
public void onCreateView(View view) {
mPrevious = view.findViewById(R.id.previous_btn);
mNext = view.findViewById(R.id.next_btn);
mPageText = view.findViewById(R.id.page);
mPrevious.setOnClickListener(view1 -> mDataSharingPageListener.onPrevious());
mNext.setOnClickListener(view12 -> mDataSharingPageListener.onNext());
setFullSpan(true);
super.onCreateView(view);
setup();
}
private void setup() {
if (mPrevious != null) {
mPrevious.setVisibility(mShowPrevious ? View.VISIBLE : View.INVISIBLE);
}
if (mNext != null) {
mNext.setVisibility(mShowNext ? View.VISIBLE : View.INVISIBLE);
}
if (mPageText != null) {
mPageText.setText(mPageText.getContext().getString(R.string.page) + " " + mPage);
}
}
public void setDataSharingPageListener(DataSharingPageListener dataSharingListener) {
mDataSharingPageListener = dataSharingListener;
}
public void showPrevious(boolean show) {
mShowPrevious = show;
setup();
}
public void showNext(boolean show) {
mShowNext = show;
setup();
}
public void setPage(int page) {
mPage = page;
setup();
}
}
| 2,866 | Java | .java | 81 | 29.839506 | 93 | 0.704159 | xxmustafacooTR/KernelManager | 2 | 1 | 1 | GPL-3.0 | 9/5/2024, 12:20:38 AM (Europe/Amsterdam) | false | false | false | false | false | true | false | true | 2,866 |
432,462 | package-info.java | SonarSource_sonarlint-core/rpc-protocol/src/main/java/org/sonarsource/sonarlint/core/rpc/protocol/backend/binding/package-info.java | /*
* SonarLint Core - RPC Protocol
* Copyright (C) 2016-2024 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonarsource.sonarlint.core.rpc.protocol.backend.binding;
import javax.annotation.ParametersAreNonnullByDefault;
| 1,020 | Java | .java | 22 | 44.454545 | 75 | 0.786145 | SonarSource/sonarlint-core | 225 | 51 | 11 | LGPL-3.0 | 9/4/2024, 7:07:11 PM (Europe/Amsterdam) | false | false | false | false | false | true | true | true | 1,020 |
4,242,651 | FlyMove.java | rubenswagner_L2J-Global/dist/game/data/scripts/handlers/effecthandlers/FlyMove.java | /*
* This file is part of the L2J Global project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package handlers.effecthandlers;
import com.l2jglobal.gameserver.GeoData;
import com.l2jglobal.gameserver.model.Location;
import com.l2jglobal.gameserver.model.StatsSet;
import com.l2jglobal.gameserver.model.actor.L2Character;
import com.l2jglobal.gameserver.model.effects.AbstractEffect;
import com.l2jglobal.gameserver.model.items.instance.L2ItemInstance;
import com.l2jglobal.gameserver.model.skills.Skill;
import com.l2jglobal.gameserver.network.serverpackets.FlyToLocation;
import com.l2jglobal.gameserver.network.serverpackets.FlyToLocation.FlyType;
import com.l2jglobal.gameserver.util.Util;
/**
* @author Nos
*/
public class FlyMove extends AbstractEffect
{
private final FlyType _flyType;
private final int _angle;
private final boolean _absoluteAngle; // Use map angle instead of character angle.
private final int _range;
private final boolean _selfPos; // Use the position and heading of yourself to move in the given range
private final int _speed;
private final int _delay;
private final int _animationSpeed;
public FlyMove(StatsSet params)
{
_flyType = params.getEnum("flyType", FlyType.class, FlyType.DUMMY);
_angle = params.getInt("angle", 0);
_absoluteAngle = params.getBoolean("absoluteAngle", false);
_range = params.getInt("range", 20);
_selfPos = params.getBoolean("selfPos", false);
_speed = params.getInt("speed", 0);
_delay = params.getInt("delay", 0);
_animationSpeed = params.getInt("animationSpeed", 0);
}
@Override
public void instant(L2Character effector, L2Character effected, Skill skill, L2ItemInstance item)
{
final L2Character target = _selfPos ? effector : effected;
// Avoid calculating heading towards yourself because it always yields 0. Same results can be achieved with absoluteAngle of 0.
final int heading = (_selfPos || (effector == effected)) ? effector.getHeading() : Util.calculateHeadingFrom(effector, effected);
double angle = _absoluteAngle ? _angle : Util.convertHeadingToDegree(heading);
angle = (angle + _angle) % 360;
if (angle < 0)
{
angle += 360;
}
final double radiansAngle = Math.toRadians(angle);
final int posX = (int) (target.getX() + (_range * Math.cos(radiansAngle)));
final int posY = (int) (target.getY() + (_range * Math.sin(radiansAngle)));
final int posZ = target.getZ();
final Location destination = GeoData.getInstance().moveCheck(effector.getX(), effector.getY(), effector.getZ(), posX, posY, posZ, effector.getInstanceWorld());
effector.broadcastPacket(new FlyToLocation(effector, destination, _flyType, _speed, _delay, _animationSpeed));
effector.setXYZ(destination);
effected.revalidateZone(true);
}
@Override
public boolean isInstant()
{
return true;
}
}
| 3,426 | Java | .java | 78 | 41.525641 | 161 | 0.768238 | rubenswagner/L2J-Global | 2 | 4 | 0 | GPL-3.0 | 9/5/2024, 12:07:03 AM (Europe/Amsterdam) | false | false | true | false | false | true | false | true | 3,426 |
433,937 | CUnitTypeJass.java | Retera_WarsmashModEngine/core/src/com/etheller/warsmash/viewer5/handlers/w3x/simulation/unit/CUnitTypeJass.java | package com.etheller.warsmash.viewer5.handlers.w3x.simulation.unit;
import com.etheller.interpreter.ast.util.CHandle;
public enum CUnitTypeJass implements CHandle {
HERO,
DEAD,
STRUCTURE,
FLYING,
GROUND,
ATTACKS_FLYING,
ATTACKS_GROUND,
MELEE_ATTACKER,
RANGED_ATTACKER,
GIANT,
SUMMONED,
STUNNED,
PLAGUED,
SNARED,
UNDEAD,
MECHANICAL,
PEON,
SAPPER,
TOWNHALL,
ANCIENT,
TAUREN,
POISONED,
POLYMORPHED,
SLEEPING,
RESISTANT,
ETHEREAL,
MAGIC_IMMUNE;
public static CUnitTypeJass[] VALUES = values();
@Override
public int getHandleId() {
return ordinal();
}
}
| 592 | Java | .java | 36 | 14.25 | 67 | 0.796703 | Retera/WarsmashModEngine | 224 | 39 | 25 | AGPL-3.0 | 9/4/2024, 7:07:11 PM (Europe/Amsterdam) | false | false | false | true | false | false | true | true | 592 |
2,534,043 | RestClient.java | islem19_Github-Trending-Repos-Android-App/app/src/main/java/dz/islem/githubapi/data/remote/rest/RestClient.java | package dz.islem.githubapi.data.remote.rest;
import dz.islem.githubapi.utils.Constants;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
public class RestClient {
private static Retrofit getRetroInstance(){
return new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
public static RestApi getApiService(){
return getRetroInstance().create(RestApi.class);
}
}
| 673 | Java | .java | 17 | 32.705882 | 74 | 0.731595 | islem19/Github-Trending-Repos-Android-App | 7 | 1 | 0 | GPL-3.0 | 9/4/2024, 9:47:15 PM (Europe/Amsterdam) | false | true | false | false | false | true | true | true | 673 |
2,069,894 | GenTableServiceImpl.java | Link-WeChat_link-wechat/linkwe-generator/src/main/java/com/linkwechat/generator/service/GenTableServiceImpl.java | package com.linkwechat.generator.service;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.linkwechat.common.constant.Constants;
import com.linkwechat.common.constant.GenConstants;
import com.linkwechat.common.core.text.CharsetKit;
import com.linkwechat.common.exception.CustomException;
import com.linkwechat.common.utils.SecurityUtils;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.common.utils.file.FileUtils;
import com.linkwechat.generator.domain.GenTable;
import com.linkwechat.generator.domain.GenTableColumn;
import com.linkwechat.generator.mapper.GenTableColumnMapper;
import com.linkwechat.generator.mapper.GenTableMapper;
import com.linkwechat.generator.util.GenUtils;
import com.linkwechat.generator.util.VelocityInitializer;
import com.linkwechat.generator.util.VelocityUtils;
/**
* 业务 服务层实现
*
* @author ruoyi
*/
@Service
public class GenTableServiceImpl implements IGenTableService
{
private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class);
@Autowired
private GenTableMapper genTableMapper;
@Autowired
private GenTableColumnMapper genTableColumnMapper;
/**
* 查询业务信息
*
* @param id 业务ID
* @return 业务信息
*/
@Override
public GenTable selectGenTableById(Long id)
{
GenTable genTable = genTableMapper.selectGenTableById(id);
setTableFromOptions(genTable);
return genTable;
}
/**
* 查询业务列表
*
* @param genTable 业务信息
* @return 业务集合
*/
@Override
public List<GenTable> selectGenTableList(GenTable genTable)
{
return genTableMapper.selectGenTableList(genTable);
}
/**
* 查询据库列表
*
* @param genTable 业务信息
* @return 数据库表集合
*/
@Override
public List<GenTable> selectDbTableList(GenTable genTable)
{
return genTableMapper.selectDbTableList(genTable);
}
/**
* 查询据库列表
*
* @param tableNames 表名称组
* @return 数据库表集合
*/
@Override
public List<GenTable> selectDbTableListByNames(String[] tableNames)
{
return genTableMapper.selectDbTableListByNames(tableNames);
}
/**
* 修改业务
*
* @param genTable 业务信息
* @return 结果
*/
@Override
@Transactional
public void updateGenTable(GenTable genTable)
{
String options = JSON.toJSONString(genTable.getParams());
genTable.setOptions(options);
int row = genTableMapper.updateGenTable(genTable);
if (row > 0)
{
for (GenTableColumn cenTableColumn : genTable.getColumns())
{
genTableColumnMapper.updateGenTableColumn(cenTableColumn);
}
}
}
/**
* 删除业务对象
*
* @param tableIds 需要删除的数据ID
* @return 结果
*/
@Override
@Transactional
public void deleteGenTableByIds(Long[] tableIds)
{
genTableMapper.deleteGenTableByIds(tableIds);
genTableColumnMapper.deleteGenTableColumnByIds(tableIds);
}
/**
* 导入表结构
*
* @param tableList 导入表列表
*/
@Override
@Transactional
public void importGenTable(List<GenTable> tableList)
{
String operName = SecurityUtils.getUsername();
try
{
for (GenTable table : tableList)
{
String tableName = table.getTableName();
GenUtils.initTable(table, operName);
int row = genTableMapper.insertGenTable(table);
if (row > 0)
{
// 保存列信息
List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
for (GenTableColumn column : genTableColumns)
{
GenUtils.initColumnField(column, table);
genTableColumnMapper.insertGenTableColumn(column);
}
}
}
}
catch (Exception e)
{
throw new CustomException("导入失败:" + e.getMessage());
}
}
/**
* 预览代码
*
* @param tableId 表编号
* @return 预览数据列表
*/
@Override
public Map<String, String> previewCode(Long tableId)
{
Map<String, String> dataMap = new LinkedHashMap<>();
// 查询表信息
GenTable table = genTableMapper.selectGenTableById(tableId);
// 查询列信息
List<GenTableColumn> columns = table.getColumns();
setPkColumn(table, columns);
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates)
{
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
dataMap.put(template, sw.toString());
}
return dataMap;
}
/**
* 生成代码(下载方式)
*
* @param tableName 表名称
* @return 数据
*/
@Override
public byte[] downloadCode(String tableName)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
generatorCode(tableName, zip);
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}
/**
* 生成代码(自定义路径)
*
* @param tableName 表名称
* @return 数据
*/
@Override
public void generatorCode(String tableName)
{
// 查询表信息
GenTable table = genTableMapper.selectGenTableByName(tableName);
// 查询列信息
List<GenTableColumn> columns = table.getColumns();
setPkColumn(table, columns);
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates)
{
if (!StringUtils.containsAny(template, "sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm"))
{
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
try
{
String path = getGenPath(table, template);
FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
}
catch (IOException e)
{
throw new CustomException("渲染模板失败,表名:" + table.getTableName());
}
}
}
}
/**
* 批量生成代码(下载方式)
*
* @param tableNames 表数组
* @return 数据
*/
@Override
public byte[] downloadCode(String[] tableNames)
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
for (String tableName : tableNames)
{
generatorCode(tableName, zip);
}
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}
/**
* 查询表信息并生成代码
*/
private void generatorCode(String tableName, ZipOutputStream zip)
{
// 查询表信息
GenTable table = genTableMapper.selectGenTableByName(tableName);
// 查询列信息
List<GenTableColumn> columns = table.getColumns();
setPkColumn(table, columns);
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates)
{
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
try
{
// 添加到zip
zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
IOUtils.write(sw.toString(), zip, Constants.UTF8);
IOUtils.closeQuietly(sw);
zip.flush();
zip.closeEntry();
}
catch (IOException e)
{
log.error("渲染模板失败,表名:" + table.getTableName(), e);
}
}
}
/**
* 修改保存参数校验
*
* @param genTable 业务信息
*/
@Override
public void validateEdit(GenTable genTable)
{
if (GenConstants.TPL_TREE.equals(genTable.getTplCategory()))
{
String options = JSON.toJSONString(genTable.getParams());
JSONObject paramsObj = JSONObject.parseObject(options);
if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE)))
{
throw new CustomException("树编码字段不能为空");
}
else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE)))
{
throw new CustomException("树父编码字段不能为空");
}
else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME)))
{
throw new CustomException("树名称字段不能为空");
}
}
}
/**
* 设置主键列信息
*
* @param table 业务表信息
* @param columns 业务字段列表
*/
public void setPkColumn(GenTable table, List<GenTableColumn> columns)
{
for (GenTableColumn column : columns)
{
if (column.isPk())
{
table.setPkColumn(column);
break;
}
}
if (StringUtils.isNull(table.getPkColumn()))
{
table.setPkColumn(columns.get(0));
}
}
/**
* 设置代码生成其他选项值
*
* @param genTable 设置后的生成对象
*/
public void setTableFromOptions(GenTable genTable)
{
JSONObject paramsObj = JSONObject.parseObject(genTable.getOptions());
if (StringUtils.isNotNull(paramsObj))
{
String treeCode = paramsObj.getString(GenConstants.TREE_CODE);
String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE);
String treeName = paramsObj.getString(GenConstants.TREE_NAME);
String parentMenuId = paramsObj.getString(GenConstants.PARENT_MENU_ID);
String parentMenuName = paramsObj.getString(GenConstants.PARENT_MENU_NAME);
genTable.setTreeCode(treeCode);
genTable.setTreeParentCode(treeParentCode);
genTable.setTreeName(treeName);
genTable.setParentMenuId(parentMenuId);
genTable.setParentMenuName(parentMenuName);
}
}
/**
* 获取代码生成地址
*
* @param table 业务表信息
* @param template 模板文件路径
* @return 生成地址
*/
public static String getGenPath(GenTable table, String template)
{
String genPath = table.getGenPath();
if (StringUtils.equals(genPath, "/"))
{
return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
}
return genPath + File.separator + VelocityUtils.getFileName(template, table);
}
} | 12,888 | Java | .java | 383 | 23.524804 | 137 | 0.627503 | Link-WeChat/link-wechat | 16 | 7 | 0 | GPL-3.0 | 9/4/2024, 8:28:22 PM (Europe/Amsterdam) | false | false | false | false | false | false | true | true | 12,160 |
1,010,208 | DailyScheduler.java | Multitallented_Civs/src/main/java/org/redcastlemedia/multitallented/civs/scheduler/DailyScheduler.java | package org.redcastlemedia.multitallented.civs.scheduler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.redcastlemedia.multitallented.civs.Civs;
import org.redcastlemedia.multitallented.civs.ConfigManager;
import org.redcastlemedia.multitallented.civs.items.ItemManager;
import org.redcastlemedia.multitallented.civs.regions.Region;
import org.redcastlemedia.multitallented.civs.regions.RegionManager;
import org.redcastlemedia.multitallented.civs.regions.RegionType;
import org.redcastlemedia.multitallented.civs.towns.*;
import org.redcastlemedia.multitallented.civs.util.Constants;
public class DailyScheduler implements Runnable {
@Override
public void run() {
RegionManager regionManager = RegionManager.getInstance();
for (Region region : regionManager.getAllRegions()) {
RegionType regionType = (RegionType) ItemManager.getInstance().getItemType(region.getType());
if (regionType.isDailyPeriod()) {
region.runUpkeep(false);
}
}
doTaxes();
doVotes();
addDailyPower();
TownTransitionUtil.checkTownTransitions();
}
private void addDailyPower() {
HashMap<Town, Integer> addPower = new HashMap<>();
for (Town town : TownManager.getInstance().getTowns()) {
town.setGovTypeChangedToday(false);
TownType townType = (TownType) ItemManager.getInstance().getItemType(town.getType());
Government government = GovernmentManager.getInstance().getGovernment(town.getGovernmentType());
if (government != null) {
for (GovTypeBuff buff : government.getBuffs()) {
if (buff.getBuffType() == GovTypeBuff.BuffType.POWER) {
addPower.put(town, (int) Math.round((double) townType.getPower() * (1 + (double) buff.getAmount() / 100)));
break;
}
}
}
if (!addPower.containsKey(town)) {
addPower.put(town, townType.getPower());
}
}
for (Town town : addPower.keySet()) {
TownManager.getInstance().setTownPower(town, town.getPower() + addPower.get(town));
}
}
private void doVotes() {
HashSet<Town> saveTheseTowns = new HashSet<>();
for (Town town : TownManager.getInstance().getTowns()) {
if (town.getVotes().isEmpty()) {
continue;
}
Government government = GovernmentManager.getInstance().getGovernment(town.getGovernmentType());
if (government.getGovernmentType() != GovernmentType.DEMOCRACY &&
government.getGovernmentType() != GovernmentType.DEMOCRATIC_SOCIALISM &&
government.getGovernmentType() != GovernmentType.COOPERATIVE &&
government.getGovernmentType() != GovernmentType.CAPITALISM) {
continue;
}
long daysBetweenVotes = ConfigManager.getInstance().getDaysBetweenVotes() * 86400000;
if (town.getLastVote() > System.currentTimeMillis() - daysBetweenVotes) {
continue;
}
HashMap<UUID, Integer> voteTally = new HashMap<>();
for (UUID uuid : town.getVotes().keySet()) {
for (UUID cUuid : town.getVotes().get(uuid).keySet()) {
if (voteTally.containsKey(cUuid)) {
voteTally.put(cUuid, voteTally.get(cUuid) + town.getVotes().get(uuid).get(cUuid));
} else {
voteTally.put(cUuid, town.getVotes().get(uuid).get(cUuid));
}
}
}
ArrayList<UUID> mostVotesList = new ArrayList<>();
int mostVoteCount = 0;
for (UUID uuid : voteTally.keySet()) {
if (mostVoteCount < voteTally.get(uuid)) {
mostVotesList.clear();
mostVotesList.add(uuid);
mostVoteCount = voteTally.get(uuid);
} else if (mostVoteCount == voteTally.get(uuid)) {
mostVotesList.add(uuid);
}
}
if (mostVotesList.isEmpty()) {
town.setVotes(new HashMap<>());
saveTheseTowns.add(town);
continue;
}
UUID mostVotes;
if (mostVotesList.size() == 1) {
mostVotes = mostVotesList.get(0);
} else {
Random random = new Random();
int randIndex = random.nextInt(mostVotesList.size());
mostVotes = mostVotesList.get(randIndex);
}
if (town.getRawPeople().containsKey(mostVotes) &&
!town.getRawPeople().get(mostVotes).contains(Constants.OWNER)) {
HashSet<UUID> setMembers = new HashSet<>();
for (UUID uuid : town.getRawPeople().keySet()) {
if (town.getRawPeople().get(uuid).contains(Constants.OWNER)) {
setMembers.add(uuid);
}
}
for (UUID uuid : setMembers) {
town.setPeople(uuid, "member");
}
town.setPeople(mostVotes, Constants.OWNER);
}
town.setVotes(new HashMap<>());
saveTheseTowns.add(town);
}
for (Town town : saveTheseTowns) {
TownManager.getInstance().saveTown(town);
}
}
private void doTaxes() {
if (Civs.econ == null) {
return;
}
HashSet<Town> saveThese = new HashSet<>();
for (Town town : TownManager.getInstance().getTowns()) {
if (town.getTaxes() < 1) {
continue;
}
for (UUID uuid : town.getRawPeople().keySet()) {
if (town.getRawPeople().get(uuid).contains("ally")) {
continue;
}
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(uuid);
if (offlinePlayer == null || !Civs.econ.has(offlinePlayer, town.getTaxes())) {
continue;
}
Civs.econ.withdrawPlayer(offlinePlayer, town.getTaxes());
town.setBankAccount(town.getBankAccount() + town.getTaxes());
saveThese.add(town);
}
}
for (Town town : saveThese) {
TownManager.getInstance().saveTown(town);
}
}
}
| 6,716 | Java | .java | 151 | 31.688742 | 131 | 0.5689 | Multitallented/Civs | 51 | 31 | 47 | GPL-3.0 | 9/4/2024, 7:10:22 PM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 6,716 |
3,030,326 | AirshipDockHolder.java | Hl4p3x_L2Scripts_H5_2268/gameserver/src/main/java/l2s/gameserver/data/xml/holder/AirshipDockHolder.java | package l2s.gameserver.data.xml.holder;
import gnu.trove.map.hash.TIntObjectHashMap;
import l2s.commons.data.xml.AbstractHolder;
import l2s.gameserver.templates.AirshipDock;
/**
* @author: VISTALL
* @date: 10:44/14.12.2010
*/
public final class AirshipDockHolder extends AbstractHolder
{
private static final AirshipDockHolder _instance = new AirshipDockHolder();
private TIntObjectHashMap<AirshipDock> _docks = new TIntObjectHashMap<AirshipDock>(4);
public static AirshipDockHolder getInstance()
{
return _instance;
}
public void addDock(AirshipDock dock)
{
_docks.put(dock.getId(), dock);
}
public AirshipDock getDock(int dock)
{
return _docks.get(dock);
}
@Override
public int size()
{
return _docks.size();
}
@Override
public void clear()
{
_docks.clear();
}
}
| 806 | Java | .java | 35 | 20.885714 | 87 | 0.773263 | Hl4p3x/L2Scripts_H5_2268 | 5 | 6 | 0 | GPL-3.0 | 9/4/2024, 10:43:16 PM (Europe/Amsterdam) | false | false | true | true | false | true | true | true | 806 |
5,054,447 | ForumLastPostModel_.java | judgels_raguel/app/org/iatoki/judgels/raguel/forum/ForumLastPostModel_.java | package org.iatoki.judgels.raguel.forum;
import org.iatoki.judgels.play.model.AbstractModel_;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(ForumLastPostModel.class)
public abstract class ForumLastPostModel_ extends AbstractModel_ {
public static volatile SingularAttribute<ForumLastPostModel, Long> id;
public static volatile SingularAttribute<ForumLastPostModel, String> forumJid;
}
| 579 | Java | .java | 11 | 51.090909 | 79 | 0.870567 | judgels/raguel | 1 | 0 | 0 | GPL-2.0 | 9/5/2024, 12:39:56 AM (Europe/Amsterdam) | false | false | true | false | false | true | false | true | 579 |
196,192 | AbstractQueryBlackListHandler.java | mahonelau_-kykms/jeecg-boot/jeecg-boot-base/jeecg-boot-base-core/src/main/java/org/jeecg/common/util/security/AbstractQueryBlackListHandler.java | package org.jeecg.common.util.security;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 查询表/字段 黑名单处理
* @Author taoYan
* @Date 2022/3/17 11:21
**/
@Slf4j
public abstract class AbstractQueryBlackListHandler {
/**
* key-表名
* value-字段名,多个逗号隔开
* 两种配置方式-- 全部配置成小写
* ruleMap.put("sys_user", "*")sys_user所有的字段不支持查询
* ruleMap.put("sys_user", "username,password")sys_user中的username和password不支持查询
*/
public static Map<String, String> ruleMap = new HashMap<>();
/**
* 以下字符不能出现在表名中或是字段名中
*/
public static final Pattern ILLEGAL_NAME_REG = Pattern.compile("[-]{2,}");
static {
ruleMap.put("sys_user", "password,salt");
}
/**
* 根据 sql语句 获取表和字段信息,需要到具体的实现类重写此方法-
* 不同的场景 处理可能不太一样 需要自定义,但是返回值确定
* @param sql
* @return
*/
protected abstract List<QueryTable> getQueryTableInfo(String sql);
/**
* 校验sql语句 成功返回true
* @param sql
* @return
*/
public boolean isPass(String sql) {
List<QueryTable> list = null;
//【jeecg-boot/issues/4040】在线报表不支持子查询,解析报错 #4040
try {
list = this.getQueryTableInfo(sql.toLowerCase());
} catch (Exception e) {
log.warn("校验sql语句,解析报错:{}",e.getMessage());
}
if(list==null){
return true;
}
log.info("--获取sql信息--", list.toString());
boolean flag = checkTableAndFieldsName(list);
if(flag == false){
return false;
}
for (QueryTable table : list) {
String name = table.getName();
String fieldString = ruleMap.get(name);
// 有没有配置这张表
if (fieldString != null) {
if ("*".equals(fieldString) || table.isAll()) {
flag = false;
log.warn("sql黑名单校验,表【"+name+"】禁止查询");
break;
} else if (table.existSameField(fieldString)) {
flag = false;
break;
}
}
}
return flag;
}
/**
* 校验表名和字段名是否有效,或是是否会带些特殊的字符串进行sql注入
* issues/4983 SQL Injection in 3.5.1 #4983
* @return
*/
private boolean checkTableAndFieldsName(List<QueryTable> list){
boolean flag = true;
for(QueryTable queryTable: list){
String tableName = queryTable.getName();
if(hasSpecialString(tableName)){
flag = false;
log.warn("sql黑名单校验,表名【"+tableName+"】包含特殊字符");
break;
}
Set<String> fields = queryTable.getFields();
for(String name: fields){
if(hasSpecialString(name)){
flag = false;
log.warn("sql黑名单校验,字段名【"+name+"】包含特殊字符");
break;
}
}
}
return flag;
}
/**
* 是否包含特殊的字符串
* @param name
* @return
*/
private boolean hasSpecialString(String name){
Matcher m = ILLEGAL_NAME_REG.matcher(name);
if (m.find()) {
return true;
}
return false;
}
/**
* 查询的表的信息
*/
protected class QueryTable {
//表名
private String name;
//表的别名
private String alias;
// 字段名集合
private Set<String> fields;
// 是否查询所有字段
private boolean all;
public QueryTable() {
}
public QueryTable(String name, String alias) {
this.name = name;
this.alias = alias;
this.all = false;
this.fields = new HashSet<>();
}
public void addField(String field) {
this.fields.add(field);
}
public String getName() {
return name;
}
public Set<String> getFields() {
return new HashSet<>(fields);
}
public void setName(String name) {
this.name = name;
}
public void setFields(Set<String> fields) {
this.fields = fields;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public boolean isAll() {
return all;
}
public void setAll(boolean all) {
this.all = all;
}
/**
* 判断是否有相同字段
*
* @param fieldString
* @return
*/
public boolean existSameField(String fieldString) {
String[] arr = fieldString.split(",");
for (String exp : fields) {
for (String config : arr) {
if (exp.equals(config)) {
// 非常明确的列直接比较
log.warn("sql黑名单校验,表【"+name+"】中字段【"+config+"】禁止查询");
return true;
} else {
// 使用表达式的列 只能判读字符串包含了
String aliasColumn = config;
if (alias != null && alias.length() > 0) {
aliasColumn = alias + "." + config;
}
if (exp.indexOf(aliasColumn) > 0) {
log.warn("sql黑名单校验,表【"+name+"】中字段【"+config+"】禁止查询");
return true;
}
}
}
}
return false;
}
@Override
public String toString() {
return "QueryTable{" +
"name='" + name + '\'' +
", alias='" + alias + '\'' +
", fields=" + fields +
", all=" + all +
'}';
}
}
public String getError(){
// TODO
return "系统设置了安全规则,敏感表和敏感字段禁止查询,联系管理员授权!";
}
}
| 6,744 | Java | .java | 200 | 18.91 | 83 | 0.484209 | mahonelau/-kykms | 716 | 110 | 0 | GPL-3.0 | 9/4/2024, 7:05:26 PM (Europe/Amsterdam) | false | false | false | true | false | false | true | true | 5,974 |
2,604,152 | TVPDefaultMetadataPropertyType.java | ESSI-Lab_DAB/jaxb-classes/jaxb-classes-wml-2.0/src/main/java/eu/essi_lab/jaxb/wml/_2_0/TVPDefaultMetadataPropertyType.java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0
// See <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.04.17 at 03:51:45 PM CEST
//
package eu.essi_lab.jaxb.wml._2_0;
/*-
* #%L
* Discovery and Access Broker (DAB) Community Edition (CE)
* %%
* Copyright (C) 2021 - 2024 National Research Council of Italy (CNR)/Institute of Atmospheric Pollution Research (IIA)/ESSI-Lab
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for TVPDefaultMetadataPropertyType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="TVPDefaultMetadataPropertyType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{http://www.opengis.net/waterml/2.0}DefaultTVPMetadata"/>
* </sequence>
* <attGroup ref="{http://www.opengis.net/gml/3.2}OwnershipAttributeGroup"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TVPDefaultMetadataPropertyType", propOrder = {
"defaultTVPMetadata"
})
public class TVPDefaultMetadataPropertyType {
@XmlElementRef(name = "DefaultTVPMetadata", namespace = "http://www.opengis.net/waterml/2.0", type = JAXBElement.class)
protected JAXBElement<? extends TVPMetadataType> defaultTVPMetadata;
@XmlAttribute(name = "owns")
protected Boolean owns;
/**
* Gets the value of the defaultTVPMetadata property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link DefaultCategoricalTVPMetadataType }{@code >}
* {@link JAXBElement }{@code <}{@link TVPMeasurementMetadataType }{@code >}
* {@link JAXBElement }{@code <}{@link TVPMetadataType }{@code >}
*
*/
public JAXBElement<? extends TVPMetadataType> getDefaultTVPMetadata() {
return defaultTVPMetadata;
}
/**
* Sets the value of the defaultTVPMetadata property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link DefaultCategoricalTVPMetadataType }{@code >}
* {@link JAXBElement }{@code <}{@link TVPMeasurementMetadataType }{@code >}
* {@link JAXBElement }{@code <}{@link TVPMetadataType }{@code >}
*
*/
public void setDefaultTVPMetadata(JAXBElement<? extends TVPMetadataType> value) {
this.defaultTVPMetadata = value;
}
/**
* Gets the value of the owns property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isOwns() {
if (owns == null) {
return false;
} else {
return owns;
}
}
/**
* Sets the value of the owns property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setOwns(Boolean value) {
this.owns = value;
}
}
| 4,224 | Java | .java | 115 | 32.391304 | 128 | 0.676593 | ESSI-Lab/DAB | 7 | 1 | 0 | AGPL-3.0 | 9/4/2024, 9:50:42 PM (Europe/Amsterdam) | false | false | false | false | false | true | true | true | 4,224 |
485,989 | TaskDependencyMatchers.java | SonarSource_sonar-scanner-gradle/src/test/groovy/org/sonarqube/gradle/TaskDependencyMatchers.java | /*
* SonarQube Scanner for Gradle
* Copyright (C) 2015-2024 SonarSource
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonarqube.gradle;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.gradle.api.Buildable;
import org.gradle.api.Task;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.StringDescription;
import static org.hamcrest.Matchers.equalTo;
public class TaskDependencyMatchers {
@Factory
public static Matcher<Task> dependsOn(final String... tasks) {
return dependsOn(equalTo(new HashSet<>(Arrays.asList(tasks))));
}
@Factory
public static Matcher<Task> dependsOn(Matcher<? extends Iterable<String>> matcher) {
return dependsOn(matcher, false);
}
@Factory
public static Matcher<Task> dependsOnPaths(Matcher<? extends Iterable<String>> matcher) {
return dependsOn(matcher, true);
}
private static Matcher<Task> dependsOn(final Matcher<? extends Iterable<String>> matcher, final boolean matchOnPaths) {
return new BaseMatcher<Task>() {
public boolean matches(Object o) {
Task task = (Task) o;
Set<String> names = new HashSet<>();
Set<? extends Task> depTasks = task.getTaskDependencies().getDependencies(task);
for (Task depTask : depTasks) {
names.add(matchOnPaths ? depTask.getPath() : depTask.getName());
}
boolean matches = matcher.matches(names);
if (!matches) {
StringDescription description = new StringDescription();
matcher.describeTo(description);
System.out.println(String.format("expected %s, got %s.", description.toString(), names));
}
return matches;
}
public void describeTo(Description description) {
description.appendText("a Task that depends on ").appendDescriptionOf(matcher);
}
};
}
@Factory
public static <T extends Buildable> Matcher<T> builtBy(String... tasks) {
return builtBy(equalTo(new HashSet<>(Arrays.asList(tasks))));
}
@Factory
public static <T extends Buildable> Matcher<T> builtBy(final Matcher<? extends Iterable<String>> matcher) {
return new BaseMatcher<T>() {
public boolean matches(Object o) {
Buildable task = (Buildable) o;
Set<String> names = new HashSet<>();
Set<? extends Task> depTasks = task.getBuildDependencies().getDependencies(null);
for (Task depTask : depTasks) {
names.add(depTask.getName());
}
boolean matches = matcher.matches(names);
if (!matches) {
StringDescription description = new StringDescription();
matcher.describeTo(description);
System.out.println(String.format("expected %s, got %s.", description.toString(), names));
}
return matches;
}
public void describeTo(Description description) {
description.appendText("a Buildable that is built by ").appendDescriptionOf(matcher);
}
};
}
}
| 3,790 | Java | .java | 94 | 35.255319 | 121 | 0.710526 | SonarSource/sonar-scanner-gradle | 184 | 93 | 6 | LGPL-3.0 | 9/4/2024, 7:07:37 PM (Europe/Amsterdam) | false | true | false | false | false | true | true | true | 3,790 |
4,254,935 | TimerManagerTaskScheduler.java | rockleeprc_sourcecode/spring-framework/spring-context-support/src/main/java/org/springframework/scheduling/commonj/TimerManagerTaskScheduler.java | /*
* Copyright 2002-2017 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.scheduling.commonj;
import java.util.Date;
import java.util.concurrent.Delayed;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import commonj.timers.Timer;
import commonj.timers.TimerListener;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.support.SimpleTriggerContext;
import org.springframework.scheduling.support.TaskUtils;
import org.springframework.util.Assert;
import org.springframework.util.ErrorHandler;
/**
* Implementation of Spring's {@link TaskScheduler} interface, wrapping
* a CommonJ {@link commonj.timers.TimerManager}.
*
* @author Juergen Hoeller
* @author Mark Fisher
* @since 3.0
*/
public class TimerManagerTaskScheduler extends TimerManagerAccessor implements TaskScheduler {
@Nullable
private volatile ErrorHandler errorHandler;
/**
* Provide an {@link ErrorHandler} strategy.
*/
public void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
@Override
@Nullable
public ScheduledFuture<?> schedule(Runnable task, Trigger trigger) {
return new ReschedulingTimerListener(errorHandlingTask(task, true), trigger).schedule();
}
@Override
public ScheduledFuture<?> schedule(Runnable task, Date startTime) {
TimerScheduledFuture futureTask = new TimerScheduledFuture(errorHandlingTask(task, false));
Timer timer = obtainTimerManager().schedule(futureTask, startTime);
futureTask.setTimer(timer);
return futureTask;
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, Date startTime, long period) {
TimerScheduledFuture futureTask = new TimerScheduledFuture(errorHandlingTask(task, true));
Timer timer = obtainTimerManager().scheduleAtFixedRate(futureTask, startTime, period);
futureTask.setTimer(timer);
return futureTask;
}
@Override
public ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long period) {
TimerScheduledFuture futureTask = new TimerScheduledFuture(errorHandlingTask(task, true));
Timer timer = obtainTimerManager().scheduleAtFixedRate(futureTask, 0, period);
futureTask.setTimer(timer);
return futureTask;
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, Date startTime, long delay) {
TimerScheduledFuture futureTask = new TimerScheduledFuture(errorHandlingTask(task, true));
Timer timer = obtainTimerManager().schedule(futureTask, startTime, delay);
futureTask.setTimer(timer);
return futureTask;
}
@Override
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long delay) {
TimerScheduledFuture futureTask = new TimerScheduledFuture(errorHandlingTask(task, true));
Timer timer = obtainTimerManager().schedule(futureTask, 0, delay);
futureTask.setTimer(timer);
return futureTask;
}
private Runnable errorHandlingTask(Runnable delegate, boolean isRepeatingTask) {
return TaskUtils.decorateTaskWithErrorHandler(delegate, this.errorHandler, isRepeatingTask);
}
/**
* ScheduledFuture adapter that wraps a CommonJ Timer.
*/
private static class TimerScheduledFuture extends FutureTask<Object> implements TimerListener, ScheduledFuture<Object> {
@Nullable
protected transient Timer timer;
protected transient boolean cancelled = false;
public TimerScheduledFuture(Runnable runnable) {
super(runnable, null);
}
public void setTimer(Timer timer) {
this.timer = timer;
}
@Override
public void timerExpired(Timer timer) {
runAndReset();
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
boolean result = super.cancel(mayInterruptIfRunning);
if (this.timer != null) {
this.timer.cancel();
}
this.cancelled = true;
return result;
}
@Override
public long getDelay(TimeUnit unit) {
Assert.state(this.timer != null, "No Timer available");
return unit.convert(this.timer.getScheduledExecutionTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed other) {
if (this == other) {
return 0;
}
long diff = getDelay(TimeUnit.MILLISECONDS) - other.getDelay(TimeUnit.MILLISECONDS);
return (diff == 0 ? 0 : ((diff < 0)? -1 : 1));
}
}
/**
* ScheduledFuture adapter for trigger-based rescheduling.
*/
private class ReschedulingTimerListener extends TimerScheduledFuture {
private final Trigger trigger;
private final SimpleTriggerContext triggerContext = new SimpleTriggerContext();
private volatile Date scheduledExecutionTime = new Date();
public ReschedulingTimerListener(Runnable runnable, Trigger trigger) {
super(runnable);
this.trigger = trigger;
}
@Nullable
public ScheduledFuture<?> schedule() {
Date nextExecutionTime = this.trigger.nextExecutionTime(this.triggerContext);
if (nextExecutionTime == null) {
return null;
}
this.scheduledExecutionTime = nextExecutionTime;
setTimer(obtainTimerManager().schedule(this, this.scheduledExecutionTime));
return this;
}
@Override
public void timerExpired(Timer timer) {
Date actualExecutionTime = new Date();
super.timerExpired(timer);
Date completionTime = new Date();
this.triggerContext.update(this.scheduledExecutionTime, actualExecutionTime, completionTime);
if (!this.cancelled) {
schedule();
}
}
}
}
| 6,074 | Java | .java | 163 | 34.386503 | 121 | 0.788632 | 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 | 6,074 |
4,843,045 | EstimateQueryDescriptor.java | galleon1_chocolate-milk/src/org/chocolate_milk/model/descriptors/EstimateQueryDescriptor.java | /*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML
* Schema.
* $Id: EstimateQueryDescriptor.java,v 1.1.1.1 2010-05-04 22:06:00 ryan Exp $
*/
package org.chocolate_milk.model.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import org.chocolate_milk.model.EstimateQuery;
/**
* Class EstimateQueryDescriptor.
*
* @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:06:00 $
*/
public class EstimateQueryDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public EstimateQueryDescriptor() {
super();
_xmlName = "EstimateQuery";
_elementDefinition = false;
//-- set grouping compositor
setCompositorAsSequence();
org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null;
org.exolab.castor.mapping.FieldHandler handler = null;
org.exolab.castor.xml.FieldValidator fieldValidator = null;
//-- initialize attribute descriptors
//-- initialize element descriptors
//-- _estimateQueryChoice
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.chocolate_milk.model.EstimateQueryChoice.class, "_estimateQueryChoice", "-error-if-this-is-used-", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
EstimateQuery target = (EstimateQuery) object;
return target.getEstimateQueryChoice();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
EstimateQuery target = (EstimateQuery) object;
target.setEstimateQueryChoice( (org.chocolate_milk.model.EstimateQueryChoice) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.chocolate_milk.model.EstimateQueryChoice();
}
};
desc.setSchemaType("org.chocolate_milk.model.EstimateQueryChoice");
desc.setHandler(handler);
desc.setContainer(true);
desc.setClassDescriptor(new org.chocolate_milk.model.descriptors.EstimateQueryChoiceDescriptor());
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _estimateQueryChoice
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
}
desc.setValidator(fieldValidator);
//-- _includeLineItems
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_includeLineItems", "IncludeLineItems", org.exolab.castor.xml.NodeType.Element);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
EstimateQuery target = (EstimateQuery) object;
return target.getIncludeLineItems();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
EstimateQuery target = (EstimateQuery) object;
target.setIncludeLineItems( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _includeLineItems
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- _includeLinkedTxns
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_includeLinkedTxns", "IncludeLinkedTxns", org.exolab.castor.xml.NodeType.Element);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
EstimateQuery target = (EstimateQuery) object;
return target.getIncludeLinkedTxns();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
EstimateQuery target = (EstimateQuery) object;
target.setIncludeLinkedTxns( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _includeLinkedTxns
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- _includeRetElementList
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_includeRetElementList", "IncludeRetElement", org.exolab.castor.xml.NodeType.Element);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
EstimateQuery target = (EstimateQuery) object;
return target.getIncludeRetElement();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
EstimateQuery target = (EstimateQuery) object;
target.addIncludeRetElement( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException {
try {
EstimateQuery target = (EstimateQuery) object;
target.removeAllIncludeRetElement();
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("list");
desc.setComponentType("string");
desc.setHandler(handler);
desc.setMultivalued(true);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _includeRetElementList
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(0);
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
typeValidator.setMaxLength(50);
}
desc.setValidator(fieldValidator);
//-- _ownerIDList
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_ownerIDList", "OwnerID", org.exolab.castor.xml.NodeType.Element);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
EstimateQuery target = (EstimateQuery) object;
return target.getOwnerID();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
EstimateQuery target = (EstimateQuery) object;
target.addOwnerID( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException {
try {
EstimateQuery target = (EstimateQuery) object;
target.removeAllOwnerID();
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("list");
desc.setComponentType("string");
desc.setHandler(handler);
desc.setMultivalued(true);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _ownerIDList
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(0);
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.addPattern("0|(\\{[0-9a-fA-F]{8}(\\-([0-9a-fA-F]{4})){3}\\-[0-9a-fA-F]{12}\\})");
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
@Override()
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
@Override()
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
@Override()
public java.lang.Class getJavaClass(
) {
return org.chocolate_milk.model.EstimateQuery.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
@Override()
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
@Override()
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
@Override()
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
@Override()
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
| 14,543 | Java | .java | 372 | 28.758065 | 212 | 0.597609 | galleon1/chocolate-milk | 1 | 1 | 0 | LGPL-3.0 | 9/5/2024, 12:33:21 AM (Europe/Amsterdam) | false | true | true | false | false | true | true | true | 14,543 |
4,242,649 | ManaHeal.java | rubenswagner_L2J-Global/dist/game/data/scripts/handlers/effecthandlers/ManaHeal.java | /*
* This file is part of the L2J Global project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package handlers.effecthandlers;
import com.l2jglobal.gameserver.model.StatsSet;
import com.l2jglobal.gameserver.model.actor.L2Character;
import com.l2jglobal.gameserver.model.effects.AbstractEffect;
import com.l2jglobal.gameserver.model.effects.EffectFlag;
import com.l2jglobal.gameserver.model.items.instance.L2ItemInstance;
import com.l2jglobal.gameserver.model.skills.Skill;
import com.l2jglobal.gameserver.model.stats.Stats;
import com.l2jglobal.gameserver.network.SystemMessageId;
import com.l2jglobal.gameserver.network.serverpackets.SystemMessage;
/**
* Mana Heal effect implementation.
* @author UnAfraid
*/
public final class ManaHeal extends AbstractEffect
{
private final double _power;
public ManaHeal(StatsSet params)
{
_power = params.getDouble("power", 0);
}
@Override
public boolean isInstant()
{
return true;
}
@Override
public void instant(L2Character effector, L2Character effected, Skill skill, L2ItemInstance item)
{
if (effected.isDead() || effected.isDoor() || effected.isMpBlocked())
{
return;
}
if ((effected != effector) && effected.isAffected(EffectFlag.FACEOFF))
{
return;
}
double amount = _power;
if (!skill.isStatic())
{
amount = effected.getStat().getValue(Stats.MANA_CHARGE, amount);
}
// Prevents overheal and negative amount
amount = Math.max(Math.min(amount, effected.getMaxRecoverableMp() - effected.getCurrentMp()), 0);
if (amount != 0)
{
effected.broadcastStatusUpdate(effector);
}
SystemMessage sm;
if (effector.getObjectId() != effected.getObjectId())
{
sm = SystemMessage.getSystemMessage(SystemMessageId.S2_MP_HAS_BEEN_RESTORED_BY_C1);
sm.addCharName(effector);
}
else
{
sm = SystemMessage.getSystemMessage(SystemMessageId.S1_MP_HAS_BEEN_RESTORED);
}
sm.addInt((int) amount);
effected.sendPacket(sm);
}
}
| 2,562 | Java | .java | 78 | 30.230769 | 99 | 0.769886 | rubenswagner/L2J-Global | 2 | 4 | 0 | GPL-3.0 | 9/5/2024, 12:07:03 AM (Europe/Amsterdam) | false | false | true | false | false | true | false | true | 2,562 |
1,313,663 | PackageExplorerActionGroup.java | eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerActionGroup.java | /*******************************************************************************
* Copyright (c) 2000, 2011 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
* Eric Rizzo - replaced Collapse All action with generic equivalent
*******************************************************************************/
package org.eclipse.jdt.internal.ui.packageview;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.commands.ActionHandler;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.OpenStrategy;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.IWorkingSetManager;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.OpenInNewWindowAction;
import org.eclipse.ui.handlers.CollapseAllHandler;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.views.framelist.BackAction;
import org.eclipse.ui.views.framelist.ForwardAction;
import org.eclipse.ui.views.framelist.Frame;
import org.eclipse.ui.views.framelist.FrameAction;
import org.eclipse.ui.views.framelist.FrameList;
import org.eclipse.ui.views.framelist.GoIntoAction;
import org.eclipse.ui.views.framelist.TreeFrame;
import org.eclipse.ui.views.framelist.UpAction;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IOpenable;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.BuildActionGroup;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.CustomFiltersActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.ImportActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.JdtActionConstants;
import org.eclipse.jdt.ui.actions.NavigateActionGroup;
import org.eclipse.jdt.ui.actions.OpenProjectAction;
import org.eclipse.jdt.ui.actions.ProjectActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.internal.ui.actions.CollapseAllAction;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectAllAction;
import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.newsourcepage.GenerateBuildPathActionGroup;
import org.eclipse.jdt.internal.ui.workingsets.ViewActionGroup;
class PackageExplorerActionGroup extends CompositeActionGroup {
private static final String FRAME_ACTION_SEPARATOR_ID= "FRAME_ACTION_SEPARATOR_ID"; //$NON-NLS-1$
private static final String FRAME_ACTION_GROUP_ID= "FRAME_ACTION_GROUP_ID"; //$NON-NLS-1$
private PackageExplorerPart fPart;
private FrameList fFrameList;
private GoIntoAction fZoomInAction;
private BackAction fBackAction;
private ForwardAction fForwardAction;
private UpAction fUpAction;
private boolean fFrameActionsShown;
private GotoTypeAction fGotoTypeAction;
private GotoPackageAction fGotoPackageAction;
private GotoResourceAction fGotoResourceAction;
private CollapseAllAction fCollapseAllAction;
private SelectAllAction fSelectAllAction;
private ToggleLinkingAction fToggleLinkingAction;
private RefactorActionGroup fRefactorActionGroup;
private NavigateActionGroup fNavigateActionGroup;
private ViewActionGroup fViewActionGroup;
private CustomFiltersActionGroup fCustomFiltersActionGroup;
private IAction fGotoRequiredProjectAction;
private ProjectActionGroup fProjectActionGroup;
public PackageExplorerActionGroup(PackageExplorerPart part) {
super();
fPart= part;
fFrameActionsShown= false;
TreeViewer viewer= part.getTreeViewer();
IPropertyChangeListener workingSetListener= this::doWorkingSetChanged;
IWorkbenchPartSite site = fPart.getSite();
setGroups(new ActionGroup[] {
new NewWizardsActionGroup(site),
fNavigateActionGroup= new NavigateActionGroup(fPart),
new CCPActionGroup(fPart),
new GenerateBuildPathActionGroup(fPart),
new GenerateActionGroup(fPart),
fRefactorActionGroup= new RefactorActionGroup(fPart),
new ImportActionGroup(fPart),
new BuildActionGroup(fPart),
new JavaSearchActionGroup(fPart),
fProjectActionGroup= new ProjectActionGroup(fPart),
fViewActionGroup= new ViewActionGroup(fPart.getRootMode(), workingSetListener, site),
fCustomFiltersActionGroup= new CustomFiltersActionGroup(fPart, viewer),
new LayoutActionGroup(fPart)
});
fViewActionGroup.fillFilters(viewer);
PackagesFrameSource frameSource= new PackagesFrameSource(fPart);
fFrameList= new FrameList(frameSource);
frameSource.connectTo(fFrameList);
fZoomInAction= new GoIntoAction(fFrameList);
fPart.getSite().getSelectionProvider().addSelectionChangedListener(event -> fZoomInAction.update());
fBackAction= new BackAction(fFrameList);
fForwardAction= new ForwardAction(fFrameList);
fUpAction= new UpAction(fFrameList);
fFrameList.addPropertyChangeListener(event -> {
fPart.updateTitle();
fPart.updateToolbar();
});
fGotoTypeAction= new GotoTypeAction(fPart);
fGotoPackageAction= new GotoPackageAction(fPart);
fGotoResourceAction= new GotoResourceAction(fPart);
fCollapseAllAction= new CollapseAllAction(fPart.getTreeViewer());
fCollapseAllAction.setActionDefinitionId(CollapseAllHandler.COMMAND_ID);
fToggleLinkingAction = new ToggleLinkingAction(fPart);
fToggleLinkingAction.setActionDefinitionId(IWorkbenchCommandConstants.NAVIGATE_TOGGLE_LINK_WITH_EDITOR);
fGotoRequiredProjectAction= new GotoRequiredProjectAction(fPart);
fSelectAllAction= new SelectAllAction(fPart.getTreeViewer());
}
@Override
public void dispose() {
super.dispose();
}
//---- Persistent state -----------------------------------------------------------------------
/* package */ void restoreFilterAndSorterState(IMemento memento) {
fViewActionGroup.restoreState(memento);
fCustomFiltersActionGroup.restoreState(memento);
}
/* package */ void saveFilterAndSorterState(IMemento memento) {
fViewActionGroup.saveState(memento);
fCustomFiltersActionGroup.saveState(memento);
}
//---- Action Bars ----------------------------------------------------------------------------
@Override
public void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
setGlobalActionHandlers(actionBars);
fillToolBar(actionBars.getToolBarManager());
fillViewMenu(actionBars.getMenuManager());
}
private void setGlobalActionHandlers(IActionBars actionBars) {
// Navigate Go Into and Go To actions.
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_INTO, fZoomInAction);
actionBars.setGlobalActionHandler(ActionFactory.BACK.getId(), fBackAction);
actionBars.setGlobalActionHandler(ActionFactory.FORWARD.getId(), fForwardAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.UP, fUpAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_TO_RESOURCE, fGotoResourceAction);
actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_TYPE, fGotoTypeAction);
actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_PACKAGE, fGotoPackageAction);
actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), fSelectAllAction);
fRefactorActionGroup.retargetFileMenuActions(actionBars);
IHandlerService handlerService= fPart.getViewSite().getService(IHandlerService.class);
handlerService.activateHandler(IWorkbenchCommandConstants.NAVIGATE_TOGGLE_LINK_WITH_EDITOR, new ActionHandler(fToggleLinkingAction));
handlerService.activateHandler(CollapseAllHandler.COMMAND_ID, new ActionHandler(fCollapseAllAction));
}
/* package */ void fillToolBar(IToolBarManager toolBar) {
if (fBackAction.isEnabled() || fUpAction.isEnabled() || fForwardAction.isEnabled()) {
toolBar.add(fBackAction);
toolBar.add(fForwardAction);
toolBar.add(fUpAction);
toolBar.add(new Separator(FRAME_ACTION_SEPARATOR_ID));
fFrameActionsShown= true;
}
toolBar.add(new GroupMarker(FRAME_ACTION_GROUP_ID));
toolBar.add(fCollapseAllAction);
toolBar.add(fToggleLinkingAction);
toolBar.update(true);
}
public void updateToolBar(IToolBarManager toolBar) {
boolean hasBeenFrameActionsShown= fFrameActionsShown;
fFrameActionsShown= fBackAction.isEnabled() || fUpAction.isEnabled() || fForwardAction.isEnabled();
if (fFrameActionsShown != hasBeenFrameActionsShown) {
if (hasBeenFrameActionsShown) {
toolBar.remove(fBackAction.getId());
toolBar.remove(fForwardAction.getId());
toolBar.remove(fUpAction.getId());
toolBar.remove(FRAME_ACTION_SEPARATOR_ID);
} else {
toolBar.prependToGroup(FRAME_ACTION_GROUP_ID, new Separator(FRAME_ACTION_SEPARATOR_ID));
toolBar.prependToGroup(FRAME_ACTION_GROUP_ID, fUpAction);
toolBar.prependToGroup(FRAME_ACTION_GROUP_ID, fForwardAction);
toolBar.prependToGroup(FRAME_ACTION_GROUP_ID, fBackAction);
}
toolBar.update(true);
}
}
/* package */ void fillViewMenu(IMenuManager menu) {
menu.add(new Separator());
menu.add(fToggleLinkingAction);
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$
}
//---- Context menu -------------------------------------------------------------------------
@Override
public void fillContextMenu(IMenuManager menu) {
IStructuredSelection selection= (IStructuredSelection)getContext().getSelection();
int size= selection.size();
Object element= selection.getFirstElement();
if (element instanceof ClassPathContainer.RequiredProjectWrapper)
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, fGotoRequiredProjectAction);
addGotoMenu(menu, element, size);
addOpenNewWindowAction(menu, element);
super.fillContextMenu(menu);
}
private void addGotoMenu(IMenuManager menu, Object element, int size) {
boolean enabled= size == 1 && fPart.getTreeViewer().isExpandable(element) && (isGoIntoTarget(element) || element instanceof IContainer);
fZoomInAction.setEnabled(enabled);
if (enabled)
menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction);
}
private boolean isGoIntoTarget(Object element) {
if (element == null)
return false;
if (element instanceof IJavaElement) {
int type= ((IJavaElement)element).getElementType();
return type == IJavaElement.JAVA_PROJECT ||
type == IJavaElement.PACKAGE_FRAGMENT_ROOT ||
type == IJavaElement.PACKAGE_FRAGMENT;
}
if (element instanceof IWorkingSet) {
return true;
}
return false;
}
private void addOpenNewWindowAction(IMenuManager menu, Object element) {
if (element instanceof IJavaElement) {
element= ((IJavaElement)element).getResource();
}
// fix for 64890 Package explorer out of sync when open/closing projects [package explorer] 64890
if (element instanceof IProject && !((IProject)element).isOpen())
return;
if (!(element instanceof IContainer))
return;
menu.appendToGroup(
IContextMenuConstants.GROUP_OPEN,
new OpenInNewWindowAction(fPart.getSite().getWorkbenchWindow(), (IContainer)element));
}
//---- Key board and mouse handling ------------------------------------------------------------
/* package*/ void handleDoubleClick(DoubleClickEvent event) {
TreeViewer viewer= fPart.getTreeViewer();
IStructuredSelection selection= (IStructuredSelection)event.getSelection();
Object element= selection.getFirstElement();
if (viewer.isExpandable(element)) {
if (doubleClickGoesInto()) {
// don't zoom into compilation units and class files
if (element instanceof ICompilationUnit || element instanceof IClassFile)
return;
if (element instanceof IOpenable || element instanceof IContainer || element instanceof IWorkingSet) {
fZoomInAction.run();
}
} else {
IAction openAction= fNavigateActionGroup.getOpenAction();
if (openAction != null && openAction.isEnabled() && OpenStrategy.getOpenMethod() == OpenStrategy.DOUBLE_CLICK)
return;
if (selection instanceof ITreeSelection) {
for (TreePath path : ((ITreeSelection)selection).getPathsFor(element)) {
viewer.setExpandedState(path, !viewer.getExpandedState(path));
}
} else {
viewer.setExpandedState(element, !viewer.getExpandedState(element));
}
}
} else if (element instanceof IProject && !((IProject) element).isOpen()) {
OpenProjectAction openProjectAction= fProjectActionGroup.getOpenProjectAction();
if (openProjectAction.isEnabled()) {
openProjectAction.run();
}
}
}
/**
* Called by Package Explorer.
*
* @param event the open event
* @param activate <code>true</code> if the opened editor should be activated
*/
/* package */void handleOpen(ISelection event, boolean activate) {
IAction openAction= fNavigateActionGroup.getOpenAction();
if (openAction != null && openAction.isEnabled()) {
// XXX: should use the given arguments instead of using org.eclipse.jface.util.OpenStrategy.activateOnOpen()
openAction.run();
return;
}
}
/* package */ void handleKeyEvent(KeyEvent event) {
if (event.stateMask != 0)
return;
if (event.keyCode == SWT.BS) {
if (fUpAction != null && fUpAction.isEnabled()) {
fUpAction.run();
event.doit= false;
}
}
}
private void doWorkingSetChanged(PropertyChangeEvent event) {
if (ViewActionGroup.MODE_CHANGED.equals(event.getProperty())) {
fPart.rootModeChanged(((Integer)event.getNewValue()));
Object oldInput= null;
Object newInput= null;
if (fPart.getRootMode() == PackageExplorerPart.PROJECTS_AS_ROOTS) {
oldInput= fPart.getWorkingSetModel();
newInput= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
} else {
oldInput= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
newInput= fPart.getWorkingSetModel();
}
if (oldInput != null && newInput != null) {
Frame frame;
for (int i= 0; (frame= fFrameList.getFrame(i)) != null; i++) {
if (frame instanceof TreeFrame) {
TreeFrame treeFrame= (TreeFrame)frame;
if (oldInput.equals(treeFrame.getInput()))
treeFrame.setInput(newInput);
}
}
}
} else {
IWorkingSet workingSet= (IWorkingSet) event.getNewValue();
String workingSetLabel= null;
if (workingSet != null)
workingSetLabel= BasicElementLabels.getWorkingSetLabel(workingSet);
fPart.setWorkingSetLabel(workingSetLabel);
fPart.updateTitle();
String property= event.getProperty();
if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) {
TreeViewer viewer= fPart.getTreeViewer();
viewer.getControl().setRedraw(false);
viewer.refresh();
viewer.getControl().setRedraw(true);
}
}
}
private boolean doubleClickGoesInto() {
return PreferenceConstants.DOUBLE_CLICK_GOES_INTO.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.DOUBLE_CLICK));
}
public FrameAction getUpAction() {
return fUpAction;
}
public FrameAction getBackAction() {
return fBackAction;
}
public FrameAction getForwardAction() {
return fForwardAction;
}
public ViewActionGroup getWorkingSetActionGroup() {
return fViewActionGroup;
}
public CustomFiltersActionGroup getCustomFilterActionGroup() {
return fCustomFiltersActionGroup;
}
public FrameList getFrameList() {
return fFrameList;
}
}
| 16,815 | Java | .java | 381 | 41.055118 | 145 | 0.780752 | eclipse-jdt/eclipse.jdt.ui | 35 | 86 | 242 | EPL-2.0 | 9/4/2024, 7:34:16 PM (Europe/Amsterdam) | false | false | false | false | false | true | true | true | 16,815 |
1,319,586 | A_test552.java | eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/locals_out/A_test552.java | package locals_out;
public class A_test552 {
public void foo() {
int i= 0;
for (;true;) {
i = extracted(i);
}
}
protected int extracted(int i) {
/*[*/i++;/*]*/
return i;
}
}
| 195 | Java | .java | 13 | 12.384615 | 33 | 0.58427 | 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 |
4,521,677 | CloudSmsTemplate.java | mizhousoft_cloud-sdk/cloud-api/src/main/java/com/mizhousoft/cloudsdk/sms/CloudSmsTemplate.java | package com.mizhousoft.cloudsdk.sms;
/**
* 云短信模板
*
* @version
*/
public class CloudSmsTemplate
{
// 模板编码
private final String templateCode;
// 签名名称
private final String signName;
// 模板ID
private final Object templateId;
/**
* 构造函数
*
* @param templateCode
* @param signName
* @param templateId
*/
public CloudSmsTemplate(String templateCode, String signName, Object templateId)
{
super();
this.templateCode = templateCode;
this.signName = signName;
this.templateId = templateId;
}
/**
* 获取templateCode
*
* @return
*/
public String getTemplateCode()
{
return templateCode;
}
/**
* 获取signName
*
* @return
*/
public String getSignName()
{
return signName;
}
/**
* 获取templateId
*
* @return
*/
public Object getTemplateId()
{
return templateId;
}
/**
*
* @return
*/
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append("{\"");
if (templateCode != null)
{
builder.append("templateCode\":\"");
builder.append(templateCode);
builder.append("\", \"");
}
if (signName != null)
{
builder.append("signName\":\"");
builder.append(signName);
builder.append("\", \"");
}
if (templateId != null)
{
builder.append("templateId\":\"");
builder.append(templateId);
}
builder.append("\"}");
return builder.toString();
}
}
| 1,536 | Java | .java | 85 | 13.635294 | 82 | 0.626715 | mizhousoft/cloud-sdk | 2 | 2 | 0 | EPL-2.0 | 9/5/2024, 12:15:54 AM (Europe/Amsterdam) | false | false | false | true | true | false | true | true | 1,486 |
4,314,672 | MacroStateSplitNode.java | hzio_OpenJDK10/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.replacements/src/org/graalvm/compiler/replacements/nodes/MacroStateSplitNode.java | /*
* Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.replacements.nodes;
import org.graalvm.compiler.core.common.type.StampPair;
import org.graalvm.compiler.debug.GraalError;
import org.graalvm.compiler.graph.NodeClass;
import org.graalvm.compiler.nodeinfo.InputType;
import org.graalvm.compiler.nodeinfo.NodeInfo;
import org.graalvm.compiler.nodes.CallTargetNode.InvokeKind;
import org.graalvm.compiler.nodes.FrameState;
import org.graalvm.compiler.nodes.Invoke;
import org.graalvm.compiler.nodes.InvokeNode;
import org.graalvm.compiler.nodes.StateSplit;
import org.graalvm.compiler.nodes.StructuredGraph;
import org.graalvm.compiler.nodes.ValueNode;
import org.graalvm.compiler.nodes.java.MethodCallTargetNode;
import org.graalvm.compiler.nodes.memory.MemoryCheckpoint;
import org.graalvm.word.LocationIdentity;
import jdk.vm.ci.code.BytecodeFrame;
import jdk.vm.ci.meta.ResolvedJavaMethod;
/**
* This is an extension of {@link MacroNode} that is a {@link StateSplit} and a
* {@link MemoryCheckpoint}.
*/
@NodeInfo
public abstract class MacroStateSplitNode extends MacroNode implements StateSplit, MemoryCheckpoint.Single {
public static final NodeClass<MacroStateSplitNode> TYPE = NodeClass.create(MacroStateSplitNode.class);
@OptionalInput(InputType.State) protected FrameState stateAfter;
protected MacroStateSplitNode(NodeClass<? extends MacroNode> c, InvokeKind invokeKind, ResolvedJavaMethod targetMethod, int bci, StampPair returnStamp, ValueNode... arguments) {
super(c, invokeKind, targetMethod, bci, returnStamp, arguments);
}
@Override
public FrameState stateAfter() {
return stateAfter;
}
@Override
public void setStateAfter(FrameState x) {
assert x == null || x.isAlive() : "frame state must be in a graph";
updateUsages(stateAfter, x);
stateAfter = x;
}
@Override
public boolean hasSideEffect() {
return true;
}
@Override
public LocationIdentity getLocationIdentity() {
return LocationIdentity.any();
}
protected void replaceSnippetInvokes(StructuredGraph snippetGraph) {
for (MethodCallTargetNode call : snippetGraph.getNodes(MethodCallTargetNode.TYPE)) {
Invoke invoke = call.invoke();
if (!call.targetMethod().equals(getTargetMethod())) {
throw new GraalError("unexpected invoke %s in snippet", getClass().getSimpleName());
}
assert invoke.stateAfter().bci == BytecodeFrame.AFTER_BCI;
// Here we need to fix the bci of the invoke
InvokeNode newInvoke = snippetGraph.add(new InvokeNode(invoke.callTarget(), getBci()));
newInvoke.setStateAfter(invoke.stateAfter());
snippetGraph.replaceFixedWithFixed((InvokeNode) invoke.asNode(), newInvoke);
}
}
}
| 3,868 | Java | .java | 83 | 42.108434 | 181 | 0.754437 | hzio/OpenJDK10 | 2 | 4 | 0 | GPL-2.0 | 9/5/2024, 12:08:58 AM (Europe/Amsterdam) | false | false | false | true | false | true | true | true | 3,868 |
3,387,371 | zab.java | FzArnob_Covidease/sources/com/google/android/gms/common/server/converter/zab.java | package com.google.android.gms.common.server.converter;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.android.gms.common.internal.safeparcel.SafeParcelReader;
public final class zab implements Parcelable.Creator<zaa> {
public zab() {
}
public final /* synthetic */ Object[] newArray(int i) {
return new zaa[i];
}
public final /* synthetic */ Object createFromParcel(Parcel parcel) {
Object obj;
Parcel parcel2 = parcel;
Parcel parcel3 = parcel2;
int validateObjectHeader = SafeParcelReader.validateObjectHeader(parcel2);
int i = 0;
StringToIntConverter stringToIntConverter = null;
while (parcel3.dataPosition() < validateObjectHeader) {
int readHeader = SafeParcelReader.readHeader(parcel3);
int i2 = readHeader;
switch (SafeParcelReader.getFieldId(readHeader)) {
case 1:
i = SafeParcelReader.readInt(parcel3, i2);
break;
case 2:
stringToIntConverter = (StringToIntConverter) SafeParcelReader.createParcelable(parcel3, i2, StringToIntConverter.CREATOR);
break;
default:
SafeParcelReader.skipUnknownField(parcel3, i2);
break;
}
}
SafeParcelReader.ensureAtEnd(parcel3, validateObjectHeader);
new zaa(i, stringToIntConverter);
return obj;
}
}
| 1,509 | Java | .java | 37 | 30.594595 | 143 | 0.636921 | FzArnob/Covidease | 4 | 0 | 0 | GPL-3.0 | 9/4/2024, 11:17:41 PM (Europe/Amsterdam) | false | false | false | true | false | false | true | true | 1,509 |
1,704,370 | DyIOChannelEvent.java | NeuronRobotics_java-bowler/src/main/java/com/neuronrobotics/sdk/dyio/DyIOChannelEvent.java | /*******************************************************************************
* Copyright 2010 Neuron Robotics, LLC
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.neuronrobotics.sdk.dyio;
import com.neuronrobotics.sdk.common.ByteList;
// TODO: Auto-generated Javadoc
/**
* a DyIO Channel Event.
*
* @author rbreznak
*/
public class DyIOChannelEvent {
/** The data. */
private ByteList data;
/** The channel. */
private DyIOChannel channel;
/** The integer. */
private Integer integer;
/**
* Instantiates a new dy io channel event.
*
* @param channel the channel
* @param data the data
*/
public DyIOChannelEvent(DyIOChannel channel, ByteList data) {
this.channel = channel;
this.data = data;
}
/**
* Instantiates a new dy io channel event.
*
* @param c the c
* @param integer the integer
*/
public DyIOChannelEvent(DyIOChannel c, Integer integer) {
// TODO Auto-generated constructor stub
this.channel =c;
this.integer = integer;
}
/**
* Gets the channel.
*
* @return the channel
*/
public DyIOChannel getChannel() {
return channel;
}
/**
* Gets the data.
*
* @return the data
*/
public ByteList getData() {
return data;
}
/**
* Gets the value.
*
* @return the value
*/
public int getValue() {
if(integer!=null)
return integer;
int value;
DyIOChannelMode mode = getChannel().getCurrentMode();
if(channel.isStreamChannel())
return 0;
switch(mode){
case COUNT_IN_DIR:
case COUNT_IN_INT:
case COUNT_OUT_DIR:
case COUNT_OUT_INT:
value = getSignedValue();
break;
default:
value = getUnsignedValue();
break;
}
return value;
}
/**
* Gets the unsigned value.
*
* @return the unsigned value
*/
public int getUnsignedValue() {
if(integer!=null)
return integer;
return ByteList.convertToInt(getData().getBytes(),false);
}
/**
* Gets the signed value.
*
* @return the signed value
*/
public int getSignedValue() {
if(integer!=null)
return integer;
int value =ByteList.convertToInt(getData().getBytes(),true);
return value;
}
}
| 2,707 | Java | .java | 113 | 21.168142 | 80 | 0.666278 | NeuronRobotics/java-bowler | 12 | 5 | 6 | LGPL-3.0 | 9/4/2024, 8:15:25 PM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 2,707 |
4,252,881 | Projection.java | rockleeprc_sourcecode/spring-framework/spring-expression/src/main/java/org/springframework/expression/spel/ast/Projection.java | /*
* Copyright 2002-2017 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.expression.spel.ast;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.ExpressionState;
import org.springframework.expression.spel.SpelEvaluationException;
import org.springframework.expression.spel.SpelMessage;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
/**
* Represents projection, where a given operation is performed on all elements in some
* input sequence, returning a new sequence of the same size. For example:
* "{1,2,3,4,5,6,7,8,9,10}.!{#isEven(#this)}" returns "[n, y, n, y, n, y, n, y, n, y]"
*
* @author Andy Clement
* @author Mark Fisher
* @author Juergen Hoeller
* @since 3.0
*/
public class Projection extends SpelNodeImpl {
private final boolean nullSafe;
public Projection(boolean nullSafe, int pos, SpelNodeImpl expression) {
super(pos, expression);
this.nullSafe = nullSafe;
}
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
return getValueRef(state).getValue();
}
@Override
protected ValueRef getValueRef(ExpressionState state) throws EvaluationException {
TypedValue op = state.getActiveContextObject();
Object operand = op.getValue();
boolean operandIsArray = ObjectUtils.isArray(operand);
// TypeDescriptor operandTypeDescriptor = op.getTypeDescriptor();
// When the input is a map, we push a special context object on the stack
// before calling the specified operation. This special context object
// has two fields 'key' and 'value' that refer to the map entries key
// and value, and they can be referenced in the operation
// eg. {'a':'y','b':'n'}.![value=='y'?key:null]" == ['a', null]
if (operand instanceof Map) {
Map<?, ?> mapData = (Map<?, ?>) operand;
List<Object> result = new ArrayList<>();
for (Map.Entry<?, ?> entry : mapData.entrySet()) {
try {
state.pushActiveContextObject(new TypedValue(entry));
state.enterScope();
result.add(this.children[0].getValueInternal(state).getValue());
}
finally {
state.popActiveContextObject();
state.exitScope();
}
}
return new ValueRef.TypedValueHolderValueRef(new TypedValue(result), this); // TODO unable to build correct type descriptor
}
if (operand instanceof Iterable || operandIsArray) {
Iterable<?> data = (operand instanceof Iterable ?
(Iterable<?>) operand : Arrays.asList(ObjectUtils.toObjectArray(operand)));
List<Object> result = new ArrayList<>();
int idx = 0;
Class<?> arrayElementType = null;
for (Object element : data) {
try {
state.pushActiveContextObject(new TypedValue(element));
state.enterScope("index", idx);
Object value = this.children[0].getValueInternal(state).getValue();
if (value != null && operandIsArray) {
arrayElementType = determineCommonType(arrayElementType, value.getClass());
}
result.add(value);
}
finally {
state.exitScope();
state.popActiveContextObject();
}
idx++;
}
if (operandIsArray) {
if (arrayElementType == null) {
arrayElementType = Object.class;
}
Object resultArray = Array.newInstance(arrayElementType, result.size());
System.arraycopy(result.toArray(), 0, resultArray, 0, result.size());
return new ValueRef.TypedValueHolderValueRef(new TypedValue(resultArray),this);
}
return new ValueRef.TypedValueHolderValueRef(new TypedValue(result),this);
}
if (operand == null) {
if (this.nullSafe) {
return ValueRef.NullValueRef.INSTANCE;
}
throw new SpelEvaluationException(getStartPosition(), SpelMessage.PROJECTION_NOT_SUPPORTED_ON_TYPE, "null");
}
throw new SpelEvaluationException(getStartPosition(), SpelMessage.PROJECTION_NOT_SUPPORTED_ON_TYPE,
operand.getClass().getName());
}
@Override
public String toStringAST() {
return "![" + getChild(0).toStringAST() + "]";
}
private Class<?> determineCommonType(@Nullable Class<?> oldType, Class<?> newType) {
if (oldType == null) {
return newType;
}
if (oldType.isAssignableFrom(newType)) {
return oldType;
}
Class<?> nextType = newType;
while (nextType != Object.class) {
if (nextType.isAssignableFrom(oldType)) {
return nextType;
}
nextType = nextType.getSuperclass();
}
for (Class<?> nextInterface : ClassUtils.getAllInterfacesForClassAsSet(newType)) {
if (nextInterface.isAssignableFrom(oldType)) {
return nextInterface;
}
}
return Object.class;
}
}
| 5,373 | Java | .java | 143 | 34.174825 | 127 | 0.736802 | rockleeprc/sourcecode | 2 | 2 | 0 | GPL-3.0 | 9/5/2024, 12:07:03 AM (Europe/Amsterdam) | false | true | false | true | true | true | true | true | 5,373 |
4,947,207 | BudgetConstructionSynchronizationProblemsReportDaoJdbc.java | ua-eas_ua-kfs-5_3/work/src/org/kuali/kfs/module/bc/document/dataaccess/impl/BudgetConstructionSynchronizationProblemsReportDaoJdbc.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.bc.document.dataaccess.impl;
import java.util.ArrayList;
import org.kuali.kfs.module.bc.BCConstants;
import org.kuali.kfs.module.bc.batch.dataaccess.impl.SQLForStep;
import org.kuali.kfs.module.bc.document.dataaccess.BudgetConstructionSynchronizationProblemsReportDao;
import org.kuali.kfs.sys.KFSConstants.BudgetConstructionPositionConstants;
/**
* builds a report table of people whose salaries are budgeted in the wrong object class or have had a position change that merits
* an object code validity check
*/
public class BudgetConstructionSynchronizationProblemsReportDaoJdbc extends BudgetConstructionDaoJdbcBase implements BudgetConstructionSynchronizationProblemsReportDao {
private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(BudgetConstructionSynchronizationProblemsReportDaoJdbc.class);
protected static ArrayList<SQLForStep> updateReportsSynchronizationProblemsTable = new ArrayList<SQLForStep>(2);
public BudgetConstructionSynchronizationProblemsReportDaoJdbc() {
ArrayList<Integer> insertionPoints = new ArrayList<Integer>(2);
// builds and updates SynchronizationProblemsReports
// builds the salary and default object check MT table
StringBuilder sqlText = new StringBuilder(1500);
sqlText.append("INSERT INTO LD_BCN_POS_FND_T \n");
sqlText.append("(PERSON_UNVL_ID, SEL_ORG_FIN_COA, SEL_ORG_CD, PERSON_NM, EMPLID, POSITION_NBR, \n");
sqlText.append(" UNIV_FISCAL_YR, FIN_COA_CD, ACCOUNT_NBR, SUB_ACCT_NBR, FIN_OBJECT_CD, FIN_SUB_OBJ_CD) \n");
sqlText.append("SELECT ?, ctrl.sel_org_fin_coa, ctrl.sel_org_cd, COALESCE(iinc.PERSON_NM,'Name not Found'), bcaf.emplid, bcaf.position_nbr, \n");
sqlText.append(" bcaf.univ_fiscal_yr, bcaf.fin_coa_cd, bcaf.account_nbr, bcaf.sub_acct_nbr, bcaf.fin_object_cd, bcaf.fin_sub_obj_cd \n");
sqlText.append("FROM (LD_PNDBC_APPTFND_T bcaf LEFT OUTER JOIN LD_BCN_INTINCBNT_T iinc ON (bcaf.emplid = iinc.emplid)), LD_BCN_CTRL_LIST_T ctrl \n");
sqlText.append("WHERE ctrl.person_unvl_id = ? \n");
sqlText.append(" AND bcaf.univ_fiscal_yr = ctrl.univ_fiscal_yr \n");
sqlText.append(" AND bcaf.fin_coa_cd = ctrl.fin_coa_cd \n");
sqlText.append(" AND bcaf.account_nbr = ctrl.account_nbr \n");
sqlText.append(" AND bcaf.sub_acct_nbr = ctrl.sub_acct_nbr \n");
sqlText.append(" AND bcaf.appt_fnd_dlt_cd = 'N' \n");
sqlText.append(" AND (bcaf.pos_obj_chg_ind = 'Y' OR bcaf.pos_sal_chg_ind = 'Y') \n");
sqlText.append(" UNION ALL\n");
sqlText.append("SELECT ?, ctrl.sel_org_fin_coa, ctrl.sel_org_cd, COALESCE(iinc.PERSON_NM,'Name not Found'), bcaf.emplid, bcaf.position_nbr, \n");
sqlText.append(" bcaf.univ_fiscal_yr, bcaf.fin_coa_cd, bcaf.account_nbr, bcaf.sub_acct_nbr, bcaf.fin_object_cd, bcaf.fin_sub_obj_cd \n");
sqlText.append("FROM (LD_PNDBC_APPTFND_T bcaf LEFT OUTER JOIN LD_BCN_INTINCBNT_T iinc ON (bcaf.emplid = iinc.emplid)), LD_BCN_POS_T bp, LD_BCN_CTRL_LIST_T ctrl \n");
sqlText.append("WHERE ctrl.person_unvl_id = ? \n");
sqlText.append(" AND bcaf.univ_fiscal_yr = ctrl.univ_fiscal_yr \n");
sqlText.append(" AND bcaf.fin_coa_cd = ctrl.fin_coa_cd \n");
sqlText.append(" AND bcaf.account_nbr = ctrl.account_nbr \n");
sqlText.append(" AND bcaf.sub_acct_nbr = ctrl.sub_acct_nbr \n");
sqlText.append(" AND bcaf.appt_fnd_dlt_cd = 'N' \n");
sqlText.append(" AND bcaf.pos_obj_chg_ind <> 'Y' \n");
sqlText.append(" AND bcaf.pos_sal_chg_ind <> 'Y' \n");
sqlText.append(" AND bcaf.univ_fiscal_yr = bp.univ_fiscal_yr \n");
sqlText.append(" AND bcaf.position_nbr = bp.position_nbr \n");
sqlText.append(" AND (bp.pos_eff_status <> '");
// active effective status
insertionPoints.add(sqlText.length());
sqlText.append("' OR bp.budgeted_posn <> 'Y') \n");
updateReportsSynchronizationProblemsTable.add(new SQLForStep(sqlText, insertionPoints));
sqlText.delete(0, sqlText.length());
insertionPoints.clear();
sqlText.append("UPDATE LD_BCN_POS_FND_T \n");
sqlText.append("SET PERSON_NM = '");
// the string indicating a vacant EMPLID
insertionPoints.add(sqlText.length());
sqlText.append("' \n");
sqlText.append("WHERE (PERSON_UNVL_ID = ?) \n");
sqlText.append("AND (EMPLID = '");
// the string indicating a vacant EMPLID
insertionPoints.add(sqlText.length());
sqlText.append("')");
updateReportsSynchronizationProblemsTable.add(new SQLForStep(sqlText, insertionPoints));
sqlText.delete(0, sqlText.length());
insertionPoints.clear();
}
/**
* removes any rows from a previous report for this uear
*
* @param principalName--the user requesting the report
*/
protected void cleanReportsSynchronizationProblemsTable(String principalName) {
clearTempTableByUnvlId("LD_BCN_POS_FND_T", "PERSON_UNVL_ID", principalName);
}
/**
* @see org.kuali.kfs.module.bc.document.dataaccess.BudgetConstructionSynchronizationProblemsReportDao#updateReportsSynchronizationProblemsTable(java.lang.String)
*/
public void updateReportsSynchronizationProblemsTable(String principalName) {
ArrayList<String> stringsToInsert = new ArrayList<String>(2);
// get rid of any old reports sitting around for this user
cleanReportsSynchronizationProblemsTable(principalName);
// insert the code for an active position
stringsToInsert.add(BudgetConstructionPositionConstants.POSITION_EFFECTIVE_STATUS_ACTIVE);
// insert into the report table filled or vacant lines with an object code change, a position change, or an inactive
// position
getSimpleJdbcTemplate().update(updateReportsSynchronizationProblemsTable.get(0).getSQL(stringsToInsert), principalName, principalName, principalName, principalName);
// change the name field for any line with a vacant position
stringsToInsert.clear();
stringsToInsert.add(BCConstants.VACANT_EMPLID);
stringsToInsert.add(BCConstants.VACANT_EMPLID);
getSimpleJdbcTemplate().update(updateReportsSynchronizationProblemsTable.get(1).getSQL(stringsToInsert), principalName);
}
}
| 7,326 | Java | .java | 111 | 58.189189 | 174 | 0.705637 | ua-eas/ua-kfs-5.3 | 1 | 0 | 0 | AGPL-3.0 | 9/5/2024, 12:36:54 AM (Europe/Amsterdam) | true | true | true | true | false | true | false | true | 7,326 |
4,916,435 | SelectionOnParameterizedQualifiedTypeReference.java | trylimits_Eclipse-Postfix-Code-Completion-Juno38/juno38/org.eclipse.jdt.core/codeassist/org/eclipse/jdt/internal/codeassist/select/SelectionOnParameterizedQualifiedTypeReference.java | /*******************************************************************************
* Copyright (c) 2000, 2009 IBM Corporation 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
*******************************************************************************/
package org.eclipse.jdt.internal.codeassist.select;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.internal.compiler.ast.ParameterizedQualifiedTypeReference;
import org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.eclipse.jdt.internal.compiler.lookup.BlockScope;
import org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
public class SelectionOnParameterizedQualifiedTypeReference extends ParameterizedQualifiedTypeReference {
public SelectionOnParameterizedQualifiedTypeReference(char[][] previousIdentifiers, char[] selectionIdentifier, TypeReference[][] typeArguments, TypeReference[] assistTypeArguments, long[] positions) {
super(
CharOperation.arrayConcat(previousIdentifiers, selectionIdentifier),
typeArguments,
0,
positions);
int length = this.typeArguments.length;
System.arraycopy(this.typeArguments, 0, this.typeArguments = new TypeReference[length + 1][], 0, length);
this.typeArguments[length] = assistTypeArguments;
}
public TypeBinding resolveType(BlockScope scope, boolean checkBounds) {
super.resolveType(scope, checkBounds);
//// removed unnecessary code to solve bug 94653
//if(this.resolvedType != null && this.resolvedType.isRawType()) {
// ParameterizedTypeBinding parameterizedTypeBinding = scope.createParameterizedType(((RawTypeBinding)this.resolvedType).type, new TypeBinding[0], this.resolvedType.enclosingType());
// throw new SelectionNodeFound(parameterizedTypeBinding);
//}
throw new SelectionNodeFound(this.resolvedType);
}
public TypeBinding resolveType(ClassScope scope) {
super.resolveType(scope);
//// removed unnecessary code to solve bug 94653
//if(this.resolvedType != null && this.resolvedType.isRawType()) {
// ParameterizedTypeBinding parameterizedTypeBinding = scope.createParameterizedType(((RawTypeBinding)this.resolvedType).type, new TypeBinding[0], this.resolvedType.enclosingType());
// throw new SelectionNodeFound(parameterizedTypeBinding);
//}
throw new SelectionNodeFound(this.resolvedType);
}
public StringBuffer printExpression(int indent, StringBuffer output) {
output.append("<SelectOnType:");//$NON-NLS-1$
int length = this.tokens.length;
for (int i = 0; i < length; i++) {
if(i != 0) {
output.append('.');
}
output.append(this.tokens[i]);
TypeReference[] typeArgument = this.typeArguments[i];
if (typeArgument != null) {
output.append('<');
int max = typeArgument.length - 1;
for (int j = 0; j < max; j++) {
typeArgument[j].print(0, output);
output.append(", ");//$NON-NLS-1$
}
typeArgument[max].print(0, output);
output.append('>');
}
}
output.append('>');
return output;
}
}
| 3,314 | Java | .java | 70 | 44.357143 | 202 | 0.731933 | trylimits/Eclipse-Postfix-Code-Completion-Juno38 | 1 | 0 | 0 | EPL-1.0 | 9/5/2024, 12:35:46 AM (Europe/Amsterdam) | false | false | true | false | true | true | true | true | 3,314 |
1,591,588 | Obfuscation.java | Tianscar_carbonized-pixel-dungeon/core/src/main/java/com/tianscar/carbonizedpixeldungeon/items/armor/glyphs/Obfuscation.java | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2021 Evan Debenham
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.tianscar.carbonizedpixeldungeon.items.armor.glyphs;
import com.tianscar.carbonizedpixeldungeon.actors.Char;
import com.tianscar.carbonizedpixeldungeon.items.armor.Armor;
import com.tianscar.carbonizedpixeldungeon.sprites.ItemSprite;
public class Obfuscation extends Armor.Glyph {
private static ItemSprite.Glowing GREY = new ItemSprite.Glowing( 0x888888 );
@Override
public int proc(Armor armor, Char attacker, Char defender, int damage) {
//no proc effect, see armor.stealthfactor for effect.
return damage;
}
@Override
public ItemSprite.Glowing glowing() {
return GREY;
}
}
| 1,389 | Java | .java | 36 | 36.5 | 77 | 0.786033 | Tianscar/carbonized-pixel-dungeon | 29 | 5 | 1 | GPL-3.0 | 9/4/2024, 8:01:39 PM (Europe/Amsterdam) | false | false | false | false | false | true | true | true | 1,389 |
1,314,386 | AFileFilter.java | eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests/examples/org/eclipse/jdt/ui/examples/filters/AFileFilter.java | /*******************************************************************************
* Copyright (c) 2005, 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 org.eclipse.jdt.ui.examples.filters;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jdt.core.ICompilationUnit;
public class AFileFilter extends ViewerFilter {
public AFileFilter() {
// TODO Auto-generated constructor stub
}
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (element instanceof ICompilationUnit) {
return !"A.java".equals(((ICompilationUnit) element).getElementName());
}
return true;
}
}
| 1,093 | Java | .java | 29 | 35.517241 | 81 | 0.661626 | eclipse-jdt/eclipse.jdt.ui | 35 | 86 | 242 | EPL-2.0 | 9/4/2024, 7:34:16 PM (Europe/Amsterdam) | false | false | false | false | false | true | true | true | 1,093 |
1,312,748 | FindReferencesInProjectAction.java | eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/FindReferencesInProjectAction.java | /*******************************************************************************
* Copyright (c) 2000, 2017 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.ui.actions;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ILocalVariable;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IModuleDescription;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeParameter;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.ui.search.ElementQuerySpecification;
import org.eclipse.jdt.ui.search.QuerySpecification;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.search.JavaSearchScopeFactory;
import org.eclipse.jdt.internal.ui.search.SearchMessages;
/**
* Finds references to the selected element in the enclosing project
* of the selected element.
* The action is applicable to selections representing a Java element.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 3.0
*
* @noextend This class is not intended to be subclassed by clients.
*/
public class FindReferencesInProjectAction extends FindReferencesAction {
/**
* Creates a new <code>FindReferencesInProjectAction</code>. The action
* requires that the selection provided by the site's selection provider is of type
* <code>IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public FindReferencesInProjectAction(IWorkbenchSite site) {
super(site);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
* @param editor the Java editor
*
* @noreference This constructor is not intended to be referenced by clients.
*/
public FindReferencesInProjectAction(JavaEditor editor) {
super(editor);
}
@Override
Class<?>[] getValidTypes() {
return new Class[] { IField.class, IMethod.class, IType.class, ICompilationUnit.class, IPackageDeclaration.class, IImportDeclaration.class, IPackageFragment.class, ILocalVariable.class,
ITypeParameter.class, IModuleDescription.class };
}
@Override
void init() {
setText(SearchMessages.Search_FindReferencesInProjectAction_label);
setToolTipText(SearchMessages.Search_FindReferencesInProjectAction_tooltip);
setImageDescriptor(JavaPluginImages.DESC_OBJS_SEARCH_REF);
PlatformUI.getWorkbench().getHelpSystem().setHelp(this, IJavaHelpContextIds.FIND_REFERENCES_IN_PROJECT_ACTION);
}
@Override
QuerySpecification createQuery(IJavaElement element) throws JavaModelException {
JavaSearchScopeFactory factory= JavaSearchScopeFactory.getInstance();
JavaEditor editor= getEditor();
IJavaSearchScope scope;
String description;
boolean isInsideJRE= factory.isInsideJRE(element);
if (editor != null) {
scope= factory.createJavaProjectSearchScope(editor.getEditorInput(), isInsideJRE);
description= factory.getProjectScopeDescription(editor.getEditorInput(), isInsideJRE);
} else {
scope= factory.createJavaProjectSearchScope(element.getJavaProject(), isInsideJRE);
description= factory.getProjectScopeDescription(element.getJavaProject(), isInsideJRE);
}
return new ElementQuerySpecification(element, getLimitTo(), scope, description);
}
}
| 4,170 | Java | .java | 98 | 40.316327 | 187 | 0.777586 | eclipse-jdt/eclipse.jdt.ui | 35 | 86 | 242 | EPL-2.0 | 9/4/2024, 7:34:16 PM (Europe/Amsterdam) | false | true | true | false | false | true | true | true | 4,170 |
3,387,343 | Clock.java | FzArnob_Covidease/sources/com/google/android/gms/common/util/Clock.java | package com.google.android.gms.common.util;
import com.google.android.gms.common.annotation.KeepForSdk;
import com.google.android.gms.common.internal.ShowFirstParty;
@ShowFirstParty
@KeepForSdk
public interface Clock {
@KeepForSdk
long currentThreadTimeMillis();
@KeepForSdk
long currentTimeMillis();
@KeepForSdk
long elapsedRealtime();
@KeepForSdk
long nanoTime();
}
| 405 | Java | .java | 15 | 23.533333 | 61 | 0.787013 | FzArnob/Covidease | 4 | 0 | 0 | GPL-3.0 | 9/4/2024, 11:17:41 PM (Europe/Amsterdam) | false | false | false | true | false | false | true | true | 405 |
36,301 | Bug3079260.java | spotbugs_spotbugs/spotbugsTestCases/src/java/sfBugs/Bug3079260.java | package sfBugs;
import java.sql.Connection;
import java.sql.PreparedStatement;
import edu.umd.cs.findbugs.annotations.ExpectWarning;
import edu.umd.cs.findbugs.annotations.NoWarning;
public class Bug3079260 {
@NoWarning("OBL_UNSATISFIED_OBLIGATION")
@ExpectWarning("OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE")
public PreparedStatement buildGetDataSetStatement(Connection conn) throws Exception {
PreparedStatement stmt = conn.prepareStatement("select * from blah");
stmt.execute();
return stmt;
}
}
| 542 | Java | .java | 14 | 34.642857 | 89 | 0.780952 | spotbugs/spotbugs | 3,446 | 585 | 442 | LGPL-2.1 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | true | false | true | true | true | true | 542 |
2,240,960 | ReadStreamInput.java | dlitz_resin/modules/quercus/src/com/caucho/quercus/lib/file/ReadStreamInput.java | /*
* Copyright (c) 1998-2011 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.lib.file;
import com.caucho.quercus.QuercusModuleException;
import com.caucho.quercus.env.*;
import com.caucho.vfs.ReadStream;
import com.caucho.vfs.VfsStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Represents a Quercus file open for reading
*/
public class ReadStreamInput extends InputStream implements BinaryInput {
private static final Logger log
= Logger.getLogger(ReadStreamInput.class.getName());
private Env _env;
private LineReader _lineReader;
private ReadStream _is;
public ReadStreamInput(Env env)
{
_env = env;
}
public ReadStreamInput(Env env, InputStream is)
{
_env = env;
if (is instanceof ReadStream)
init((ReadStream) is);
else if (is != null)
init(new ReadStream(new VfsStream(is, null)));
}
protected ReadStreamInput(Env env, LineReader lineReader)
{
_env = env;
_lineReader = lineReader;
}
protected ReadStreamInput(Env env, LineReader lineReader, ReadStream is)
{
this(env, lineReader);
init(is);
}
public void init(ReadStream is)
{
_is = is;
}
/**
* Returns the input stream.
*/
public InputStream getInputStream()
{
return _is;
}
/**
* Opens a copy.
*/
public BinaryInput openCopy()
throws IOException
{
return new ReadStreamInput(_env, _lineReader, _is.getPath().openRead());
}
public void setEncoding(String encoding)
throws UnsupportedEncodingException
{
if (_is != null)
_is.setEncoding(encoding);
}
/**
*
*/
public void unread()
throws IOException
{
if (_is != null)
_is.unread();
}
/**
* Reads a character from a file, returning -1 on EOF.
*/
public int read()
throws IOException
{
if (_is != null)
return _is.read();
else
return -1;
}
/**
* Reads a buffer from a file, returning -1 on EOF.
*/
@Override
public int read(byte []buffer, int offset, int length)
throws IOException
{
ReadStream is = _is;
if (is == null)
return -1;
int readLength = 0;
do {
int sublen = is.read(buffer, offset, length);
if (sublen < 0)
return readLength > 0 ? readLength : sublen;
readLength += sublen;
length -= sublen;
offset += sublen;
} while (length > 0 && is.getAvailable() > 0);
return readLength;
}
/**
* Reads a buffer from a file, returning -1 on EOF.
*/
public int read(char []buffer, int offset, int length)
throws IOException
{
if (_is != null) {
return _is.read(buffer, offset, length);
}
else
return -1;
}
/**
* Reads into a binary builder.
*/
public StringValue read(int length)
throws IOException
{
if (_is == null)
return null;
StringValue bb = _env.createBinaryBuilder();
bb.appendReadAll(_is, length);
return bb;
}
/**
* Reads the optional linefeed character from a \r\n
*/
public boolean readOptionalLinefeed()
throws IOException
{
if (_is == null)
return false;
int ch = _is.read();
if (ch == '\n') {
return true;
}
else {
_is.unread();
return false;
}
}
public void writeToStream(OutputStream os, int length)
throws IOException
{
if (_is != null) {
_is.writeToStream(os, length);
}
}
/**
* Appends to a string builder.
*/
public StringValue appendTo(StringValue builder)
{
if (_is != null)
return builder.append(_is);
else
return builder;
}
/**
* Reads a line from a file, returning null on EOF.
*/
public StringValue readLine(long length)
throws IOException
{
return getLineReader().readLine(_env, this, length);
}
/**
* Returns true on the EOF.
*/
public boolean isEOF()
{
if (_is == null)
return true;
else {
try {
// XXX: not quite right for sockets
return _is.available() <= 0;
} catch (IOException e) {
log.log(Level.FINE, e.toString(), e);
return true;
}
}
}
/**
* Returns the current location in the file.
*/
public long getPosition()
{
if (_is == null)
return -1;
else
return _is.getPosition();
}
/**
* Returns the current location in the file.
*/
public boolean setPosition(long offset)
{
if (_is == null)
return false;
try {
return _is.setPosition(offset);
} catch (IOException e) {
throw new QuercusModuleException(e);
}
}
public long seek(long offset, int whence)
{
long position;
switch (whence) {
case BinaryStream.SEEK_CUR:
position = getPosition() + offset;
break;
case BinaryStream.SEEK_END:
// don't necessarily have an end
position = getPosition();
break;
case BinaryStream.SEEK_SET:
default:
position = offset;
break;
}
if (! setPosition(position))
return -1L;
else
return position;
}
public Value stat()
{
return BooleanValue.FALSE;
}
private LineReader getLineReader()
{
if (_lineReader == null)
_lineReader = new LineReader(_env);
return _lineReader;
}
/**
* Closes the stream for reading.
*/
public void closeRead()
{
close();
}
/**
* Closes the file.
*/
public void close()
{
ReadStream is = _is;
_is = null;
if (is != null)
is.close();
}
public Object toJavaObject()
{
return this;
}
public String getResourceType()
{
return "stream";
}
/**
* Converts to a string.
*/
public String toString()
{
return "ReadStreamInput[" + _is.getPath() + "]";
}
}
| 6,964 | Java | .java | 306 | 18.29085 | 76 | 0.644553 | dlitz/resin | 9 | 8 | 0 | GPL-2.0 | 9/4/2024, 8:40:27 PM (Europe/Amsterdam) | false | false | true | false | false | true | false | true | 6,964 |
1,786,300 | ListOrderedSet.java | stefandmn_AREasy/src/java/org/areasy/common/data/type/set/ListOrderedSet.java | package org.areasy.common.data.type.set;
/*
* Copyright (c) 2007-2020 AREasy Runtime
*
* This library, AREasy Runtime and API for BMC Remedy AR System, is free software ("Licensed Software");
* you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either version 2.1 of the License,
* or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* including but not limited to, the implied warranty of MERCHANTABILITY, NONINFRINGEMENT,
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*/
import org.areasy.common.data.type.iterator.AbstractIteratorDecorator;
import org.areasy.common.data.type.list.UnmodifiableList;
import java.util.*;
/**
* Decorates another <code>Set</code> to ensure that the order of addition
* is retained and used by the iterator.
* <p/>
* If an object is added to the set for a second time, it will remain in the
* original position in the iteration.
* The order can be observed from the set via the iterator or toArray methods.
* <p/>
* The ListOrderedSet also has various useful direct methods. These include many
* from <code>List</code>, such as <code>get(int)</code>, <code>remove(int)</code>
* and <code>indexOf(int)</code>. An unmodifiable <code>List</code> view of
* the set can be obtained via <code>asList()</code>.
* <p/>
* This class cannot implement the <code>List</code> interface directly as
* various interface methods (notably equals/hashCode) are incompatable with a set.
*
* @version $Id: ListOrderedSet.java,v 1.2 2008/05/14 09:32:37 swd\stefan.damian Exp $
*/
public class ListOrderedSet extends AbstractSerializableSetDecorator implements Set
{
/**
* Internal list to hold the sequence of objects
*/
protected final List setOrder;
/**
* Factory method to create an ordered set specifying the list and set to use.
*
* @param set the set to decorate, must be empty and not null
* @param list the list to decorate, must be empty and not null
* @throws IllegalArgumentException if set or list is null
* @throws IllegalArgumentException if either the set or list is not empty
*/
public static ListOrderedSet decorate(Set set, List list)
{
if (set == null) throw new IllegalArgumentException("Set must not be null");
if (list == null) throw new IllegalArgumentException("List must not be null");
if (set.size() > 0 || list.size() > 0) throw new IllegalArgumentException("Set and List must be empty");
return new ListOrderedSet(set, list);
}
/**
* Factory method to create an ordered set.
* <p/>
* An <code>ArrayList</code> is used to retain order.
*
* @param set the set to decorate, must not be null
* @throws IllegalArgumentException if set is null
*/
public static ListOrderedSet decorate(Set set)
{
return new ListOrderedSet(set);
}
/**
* Factory method to create an ordered set using the supplied list to retain order.
* <p/>
* A <code>HashSet</code> is used for the set behaviour.
*
* @param list the list to decorate, must not be null
* @throws IllegalArgumentException if list is null
*/
public static ListOrderedSet decorate(List list)
{
if (list == null) throw new IllegalArgumentException("List must not be null");
Set set = new HashSet(list);
list.retainAll(set);
return new ListOrderedSet(set, list);
}
/**
* Constructs a new empty <code>ListOrderedSet</code> using
* a <code>HashSet</code> and an <code>ArrayList</code> internally.
*
*/
public ListOrderedSet()
{
super(new HashSet());
setOrder = new ArrayList();
}
/**
* Constructor that wraps (not copies).
*
* @param set the set to decorate, must not be null
* @throws IllegalArgumentException if set is null
*/
protected ListOrderedSet(Set set)
{
super(set);
setOrder = new ArrayList(set);
}
/**
* Constructor that wraps (not copies) the Set and specifies the list to use.
* <p/>
* The set and list must both be correctly initialised to the same elements.
*
* @param set the set to decorate, must not be null
* @param list the list to decorate, must not be null
* @throws IllegalArgumentException if set or list is null
*/
protected ListOrderedSet(Set set, List list)
{
super(set);
if (list == null) throw new IllegalArgumentException("List must not be null");
setOrder = list;
}
/**
* Gets an unmodifiable view of the order of the Set.
*
* @return an unmodifiable list view
*/
public List asList()
{
return UnmodifiableList.decorate(setOrder);
}
public void clear()
{
collection.clear();
setOrder.clear();
}
public Iterator iterator()
{
return new OrderedSetIterator(setOrder.iterator(), collection);
}
public boolean add(Object object)
{
if (collection.contains(object)) return collection.add(object);
else
{
// first add, so add to both set and list
boolean result = collection.add(object);
setOrder.add(object);
return result;
}
}
public boolean addAll(Collection coll)
{
boolean result = false;
for (Iterator it = coll.iterator(); it.hasNext();)
{
Object object = it.next();
result = result | add(object);
}
return result;
}
public boolean remove(Object object)
{
boolean result = collection.remove(object);
setOrder.remove(object);
return result;
}
public boolean removeAll(Collection coll)
{
boolean result = false;
for (Iterator it = coll.iterator(); it.hasNext();)
{
Object object = it.next();
result = result | remove(object);
}
return result;
}
public boolean retainAll(Collection coll)
{
boolean result = collection.retainAll(coll);
if (result == false) return false;
else if (collection.size() == 0) setOrder.clear();
else
{
for (Iterator it = setOrder.iterator(); it.hasNext();)
{
Object object = it.next();
if (collection.contains(object) == false) it.remove();
}
}
return result;
}
public Object[] toArray()
{
return setOrder.toArray();
}
public Object[] toArray(Object a[])
{
return setOrder.toArray(a);
}
public Object get(int index)
{
return setOrder.get(index);
}
public int indexOf(Object object)
{
return setOrder.indexOf(object);
}
public void add(int index, Object object)
{
if (contains(object) == false)
{
collection.add(object);
setOrder.add(index, object);
}
}
public boolean addAll(int index, Collection coll)
{
boolean changed = false;
for (Iterator it = coll.iterator(); it.hasNext();)
{
Object object = it.next();
if (contains(object) == false)
{
collection.add(object);
setOrder.add(index, object);
index++;
changed = true;
}
}
return changed;
}
public Object remove(int index)
{
Object obj = setOrder.remove(index);
remove(obj);
return obj;
}
/**
* Uses the underlying List's toString so that order is achieved.
* This means that the decorated Set's toString is not used, so
* any custom toStrings will be ignored.
*/
public String toString()
{
return setOrder.toString();
}
/**
* Internal iterator handle remove.
*/
static class OrderedSetIterator extends AbstractIteratorDecorator
{
/**
* Object we iterate on
*/
protected final Collection set;
/**
* Last object retrieved
*/
protected Object last;
private OrderedSetIterator(Iterator iterator, Collection set)
{
super(iterator);
this.set = set;
}
public Object next()
{
last = iterator.next();
return last;
}
public void remove()
{
set.remove(last);
iterator.remove();
last = null;
}
}
}
| 8,040 | Java | .java | 274 | 25.273723 | 107 | 0.692107 | stefandmn/AREasy | 10 | 1 | 3 | LGPL-3.0 | 9/4/2024, 8:18:34 PM (Europe/Amsterdam) | false | false | true | false | false | true | true | true | 8,040 |
888,683 | Keccak512.java | hyperchain_javasdk/src/main/java/cn/hyperchain/sdk/crypto/cryptohash/Keccak512.java | package cn.hyperchain.sdk.crypto.cryptohash;
/**
* <p>This class implements the Keccak-256 digest algorithm under the
* {@link Digest} API.</p>
*
* <pre>
* ==========================(LICENSE BEGIN)============================
*
* Copyright (c) 2007-2010 Projet RNRT SAPHIR
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* ===========================(LICENSE END)=============================
* </pre>
*
* @author Thomas Pornin <thomas.pornin@cryptolog.com>
* @version $Revision: 189 $
*/
public class Keccak512 extends KeccakCore {
/**
* Create the engine.
*/
public Keccak512() {
}
/**
* @see Digest
*/
public Digest copy() {
return copyState(new Keccak512());
}
/**
* @see Digest
*/
public int getDigestLength() {
return 64;
}
}
| 1,872 | Java | .java | 54 | 31.444444 | 73 | 0.672366 | hyperchain/javasdk | 66 | 37 | 14 | LGPL-3.0 | 9/4/2024, 7:09:48 PM (Europe/Amsterdam) | false | false | false | false | false | true | true | true | 1,872 |
1,926,837 | WorkflowStateApplication.java | gxing19_Spring-Boot-Example/spring-boot-workflow-state/src/main/java/com/gxitsky/WorkflowStateApplication.java | package com.gxitsky;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WorkflowStateApplication {
public static void main(String[] args) {
SpringApplication.run(WorkflowStateApplication.class, args);
}
}
| 330 | Java | .java | 9 | 33.444444 | 68 | 0.829653 | gxing19/Spring-Boot-Example | 13 | 12 | 39 | GPL-3.0 | 9/4/2024, 8:23:29 PM (Europe/Amsterdam) | false | true | false | false | false | true | true | true | 330 |
4,494,299 | UpdateAnimationStateSystem.java | timtheemployee_pirates-public/core/src/com/wxxtfxrmx/pirates/screen/levelv2/layer/board/system/animation/UpdateAnimationStateSystem.java | package com.wxxtfxrmx.pirates.screen.levelv2.layer.board.system.animation;
import com.badlogic.ashley.core.ComponentMapper;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.systems.IteratingSystem;
import com.wxxtfxrmx.pirates.screen.levelv2.component.AnimationComponent;
import com.wxxtfxrmx.pirates.screen.levelv2.layer.board.component.TilePickedComponent;
public class UpdateAnimationStateSystem extends IteratingSystem {
private final ComponentMapper<AnimationComponent> animationMapper = ComponentMapper.getFor(AnimationComponent.class);
public UpdateAnimationStateSystem() {
super(Family.all(AnimationComponent.class, TilePickedComponent.class).get());
}
@Override
protected void processEntity(Entity entity, float deltaTime) {
animationMapper.get(entity).frameDelta += deltaTime;
}
}
| 894 | Java | .java | 17 | 48.941176 | 121 | 0.825688 | timtheemployee/pirates-public | 2 | 0 | 0 | GPL-3.0 | 9/5/2024, 12:14:53 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 894 |
5,037,833 | UnsupportedSchemeException.java | jrconlin_mc_backup/thirdparty/ch/boye/httpclientandroidlib/conn/UnsupportedSchemeException.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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package ch.boye.httpclientandroidlib.conn;
import java.io.IOException;
import ch.boye.httpclientandroidlib.annotation.Immutable;
/**
* Signals failure to establish connection using an unknown protocol scheme.
*
* @since 4.3
*/
@Immutable
public class UnsupportedSchemeException extends IOException {
private static final long serialVersionUID = 3597127619218687636L;
/**
* Creates a UnsupportedSchemeException with the specified detail message.
*/
public UnsupportedSchemeException(final String message) {
super(message);
}
}
| 1,755 | Java | .java | 44 | 37.295455 | 78 | 0.709507 | jrconlin/mc_backup | 1 | 0 | 0 | MPL-2.0 | 9/5/2024, 12:39:25 AM (Europe/Amsterdam) | false | true | true | false | false | true | true | true | 1,755 |
4,790,684 | VCardParser.java | mateor_PDroidHistory/frameworks/base/core/java/android/pim/vcard/VCardParser.java | /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.pim.vcard;
import android.pim.vcard.exception.VCardException;
import java.io.IOException;
import java.io.InputStream;
public interface VCardParser {
/**
* <p>
* Parses the given stream and send the vCard data into VCardBuilderBase object.
* </p>.
* <p>
* Note that vCard 2.1 specification allows "CHARSET" parameter, and some career sets
* local encoding to it. For example, Japanese phone career uses Shift_JIS, which is
* formally allowed in vCard 2.1, but not allowed in vCard 3.0. In vCard 2.1,
* In some exreme case, it is allowed for vCard to have different charsets in one vCard.
* </p>
* <p>
* We recommend you use {@link VCardSourceDetector} and detect which kind of source the
* vCard comes from and explicitly specify a charset using the result.
* </p>
*
* @param is The source to parse.
* @param interepreter A {@link VCardInterpreter} object which used to construct data.
* @throws IOException, VCardException
*/
public void parse(InputStream is, VCardInterpreter interepreter)
throws IOException, VCardException;
/**
* <p>
* Cancel parsing vCard. Useful when you want to stop the parse in the other threads.
* </p>
* <p>
* Actual cancel is done after parsing the current vcard.
* </p>
*/
public abstract void cancel();
}
| 2,028 | Java | .java | 51 | 35.411765 | 92 | 0.706538 | mateor/PDroidHistory | 1 | 2 | 0 | GPL-3.0 | 9/5/2024, 12:31:53 AM (Europe/Amsterdam) | false | false | true | true | false | true | true | true | 2,028 |
3,076,853 | PipelineImpl.java | eclipse_org_eclipse_rcptt/ecl/plugins/org.eclipse.rcptt.ecl.core/src/org/eclipse/rcptt/ecl/core/impl/PipelineImpl.java | /*******************************************************************************
* Copyright (c) 2009, 2019 Xored Software Inc 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
* https://www.eclipse.org/legal/epl-v20.html
*
* Contributors:
* Xored Software Inc - initial API and implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.rcptt.ecl.core.impl;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.rcptt.ecl.core.CorePackage;
import org.eclipse.rcptt.ecl.core.Pipeline;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Pipeline</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public class PipelineImpl extends BlockImpl implements Pipeline {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected PipelineImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return CorePackage.Literals.PIPELINE;
}
} //PipelineImpl
| 1,269 | Java | .java | 40 | 29.55 | 87 | 0.617647 | eclipse/org.eclipse.rcptt | 5 | 12 | 18 | EPL-2.0 | 9/4/2024, 10:46:42 PM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 1,269 |
3,024,589 | RasterChannel.java | sensiasoft_lib-ogc/ogc-services-sld/src/main/java/org/vast/ows/sld/RasterChannel.java | /***************************** BEGIN LICENSE BLOCK ***************************
The contents of this file are subject to the Mozilla Public License Version
1.1 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/MPL-1.1.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the License.
The Original Code is the "OGC Service Framework".
The Initial Developer of the Original Code is the VAST team at the
University of Alabama in Huntsville (UAH). <http://vast.uah.edu>
Portions created by the Initial Developer are Copyright (C) 2007
the Initial Developer. All Rights Reserved.
Please Contact Mike Botts <mike.botts@uah.edu> for more information.
Contributor(s):
Alexandre Robin <robin@nsstc.uah.edu>
******************************* END LICENSE BLOCK ***************************/
package org.vast.ows.sld;
/**
* <p>
* Object used for one of the channel selections.
* </p>
*
* @author Alex Robin
* @date Nov 11, 2005
* */
public class RasterChannel extends ScalarParameter
{
protected boolean normalize;
protected boolean histogram;
protected double gamma = 1.0;
public RasterChannel(ScalarParameter param)
{
this.constant = param.constant;
this.constantValue = param.constantValue;
this.mappingFunction = param.mappingFunction;
this.propertyName = param.propertyName;
}
public double getGamma()
{
return gamma;
}
public void setGamma(double gamma)
{
this.gamma = gamma;
}
public boolean isHistogram()
{
return histogram;
}
public void setHistogram(boolean histogram)
{
this.histogram = histogram;
}
public boolean isNormalize()
{
return normalize;
}
public void setNormalize(boolean normalize)
{
this.normalize = normalize;
}
}
| 2,123 | Java | .java | 59 | 31.084746 | 315 | 0.677467 | sensiasoft/lib-ogc | 5 | 2 | 7 | MPL-2.0 | 9/4/2024, 10:43:08 PM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 2,123 |
2,290,923 | AdxpAdditionalLocator.java | konczak_erecepta/erecepta-client-model/src/main/java/org/hl7/v3/AdxpAdditionalLocator.java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.10.03 at 11:02:58 PM CEST
//
package org.hl7.v3;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for adxp.additionalLocator complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="adxp.additionalLocator">
* <complexContent>
* <restriction base="{urn:hl7-org:v3}ADXP">
* <attribute name="partType" type="{urn:hl7-org:v3}AddressPartType" fixed="ADL" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "adxp.additionalLocator")
public class AdxpAdditionalLocator
extends ADXP {
}
| 1,142 | Java | .java | 30 | 35.966667 | 110 | 0.738462 | konczak/erecepta | 9 | 10 | 0 | AGPL-3.0 | 9/4/2024, 8:52:33 PM (Europe/Amsterdam) | true | true | true | true | true | true | true | true | 1,142 |
3,309,124 | ContactsController.java | LinXueyuanStdio_LearnTelegram/TMessagesProj/src/main/java/org/telegram/messenger/ContactsController.java | /*
* This is the source code of Telegram for Android v. 1.3.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2018.
*/
package org.telegram.messenger;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.net.Uri;
import android.os.Build;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.SparseArray;
import org.telegram.PhoneFormat.PhoneFormat;
import org.telegram.messenger.support.SparseLongArray;
import org.telegram.tgnet.ConnectionsManager;
import org.telegram.tgnet.TLRPC;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
public class ContactsController extends BaseController {
private Account systemAccount;
private boolean loadingContacts;
private final Object loadContactsSync = new Object();
private boolean ignoreChanges;
private boolean contactsSyncInProgress;
private final Object observerLock = new Object();
public boolean contactsLoaded;
private boolean contactsBookLoaded;
private boolean migratingContacts;
private String lastContactsVersions = "";
private ArrayList<Integer> delayedContactsUpdate = new ArrayList<>();
private String inviteLink;
private boolean updatingInviteLink;
private HashMap<String, String> sectionsToReplace = new HashMap<>();
private int loadingDeleteInfo;
private int deleteAccountTTL;
private int[] loadingPrivacyInfo = new int[PRIVACY_RULES_TYPE_COUNT];
private ArrayList<TLRPC.PrivacyRule> lastseenPrivacyRules;
private ArrayList<TLRPC.PrivacyRule> groupPrivacyRules;
private ArrayList<TLRPC.PrivacyRule> callPrivacyRules;
private ArrayList<TLRPC.PrivacyRule> p2pPrivacyRules;
private ArrayList<TLRPC.PrivacyRule> profilePhotoPrivacyRules;
private ArrayList<TLRPC.PrivacyRule> forwardsPrivacyRules;
private ArrayList<TLRPC.PrivacyRule> phonePrivacyRules;
private ArrayList<TLRPC.PrivacyRule> addedByPhonePrivacyRules;
public final static int PRIVACY_RULES_TYPE_LASTSEEN = 0;
public final static int PRIVACY_RULES_TYPE_INVITE = 1;
public final static int PRIVACY_RULES_TYPE_CALLS = 2;
public final static int PRIVACY_RULES_TYPE_P2P = 3;
public final static int PRIVACY_RULES_TYPE_PHOTO = 4;
public final static int PRIVACY_RULES_TYPE_FORWARDS = 5;
public final static int PRIVACY_RULES_TYPE_PHONE = 6;
public final static int PRIVACY_RULES_TYPE_ADDED_BY_PHONE = 7;
public final static int PRIVACY_RULES_TYPE_COUNT = 8;
private class MyContentObserver extends ContentObserver {
private Runnable checkRunnable = () -> {
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
if (UserConfig.getInstance(a).isClientActivated()) {
ConnectionsManager.getInstance(a).resumeNetworkMaybe();
ContactsController.getInstance(a).checkContacts();
}
}
};
public MyContentObserver() {
super(null);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
synchronized (observerLock) {
if (ignoreChanges) {
return;
}
}
Utilities.globalQueue.cancelRunnable(checkRunnable);
Utilities.globalQueue.postRunnable(checkRunnable, 500);
}
@Override
public boolean deliverSelfNotifications() {
return false;
}
}
public static class Contact {
public int contact_id;
public String key;
public String provider;
public boolean isGoodProvider;
public ArrayList<String> phones = new ArrayList<>(4);
public ArrayList<String> phoneTypes = new ArrayList<>(4);
public ArrayList<String> shortPhones = new ArrayList<>(4);
public ArrayList<Integer> phoneDeleted = new ArrayList<>(4);
public String first_name;
public String last_name;
public boolean namesFilled;
public int imported;
public TLRPC.User user;
public String getLetter() {
return getLetter(first_name, last_name);
}
public static String getLetter(String first_name, String last_name) {
String key;
if (!TextUtils.isEmpty(first_name)) {
return first_name.substring(0, 1);
} else if (!TextUtils.isEmpty(last_name)) {
return last_name.substring(0, 1);
} else {
return "#";
}
}
}
private String[] projectionPhones = {
ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.LABEL,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.RawContacts.ACCOUNT_TYPE,
};
private String[] projectionNames = {
ContactsContract.CommonDataKinds.StructuredName.LOOKUP_KEY,
ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME,
ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME,
};
public HashMap<String, Contact> contactsBook = new HashMap<>();
public HashMap<String, Contact> contactsBookSPhones = new HashMap<>();
public ArrayList<Contact> phoneBookContacts = new ArrayList<>();
public HashMap<String, ArrayList<Object>> phoneBookSectionsDict = new HashMap<>();
public ArrayList<String> phoneBookSectionsArray = new ArrayList<>();
public ArrayList<TLRPC.TL_contact> contacts = new ArrayList<>();
public ConcurrentHashMap<Integer, TLRPC.TL_contact> contactsDict = new ConcurrentHashMap<>(20, 1.0f, 2);
public HashMap<String, ArrayList<TLRPC.TL_contact>> usersSectionsDict = new HashMap<>();
public ArrayList<String> sortedUsersSectionsArray = new ArrayList<>();
public HashMap<String, ArrayList<TLRPC.TL_contact>> usersMutualSectionsDict = new HashMap<>();
public ArrayList<String> sortedUsersMutualSectionsArray = new ArrayList<>();
public HashMap<String, TLRPC.TL_contact> contactsByPhone = new HashMap<>();
public HashMap<String, TLRPC.TL_contact> contactsByShortPhone = new HashMap<>();
private int completedRequestsCount;
private static volatile ContactsController[] Instance = new ContactsController[UserConfig.MAX_ACCOUNT_COUNT];
public static ContactsController getInstance(int num) {
ContactsController localInstance = Instance[num];
if (localInstance == null) {
synchronized (ContactsController.class) {
localInstance = Instance[num];
if (localInstance == null) {
Instance[num] = localInstance = new ContactsController(num);
}
}
}
return localInstance;
}
public ContactsController(int instance) {
super(instance);
SharedPreferences preferences = MessagesController.getMainSettings(currentAccount);
if (preferences.getBoolean("needGetStatuses", false)) {
reloadContactsStatuses();
}
sectionsToReplace.put("À", "A");
sectionsToReplace.put("Á", "A");
sectionsToReplace.put("Ä", "A");
sectionsToReplace.put("Ù", "U");
sectionsToReplace.put("Ú", "U");
sectionsToReplace.put("Ü", "U");
sectionsToReplace.put("Ì", "I");
sectionsToReplace.put("Í", "I");
sectionsToReplace.put("Ï", "I");
sectionsToReplace.put("È", "E");
sectionsToReplace.put("É", "E");
sectionsToReplace.put("Ê", "E");
sectionsToReplace.put("Ë", "E");
sectionsToReplace.put("Ò", "O");
sectionsToReplace.put("Ó", "O");
sectionsToReplace.put("Ö", "O");
sectionsToReplace.put("Ç", "C");
sectionsToReplace.put("Ñ", "N");
sectionsToReplace.put("Ÿ", "Y");
sectionsToReplace.put("Ý", "Y");
sectionsToReplace.put("Ţ", "Y");
if (instance == 0) {
Utilities.globalQueue.postRunnable(() -> {
try {
if (hasContactsPermission()) {
ApplicationLoader.applicationContext.getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, new MyContentObserver());
}
} catch (Throwable ignore) {
}
});
}
}
public void cleanup() {
contactsBook.clear();
contactsBookSPhones.clear();
phoneBookContacts.clear();
contacts.clear();
contactsDict.clear();
usersSectionsDict.clear();
usersMutualSectionsDict.clear();
sortedUsersSectionsArray.clear();
sortedUsersMutualSectionsArray.clear();
delayedContactsUpdate.clear();
contactsByPhone.clear();
contactsByShortPhone.clear();
phoneBookSectionsDict.clear();
phoneBookSectionsArray.clear();
loadingContacts = false;
contactsSyncInProgress = false;
contactsLoaded = false;
contactsBookLoaded = false;
lastContactsVersions = "";
loadingDeleteInfo = 0;
deleteAccountTTL = 0;
for (int a = 0; a < loadingPrivacyInfo.length; a++) {
loadingPrivacyInfo[a] = 0;
}
lastseenPrivacyRules = null;
groupPrivacyRules = null;
callPrivacyRules = null;
p2pPrivacyRules = null;
profilePhotoPrivacyRules = null;
forwardsPrivacyRules = null;
phonePrivacyRules = null;
Utilities.globalQueue.postRunnable(() -> {
migratingContacts = false;
completedRequestsCount = 0;
});
}
public void checkInviteText() {
SharedPreferences preferences = MessagesController.getMainSettings(currentAccount);
inviteLink = preferences.getString("invitelink", null);
int time = preferences.getInt("invitelinktime", 0);
if (!updatingInviteLink && (inviteLink == null || Math.abs(System.currentTimeMillis() / 1000 - time) >= 86400)) {
updatingInviteLink = true;
TLRPC.TL_help_getInviteText req = new TLRPC.TL_help_getInviteText();
getConnectionsManager().sendRequest(req, (response, error) -> {
if (response != null) {
final TLRPC.TL_help_inviteText res = (TLRPC.TL_help_inviteText) response;
if (res.message.length() != 0) {
AndroidUtilities.runOnUIThread(() -> {
updatingInviteLink = false;
SharedPreferences preferences1 = MessagesController.getMainSettings(currentAccount);
SharedPreferences.Editor editor = preferences1.edit();
editor.putString("invitelink", inviteLink = res.message);
editor.putInt("invitelinktime", (int) (System.currentTimeMillis() / 1000));
editor.commit();
});
}
}
}, ConnectionsManager.RequestFlagFailOnServerErrors);
}
}
public String getInviteText(int contacts) {
String link = inviteLink == null ? "https://telegram.org/dl" : inviteLink;
if (contacts <= 1) {
return LocaleController.formatString("InviteText2", R.string.InviteText2, link);
} else {
try {
return String.format(LocaleController.getPluralString("InviteTextNum", contacts), contacts, link);
} catch (Exception e) {
return LocaleController.formatString("InviteText2", R.string.InviteText2, link);
}
}
}
public void checkAppAccount() {
AccountManager am = AccountManager.get(ApplicationLoader.applicationContext);
try {
Account[] accounts = am.getAccountsByType("org.telegram.messenger");
systemAccount = null;
for (int a = 0; a < accounts.length; a++) {
Account acc = accounts[a];
boolean found = false;
for (int b = 0; b < UserConfig.MAX_ACCOUNT_COUNT; b++) {
TLRPC.User user = UserConfig.getInstance(b).getCurrentUser();
if (user != null) {
if (acc.name.equals("" + user.id)) {
if (b == currentAccount) {
systemAccount = acc;
}
found = true;
break;
}
}
}
if (!found) {
try {
am.removeAccount(accounts[a], null, null);
} catch (Exception ignore) {
}
}
}
} catch (Throwable ignore) {
}
if (getUserConfig().isClientActivated()) {
readContacts();
if (systemAccount == null) {
try {
systemAccount = new Account("" + getUserConfig().getClientUserId(), "org.telegram.messenger");
am.addAccountExplicitly(systemAccount, "", null);
} catch (Exception ignore) {
}
}
}
}
public void deleteUnknownAppAccounts() {
try {
systemAccount = null;
AccountManager am = AccountManager.get(ApplicationLoader.applicationContext);
Account[] accounts = am.getAccountsByType("org.telegram.messenger");
for (int a = 0; a < accounts.length; a++) {
Account acc = accounts[a];
boolean found = false;
for (int b = 0; b < UserConfig.MAX_ACCOUNT_COUNT; b++) {
TLRPC.User user = UserConfig.getInstance(b).getCurrentUser();
if (user != null) {
if (acc.name.equals("" + user.id)) {
found = true;
break;
}
}
}
if (!found) {
try {
am.removeAccount(accounts[a], null, null);
} catch (Exception ignore) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void checkContacts() {
Utilities.globalQueue.postRunnable(() -> {
if (checkContactsInternal()) {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("detected contacts change");
}
performSyncPhoneBook(getContactsCopy(contactsBook), true, false, true, false, true, false);
}
});
}
public void forceImportContacts() {
Utilities.globalQueue.postRunnable(() -> {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("force import contacts");
}
performSyncPhoneBook(new HashMap<>(), true, true, true, true, false, false);
});
}
public void syncPhoneBookByAlert(final HashMap<String, Contact> contacts, final boolean first, final boolean schedule, final boolean cancel) {
Utilities.globalQueue.postRunnable(() -> {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("sync contacts by alert");
}
performSyncPhoneBook(contacts, true, first, schedule, false, false, cancel);
});
}
public void deleteAllContacts(final Runnable runnable) {
resetImportedContacts();
TLRPC.TL_contacts_deleteContacts req = new TLRPC.TL_contacts_deleteContacts();
for (int a = 0, size = contacts.size(); a < size; a++) {
TLRPC.TL_contact contact = contacts.get(a);
req.id.add(getMessagesController().getInputUser(contact.user_id));
}
getConnectionsManager().sendRequest(req, (response, error) -> {
if (error == null) {
contactsBookSPhones.clear();
contactsBook.clear();
completedRequestsCount = 0;
migratingContacts = false;
contactsSyncInProgress = false;
contactsLoaded = false;
loadingContacts = false;
contactsBookLoaded = false;
lastContactsVersions = "";
AndroidUtilities.runOnUIThread(() -> {
AccountManager am = AccountManager.get(ApplicationLoader.applicationContext);
try {
Account[] accounts = am.getAccountsByType("org.telegram.messenger");
systemAccount = null;
for (int a = 0; a < accounts.length; a++) {
Account acc = accounts[a];
for (int b = 0; b < UserConfig.MAX_ACCOUNT_COUNT; b++) {
TLRPC.User user = UserConfig.getInstance(b).getCurrentUser();
if (user != null) {
if (acc.name.equals("" + user.id)) {
am.removeAccount(acc, null, null);
break;
}
}
}
}
} catch (Throwable ignore) {
}
try {
systemAccount = new Account("" + getUserConfig().getClientUserId(), "org.telegram.messenger");
am.addAccountExplicitly(systemAccount, "", null);
} catch (Exception ignore) {
}
getMessagesStorage().putCachedPhoneBook(new HashMap<>(), false, true);
getMessagesStorage().putContacts(new ArrayList<>(), true);
phoneBookContacts.clear();
contacts.clear();
contactsDict.clear();
usersSectionsDict.clear();
usersMutualSectionsDict.clear();
sortedUsersSectionsArray.clear();
phoneBookSectionsDict.clear();
phoneBookSectionsArray.clear();
delayedContactsUpdate.clear();
sortedUsersMutualSectionsArray.clear();
contactsByPhone.clear();
contactsByShortPhone.clear();
getNotificationCenter().postNotificationName(NotificationCenter.contactsDidLoad);
loadContacts(false, 0);
runnable.run();
});
} else {
AndroidUtilities.runOnUIThread(runnable);
}
});
}
public void resetImportedContacts() {
TLRPC.TL_contacts_resetSaved req = new TLRPC.TL_contacts_resetSaved();
getConnectionsManager().sendRequest(req, (response, error) -> {
});
}
private boolean checkContactsInternal() {
boolean reload = false;
try {
if (!hasContactsPermission()) {
return false;
}
ContentResolver cr = ApplicationLoader.applicationContext.getContentResolver();
try (Cursor pCur = cr.query(ContactsContract.RawContacts.CONTENT_URI, new String[]{ContactsContract.RawContacts.VERSION}, null, null, null)) {
if (pCur != null) {
StringBuilder currentVersion = new StringBuilder();
while (pCur.moveToNext()) {
currentVersion.append(pCur.getString(pCur.getColumnIndex(ContactsContract.RawContacts.VERSION)));
}
String newContactsVersion = currentVersion.toString();
if (lastContactsVersions.length() != 0 && !lastContactsVersions.equals(newContactsVersion)) {
reload = true;
}
lastContactsVersions = newContactsVersion;
}
} catch (Exception e) {
FileLog.e(e);
}
} catch (Exception e) {
FileLog.e(e);
}
return reload;
}
public void readContacts() {
synchronized (loadContactsSync) {
if (loadingContacts) {
return;
}
loadingContacts = true;
}
Utilities.stageQueue.postRunnable(() -> {
if (!contacts.isEmpty() || contactsLoaded) {
synchronized (loadContactsSync) {
loadingContacts = false;
}
return;
}
loadContacts(true, 0);
});
}
private boolean isNotValidNameString(String src) {
if (TextUtils.isEmpty(src)) {
return true;
}
int count = 0;
for (int a = 0, len = src.length(); a < len; a++) {
char c = src.charAt(a);
if (c >= '0' && c <= '9') {
count++;
}
}
return count > 3;
}
private HashMap<String, Contact> readContactsFromPhoneBook() {
if (!getUserConfig().syncContacts) {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("contacts sync disabled");
}
return new HashMap<>();
}
if (!hasContactsPermission()) {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("app has no contacts permissions");
}
return new HashMap<>();
}
Cursor pCur = null;
HashMap<String, Contact> contactsMap = null;
try {
StringBuilder escaper = new StringBuilder();
ContentResolver cr = ApplicationLoader.applicationContext.getContentResolver();
HashMap<String, Contact> shortContacts = new HashMap<>();
ArrayList<String> idsArr = new ArrayList<>();
pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projectionPhones, null, null, null);
int lastContactId = 1;
if (pCur != null) {
int count = pCur.getCount();
if (count > 0) {
if (contactsMap == null) {
contactsMap = new HashMap<>(count);
}
while (pCur.moveToNext()) {
String number = pCur.getString(1);
String accountType = pCur.getString(5);
if (accountType == null) {
accountType = "";
}
boolean isGoodAccountType = accountType.indexOf(".sim") != 0;
if (TextUtils.isEmpty(number)) {
continue;
}
number = PhoneFormat.stripExceptNumbers(number, true);
if (TextUtils.isEmpty(number)) {
continue;
}
String shortNumber = number;
if (number.startsWith("+")) {
shortNumber = number.substring(1);
}
String lookup_key = pCur.getString(0);
escaper.setLength(0);
DatabaseUtils.appendEscapedSQLString(escaper, lookup_key);
String key = escaper.toString();
Contact existingContact = shortContacts.get(shortNumber);
if (existingContact != null) {
if (!existingContact.isGoodProvider && !accountType.equals(existingContact.provider)) {
escaper.setLength(0);
DatabaseUtils.appendEscapedSQLString(escaper, existingContact.key);
idsArr.remove(escaper.toString());
idsArr.add(key);
existingContact.key = lookup_key;
existingContact.isGoodProvider = isGoodAccountType;
existingContact.provider = accountType;
}
continue;
}
if (!idsArr.contains(key)) {
idsArr.add(key);
}
int type = pCur.getInt(2);
Contact contact = contactsMap.get(lookup_key);
if (contact == null) {
contact = new Contact();
String displayName = pCur.getString(4);
if (displayName == null) {
displayName = "";
} else {
displayName = displayName.trim();
}
if (isNotValidNameString(displayName)) {
contact.first_name = displayName;
contact.last_name = "";
} else {
int spaceIndex = displayName.lastIndexOf(' ');
if (spaceIndex != -1) {
contact.first_name = displayName.substring(0, spaceIndex).trim();
contact.last_name = displayName.substring(spaceIndex + 1).trim();
} else {
contact.first_name = displayName;
contact.last_name = "";
}
}
contact.provider = accountType;
contact.isGoodProvider = isGoodAccountType;
contact.key = lookup_key;
contact.contact_id = lastContactId++;
contactsMap.put(lookup_key, contact);
}
contact.shortPhones.add(shortNumber);
contact.phones.add(number);
contact.phoneDeleted.add(0);
if (type == ContactsContract.CommonDataKinds.Phone.TYPE_CUSTOM) {
String custom = pCur.getString(3);
contact.phoneTypes.add(custom != null ? custom : LocaleController.getString("PhoneMobile", R.string.PhoneMobile));
} else if (type == ContactsContract.CommonDataKinds.Phone.TYPE_HOME) {
contact.phoneTypes.add(LocaleController.getString("PhoneHome", R.string.PhoneHome));
} else if (type == ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) {
contact.phoneTypes.add(LocaleController.getString("PhoneMobile", R.string.PhoneMobile));
} else if (type == ContactsContract.CommonDataKinds.Phone.TYPE_WORK) {
contact.phoneTypes.add(LocaleController.getString("PhoneWork", R.string.PhoneWork));
} else if (type == ContactsContract.CommonDataKinds.Phone.TYPE_MAIN) {
contact.phoneTypes.add(LocaleController.getString("PhoneMain", R.string.PhoneMain));
} else {
contact.phoneTypes.add(LocaleController.getString("PhoneOther", R.string.PhoneOther));
}
shortContacts.put(shortNumber, contact);
}
}
try {
pCur.close();
} catch (Exception ignore) {
}
pCur = null;
}
String ids = TextUtils.join(",", idsArr);
pCur = cr.query(ContactsContract.Data.CONTENT_URI, projectionNames, ContactsContract.CommonDataKinds.StructuredName.LOOKUP_KEY + " IN (" + ids + ") AND " + ContactsContract.Data.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE + "'", null, null);
if (pCur != null) {
while (pCur.moveToNext()) {
String lookup_key = pCur.getString(0);
String fname = pCur.getString(1);
String sname = pCur.getString(2);
String mname = pCur.getString(3);
Contact contact = contactsMap.get(lookup_key);
if (contact != null && !contact.namesFilled) {
if (contact.isGoodProvider) {
if (fname != null) {
contact.first_name = fname;
} else {
contact.first_name = "";
}
if (sname != null) {
contact.last_name = sname;
} else {
contact.last_name = "";
}
if (!TextUtils.isEmpty(mname)) {
if (!TextUtils.isEmpty(contact.first_name)) {
contact.first_name += " " + mname;
} else {
contact.first_name = mname;
}
}
} else {
if (!isNotValidNameString(fname) && (contact.first_name.contains(fname) || fname.contains(contact.first_name)) ||
!isNotValidNameString(sname) && (contact.last_name.contains(sname) || fname.contains(contact.last_name))) {
if (fname != null) {
contact.first_name = fname;
} else {
contact.first_name = "";
}
if (!TextUtils.isEmpty(mname)) {
if (!TextUtils.isEmpty(contact.first_name)) {
contact.first_name += " " + mname;
} else {
contact.first_name = mname;
}
}
if (sname != null) {
contact.last_name = sname;
} else {
contact.last_name = "";
}
}
}
contact.namesFilled = true;
}
}
try {
pCur.close();
} catch (Exception ignore) {
}
pCur = null;
}
} catch (Throwable e) {
FileLog.e(e);
if (contactsMap != null) {
contactsMap.clear();
}
} finally {
try {
if (pCur != null) {
pCur.close();
}
} catch (Exception e) {
FileLog.e(e);
}
}
/*if (BuildVars.LOGS_ENABLED && contactsMap != null) {
for (HashMap.Entry<String, Contact> entry : contactsMap.entrySet()) {
Contact contact = entry.getValue();
FileLog.e("contact = " + contact.first_name + " " + contact.last_name);
if (contact.first_name.length() == 0 && contact.last_name.length() == 0 && contact.phones.size() > 0) {
FileLog.e("warning, empty name for contact = " + contact.key);
}
FileLog.e("phones:");
for (String s : contact.phones) {
FileLog.e("phone = " + s);
}
FileLog.e("short phones:");
for (String s : contact.shortPhones) {
FileLog.e("short phone = " + s);
}
}
}*/
return contactsMap != null ? contactsMap : new HashMap<>();
}
public HashMap<String, Contact> getContactsCopy(HashMap<String, Contact> original) {
HashMap<String, Contact> ret = new HashMap<>();
for (HashMap.Entry<String, Contact> entry : original.entrySet()) {
Contact copyContact = new Contact();
Contact originalContact = entry.getValue();
copyContact.phoneDeleted.addAll(originalContact.phoneDeleted);
copyContact.phones.addAll(originalContact.phones);
copyContact.phoneTypes.addAll(originalContact.phoneTypes);
copyContact.shortPhones.addAll(originalContact.shortPhones);
copyContact.first_name = originalContact.first_name;
copyContact.last_name = originalContact.last_name;
copyContact.contact_id = originalContact.contact_id;
copyContact.key = originalContact.key;
ret.put(copyContact.key, copyContact);
}
return ret;
}
protected void migratePhoneBookToV7(final SparseArray<Contact> contactHashMap) {
Utilities.globalQueue.postRunnable(() -> {
if (migratingContacts) {
return;
}
migratingContacts = true;
HashMap<String, Contact> migratedMap = new HashMap<>();
HashMap<String, Contact> contactsMap = readContactsFromPhoneBook();
final HashMap<String, String> contactsBookShort = new HashMap<>();
for (HashMap.Entry<String, Contact> entry : contactsMap.entrySet()) {
Contact value = entry.getValue();
for (int a = 0; a < value.shortPhones.size(); a++) {
contactsBookShort.put(value.shortPhones.get(a), value.key);
}
}
for (int b = 0; b < contactHashMap.size(); b++) {
Contact value = contactHashMap.valueAt(b);
for (int a = 0; a < value.shortPhones.size(); a++) {
String sphone = value.shortPhones.get(a);
String key = contactsBookShort.get(sphone);
if (key != null) {
value.key = key;
migratedMap.put(key, value);
break;
}
}
}
if (BuildVars.LOGS_ENABLED) {
FileLog.d("migrated contacts " + migratedMap.size() + " of " + contactHashMap.size());
}
getMessagesStorage().putCachedPhoneBook(migratedMap, true, false);
});
}
protected void performSyncPhoneBook(final HashMap<String, Contact> contactHashMap, final boolean request, final boolean first, final boolean schedule, final boolean force, final boolean checkCount, final boolean canceled) {
if (!first && !contactsBookLoaded) {
return;
}
Utilities.globalQueue.postRunnable(() -> {
int newPhonebookContacts = 0;
int serverContactsInPhonebook = 0;
boolean disableDeletion = true; //disable contacts deletion, because phone numbers can't be compared due to different numbers format
/*if (schedule) {
try {
AccountManager am = AccountManager.get(ApplicationLoader.applicationContext);
Account[] accounts = am.getAccountsByType("org.telegram.account");
boolean recreateAccount = false;
if (getUserConfig().isClientActivated()) {
if (accounts.length != 1) {
FileLog.e("detected account deletion!");
currentAccount = new Account(getUserConfig().getCurrentUser().phone, "org.telegram.account");
am.addAccountExplicitly(currentAccount, "", null);
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
performWriteContactsToPhoneBook();
}
});
}
}
} catch (Exception e) {
FileLog.e(e);
}
}*/
HashMap<String, Contact> contactShortHashMap = new HashMap<>();
for (HashMap.Entry<String, Contact> entry : contactHashMap.entrySet()) {
Contact c = entry.getValue();
for (int a = 0; a < c.shortPhones.size(); a++) {
contactShortHashMap.put(c.shortPhones.get(a), c);
}
}
if (BuildVars.LOGS_ENABLED) {
FileLog.d("start read contacts from phone");
}
if (!schedule) {
checkContactsInternal();
}
final HashMap<String, Contact> contactsMap = readContactsFromPhoneBook();
final HashMap<String, ArrayList<Object>> phoneBookSectionsDictFinal = new HashMap<>();
final HashMap<String, Contact> phoneBookByShortPhonesFinal = new HashMap<>();
final ArrayList<String> phoneBookSectionsArrayFinal = new ArrayList<>();
for (HashMap.Entry<String, Contact> entry : contactsMap.entrySet()) {
Contact contact = entry.getValue();
for (int a = 0, size = contact.shortPhones.size(); a < size; a++) {
String phone = contact.shortPhones.get(a);
phoneBookByShortPhonesFinal.put(phone.substring(Math.max(0, phone.length() - 7)), contact);
}
String key = contact.getLetter();
ArrayList<Object> arrayList = phoneBookSectionsDictFinal.get(key);
if (arrayList == null) {
arrayList = new ArrayList<>();
phoneBookSectionsDictFinal.put(key, arrayList);
phoneBookSectionsArrayFinal.add(key);
}
arrayList.add(contact);
}
final HashMap<String, Contact> contactsBookShort = new HashMap<>();
int alreadyImportedContacts = contactHashMap.size();
ArrayList<TLRPC.TL_inputPhoneContact> toImport = new ArrayList<>();
if (!contactHashMap.isEmpty()) {
for (HashMap.Entry<String, Contact> pair : contactsMap.entrySet()) {
String id = pair.getKey();
Contact value = pair.getValue();
Contact existing = contactHashMap.get(id);
if (existing == null) {
for (int a = 0; a < value.shortPhones.size(); a++) {
Contact c = contactShortHashMap.get(value.shortPhones.get(a));
if (c != null) {
existing = c;
id = existing.key;
break;
}
}
}
if (existing != null) {
value.imported = existing.imported;
}
boolean nameChanged = existing != null && (!TextUtils.isEmpty(value.first_name) && !existing.first_name.equals(value.first_name) || !TextUtils.isEmpty(value.last_name) && !existing.last_name.equals(value.last_name));
if (existing == null || nameChanged) {
for (int a = 0; a < value.phones.size(); a++) {
String sphone = value.shortPhones.get(a);
String sphone9 = sphone.substring(Math.max(0, sphone.length() - 7));
contactsBookShort.put(sphone, value);
if (existing != null) {
int index = existing.shortPhones.indexOf(sphone);
if (index != -1) {
Integer deleted = existing.phoneDeleted.get(index);
value.phoneDeleted.set(a, deleted);
if (deleted == 1) {
continue;
}
}
}
if (request) {
if (!nameChanged) {
if (contactsByPhone.containsKey(sphone)) {
serverContactsInPhonebook++;
continue;
}
newPhonebookContacts++;
}
TLRPC.TL_inputPhoneContact imp = new TLRPC.TL_inputPhoneContact();
imp.client_id = value.contact_id;
imp.client_id |= ((long) a) << 32;
imp.first_name = value.first_name;
imp.last_name = value.last_name;
imp.phone = value.phones.get(a);
toImport.add(imp);
}
}
if (existing != null) {
contactHashMap.remove(id);
}
} else {
for (int a = 0; a < value.phones.size(); a++) {
String sphone = value.shortPhones.get(a);
String sphone9 = sphone.substring(Math.max(0, sphone.length() - 7));
contactsBookShort.put(sphone, value);
int index = existing.shortPhones.indexOf(sphone);
boolean emptyNameReimport = false;
if (request) {
TLRPC.TL_contact contact = contactsByPhone.get(sphone);
if (contact != null) {
TLRPC.User user = getMessagesController().getUser(contact.user_id);
if (user != null) {
serverContactsInPhonebook++;
if (TextUtils.isEmpty(user.first_name) && TextUtils.isEmpty(user.last_name) && (!TextUtils.isEmpty(value.first_name) || !TextUtils.isEmpty(value.last_name))) {
index = -1;
emptyNameReimport = true;
}
}
} else if (contactsByShortPhone.containsKey(sphone9)) {
serverContactsInPhonebook++;
}
}
if (index == -1) {
if (request) {
if (!emptyNameReimport) {
TLRPC.TL_contact contact = contactsByPhone.get(sphone);
if (contact != null) {
TLRPC.User user = getMessagesController().getUser(contact.user_id);
if (user != null) {
serverContactsInPhonebook++;
String firstName = user.first_name != null ? user.first_name : "";
String lastName = user.last_name != null ? user.last_name : "";
if (firstName.equals(value.first_name) && lastName.equals(value.last_name) || TextUtils.isEmpty(value.first_name) && TextUtils.isEmpty(value.last_name)) {
continue;
}
} else {
newPhonebookContacts++;
}
} else if (contactsByShortPhone.containsKey(sphone9)) {
serverContactsInPhonebook++;
}
}
TLRPC.TL_inputPhoneContact imp = new TLRPC.TL_inputPhoneContact();
imp.client_id = value.contact_id;
imp.client_id |= ((long) a) << 32;
imp.first_name = value.first_name;
imp.last_name = value.last_name;
imp.phone = value.phones.get(a);
toImport.add(imp);
}
} else {
value.phoneDeleted.set(a, existing.phoneDeleted.get(index));
existing.phones.remove(index);
existing.shortPhones.remove(index);
existing.phoneDeleted.remove(index);
existing.phoneTypes.remove(index);
}
}
if (existing.phones.isEmpty()) {
contactHashMap.remove(id);
}
}
}
if (!first && contactHashMap.isEmpty() && toImport.isEmpty() && alreadyImportedContacts == contactsMap.size()) {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("contacts not changed!");
}
return;
}
if (request && !contactHashMap.isEmpty() && !contactsMap.isEmpty()) {
if (toImport.isEmpty()) {
getMessagesStorage().putCachedPhoneBook(contactsMap, false, false);
}
if (!disableDeletion && !contactHashMap.isEmpty()) {
AndroidUtilities.runOnUIThread(() -> {
/*if (BuildVars.DEBUG_VERSION) {
FileLog.e("need delete contacts");
for (HashMap.Entry<Integer, Contact> c : contactHashMap.entrySet()) {
Contact contact = c.getValue();
FileLog.e("delete contact " + contact.first_name + " " + contact.last_name);
for (String phone : contact.phones) {
FileLog.e(phone);
}
}
}*/
final ArrayList<TLRPC.User> toDelete = new ArrayList<>();
if (contactHashMap != null && !contactHashMap.isEmpty()) {
try {
final HashMap<String, TLRPC.User> contactsPhonesShort = new HashMap<>();
for (int a = 0; a < contacts.size(); a++) {
TLRPC.TL_contact value = contacts.get(a);
TLRPC.User user = getMessagesController().getUser(value.user_id);
if (user == null || TextUtils.isEmpty(user.phone)) {
continue;
}
contactsPhonesShort.put(user.phone, user);
}
int removed = 0;
for (HashMap.Entry<String, Contact> entry : contactHashMap.entrySet()) {
Contact contact = entry.getValue();
boolean was = false;
for (int a = 0; a < contact.shortPhones.size(); a++) {
String phone = contact.shortPhones.get(a);
TLRPC.User user = contactsPhonesShort.get(phone);
if (user != null) {
was = true;
toDelete.add(user);
contact.shortPhones.remove(a);
a--;
}
}
if (!was || contact.shortPhones.size() == 0) {
removed++;
}
}
} catch (Exception e) {
FileLog.e(e);
}
}
if (!toDelete.isEmpty()) {
deleteContact(toDelete);
}
});
}
}
} else if (request) {
for (HashMap.Entry<String, Contact> pair : contactsMap.entrySet()) {
Contact value = pair.getValue();
String key = pair.getKey();
for (int a = 0; a < value.phones.size(); a++) {
if (!force) {
String sphone = value.shortPhones.get(a);
String sphone9 = sphone.substring(Math.max(0, sphone.length() - 7));
TLRPC.TL_contact contact = contactsByPhone.get(sphone);
if (contact != null) {
TLRPC.User user = getMessagesController().getUser(contact.user_id);
if (user != null) {
serverContactsInPhonebook++;
String firstName = user.first_name != null ? user.first_name : "";
String lastName = user.last_name != null ? user.last_name : "";
if (firstName.equals(value.first_name) && lastName.equals(value.last_name) || TextUtils.isEmpty(value.first_name) && TextUtils.isEmpty(value.last_name)) {
continue;
}
}
} else if (contactsByShortPhone.containsKey(sphone9)) {
serverContactsInPhonebook++;
}
}
TLRPC.TL_inputPhoneContact imp = new TLRPC.TL_inputPhoneContact();
imp.client_id = value.contact_id;
imp.client_id |= ((long) a) << 32;
imp.first_name = value.first_name;
imp.last_name = value.last_name;
imp.phone = value.phones.get(a);
toImport.add(imp);
}
}
}
if (BuildVars.LOGS_ENABLED) {
FileLog.d("done processing contacts");
}
if (request) {
if (!toImport.isEmpty()) {
if (BuildVars.LOGS_ENABLED) {
FileLog.e("start import contacts");
/*for (TLRPC.TL_inputPhoneContact contact : toImport) {
FileLog.e("add contact " + contact.first_name + " " + contact.last_name + " " + contact.phone);
}*/
}
final int checkType;
if (checkCount && newPhonebookContacts != 0) {
if (newPhonebookContacts >= 30) {
checkType = 1;
} else if (first && alreadyImportedContacts == 0 && contactsByPhone.size() - serverContactsInPhonebook > contactsByPhone.size() / 3 * 2) {
checkType = 2;
} else {
checkType = 0;
}
} else {
checkType = 0;
}
if (BuildVars.LOGS_ENABLED) {
FileLog.d("new phone book contacts " + newPhonebookContacts + " serverContactsInPhonebook " + serverContactsInPhonebook + " totalContacts " + contactsByPhone.size());
}
if (checkType != 0) {
AndroidUtilities.runOnUIThread(() -> getNotificationCenter().postNotificationName(NotificationCenter.hasNewContactsToImport, checkType, contactHashMap, first, schedule));
return;
} else if (canceled) {
Utilities.stageQueue.postRunnable(() -> {
contactsBookSPhones = contactsBookShort;
contactsBook = contactsMap;
contactsSyncInProgress = false;
contactsBookLoaded = true;
if (first) {
contactsLoaded = true;
}
if (!delayedContactsUpdate.isEmpty() && contactsLoaded) {
applyContactsUpdates(delayedContactsUpdate, null, null, null);
delayedContactsUpdate.clear();
}
getMessagesStorage().putCachedPhoneBook(contactsMap, false, false);
AndroidUtilities.runOnUIThread(() -> {
mergePhonebookAndTelegramContacts(phoneBookSectionsDictFinal, phoneBookSectionsArrayFinal, phoneBookByShortPhonesFinal);
updateUnregisteredContacts();
getNotificationCenter().postNotificationName(NotificationCenter.contactsDidLoad);
getNotificationCenter().postNotificationName(NotificationCenter.contactsImported);
});
});
return;
}
final boolean[] hasErrors = new boolean[]{false};
final HashMap<String, Contact> contactsMapToSave = new HashMap<>(contactsMap);
final SparseArray<String> contactIdToKey = new SparseArray<>();
for (HashMap.Entry<String, Contact> entry : contactsMapToSave.entrySet()) {
Contact value = entry.getValue();
contactIdToKey.put(value.contact_id, value.key);
}
completedRequestsCount = 0;
final int count = (int) Math.ceil(toImport.size() / 500.0);
for (int a = 0; a < count; a++) {
final TLRPC.TL_contacts_importContacts req = new TLRPC.TL_contacts_importContacts();
int start = a * 500;
int end = Math.min(start + 500, toImport.size());
req.contacts = new ArrayList<>(toImport.subList(start, end));
getConnectionsManager().sendRequest(req, (response, error) -> {
completedRequestsCount++;
if (error == null) {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("contacts imported");
}
final TLRPC.TL_contacts_importedContacts res = (TLRPC.TL_contacts_importedContacts) response;
if (!res.retry_contacts.isEmpty()) {
for (int a1 = 0; a1 < res.retry_contacts.size(); a1++) {
long id = res.retry_contacts.get(a1);
contactsMapToSave.remove(contactIdToKey.get((int) id));
}
hasErrors[0] = true;
if (BuildVars.LOGS_ENABLED) {
FileLog.d("result has retry contacts");
}
}
for (int a1 = 0; a1 < res.popular_invites.size(); a1++) {
TLRPC.TL_popularContact popularContact = res.popular_invites.get(a1);
Contact contact = contactsMap.get(contactIdToKey.get((int) popularContact.client_id));
if (contact != null) {
contact.imported = popularContact.importers;
}
}
/*if (BuildVars.LOGS_ENABLED) {
for (TLRPC.User user : res.users) {
FileLog.e("received user " + user.first_name + " " + user.last_name + " " + user.phone);
}
}*/
getMessagesStorage().putUsersAndChats(res.users, null, true, true);
ArrayList<TLRPC.TL_contact> cArr = new ArrayList<>();
for (int a1 = 0; a1 < res.imported.size(); a1++) {
TLRPC.TL_contact contact = new TLRPC.TL_contact();
contact.user_id = res.imported.get(a1).user_id;
cArr.add(contact);
}
processLoadedContacts(cArr, res.users, 2);
} else {
for (int a1 = 0; a1 < req.contacts.size(); a1++) {
TLRPC.TL_inputPhoneContact contact = req.contacts.get(a1);
contactsMapToSave.remove(contactIdToKey.get((int) contact.client_id));
}
hasErrors[0] = true;
if (BuildVars.LOGS_ENABLED) {
FileLog.d("import contacts error " + error.text);
}
}
if (completedRequestsCount == count) {
if (!contactsMapToSave.isEmpty()) {
getMessagesStorage().putCachedPhoneBook(contactsMapToSave, false, false);
}
Utilities.stageQueue.postRunnable(() -> {
contactsBookSPhones = contactsBookShort;
contactsBook = contactsMap;
contactsSyncInProgress = false;
contactsBookLoaded = true;
if (first) {
contactsLoaded = true;
}
if (!delayedContactsUpdate.isEmpty() && contactsLoaded) {
applyContactsUpdates(delayedContactsUpdate, null, null, null);
delayedContactsUpdate.clear();
}
AndroidUtilities.runOnUIThread(() -> {
mergePhonebookAndTelegramContacts(phoneBookSectionsDictFinal, phoneBookSectionsArrayFinal, phoneBookByShortPhonesFinal);
getNotificationCenter().postNotificationName(NotificationCenter.contactsImported);
});
if (hasErrors[0]) {
Utilities.globalQueue.postRunnable(() -> getMessagesStorage().getCachedPhoneBook(true), 60000 * 5);
}
});
}
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagCanCompress);
}
} else {
Utilities.stageQueue.postRunnable(() -> {
contactsBookSPhones = contactsBookShort;
contactsBook = contactsMap;
contactsSyncInProgress = false;
contactsBookLoaded = true;
if (first) {
contactsLoaded = true;
}
if (!delayedContactsUpdate.isEmpty() && contactsLoaded) {
applyContactsUpdates(delayedContactsUpdate, null, null, null);
delayedContactsUpdate.clear();
}
AndroidUtilities.runOnUIThread(() -> {
mergePhonebookAndTelegramContacts(phoneBookSectionsDictFinal, phoneBookSectionsArrayFinal, phoneBookByShortPhonesFinal);
updateUnregisteredContacts();
getNotificationCenter().postNotificationName(NotificationCenter.contactsDidLoad);
getNotificationCenter().postNotificationName(NotificationCenter.contactsImported);
});
});
}
} else {
Utilities.stageQueue.postRunnable(() -> {
contactsBookSPhones = contactsBookShort;
contactsBook = contactsMap;
contactsSyncInProgress = false;
contactsBookLoaded = true;
if (first) {
contactsLoaded = true;
}
if (!delayedContactsUpdate.isEmpty() && contactsLoaded && contactsBookLoaded) {
applyContactsUpdates(delayedContactsUpdate, null, null, null);
delayedContactsUpdate.clear();
}
AndroidUtilities.runOnUIThread(() -> mergePhonebookAndTelegramContacts(phoneBookSectionsDictFinal, phoneBookSectionsArrayFinal, phoneBookByShortPhonesFinal));
});
if (!contactsMap.isEmpty()) {
getMessagesStorage().putCachedPhoneBook(contactsMap, false, false);
}
}
});
}
public boolean isLoadingContacts() {
synchronized (loadContactsSync) {
return loadingContacts;
}
}
private int getContactsHash(ArrayList<TLRPC.TL_contact> contacts) {
long acc = 0;
contacts = new ArrayList<>(contacts);
Collections.sort(contacts, (tl_contact, tl_contact2) -> {
if (tl_contact.user_id > tl_contact2.user_id) {
return 1;
} else if (tl_contact.user_id < tl_contact2.user_id) {
return -1;
}
return 0;
});
int count = contacts.size();
for (int a = -1; a < count; a++) {
if (a == -1) {
acc = ((acc * 20261) + 0x80000000L + getUserConfig().contactsSavedCount) % 0x80000000L;
} else {
TLRPC.TL_contact set = contacts.get(a);
acc = ((acc * 20261) + 0x80000000L + set.user_id) % 0x80000000L;
}
}
return (int) acc;
}
public void loadContacts(boolean fromCache, final int hash) {
synchronized (loadContactsSync) {
loadingContacts = true;
}
if (fromCache) {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("load contacts from cache");
}
getMessagesStorage().getContacts();
} else {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("load contacts from server");
}
TLRPC.TL_contacts_getContacts req = new TLRPC.TL_contacts_getContacts();
req.hash = hash;
getConnectionsManager().sendRequest(req, (response, error) -> {
if (error == null) {
TLRPC.contacts_Contacts res = (TLRPC.contacts_Contacts) response;
if (hash != 0 && res instanceof TLRPC.TL_contacts_contactsNotModified) {
contactsLoaded = true;
if (!delayedContactsUpdate.isEmpty() && contactsBookLoaded) {
applyContactsUpdates(delayedContactsUpdate, null, null, null);
delayedContactsUpdate.clear();
}
getUserConfig().lastContactsSyncTime = (int) (System.currentTimeMillis() / 1000);
getUserConfig().saveConfig(false);
AndroidUtilities.runOnUIThread(() -> {
synchronized (loadContactsSync) {
loadingContacts = false;
}
getNotificationCenter().postNotificationName(NotificationCenter.contactsDidLoad);
});
if (BuildVars.LOGS_ENABLED) {
FileLog.d("load contacts don't change");
}
return;
} else {
getUserConfig().contactsSavedCount = res.saved_count;
getUserConfig().saveConfig(false);
}
processLoadedContacts(res.contacts, res.users, 0);
}
});
}
}
public void processLoadedContacts(final ArrayList<TLRPC.TL_contact> contactsArr, final ArrayList<TLRPC.User> usersArr, final int from) {
//from: 0 - from server, 1 - from db, 2 - from imported contacts
AndroidUtilities.runOnUIThread(() -> {
getMessagesController().putUsers(usersArr, from == 1);
final SparseArray<TLRPC.User> usersDict = new SparseArray<>();
final boolean isEmpty = contactsArr.isEmpty();
if (!contacts.isEmpty()) {
for (int a = 0; a < contactsArr.size(); a++) {
TLRPC.TL_contact contact = contactsArr.get(a);
if (contactsDict.get(contact.user_id) != null) {
contactsArr.remove(a);
a--;
}
}
contactsArr.addAll(contacts);
}
for (int a = 0; a < contactsArr.size(); a++) {
TLRPC.User user = getMessagesController().getUser(contactsArr.get(a).user_id);
if (user != null) {
usersDict.put(user.id, user);
//if (BuildVars.DEBUG_VERSION) {
// FileLog.e("loaded user contact " + user.first_name + " " + user.last_name + " " + user.phone);
//}
}
}
Utilities.stageQueue.postRunnable(() -> {
if (BuildVars.LOGS_ENABLED) {
FileLog.d("done loading contacts");
}
if (from == 1 && (contactsArr.isEmpty() || Math.abs(System.currentTimeMillis() / 1000 - getUserConfig().lastContactsSyncTime) >= 24 * 60 * 60)) {
loadContacts(false, getContactsHash(contactsArr));
if (contactsArr.isEmpty()) {
return;
}
}
if (from == 0) {
getUserConfig().lastContactsSyncTime = (int) (System.currentTimeMillis() / 1000);
getUserConfig().saveConfig(false);
}
for (int a = 0; a < contactsArr.size(); a++) {
TLRPC.TL_contact contact = contactsArr.get(a);
if (usersDict.get(contact.user_id) == null && contact.user_id != getUserConfig().getClientUserId()) {
loadContacts(false, 0);
if (BuildVars.LOGS_ENABLED) {
FileLog.d("contacts are broken, load from server");
}
return;
}
}
if (from != 1) {
getMessagesStorage().putUsersAndChats(usersArr, null, true, true);
getMessagesStorage().putContacts(contactsArr, from != 2);
}
Collections.sort(contactsArr, (tl_contact, tl_contact2) -> {
TLRPC.User user1 = usersDict.get(tl_contact.user_id);
TLRPC.User user2 = usersDict.get(tl_contact2.user_id);
String name1 = UserObject.getFirstName(user1);
String name2 = UserObject.getFirstName(user2);
return name1.compareTo(name2);
});
final ConcurrentHashMap<Integer, TLRPC.TL_contact> contactsDictionary = new ConcurrentHashMap<>(20, 1.0f, 2);
final HashMap<String, ArrayList<TLRPC.TL_contact>> sectionsDict = new HashMap<>();
final HashMap<String, ArrayList<TLRPC.TL_contact>> sectionsDictMutual = new HashMap<>();
final ArrayList<String> sortedSectionsArray = new ArrayList<>();
final ArrayList<String> sortedSectionsArrayMutual = new ArrayList<>();
HashMap<String, TLRPC.TL_contact> contactsByPhonesDict = null;
HashMap<String, TLRPC.TL_contact> contactsByPhonesShortDict = null;
if (!contactsBookLoaded) {
contactsByPhonesDict = new HashMap<>();
contactsByPhonesShortDict = new HashMap<>();
}
final HashMap<String, TLRPC.TL_contact> contactsByPhonesDictFinal = contactsByPhonesDict;
final HashMap<String, TLRPC.TL_contact> contactsByPhonesShortDictFinal = contactsByPhonesShortDict;
for (int a = 0; a < contactsArr.size(); a++) {
TLRPC.TL_contact value = contactsArr.get(a);
TLRPC.User user = usersDict.get(value.user_id);
if (user == null) {
continue;
}
contactsDictionary.put(value.user_id, value);
if (contactsByPhonesDict != null && !TextUtils.isEmpty(user.phone)) {
contactsByPhonesDict.put(user.phone, value);
contactsByPhonesShortDict.put(user.phone.substring(Math.max(0, user.phone.length() - 7)), value);
}
String key = UserObject.getFirstName(user);
if (key.length() > 1) {
key = key.substring(0, 1);
}
if (key.length() == 0) {
key = "#";
} else {
key = key.toUpperCase();
}
String replace = sectionsToReplace.get(key);
if (replace != null) {
key = replace;
}
ArrayList<TLRPC.TL_contact> arr = sectionsDict.get(key);
if (arr == null) {
arr = new ArrayList<>();
sectionsDict.put(key, arr);
sortedSectionsArray.add(key);
}
arr.add(value);
if (user.mutual_contact) {
arr = sectionsDictMutual.get(key);
if (arr == null) {
arr = new ArrayList<>();
sectionsDictMutual.put(key, arr);
sortedSectionsArrayMutual.add(key);
}
arr.add(value);
}
}
Collections.sort(sortedSectionsArray, (s, s2) -> {
char cv1 = s.charAt(0);
char cv2 = s2.charAt(0);
if (cv1 == '#') {
return 1;
} else if (cv2 == '#') {
return -1;
}
return s.compareTo(s2);
});
Collections.sort(sortedSectionsArrayMutual, (s, s2) -> {
char cv1 = s.charAt(0);
char cv2 = s2.charAt(0);
if (cv1 == '#') {
return 1;
} else if (cv2 == '#') {
return -1;
}
return s.compareTo(s2);
});
AndroidUtilities.runOnUIThread(() -> {
contacts = contactsArr;
contactsDict = contactsDictionary;
usersSectionsDict = sectionsDict;
usersMutualSectionsDict = sectionsDictMutual;
sortedUsersSectionsArray = sortedSectionsArray;
sortedUsersMutualSectionsArray = sortedSectionsArrayMutual;
if (from != 2) {
synchronized (loadContactsSync) {
loadingContacts = false;
}
}
performWriteContactsToPhoneBook();
updateUnregisteredContacts();
getNotificationCenter().postNotificationName(NotificationCenter.contactsDidLoad);
if (from != 1 && !isEmpty) {
saveContactsLoadTime();
} else {
reloadContactsStatusesMaybe();
}
});
if (!delayedContactsUpdate.isEmpty() && contactsLoaded && contactsBookLoaded) {
applyContactsUpdates(delayedContactsUpdate, null, null, null);
delayedContactsUpdate.clear();
}
if (contactsByPhonesDictFinal != null) {
AndroidUtilities.runOnUIThread(() -> {
Utilities.globalQueue.postRunnable(() -> {
contactsByPhone = contactsByPhonesDictFinal;
contactsByShortPhone = contactsByPhonesShortDictFinal;
});
if (contactsSyncInProgress) {
return;
}
contactsSyncInProgress = true;
getMessagesStorage().getCachedPhoneBook(false);
});
} else {
contactsLoaded = true;
}
});
});
}
public boolean isContact(int uid) {
return contactsDict.get(uid) != null;
}
public void reloadContactsStatusesMaybe() {
try {
SharedPreferences preferences = MessagesController.getMainSettings(currentAccount);
long lastReloadStatusTime = preferences.getLong("lastReloadStatusTime", 0);
if (lastReloadStatusTime < System.currentTimeMillis() - 1000 * 60 * 60 * 3) {
reloadContactsStatuses();
}
} catch (Exception e) {
FileLog.e(e);
}
}
private void saveContactsLoadTime() {
try {
SharedPreferences preferences = MessagesController.getMainSettings(currentAccount);
preferences.edit().putLong("lastReloadStatusTime", System.currentTimeMillis()).commit();
} catch (Exception e) {
FileLog.e(e);
}
}
private void mergePhonebookAndTelegramContacts(final HashMap<String, ArrayList<Object>> phoneBookSectionsDictFinal, final ArrayList<String> phoneBookSectionsArrayFinal, final HashMap<String, Contact> phoneBookByShortPhonesFinal) {
final ArrayList<TLRPC.TL_contact> contactsCopy = new ArrayList<>(contacts);
Utilities.globalQueue.postRunnable(() -> {
for (int a = 0, size = contactsCopy.size(); a < size; a++) {
TLRPC.TL_contact value = contactsCopy.get(a);
TLRPC.User user = getMessagesController().getUser(value.user_id);
if (user == null || TextUtils.isEmpty(user.phone)) {
continue;
}
String phone = user.phone.substring(Math.max(0, user.phone.length() - 7));
Contact contact = phoneBookByShortPhonesFinal.get(phone);
if (contact != null) {
if (contact.user == null) {
contact.user = user;
}
} else {
String key = Contact.getLetter(user.first_name, user.last_name);
ArrayList<Object> arrayList = phoneBookSectionsDictFinal.get(key);
if (arrayList == null) {
arrayList = new ArrayList<>();
phoneBookSectionsDictFinal.put(key, arrayList);
phoneBookSectionsArrayFinal.add(key);
}
arrayList.add(user);
}
}
for (ArrayList<Object> arrayList : phoneBookSectionsDictFinal.values()) {
Collections.sort(arrayList, (o1, o2) -> {
String name1;
String name2;
if (o1 instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) o1;
name1 = ContactsController.formatName(user.first_name, user.last_name);
} else if (o1 instanceof Contact) {
Contact contact = (Contact) o1;
if (contact.user != null) {
name1 = ContactsController.formatName(contact.user.first_name, contact.user.last_name);
} else {
name1 = ContactsController.formatName(contact.first_name, contact.last_name);
}
} else {
name1 = "";
}
if (o2 instanceof TLRPC.User) {
TLRPC.User user = (TLRPC.User) o2;
name2 = ContactsController.formatName(user.first_name, user.last_name);
} else if (o2 instanceof Contact) {
Contact contact = (Contact) o2;
if (contact.user != null) {
name2 = ContactsController.formatName(contact.user.first_name, contact.user.last_name);
} else {
name2 = ContactsController.formatName(contact.first_name, contact.last_name);
}
} else {
name2 = "";
}
return name1.compareTo(name2);
});
}
Collections.sort(phoneBookSectionsArrayFinal, (s, s2) -> {
char cv1 = s.charAt(0);
char cv2 = s2.charAt(0);
if (cv1 == '#') {
return 1;
} else if (cv2 == '#') {
return -1;
}
return s.compareTo(s2);
});
AndroidUtilities.runOnUIThread(() -> {
phoneBookSectionsArray = phoneBookSectionsArrayFinal;
phoneBookSectionsDict = phoneBookSectionsDictFinal;
});
});
}
private void updateUnregisteredContacts() {
final HashMap<String, TLRPC.TL_contact> contactsPhonesShort = new HashMap<>();
for (int a = 0, size = contacts.size(); a < size; a++) {
TLRPC.TL_contact value = contacts.get(a);
TLRPC.User user = getMessagesController().getUser(value.user_id);
if (user == null || TextUtils.isEmpty(user.phone)) {
continue;
}
contactsPhonesShort.put(user.phone, value);
}
final ArrayList<Contact> sortedPhoneBookContacts = new ArrayList<>();
for (HashMap.Entry<String, Contact> pair : contactsBook.entrySet()) {
Contact value = pair.getValue();
boolean skip = false;
for (int a = 0; a < value.phones.size(); a++) {
String sphone = value.shortPhones.get(a);
if (contactsPhonesShort.containsKey(sphone) || value.phoneDeleted.get(a) == 1) {
skip = true;
break;
}
}
if (skip) {
continue;
}
sortedPhoneBookContacts.add(value);
}
Collections.sort(sortedPhoneBookContacts, (contact, contact2) -> {
String toComapre1 = contact.first_name;
if (toComapre1.length() == 0) {
toComapre1 = contact.last_name;
}
String toComapre2 = contact2.first_name;
if (toComapre2.length() == 0) {
toComapre2 = contact2.last_name;
}
return toComapre1.compareTo(toComapre2);
});
phoneBookContacts = sortedPhoneBookContacts;
}
private void buildContactsSectionsArrays(boolean sort) {
if (sort) {
Collections.sort(contacts, (tl_contact, tl_contact2) -> {
TLRPC.User user1 = getMessagesController().getUser(tl_contact.user_id);
TLRPC.User user2 = getMessagesController().getUser(tl_contact2.user_id);
String name1 = UserObject.getFirstName(user1);
String name2 = UserObject.getFirstName(user2);
return name1.compareTo(name2);
});
}
final HashMap<String, ArrayList<TLRPC.TL_contact>> sectionsDict = new HashMap<>();
final ArrayList<String> sortedSectionsArray = new ArrayList<>();
for (int a = 0; a < contacts.size(); a++) {
TLRPC.TL_contact value = contacts.get(a);
TLRPC.User user = getMessagesController().getUser(value.user_id);
if (user == null) {
continue;
}
String key = UserObject.getFirstName(user);
if (key.length() > 1) {
key = key.substring(0, 1);
}
if (key.length() == 0) {
key = "#";
} else {
key = key.toUpperCase();
}
String replace = sectionsToReplace.get(key);
if (replace != null) {
key = replace;
}
ArrayList<TLRPC.TL_contact> arr = sectionsDict.get(key);
if (arr == null) {
arr = new ArrayList<>();
sectionsDict.put(key, arr);
sortedSectionsArray.add(key);
}
arr.add(value);
}
Collections.sort(sortedSectionsArray, (s, s2) -> {
char cv1 = s.charAt(0);
char cv2 = s2.charAt(0);
if (cv1 == '#') {
return 1;
} else if (cv2 == '#') {
return -1;
}
return s.compareTo(s2);
});
usersSectionsDict = sectionsDict;
sortedUsersSectionsArray = sortedSectionsArray;
}
private boolean hasContactsPermission() {
if (Build.VERSION.SDK_INT >= 23) {
return ApplicationLoader.applicationContext.checkSelfPermission(android.Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED;
}
Cursor cursor = null;
try {
ContentResolver cr = ApplicationLoader.applicationContext.getContentResolver();
cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projectionPhones, null, null, null);
if (cursor == null || cursor.getCount() == 0) {
return false;
}
} catch (Throwable e) {
FileLog.e(e);
} finally {
try {
if (cursor != null) {
cursor.close();
}
} catch (Exception e) {
FileLog.e(e);
}
}
return true;
}
private void performWriteContactsToPhoneBookInternal(ArrayList<TLRPC.TL_contact> contactsArray) {
Cursor cursor = null;
try {
if (!hasContactsPermission()) {
return;
}
Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, systemAccount.name).appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, systemAccount.type).build();
cursor = ApplicationLoader.applicationContext.getContentResolver().query(rawContactUri, new String[]{BaseColumns._ID, ContactsContract.RawContacts.SYNC2}, null, null, null);
SparseLongArray bookContacts = new SparseLongArray();
if (cursor != null) {
while (cursor.moveToNext()) {
bookContacts.put(cursor.getInt(1), cursor.getLong(0));
}
cursor.close();
cursor = null;
for (int a = 0; a < contactsArray.size(); a++) {
TLRPC.TL_contact u = contactsArray.get(a);
if (bookContacts.indexOfKey(u.user_id) < 0) {
TLRPC.User user = getMessagesController().getUser(u.user_id);
addContactToPhoneBook(user, false);
}
}
}
} catch (Exception e) {
FileLog.e(e);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private void performWriteContactsToPhoneBook() {
final ArrayList<TLRPC.TL_contact> contactsArray = new ArrayList<>(contacts);
Utilities.phoneBookQueue.postRunnable(() -> performWriteContactsToPhoneBookInternal(contactsArray));
}
private void applyContactsUpdates(ArrayList<Integer> ids, ConcurrentHashMap<Integer, TLRPC.User> userDict, ArrayList<TLRPC.TL_contact> newC, ArrayList<Integer> contactsTD) {
if (newC == null || contactsTD == null) {
newC = new ArrayList<>();
contactsTD = new ArrayList<>();
for (int a = 0; a < ids.size(); a++) {
Integer uid = ids.get(a);
if (uid > 0) {
TLRPC.TL_contact contact = new TLRPC.TL_contact();
contact.user_id = uid;
newC.add(contact);
} else if (uid < 0) {
contactsTD.add(-uid);
}
}
}
if (BuildVars.LOGS_ENABLED) {
FileLog.d("process update - contacts add = " + newC.size() + " delete = " + contactsTD.size());
}
StringBuilder toAdd = new StringBuilder();
StringBuilder toDelete = new StringBuilder();
boolean reloadContacts = false;
for (int a = 0; a < newC.size(); a++) {
TLRPC.TL_contact newContact = newC.get(a);
TLRPC.User user = null;
if (userDict != null) {
user = userDict.get(newContact.user_id);
}
if (user == null) {
user = getMessagesController().getUser(newContact.user_id);
} else {
getMessagesController().putUser(user, true);
}
if (user == null || TextUtils.isEmpty(user.phone)) {
reloadContacts = true;
continue;
}
Contact contact = contactsBookSPhones.get(user.phone);
if (contact != null) {
int index = contact.shortPhones.indexOf(user.phone);
if (index != -1) {
contact.phoneDeleted.set(index, 0);
}
}
if (toAdd.length() != 0) {
toAdd.append(",");
}
toAdd.append(user.phone);
}
for (int a = 0; a < contactsTD.size(); a++) {
final Integer uid = contactsTD.get(a);
Utilities.phoneBookQueue.postRunnable(() -> deleteContactFromPhoneBook(uid));
TLRPC.User user = null;
if (userDict != null) {
user = userDict.get(uid);
}
if (user == null) {
user = getMessagesController().getUser(uid);
} else {
getMessagesController().putUser(user, true);
}
if (user == null) {
reloadContacts = true;
continue;
}
if (!TextUtils.isEmpty(user.phone)) {
Contact contact = contactsBookSPhones.get(user.phone);
if (contact != null) {
int index = contact.shortPhones.indexOf(user.phone);
if (index != -1) {
contact.phoneDeleted.set(index, 1);
}
}
if (toDelete.length() != 0) {
toDelete.append(",");
}
toDelete.append(user.phone);
}
}
if (toAdd.length() != 0 || toDelete.length() != 0) {
getMessagesStorage().applyPhoneBookUpdates(toAdd.toString(), toDelete.toString());
}
if (reloadContacts) {
Utilities.stageQueue.postRunnable(() -> loadContacts(false, 0));
} else {
final ArrayList<TLRPC.TL_contact> newContacts = newC;
final ArrayList<Integer> contactsToDelete = contactsTD;
AndroidUtilities.runOnUIThread(() -> {
for (int a = 0; a < newContacts.size(); a++) {
TLRPC.TL_contact contact = newContacts.get(a);
if (contactsDict.get(contact.user_id) == null) {
contacts.add(contact);
contactsDict.put(contact.user_id, contact);
}
}
for (int a = 0; a < contactsToDelete.size(); a++) {
Integer uid = contactsToDelete.get(a);
TLRPC.TL_contact contact = contactsDict.get(uid);
if (contact != null) {
contacts.remove(contact);
contactsDict.remove(uid);
}
}
if (!newContacts.isEmpty()) {
updateUnregisteredContacts();
performWriteContactsToPhoneBook();
}
performSyncPhoneBook(getContactsCopy(contactsBook), false, false, false, false, true, false);
buildContactsSectionsArrays(!newContacts.isEmpty());
getNotificationCenter().postNotificationName(NotificationCenter.contactsDidLoad);
});
}
}
public void processContactsUpdates(ArrayList<Integer> ids, ConcurrentHashMap<Integer, TLRPC.User> userDict) {
final ArrayList<TLRPC.TL_contact> newContacts = new ArrayList<>();
final ArrayList<Integer> contactsToDelete = new ArrayList<>();
for (Integer uid : ids) {
if (uid > 0) {
TLRPC.TL_contact contact = new TLRPC.TL_contact();
contact.user_id = uid;
newContacts.add(contact);
if (!delayedContactsUpdate.isEmpty()) {
int idx = delayedContactsUpdate.indexOf(-uid);
if (idx != -1) {
delayedContactsUpdate.remove(idx);
}
}
} else if (uid < 0) {
contactsToDelete.add(-uid);
if (!delayedContactsUpdate.isEmpty()) {
int idx = delayedContactsUpdate.indexOf(-uid);
if (idx != -1) {
delayedContactsUpdate.remove(idx);
}
}
}
}
if (!contactsToDelete.isEmpty()) {
getMessagesStorage().deleteContacts(contactsToDelete);
}
if (!newContacts.isEmpty()) {
getMessagesStorage().putContacts(newContacts, false);
}
if (!contactsLoaded || !contactsBookLoaded) {
delayedContactsUpdate.addAll(ids);
if (BuildVars.LOGS_ENABLED) {
FileLog.d("delay update - contacts add = " + newContacts.size() + " delete = " + contactsToDelete.size());
}
} else {
applyContactsUpdates(ids, userDict, newContacts, contactsToDelete);
}
}
public long addContactToPhoneBook(TLRPC.User user, boolean check) {
if (systemAccount == null || user == null) {
return -1;
}
if (!hasContactsPermission()) {
return -1;
}
long res = -1;
synchronized (observerLock) {
ignoreChanges = true;
}
ContentResolver contentResolver = ApplicationLoader.applicationContext.getContentResolver();
if (check) {
try {
Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, systemAccount.name).appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, systemAccount.type).build();
int value = contentResolver.delete(rawContactUri, ContactsContract.RawContacts.SYNC2 + " = " + user.id, null);
} catch (Exception ignore) {
}
}
ArrayList<ContentProviderOperation> query = new ArrayList<>();
ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI);
builder.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, systemAccount.name);
builder.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, systemAccount.type);
builder.withValue(ContactsContract.RawContacts.SYNC1, TextUtils.isEmpty(user.phone) ? "" : user.phone);
builder.withValue(ContactsContract.RawContacts.SYNC2, user.id);
query.add(builder.build());
builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, user.first_name);
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, user.last_name);
query.add(builder.build());
// builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
// builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
// builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
// builder.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "+" + user.phone);
// builder.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
// query.add(builder.build());
builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);
builder.withValue(ContactsContract.Data.MIMETYPE, "vnd.android.cursor.item/vnd.org.telegram.messenger.android.profile");
builder.withValue(ContactsContract.Data.DATA1, user.id);
builder.withValue(ContactsContract.Data.DATA2, "Telegram Profile");
builder.withValue(ContactsContract.Data.DATA3, TextUtils.isEmpty(user.phone) ? ContactsController.formatName(user.first_name, user.last_name) : "+" + user.phone);
builder.withValue(ContactsContract.Data.DATA4, user.id);
query.add(builder.build());
try {
ContentProviderResult[] result = contentResolver.applyBatch(ContactsContract.AUTHORITY, query);
if (result != null && result.length > 0 && result[0].uri != null) {
res = Long.parseLong(result[0].uri.getLastPathSegment());
}
} catch (Exception ignore) {
}
synchronized (observerLock) {
ignoreChanges = false;
}
return res;
}
private void deleteContactFromPhoneBook(int uid) {
if (!hasContactsPermission()) {
return;
}
synchronized (observerLock) {
ignoreChanges = true;
}
try {
ContentResolver contentResolver = ApplicationLoader.applicationContext.getContentResolver();
Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, systemAccount.name).appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, systemAccount.type).build();
int value = contentResolver.delete(rawContactUri, ContactsContract.RawContacts.SYNC2 + " = " + uid, null);
} catch (Exception e) {
FileLog.e(e);
}
synchronized (observerLock) {
ignoreChanges = false;
}
}
protected void markAsContacted(final String contactId) {
if (contactId == null) {
return;
}
Utilities.phoneBookQueue.postRunnable(() -> {
Uri uri = Uri.parse(contactId);
ContentValues values = new ContentValues();
values.put(ContactsContract.Contacts.LAST_TIME_CONTACTED, System.currentTimeMillis());
ContentResolver cr = ApplicationLoader.applicationContext.getContentResolver();
cr.update(uri, values, null, null);
});
}
public void addContact(TLRPC.User user, boolean exception) {
if (user == null) {
return;
}
TLRPC.TL_contacts_addContact req = new TLRPC.TL_contacts_addContact();
req.id = getMessagesController().getInputUser(user);
req.first_name = user.first_name;
req.last_name = user.last_name;
req.phone = user.phone;
req.add_phone_privacy_exception = exception;
if (req.phone == null) {
req.phone = "";
} else if (req.phone.length() > 0 && !req.phone.startsWith("+")) {
req.phone = "+" + req.phone;
}
getConnectionsManager().sendRequest(req, (response, error) -> {
if (error != null) {
return;
}
final TLRPC.Updates res = (TLRPC.Updates) response;
getMessagesController().processUpdates(res, false);
/*if (BuildVars.DEBUG_VERSION) {
for (TLRPC.User user : res.users) {
FileLog.e("received user " + user.first_name + " " + user.last_name + " " + user.phone);
}
}*/
for (int a = 0; a < res.users.size(); a++) {
final TLRPC.User u = res.users.get(a);
if (u.id != user.id) {
continue;
}
Utilities.phoneBookQueue.postRunnable(() -> addContactToPhoneBook(u, true));
TLRPC.TL_contact newContact = new TLRPC.TL_contact();
newContact.user_id = u.id;
ArrayList<TLRPC.TL_contact> arrayList = new ArrayList<>();
arrayList.add(newContact);
getMessagesStorage().putContacts(arrayList, false);
if (!TextUtils.isEmpty(u.phone)) {
CharSequence name = formatName(u.first_name, u.last_name);
getMessagesStorage().applyPhoneBookUpdates(u.phone, "");
Contact contact = contactsBookSPhones.get(u.phone);
if (contact != null) {
int index = contact.shortPhones.indexOf(u.phone);
if (index != -1) {
contact.phoneDeleted.set(index, 0);
}
}
}
}
AndroidUtilities.runOnUIThread(() -> {
for (int a = 0; a < res.users.size(); a++) {
TLRPC.User u = res.users.get(a);
if (!u.contact || contactsDict.get(u.id) != null) {
continue;
}
TLRPC.TL_contact newContact = new TLRPC.TL_contact();
newContact.user_id = u.id;
contacts.add(newContact);
contactsDict.put(newContact.user_id, newContact);
}
buildContactsSectionsArrays(true);
getNotificationCenter().postNotificationName(NotificationCenter.contactsDidLoad);
});
}, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagCanCompress);
}
public void deleteContact(final ArrayList<TLRPC.User> users) {
if (users == null || users.isEmpty()) {
return;
}
TLRPC.TL_contacts_deleteContacts req = new TLRPC.TL_contacts_deleteContacts();
final ArrayList<Integer> uids = new ArrayList<>();
for (TLRPC.User user : users) {
TLRPC.InputUser inputUser = getMessagesController().getInputUser(user);
if (inputUser == null) {
continue;
}
user.contact = false;
uids.add(user.id);
req.id.add(inputUser);
}
getConnectionsManager().sendRequest(req, (response, error) -> {
if (error != null) {
return;
}
getMessagesController().processUpdates((TLRPC.Updates) response, false);
getMessagesStorage().deleteContacts(uids);
Utilities.phoneBookQueue.postRunnable(() -> {
for (TLRPC.User user : users) {
deleteContactFromPhoneBook(user.id);
}
});
for (int a = 0; a < users.size(); a++) {
TLRPC.User user = users.get(a);
if (TextUtils.isEmpty(user.phone)) {
continue;
}
getMessagesStorage().applyPhoneBookUpdates(user.phone, "");
Contact contact = contactsBookSPhones.get(user.phone);
if (contact != null) {
int index = contact.shortPhones.indexOf(user.phone);
if (index != -1) {
contact.phoneDeleted.set(index, 1);
}
}
}
AndroidUtilities.runOnUIThread(() -> {
boolean remove = false;
for (TLRPC.User user : users) {
TLRPC.TL_contact contact = contactsDict.get(user.id);
if (contact != null) {
remove = true;
contacts.remove(contact);
contactsDict.remove(user.id);
}
}
if (remove) {
buildContactsSectionsArrays(false);
}
getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_NAME);
getNotificationCenter().postNotificationName(NotificationCenter.contactsDidLoad);
});
});
}
private void reloadContactsStatuses() {
saveContactsLoadTime();
getMessagesController().clearFullUsers();
SharedPreferences preferences = MessagesController.getMainSettings(currentAccount);
final SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("needGetStatuses", true).commit();
TLRPC.TL_contacts_getStatuses req = new TLRPC.TL_contacts_getStatuses();
getConnectionsManager().sendRequest(req, (response, error) -> {
if (error == null) {
AndroidUtilities.runOnUIThread(() -> {
editor.remove("needGetStatuses").commit();
TLRPC.Vector vector = (TLRPC.Vector) response;
if (!vector.objects.isEmpty()) {
ArrayList<TLRPC.User> dbUsersStatus = new ArrayList<>();
for (Object object : vector.objects) {
TLRPC.User toDbUser = new TLRPC.TL_user();
TLRPC.TL_contactStatus status = (TLRPC.TL_contactStatus) object;
if (status == null) {
continue;
}
if (status.status instanceof TLRPC.TL_userStatusRecently) {
status.status.expires = -100;
} else if (status.status instanceof TLRPC.TL_userStatusLastWeek) {
status.status.expires = -101;
} else if (status.status instanceof TLRPC.TL_userStatusLastMonth) {
status.status.expires = -102;
}
TLRPC.User user = getMessagesController().getUser(status.user_id);
if (user != null) {
user.status = status.status;
}
toDbUser.status = status.status;
dbUsersStatus.add(toDbUser);
}
getMessagesStorage().updateUsers(dbUsersStatus, true, true, true);
}
getNotificationCenter().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_STATUS);
});
}
});
}
public void loadPrivacySettings() {
if (loadingDeleteInfo == 0) {
loadingDeleteInfo = 1;
TLRPC.TL_account_getAccountTTL req = new TLRPC.TL_account_getAccountTTL();
getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
if (error == null) {
TLRPC.TL_accountDaysTTL ttl = (TLRPC.TL_accountDaysTTL) response;
deleteAccountTTL = ttl.days;
loadingDeleteInfo = 2;
} else {
loadingDeleteInfo = 0;
}
getNotificationCenter().postNotificationName(NotificationCenter.privacyRulesUpdated);
}));
}
for (int a = 0; a < loadingPrivacyInfo.length; a++) {
if (loadingPrivacyInfo[a] != 0) {
continue;
}
loadingPrivacyInfo[a] = 1;
final int num = a;
TLRPC.TL_account_getPrivacy req = new TLRPC.TL_account_getPrivacy();
switch (num) {
case PRIVACY_RULES_TYPE_LASTSEEN:
req.key = new TLRPC.TL_inputPrivacyKeyStatusTimestamp();
break;
case PRIVACY_RULES_TYPE_INVITE:
req.key = new TLRPC.TL_inputPrivacyKeyChatInvite();
break;
case PRIVACY_RULES_TYPE_CALLS:
req.key = new TLRPC.TL_inputPrivacyKeyPhoneCall();
break;
case PRIVACY_RULES_TYPE_P2P:
req.key = new TLRPC.TL_inputPrivacyKeyPhoneP2P();
break;
case PRIVACY_RULES_TYPE_PHOTO:
req.key = new TLRPC.TL_inputPrivacyKeyProfilePhoto();
break;
case PRIVACY_RULES_TYPE_FORWARDS:
req.key = new TLRPC.TL_inputPrivacyKeyForwards();
break;
case PRIVACY_RULES_TYPE_PHONE:
req.key = new TLRPC.TL_inputPrivacyKeyPhoneNumber();
break;
case PRIVACY_RULES_TYPE_ADDED_BY_PHONE:
default:
req.key = new TLRPC.TL_inputPrivacyKeyAddedByPhone();
break;
}
getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
if (error == null) {
TLRPC.TL_account_privacyRules rules = (TLRPC.TL_account_privacyRules) response;
getMessagesController().putUsers(rules.users, false);
getMessagesController().putChats(rules.chats, false);
switch (num) {
case PRIVACY_RULES_TYPE_LASTSEEN:
lastseenPrivacyRules = rules.rules;
break;
case PRIVACY_RULES_TYPE_INVITE:
groupPrivacyRules = rules.rules;
break;
case PRIVACY_RULES_TYPE_CALLS:
callPrivacyRules = rules.rules;
break;
case PRIVACY_RULES_TYPE_P2P:
p2pPrivacyRules = rules.rules;
break;
case PRIVACY_RULES_TYPE_PHOTO:
profilePhotoPrivacyRules = rules.rules;
break;
case PRIVACY_RULES_TYPE_FORWARDS:
forwardsPrivacyRules = rules.rules;
break;
case PRIVACY_RULES_TYPE_PHONE:
phonePrivacyRules = rules.rules;
break;
case PRIVACY_RULES_TYPE_ADDED_BY_PHONE:
default:
addedByPhonePrivacyRules = rules.rules;
break;
}
loadingPrivacyInfo[num] = 2;
} else {
loadingPrivacyInfo[num] = 0;
}
getNotificationCenter().postNotificationName(NotificationCenter.privacyRulesUpdated);
}));
}
getNotificationCenter().postNotificationName(NotificationCenter.privacyRulesUpdated);
}
public void setDeleteAccountTTL(int ttl) {
deleteAccountTTL = ttl;
}
public int getDeleteAccountTTL() {
return deleteAccountTTL;
}
public boolean getLoadingDeleteInfo() {
return loadingDeleteInfo != 2;
}
public boolean getLoadingPrivicyInfo(int type) {
return loadingPrivacyInfo[type] != 2;
}
public ArrayList<TLRPC.PrivacyRule> getPrivacyRules(int type) {
switch (type) {
case PRIVACY_RULES_TYPE_LASTSEEN:
return lastseenPrivacyRules;
case PRIVACY_RULES_TYPE_INVITE:
return groupPrivacyRules;
case PRIVACY_RULES_TYPE_CALLS:
return callPrivacyRules;
case PRIVACY_RULES_TYPE_P2P:
return p2pPrivacyRules;
case PRIVACY_RULES_TYPE_PHOTO:
return profilePhotoPrivacyRules;
case PRIVACY_RULES_TYPE_FORWARDS:
return forwardsPrivacyRules;
case PRIVACY_RULES_TYPE_PHONE:
return phonePrivacyRules;
case PRIVACY_RULES_TYPE_ADDED_BY_PHONE:
return addedByPhonePrivacyRules;
}
return null;
}
public void setPrivacyRules(ArrayList<TLRPC.PrivacyRule> rules, int type) {
switch (type) {
case PRIVACY_RULES_TYPE_LASTSEEN:
lastseenPrivacyRules = rules;
break;
case PRIVACY_RULES_TYPE_INVITE:
groupPrivacyRules = rules;
break;
case PRIVACY_RULES_TYPE_CALLS:
callPrivacyRules = rules;
break;
case PRIVACY_RULES_TYPE_P2P:
p2pPrivacyRules = rules;
break;
case PRIVACY_RULES_TYPE_PHOTO:
profilePhotoPrivacyRules = rules;
break;
case PRIVACY_RULES_TYPE_FORWARDS:
forwardsPrivacyRules = rules;
break;
case PRIVACY_RULES_TYPE_PHONE:
phonePrivacyRules = rules;
break;
case PRIVACY_RULES_TYPE_ADDED_BY_PHONE:
addedByPhonePrivacyRules = rules;
break;
}
getNotificationCenter().postNotificationName(NotificationCenter.privacyRulesUpdated);
reloadContactsStatuses();
}
public void createOrUpdateConnectionServiceContact(int id, String firstName, String lastName) {
if (!hasContactsPermission())
return;
try {
ContentResolver resolver = ApplicationLoader.applicationContext.getContentResolver();
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
final Uri groupsURI = ContactsContract.Groups.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
final Uri rawContactsURI = ContactsContract.RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
// 1. Check if we already have the invisible group/label and create it if we don't
Cursor cursor = resolver.query(groupsURI, new String[]{ContactsContract.Groups._ID},
ContactsContract.Groups.TITLE + "=? AND " + ContactsContract.Groups.ACCOUNT_TYPE + "=? AND " + ContactsContract.Groups.ACCOUNT_NAME + "=?",
new String[]{"TelegramConnectionService", systemAccount.type, systemAccount.name}, null);
int groupID;
if (cursor != null && cursor.moveToFirst()) {
groupID = cursor.getInt(0);
/*ops.add(ContentProviderOperation.newUpdate(groupsURI)
.withSelection(ContactsContract.Groups._ID+"=?", new String[]{groupID+""})
.withValue(ContactsContract.Groups.DELETED, 0)
.build());*/
} else {
ContentValues values = new ContentValues();
values.put(ContactsContract.Groups.ACCOUNT_TYPE, systemAccount.type);
values.put(ContactsContract.Groups.ACCOUNT_NAME, systemAccount.name);
values.put(ContactsContract.Groups.GROUP_VISIBLE, 0);
values.put(ContactsContract.Groups.GROUP_IS_READ_ONLY, 1);
values.put(ContactsContract.Groups.TITLE, "TelegramConnectionService");
Uri res = resolver.insert(groupsURI, values);
groupID = Integer.parseInt(res.getLastPathSegment());
}
if (cursor != null)
cursor.close();
// 2. Find the existing ConnectionService contact and update it or create it
cursor = resolver.query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.Data.RAW_CONTACT_ID},
ContactsContract.Data.MIMETYPE + "=? AND " + ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "=?",
new String[]{ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE, groupID + ""}, null);
int backRef = ops.size();
if (cursor != null && cursor.moveToFirst()) {
int contactID = cursor.getInt(0);
ops.add(ContentProviderOperation.newUpdate(rawContactsURI)
.withSelection(ContactsContract.RawContacts._ID + "=?", new String[]{contactID + ""})
.withValue(ContactsContract.RawContacts.DELETED, 0)
.build());
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[]{contactID + "", ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE})
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "+99084" + id)
.build());
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[]{contactID + "", ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE})
.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, firstName)
.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, lastName)
.build());
} else {
ops.add(ContentProviderOperation.newInsert(rawContactsURI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, systemAccount.type)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, systemAccount.name)
.withValue(ContactsContract.RawContacts.RAW_CONTACT_IS_READ_ONLY, 1)
.withValue(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DISABLED)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, backRef)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, firstName)
.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, lastName)
.build());
// The prefix +990 isn't assigned to anything, so our "phone number" is going to be +990-TG-UserID
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, backRef)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "+99084" + id)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, backRef)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID, groupID)
.build());
}
if (cursor != null)
cursor.close();
resolver.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception x) {
FileLog.e(x);
}
}
public void deleteConnectionServiceContact() {
if (!hasContactsPermission())
return;
try {
ContentResolver resolver = ApplicationLoader.applicationContext.getContentResolver();
Cursor cursor = resolver.query(ContactsContract.Groups.CONTENT_URI, new String[]{ContactsContract.Groups._ID},
ContactsContract.Groups.TITLE + "=? AND " + ContactsContract.Groups.ACCOUNT_TYPE + "=? AND " + ContactsContract.Groups.ACCOUNT_NAME + "=?",
new String[]{"TelegramConnectionService", systemAccount.type, systemAccount.name}, null);
int groupID;
if (cursor != null && cursor.moveToFirst()) {
groupID = cursor.getInt(0);
cursor.close();
} else {
if (cursor != null)
cursor.close();
return;
}
cursor = resolver.query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.Data.RAW_CONTACT_ID},
ContactsContract.Data.MIMETYPE + "=? AND " + ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "=?",
new String[]{ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE, groupID + ""}, null);
int contactID;
if (cursor != null && cursor.moveToFirst()) {
contactID = cursor.getInt(0);
cursor.close();
} else {
if (cursor != null)
cursor.close();
return;
}
resolver.delete(ContactsContract.RawContacts.CONTENT_URI, ContactsContract.RawContacts._ID + "=?", new String[]{contactID + ""});
//resolver.delete(ContactsContract.Groups.CONTENT_URI, ContactsContract.Groups._ID+"=?", new String[]{groupID+""});
} catch (Exception x) {
FileLog.e(x);
}
}
public static String formatName(String firstName, String lastName) {
/*if ((firstName == null || firstName.length() == 0) && (lastName == null || lastName.length() == 0)) {
return LocaleController.getString("HiddenName", R.string.HiddenName);
}*/
if (firstName != null) {
firstName = firstName.trim();
}
if (lastName != null) {
lastName = lastName.trim();
}
StringBuilder result = new StringBuilder((firstName != null ? firstName.length() : 0) + (lastName != null ? lastName.length() : 0) + 1);
if (LocaleController.nameDisplayOrder == 1) {
if (firstName != null && firstName.length() > 0) {
result.append(firstName);
if (lastName != null && lastName.length() > 0) {
result.append(" ");
result.append(lastName);
}
} else if (lastName != null && lastName.length() > 0) {
result.append(lastName);
}
} else {
if (lastName != null && lastName.length() > 0) {
result.append(lastName);
if (firstName != null && firstName.length() > 0) {
result.append(" ");
result.append(firstName);
}
} else if (firstName != null && firstName.length() > 0) {
result.append(firstName);
}
}
return result.toString();
}
}
| 124,825 | Java | .java | 2,426 | 33.011542 | 334 | 0.50843 | LinXueyuanStdio/LearnTelegram | 4 | 4 | 1 | GPL-2.0 | 9/4/2024, 11:11:54 PM (Europe/Amsterdam) | false | false | true | true | true | true | true | true | 124,804 |
4,505,079 | Slayer.java | Marsunpaisti_openosrs-plugins/webwalker/src/main/java/net/runelite/client/plugins/webwalker/Slayer.java | /*
* Copyright (c) 2019-2020, ganom <https://github.com/Ganom>
* All rights reserved.
* Licensed under GPL3, see LICENSE for the full scope.
*/
package net.runelite.client.plugins.webwalker;
import lombok.Getter;
import net.runelite.api.coords.WorldPoint;
@Getter
public enum Slayer
{
NONE(""),
BURTHORPE_SLAYER("Turael", new WorldPoint(2931, 3536, 0)),
FREMENNIK_CAVE("Fremennik Cave", new WorldPoint(2794, 3615, 0)),
KARUULM_KONAR("Konar", new WorldPoint(1308, 3786, 0)),
LUMBRIDGE_SWAMP_CAVE("Lumby Swamp Cave", new WorldPoint(3169, 3172, 0)),
SLAYER_TOWER("Slayer Tower", new WorldPoint(3429, 3530, 0)),
TREE_GNOME_NIEVE("Nieve", new WorldPoint(2611, 3092, 0));
private final String name;
private WorldPoint worldPoint;
Slayer(String name)
{
this.name = name;
}
Slayer(String name, WorldPoint worldPoint)
{
this.name = name;
this.worldPoint = worldPoint;
}
}
| 893 | Java | .java | 30 | 27.766667 | 73 | 0.744755 | Marsunpaisti/openosrs-plugins | 2 | 22 | 0 | GPL-3.0 | 9/5/2024, 12:15:15 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 893 |
1,555,110 | FieldsGenerator.java | He-Ze_Autonomous-Surface-Vehicle-Simulator/lib/lwjgl/jars/lwjgl-source-2.9.3/src/java/org/lwjgl/util/generator/FieldsGenerator.java | /*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.lwjgl.util.generator;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.PrimitiveType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
public class FieldsGenerator {
private static void validateField(VariableElement field) {
// Check if field is "public static final"
Set<Modifier> modifiers = field.getModifiers();
if ( modifiers.size() != 3
|| !modifiers.contains(Modifier.PUBLIC)
|| !modifiers.contains(Modifier.STATIC)
|| !modifiers.contains(Modifier.FINAL) ) {
throw new RuntimeException("Field " + field.getSimpleName() + " is not declared public static final");
}
// Check suported types (int, long, float, String)
TypeMirror field_type = field.asType();
if ( "java.lang.String".equals(field_type.toString()) ) {
} else if ( field_type instanceof PrimitiveType ) {
PrimitiveType field_type_prim = (PrimitiveType)field_type;
TypeKind field_kind = field_type_prim.getKind();
if ( field_kind != TypeKind.INT
&& field_kind != TypeKind.LONG
&& field_kind != TypeKind.FLOAT
&& field_kind != TypeKind.BYTE ) {
throw new RuntimeException("Field " + field.getSimpleName() + " is not of type 'int', 'long', 'float' or 'byte' " + field_kind.toString());
}
} else {
throw new RuntimeException("Field " + field.getSimpleName() + " is not a primitive type or String");
}
Object field_value = field.getConstantValue();
if ( field_value == null ) {
throw new RuntimeException("Field " + field.getSimpleName() + " has no initial value");
}
}
private static void generateField(PrintWriter writer, VariableElement field, VariableElement prev_field, ProcessingEnvironment env) {
validateField(field);
Object value = field.getConstantValue();
String field_value_string;
Class field_value_class = value.getClass();
if ( field_value_class.equals(Integer.class) ) {
field_value_string = "0x" + Integer.toHexString((Integer)field.getConstantValue()).toUpperCase();
} else if ( field_value_class.equals(Long.class) ) {
field_value_string = "0x" + Long.toHexString((Long)field.getConstantValue()).toUpperCase() + 'L';
} else if ( field_value_class.equals(Float.class) ) {
field_value_string = field.getConstantValue() + "f";
} else if ( value.getClass().equals(Byte.class) ) {
field_value_string = "0x" + Integer.toHexString((Byte)field.getConstantValue()).toUpperCase();
} else if ( field_value_class.equals(String.class) ) {
field_value_string = "\"" + field.getConstantValue() + "\"";
} else {
throw new RuntimeException("Field is of unexpected type. This means there is a bug in validateField().");
}
boolean hadDoc = prev_field != null && env.getElementUtils().getDocComment(prev_field) != null;
boolean hasDoc = env.getElementUtils().getDocComment(field) != null;
boolean newBatch = prev_field == null || !prev_field.asType().equals(field.asType()) || (!hadDoc && env.getElementUtils().getDocComment(field) != null) || (hadDoc && hasDoc && !env.getElementUtils().getDocComment(prev_field).equals(env.getElementUtils().getDocComment(field)));
// Print field declaration
if ( newBatch ) {
if ( prev_field != null ) {
writer.println(";\n");
}
Utils.printDocComment(writer, field, env);
writer.print("\tpublic static final " + field.asType().toString() + " " + field.getSimpleName() + " = " + field_value_string);
} else {
writer.print(",\n\t\t" + field.getSimpleName() + " = " + field_value_string);
}
}
public static void generateFields(ProcessingEnvironment env, PrintWriter writer, Collection<? extends VariableElement> fields) {
if ( 0 < fields.size() ) {
writer.println();
VariableElement prev_field = null;
for ( VariableElement field : fields ) {
generateField(writer, field, prev_field, env);
prev_field = field;
}
writer.println(";");
}
}
} | 5,667 | Java | .java | 115 | 46.165217 | 279 | 0.72893 | He-Ze/Autonomous-Surface-Vehicle-Simulator | 20 | 2 | 1 | GPL-3.0 | 9/4/2024, 7:58:53 PM (Europe/Amsterdam) | true | true | true | true | false | true | true | true | 5,667 |
3,900,089 | EntityNotFoundException.java | DeykyPinheiro_finances-api/src/main/java/com/finances/domain/exception/EntityNotFoundException.java | package com.finances.domain.exception;
public class EntityNotFoundException extends BusinessException {
public EntityNotFoundException(String message) {
super(message);
}
}
| 191 | Java | .java | 6 | 27.833333 | 64 | 0.79235 | DeykyPinheiro/finances-api | 3 | 0 | 0 | GPL-3.0 | 9/4/2024, 11:47:43 PM (Europe/Amsterdam) | false | false | false | false | false | false | true | true | 191 |
572,453 | ConfigReader.java | the8472_mldht/src/the8472/utils/ConfigReader.java | /*******************************************************************************
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
******************************************************************************/
package the8472.utils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ConfigReader {
public static class ParseException extends RuntimeException {
public ParseException(Exception cause) {
super(cause);
}
};
FilesystemNotifications notifications;
Path configFile;
Schema schema;
Supplier<InputStream> defaults;
Document current;
public ConfigReader(Path toRead, Supplier<InputStream> defaults, Supplier<InputStream> schemaSource) {
configFile = toRead;
this.defaults = defaults;
try {
buildSchema(schemaSource.get());
} catch (SAXException e1) {
throw new RuntimeException(e1);
}
if(!Files.exists(configFile)) {
try {
Files.copy(defaults.get(), configFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void buildSchema(InputStream source) throws SAXException {
// create a SchemaFactory capable of understanding WXS schemas
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// load a WXS schema, represented by a Schema instance
Source schemaFile = new StreamSource(source);
schema = schemaFactory.newSchema(schemaFile);
}
List<Runnable> callbacks = new ArrayList<>();
public void addChangeCallback(Runnable callback) {
callbacks.add(callback);
}
public void registerFsNotifications(FilesystemNotifications notifier) {
notifications = notifier;
notifier.addRegistration(configFile, (path, kind) -> {
if(path.equals(configFile)) {
current = readFile(configFile);
callbacks.forEach(Runnable::run);
}
});
}
private void write(Path source) {
/*
JSONObject obj = new JSONObject(toWrite);
try {
Files.write(configFile, obj.toJSONString().getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
}
public Document read() {
if(current == null)
readConfig();
return current;
}
void readConfig() {
current = readFile(configFile);
}
public Optional<String> get(XPathExpression expr) {
Node result;
try {
result = (Node) expr.evaluate(current, XPathConstants.NODE);
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
if(result == null)
return Optional.empty();
return Optional.of(result.getTextContent());
}
public Optional<Boolean> getBoolean(String path) {
return get(XMLUtils.buildXPath(path)).map(str -> str.equals("true") || str.equals("1"));
}
public Optional<Long> getLong(String path) {
return get(XMLUtils.buildXPath(path)).map(Long::valueOf);
}
public Stream<String> getAll(XPathExpression path) {
NodeList result;
try {
result = (NodeList) path.evaluate(current, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
if(result == null)
return Stream.empty();
return IntStream.range(0, result.getLength()).mapToObj(result::item).map(Node::getTextContent);
}
Document readFile(Path p) {
Document document = null;
try {
// parse an XML document into a DOM tree
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder parser = factory.newDocumentBuilder();
document = parser.parse(p.toFile());
// create a Validator instance, which can be used to validate an instance document
Validator validator = schema.newValidator();
// validate the DOM tree
validator.validate(new DOMSource(document));
} catch (SAXException | IOException | ParserConfigurationException e) {
throw new ParseException(e);
}
return document;
}
}
| 5,001 | Java | .java | 146 | 31.054795 | 103 | 0.743391 | the8472/mldht | 147 | 45 | 7 | MPL-2.0 | 9/4/2024, 7:08:18 PM (Europe/Amsterdam) | true | true | true | true | true | true | true | true | 5,001 |
4,167,802 | DomConcurrentDataBrokerModule.java | Sushma7785_OpenDayLight-Load-Balancer/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/concurrent_data_broker/DomConcurrentDataBrokerModule.java | /*
* Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.config.yang.config.concurrent_data_broker;
import com.google.common.collect.Lists;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import org.opendaylight.controller.cluster.datastore.ConcurrentDOMDataBroker;
import org.opendaylight.controller.config.api.DependencyResolver;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
import org.opendaylight.controller.md.sal.common.util.jmx.ThreadExecutorStatsMXBeanImpl;
import org.opendaylight.controller.md.sal.dom.broker.impl.jmx.CommitStatsMXBeanImpl;
import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
import org.opendaylight.controller.sal.core.spi.data.DOMStore;
import org.opendaylight.yangtools.util.DurationStatisticsTracker;
import org.opendaylight.yangtools.util.concurrent.SpecialExecutors;
public class DomConcurrentDataBrokerModule extends AbstractDomConcurrentDataBrokerModule {
private static final String JMX_BEAN_TYPE = "DOMDataBroker";
public DomConcurrentDataBrokerModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final DependencyResolver dependencyResolver) {
super(identifier, dependencyResolver);
}
public DomConcurrentDataBrokerModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final DependencyResolver dependencyResolver, final DomConcurrentDataBrokerModule oldModule, final AutoCloseable oldInstance) {
super(identifier, dependencyResolver, oldModule, oldInstance);
}
@Override
public boolean canReuseInstance(AbstractDomConcurrentDataBrokerModule oldModule) {
return true;
}
@Override
public AutoCloseable createInstance() {
//Initializing Operational DOM DataStore defaulting to InMemoryDOMDataStore if one is not configured
DOMStore operStore = getOperationalDataStoreDependency();
if(operStore == null){
//we will default to InMemoryDOMDataStore creation
operStore = InMemoryDOMDataStoreFactory.create("DOM-OPER", getSchemaServiceDependency());
}
DOMStore configStore = getConfigDataStoreDependency();
if(configStore == null){
//we will default to InMemoryDOMDataStore creation
configStore = InMemoryDOMDataStoreFactory.create("DOM-CFG", getSchemaServiceDependency());
}
final Map<LogicalDatastoreType, DOMStore> datastores = new EnumMap<>(LogicalDatastoreType.class);
datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
datastores.put(LogicalDatastoreType.CONFIGURATION, configStore);
/*
* We use an executor for commit ListenableFuture callbacks that favors reusing available
* threads over creating new threads at the expense of execution time. The assumption is
* that most ListenableFuture callbacks won't execute a lot of business logic where we want
* it to run quicker - many callbacks will likely just handle error conditions and do
* nothing on success. The executor queue capacity is bounded and, if the capacity is
* reached, subsequent submitted tasks will block the caller.
*/
ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
getMaxDataBrokerFutureCallbackPoolSize(), getMaxDataBrokerFutureCallbackQueueSize(),
"CommitFutures");
final List<AbstractMXBean> mBeans = Lists.newArrayList();
final DurationStatisticsTracker commitStatsTracker;
final ConcurrentDOMDataBroker cdb = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
commitStatsTracker = cdb.getCommitStatsTracker();
if(commitStatsTracker != null) {
final CommitStatsMXBeanImpl commitStatsMXBean = new CommitStatsMXBeanImpl(
commitStatsTracker, JMX_BEAN_TYPE);
commitStatsMXBean.registerMBean();
mBeans.add(commitStatsMXBean);
}
final AbstractMXBean commitFutureStatsMXBean =
ThreadExecutorStatsMXBeanImpl.create(listenableFutureExecutor,
"CommitFutureExecutorStats", JMX_BEAN_TYPE, null);
if(commitFutureStatsMXBean != null) {
mBeans.add(commitFutureStatsMXBean);
}
cdb.setCloseable(new AutoCloseable() {
@Override
public void close() {
for(AbstractMXBean mBean: mBeans) {
mBean.unregisterMBean();
}
}
});
return cdb;
}
}
| 5,066 | Java | .java | 89 | 49.011236 | 241 | 0.752116 | Sushma7785/OpenDayLight-Load-Balancer | 2 | 0 | 0 | EPL-1.0 | 9/5/2024, 12:04:53 AM (Europe/Amsterdam) | false | false | true | false | false | true | false | true | 5,066 |
1,641,205 | BreakIterator.java | srisatish_openjdk/jdk/src/share/classes/java/text/BreakIterator.java | /*
* Copyright (c) 1996, 2006, 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.
*/
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
*
* The original version of this source code and documentation
* is copyrighted and owned by Taligent, Inc., a wholly-owned
* subsidiary of IBM. These materials are provided under terms
* of a License Agreement between Taligent and Sun. This technology
* is protected by multiple US and International patents.
*
* This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
package java.text;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.io.InputStream;
import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.text.spi.BreakIteratorProvider;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.spi.LocaleServiceProvider;
import sun.util.LocaleServiceProviderPool;
import sun.util.resources.LocaleData;
/**
* The <code>BreakIterator</code> class implements methods for finding
* the location of boundaries in text. Instances of <code>BreakIterator</code>
* maintain a current position and scan over text
* returning the index of characters where boundaries occur.
* Internally, <code>BreakIterator</code> scans text using a
* <code>CharacterIterator</code>, and is thus able to scan text held
* by any object implementing that protocol. A <code>StringCharacterIterator</code>
* is used to scan <code>String</code> objects passed to <code>setText</code>.
*
* <p>
* You use the factory methods provided by this class to create
* instances of various types of break iterators. In particular,
* use <code>getWordInstance</code>, <code>getLineInstance</code>,
* <code>getSentenceInstance</code>, and <code>getCharacterInstance</code>
* to create <code>BreakIterator</code>s that perform
* word, line, sentence, and character boundary analysis respectively.
* A single <code>BreakIterator</code> can work only on one unit
* (word, line, sentence, and so on). You must use a different iterator
* for each unit boundary analysis you wish to perform.
*
* <p><a name="line"></a>
* Line boundary analysis determines where a text string can be
* broken when line-wrapping. The mechanism correctly handles
* punctuation and hyphenated words. Actual line breaking needs
* to also consider the available line width and is handled by
* higher-level software.
*
* <p><a name="sentence"></a>
* Sentence boundary analysis allows selection with correct interpretation
* of periods within numbers and abbreviations, and trailing punctuation
* marks such as quotation marks and parentheses.
*
* <p><a name="word"></a>
* Word boundary analysis is used by search and replace functions, as
* well as within text editing applications that allow the user to
* select words with a double click. Word selection provides correct
* interpretation of punctuation marks within and following
* words. Characters that are not part of a word, such as symbols
* or punctuation marks, have word-breaks on both sides.
*
* <p><a name="character"></a>
* Character boundary analysis allows users to interact with characters
* as they expect to, for example, when moving the cursor through a text
* string. Character boundary analysis provides correct navigation
* through character strings, regardless of how the character is stored.
* The boundaries returned may be those of supplementary characters,
* combining character sequences, or ligature clusters.
* For example, an accented character might be stored as a base character
* and a diacritical mark. What users consider to be a character can
* differ between languages.
*
* <p>
* The <code>BreakIterator</code> instances returned by the factory methods
* of this class are intended for use with natural languages only, not for
* programming language text. It is however possible to define subclasses
* that tokenize a programming language.
*
* <P>
* <strong>Examples</strong>:<P>
* Creating and using text boundaries:
* <blockquote>
* <pre>
* public static void main(String args[]) {
* if (args.length == 1) {
* String stringToExamine = args[0];
* //print each word in order
* BreakIterator boundary = BreakIterator.getWordInstance();
* boundary.setText(stringToExamine);
* printEachForward(boundary, stringToExamine);
* //print each sentence in reverse order
* boundary = BreakIterator.getSentenceInstance(Locale.US);
* boundary.setText(stringToExamine);
* printEachBackward(boundary, stringToExamine);
* printFirst(boundary, stringToExamine);
* printLast(boundary, stringToExamine);
* }
* }
* </pre>
* </blockquote>
*
* Print each element in order:
* <blockquote>
* <pre>
* public static void printEachForward(BreakIterator boundary, String source) {
* int start = boundary.first();
* for (int end = boundary.next();
* end != BreakIterator.DONE;
* start = end, end = boundary.next()) {
* System.out.println(source.substring(start,end));
* }
* }
* </pre>
* </blockquote>
*
* Print each element in reverse order:
* <blockquote>
* <pre>
* public static void printEachBackward(BreakIterator boundary, String source) {
* int end = boundary.last();
* for (int start = boundary.previous();
* start != BreakIterator.DONE;
* end = start, start = boundary.previous()) {
* System.out.println(source.substring(start,end));
* }
* }
* </pre>
* </blockquote>
*
* Print first element:
* <blockquote>
* <pre>
* public static void printFirst(BreakIterator boundary, String source) {
* int start = boundary.first();
* int end = boundary.next();
* System.out.println(source.substring(start,end));
* }
* </pre>
* </blockquote>
*
* Print last element:
* <blockquote>
* <pre>
* public static void printLast(BreakIterator boundary, String source) {
* int end = boundary.last();
* int start = boundary.previous();
* System.out.println(source.substring(start,end));
* }
* </pre>
* </blockquote>
*
* Print the element at a specified position:
* <blockquote>
* <pre>
* public static void printAt(BreakIterator boundary, int pos, String source) {
* int end = boundary.following(pos);
* int start = boundary.previous();
* System.out.println(source.substring(start,end));
* }
* </pre>
* </blockquote>
*
* Find the next word:
* <blockquote>
* <pre>
* public static int nextWordStartAfter(int pos, String text) {
* BreakIterator wb = BreakIterator.getWordInstance();
* wb.setText(text);
* int last = wb.following(pos);
* int current = wb.next();
* while (current != BreakIterator.DONE) {
* for (int p = last; p < current; p++) {
* if (Character.isLetter(text.codePointAt(p)))
* return last;
* }
* last = current;
* current = wb.next();
* }
* return BreakIterator.DONE;
* }
* </pre>
* (The iterator returned by BreakIterator.getWordInstance() is unique in that
* the break positions it returns don't represent both the start and end of the
* thing being iterated over. That is, a sentence-break iterator returns breaks
* that each represent the end of one sentence and the beginning of the next.
* With the word-break iterator, the characters between two boundaries might be a
* word, or they might be the punctuation or whitespace between two words. The
* above code uses a simple heuristic to determine which boundary is the beginning
* of a word: If the characters between this boundary and the next boundary
* include at least one letter (this can be an alphabetical letter, a CJK ideograph,
* a Hangul syllable, a Kana character, etc.), then the text between this boundary
* and the next is a word; otherwise, it's the material between words.)
* </blockquote>
*
* @see CharacterIterator
*
*/
public abstract class BreakIterator implements Cloneable
{
/**
* Constructor. BreakIterator is stateless and has no default behavior.
*/
protected BreakIterator()
{
}
/**
* Create a copy of this iterator
* @return A copy of this
*/
public Object clone()
{
try {
return super.clone();
}
catch (CloneNotSupportedException e) {
throw new InternalError();
}
}
/**
* DONE is returned by previous(), next(), next(int), preceding(int)
* and following(int) when either the first or last text boundary has been
* reached.
*/
public static final int DONE = -1;
/**
* Returns the first boundary. The iterator's current position is set
* to the first text boundary.
* @return The character index of the first text boundary.
*/
public abstract int first();
/**
* Returns the last boundary. The iterator's current position is set
* to the last text boundary.
* @return The character index of the last text boundary.
*/
public abstract int last();
/**
* Returns the nth boundary from the current boundary. If either
* the first or last text boundary has been reached, it returns
* <code>BreakIterator.DONE</code> and the current position is set to either
* the first or last text boundary depending on which one is reached. Otherwise,
* the iterator's current position is set to the new boundary.
* For example, if the iterator's current position is the mth text boundary
* and three more boundaries exist from the current boundary to the last text
* boundary, the next(2) call will return m + 2. The new text position is set
* to the (m + 2)th text boundary. A next(4) call would return
* <code>BreakIterator.DONE</code> and the last text boundary would become the
* new text position.
* @param n which boundary to return. A value of 0
* does nothing. Negative values move to previous boundaries
* and positive values move to later boundaries.
* @return The character index of the nth boundary from the current position
* or <code>BreakIterator.DONE</code> if either first or last text boundary
* has been reached.
*/
public abstract int next(int n);
/**
* Returns the boundary following the current boundary. If the current boundary
* is the last text boundary, it returns <code>BreakIterator.DONE</code> and
* the iterator's current position is unchanged. Otherwise, the iterator's
* current position is set to the boundary following the current boundary.
* @return The character index of the next text boundary or
* <code>BreakIterator.DONE</code> if the current boundary is the last text
* boundary.
* Equivalent to next(1).
* @see #next(int)
*/
public abstract int next();
/**
* Returns the boundary preceding the current boundary. If the current boundary
* is the first text boundary, it returns <code>BreakIterator.DONE</code> and
* the iterator's current position is unchanged. Otherwise, the iterator's
* current position is set to the boundary preceding the current boundary.
* @return The character index of the previous text boundary or
* <code>BreakIterator.DONE</code> if the current boundary is the first text
* boundary.
*/
public abstract int previous();
/**
* Returns the first boundary following the specified character offset. If the
* specified offset equals to the last text boundary, it returns
* <code>BreakIterator.DONE</code> and the iterator's current position is unchanged.
* Otherwise, the iterator's current position is set to the returned boundary.
* The value returned is always greater than the offset or the value
* <code>BreakIterator.DONE</code>.
* @param offset the character offset to begin scanning.
* @return The first boundary after the specified offset or
* <code>BreakIterator.DONE</code> if the last text boundary is passed in
* as the offset.
* @exception IllegalArgumentException if the specified offset is less than
* the first text boundary or greater than the last text boundary.
*/
public abstract int following(int offset);
/**
* Returns the last boundary preceding the specified character offset. If the
* specified offset equals to the first text boundary, it returns
* <code>BreakIterator.DONE</code> and the iterator's current position is unchanged.
* Otherwise, the iterator's current position is set to the returned boundary.
* The value returned is always less than the offset or the value
* <code>BreakIterator.DONE</code>.
* @param offset the characater offset to begin scanning.
* @return The last boundary before the specified offset or
* <code>BreakIterator.DONE</code> if the first text boundary is passed in
* as the offset.
* @exception IllegalArgumentException if the specified offset is less than
* the first text boundary or greater than the last text boundary.
* @since 1.2
*/
public int preceding(int offset) {
// NOTE: This implementation is here solely because we can't add new
// abstract methods to an existing class. There is almost ALWAYS a
// better, faster way to do this.
int pos = following(offset);
while (pos >= offset && pos != DONE)
pos = previous();
return pos;
}
/**
* Returns true if the specified character offset is a text boundary.
* @param offset the character offset to check.
* @return <code>true</code> if "offset" is a boundary position,
* <code>false</code> otherwise.
* @since 1.2
*/
public boolean isBoundary(int offset) {
// NOTE: This implementation probably is wrong for most situations
// because it fails to take into account the possibility that a
// CharacterIterator passed to setText() may not have a begin offset
// of 0. But since the abstract BreakIterator doesn't have that
// knowledge, it assumes the begin offset is 0. If you subclass
// BreakIterator, copy the SimpleTextBoundary implementation of this
// function into your subclass. [This should have been abstract at
// this level, but it's too late to fix that now.]
if (offset == 0)
return true;
else
return following(offset - 1) == offset;
}
/**
* Returns character index of the text boundary that was most
* recently returned by next(), next(int), previous(), first(), last(),
* following(int) or preceding(int). If any of these methods returns
* <code>BreakIterator.DONE</code> because either first or last text boundary
* has been reached, it returns the first or last text boundary depending on
* which one is reached.
* @return The text boundary returned from the above methods, first or last
* text boundary.
* @see #next()
* @see #next(int)
* @see #previous()
* @see #first()
* @see #last()
* @see #following(int)
* @see #preceding(int)
*/
public abstract int current();
/**
* Get the text being scanned
* @return the text being scanned
*/
public abstract CharacterIterator getText();
/**
* Set a new text string to be scanned. The current scan
* position is reset to first().
* @param newText new text to scan.
*/
public void setText(String newText)
{
setText(new StringCharacterIterator(newText));
}
/**
* Set a new text for scanning. The current scan
* position is reset to first().
* @param newText new text to scan.
*/
public abstract void setText(CharacterIterator newText);
private static final int CHARACTER_INDEX = 0;
private static final int WORD_INDEX = 1;
private static final int LINE_INDEX = 2;
private static final int SENTENCE_INDEX = 3;
private static final SoftReference[] iterCache = new SoftReference[4];
/**
* Returns a new <code>BreakIterator</code> instance
* for <a href="#word">word breaks</a>
* for the {@linkplain Locale#getDefault() default locale}.
* @return A break iterator for word breaks
*/
public static BreakIterator getWordInstance()
{
return getWordInstance(Locale.getDefault());
}
/**
* Returns a new <code>BreakIterator</code> instance
* for <a href="#word">word breaks</a>
* for the given locale.
* @param locale the desired locale
* @return A break iterator for word breaks
* @exception NullPointerException if <code>locale</code> is null
*/
public static BreakIterator getWordInstance(Locale locale)
{
return getBreakInstance(locale,
WORD_INDEX,
"WordData",
"WordDictionary");
}
/**
* Returns a new <code>BreakIterator</code> instance
* for <a href="#line">line breaks</a>
* for the {@linkplain Locale#getDefault() default locale}.
* @return A break iterator for line breaks
*/
public static BreakIterator getLineInstance()
{
return getLineInstance(Locale.getDefault());
}
/**
* Returns a new <code>BreakIterator</code> instance
* for <a href="#line">line breaks</a>
* for the given locale.
* @param locale the desired locale
* @return A break iterator for line breaks
* @exception NullPointerException if <code>locale</code> is null
*/
public static BreakIterator getLineInstance(Locale locale)
{
return getBreakInstance(locale,
LINE_INDEX,
"LineData",
"LineDictionary");
}
/**
* Returns a new <code>BreakIterator</code> instance
* for <a href="#character">character breaks</a>
* for the {@linkplain Locale#getDefault() default locale}.
* @return A break iterator for character breaks
*/
public static BreakIterator getCharacterInstance()
{
return getCharacterInstance(Locale.getDefault());
}
/**
* Returns a new <code>BreakIterator</code> instance
* for <a href="#character">character breaks</a>
* for the given locale.
* @param locale the desired locale
* @return A break iterator for character breaks
* @exception NullPointerException if <code>locale</code> is null
*/
public static BreakIterator getCharacterInstance(Locale locale)
{
return getBreakInstance(locale,
CHARACTER_INDEX,
"CharacterData",
"CharacterDictionary");
}
/**
* Returns a new <code>BreakIterator</code> instance
* for <a href="#sentence">sentence breaks</a>
* for the {@linkplain Locale#getDefault() default locale}.
* @return A break iterator for sentence breaks
*/
public static BreakIterator getSentenceInstance()
{
return getSentenceInstance(Locale.getDefault());
}
/**
* Returns a new <code>BreakIterator</code> instance
* for <a href="#sentence">sentence breaks</a>
* for the given locale.
* @param locale the desired locale
* @return A break iterator for sentence breaks
* @exception NullPointerException if <code>locale</code> is null
*/
public static BreakIterator getSentenceInstance(Locale locale)
{
return getBreakInstance(locale,
SENTENCE_INDEX,
"SentenceData",
"SentenceDictionary");
}
private static BreakIterator getBreakInstance(Locale locale,
int type,
String dataName,
String dictionaryName) {
if (iterCache[type] != null) {
BreakIteratorCache cache = (BreakIteratorCache) iterCache[type].get();
if (cache != null) {
if (cache.getLocale().equals(locale)) {
return cache.createBreakInstance();
}
}
}
BreakIterator result = createBreakInstance(locale,
type,
dataName,
dictionaryName);
BreakIteratorCache cache = new BreakIteratorCache(locale, result);
iterCache[type] = new SoftReference(cache);
return result;
}
private static ResourceBundle getBundle(final String baseName, final Locale locale) {
return (ResourceBundle) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return ResourceBundle.getBundle(baseName, locale);
}
});
}
private static BreakIterator createBreakInstance(Locale locale,
int type,
String dataName,
String dictionaryName) {
// Check whether a provider can provide an implementation that's closer
// to the requested locale than what the Java runtime itself can provide.
LocaleServiceProviderPool pool =
LocaleServiceProviderPool.getPool(BreakIteratorProvider.class);
if (pool.hasProviders()) {
BreakIterator providersInstance = pool.getLocalizedObject(
BreakIteratorGetter.INSTANCE,
locale, type);
if (providersInstance != null) {
return providersInstance;
}
}
ResourceBundle bundle = getBundle(
"sun.text.resources.BreakIteratorInfo", locale);
String[] classNames = bundle.getStringArray("BreakIteratorClasses");
String dataFile = bundle.getString(dataName);
try {
if (classNames[type].equals("RuleBasedBreakIterator")) {
return new RuleBasedBreakIterator(dataFile);
}
else if (classNames[type].equals("DictionaryBasedBreakIterator")) {
String dictionaryFile = bundle.getString(dictionaryName);
return new DictionaryBasedBreakIterator(dataFile, dictionaryFile);
}
else {
throw new IllegalArgumentException("Invalid break iterator class \"" +
classNames[type] + "\"");
}
}
catch (Exception e) {
throw new InternalError(e.toString());
}
}
/**
* Returns an array of all locales for which the
* <code>get*Instance</code> methods of this class can return
* localized instances.
* The returned array represents the union of locales supported by the Java
* runtime and by installed
* {@link java.text.spi.BreakIteratorProvider BreakIteratorProvider} implementations.
* It must contain at least a <code>Locale</code>
* instance equal to {@link java.util.Locale#US Locale.US}.
*
* @return An array of locales for which localized
* <code>BreakIterator</code> instances are available.
*/
public static synchronized Locale[] getAvailableLocales()
{
LocaleServiceProviderPool pool =
LocaleServiceProviderPool.getPool(BreakIteratorProvider.class);
return pool.getAvailableLocales();
}
private static final class BreakIteratorCache {
private BreakIterator iter;
private Locale locale;
BreakIteratorCache(Locale locale, BreakIterator iter) {
this.locale = locale;
this.iter = (BreakIterator) iter.clone();
}
Locale getLocale() {
return locale;
}
BreakIterator createBreakInstance() {
return (BreakIterator) iter.clone();
}
}
static long getLong(byte[] buf, int offset) {
long num = buf[offset]&0xFF;
for (int i = 1; i < 8; i++) {
num = num<<8 | (buf[offset+i]&0xFF);
}
return num;
}
static int getInt(byte[] buf, int offset) {
int num = buf[offset]&0xFF;
for (int i = 1; i < 4; i++) {
num = num<<8 | (buf[offset+i]&0xFF);
}
return num;
}
static short getShort(byte[] buf, int offset) {
short num = (short)(buf[offset]&0xFF);
num = (short)(num<<8 | (buf[offset+1]&0xFF));
return num;
}
/**
* Obtains a BreakIterator instance from a BreakIteratorProvider
* implementation.
*/
private static class BreakIteratorGetter
implements LocaleServiceProviderPool.LocalizedObjectGetter<BreakIteratorProvider, BreakIterator> {
private static final BreakIteratorGetter INSTANCE =
new BreakIteratorGetter();
public BreakIterator getObject(BreakIteratorProvider breakIteratorProvider,
Locale locale,
String key,
Object... params) {
assert params.length == 1;
switch ((Integer)params[0]) {
case CHARACTER_INDEX:
return breakIteratorProvider.getCharacterInstance(locale);
case WORD_INDEX:
return breakIteratorProvider.getWordInstance(locale);
case LINE_INDEX:
return breakIteratorProvider.getLineInstance(locale);
case SENTENCE_INDEX:
return breakIteratorProvider.getSentenceInstance(locale);
default:
assert false : "should not happen";
}
return null;
}
}
}
| 27,597 | Java | .java | 660 | 34.898485 | 106 | 0.659551 | srisatish/openjdk | 14 | 22 | 0 | GPL-2.0 | 9/4/2024, 8:10:41 PM (Europe/Amsterdam) | true | true | true | true | true | true | true | true | 27,597 |
4,204,241 | AlipayTradeCustomsQueryModel.java | zeatul_poc/e-commerce/e-commerce-ecom-pay-service/src/main/java/com/alipay/api/domain/AlipayTradeCustomsQueryModel.java | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 查询报关详细信息
*
* @author auto create
* @since 1.0, 2016-11-09 19:11:58
*/
public class AlipayTradeCustomsQueryModel extends AlipayObject {
private static final long serialVersionUID = 1566741575329731388L;
/**
* 报关请求号。需要查询的商户端报关请求号,支持批量查询,
多个值用英文半角逗号分隔,单次请求最多10个;
*/
@ApiField("out_request_nos")
private String outRequestNos;
public String getOutRequestNos() {
return this.outRequestNos;
}
public void setOutRequestNos(String outRequestNos) {
this.outRequestNos = outRequestNos;
}
}
| 738 | Java | .java | 24 | 24.041667 | 67 | 0.794314 | zeatul/poc | 2 | 3 | 0 | GPL-3.0 | 9/5/2024, 12:05:46 AM (Europe/Amsterdam) | false | true | true | true | false | true | true | true | 628 |
4,286,169 | serviceui_sv.java | techsaint_ikvm_openjdk/build/linux-x86_64-normal-server-release/jdk/gensrc/sun/print/resources/serviceui_sv.java | package sun.print.resources;
import java.util.ListResourceBundle;
public final class serviceui_sv extends ListResourceBundle {
protected final Object[][] getContents() {
return new Object[][] {
{ "Automatic-Feeder", "Automatisk matning" },
{ "Cassette", "Kassett" },
{ "Form-Source", "Formul\u00E4rk\u00E4lla" },
{ "Large-Format", "Stort format" },
{ "Manual-Envelope", "Manuell kuvertmatning" },
{ "Small-Format", "Litet format" },
{ "Tractor-Feeder", "Traktormatning" },
{ "a", "Engineering A" },
{ "accepting-jobs", "Accepterar jobb" },
{ "auto-select", "V\u00E4lj automatiskt" },
{ "b", "Engineering B" },
{ "border.chromaticity", "F\u00E4rg" },
{ "border.copies", "Antal exemplar" },
{ "border.jobattributes", "Utskriftsattribut" },
{ "border.margins", "Marginaler" },
{ "border.media", "Media" },
{ "border.orientation", "Orientering" },
{ "border.printrange", "Utskriftsintervall" },
{ "border.printservice", "Utskriftstj\u00E4nst" },
{ "border.quality", "Kvalitet" },
{ "border.sides", "Sidor" },
{ "bottom", "Botten" },
{ "button.cancel", "Avbryt" },
{ "button.ok", "OK" },
{ "button.print", "Skriv ut" },
{ "button.properties", "&Egenskaper..." },
{ "c", "Engineering C" },
{ "checkbox.collate", "&Sortera" },
{ "checkbox.jobsheets", "F&\u00F6rs\u00E4ttsblad" },
{ "checkbox.printtofile", "Skriv ut till &fil" },
{ "d", "Engineering D" },
{ "dialog.noprintermsg", "Hittade ingen utskriftstj\u00E4nst." },
{ "dialog.overwrite", "Denna fil finns redan. Vill du skriva \u00F6ver den befintliga filen?" },
{ "dialog.owtitle", "Skriv till fil" },
{ "dialog.printtitle", "Skriv ut" },
{ "dialog.printtofile", "Skriv till fil" },
{ "dialog.pstitle", "Utskriftsformat" },
{ "dialog.writeerror", "Kan inte skriva till filen:" },
{ "e", "Engineering E" },
{ "envelope", "Kuvert" },
{ "error.destination", "Ogiltigt filnamn. F\u00F6rs\u00F6k igen." },
{ "error.pagerange", "Ogiltigt sidintervall. Skriv in v\u00E4rdena igen (t ex 1-3,5,7-10)" },
{ "executive", "Executive" },
{ "folio", "Folio" },
{ "invite-envelope", "Invitation-kuvert" },
{ "invoice", "Invoice" },
{ "iso-2a0", "2A0 (ISO/DIN & JIS)" },
{ "iso-4a0", "4A0 (ISO/DIN & JIS)" },
{ "iso-a0", "A0 (ISO/DIN & JIS)" },
{ "iso-a1", "A1 (ISO/DIN & JIS)" },
{ "iso-a10", "A10 (ISO/DIN & JIS)" },
{ "iso-a2", "A2 (ISO/DIN & JIS)" },
{ "iso-a3", "A3 (ISO/DIN & JIS)" },
{ "iso-a4", "A4 (ISO/DIN & JIS)" },
{ "iso-a5", "A5 (ISO/DIN & JIS)" },
{ "iso-a6", "A6 (ISO/DIN & JIS)" },
{ "iso-a7", "A7 (ISO/DIN & JIS)" },
{ "iso-a8", "A8 (ISO/DIN & JIS)" },
{ "iso-a9", "A9 (ISO/DIN & JIS)" },
{ "iso-b0", "B0 (ISO/DIN)" },
{ "iso-b1", "B1 (ISO/DIN)" },
{ "iso-b10", "B10 (ISO/DIN)" },
{ "iso-b2", "B2 (ISO/DIN)" },
{ "iso-b3", "B3 (ISO/DIN)" },
{ "iso-b4", "B4 (ISO/DIN)" },
{ "iso-b5", "B5 (ISO/DIN)" },
{ "iso-b6", "B6 (ISO/DIN)" },
{ "iso-b7", "B7 (ISO/DIN)" },
{ "iso-b8", "B8 (ISO/DIN)" },
{ "iso-b9", "B9 (ISO/DIN)" },
{ "iso-c0", "C0 (ISO/DIN)" },
{ "iso-c1", "C1 (ISO/DIN)" },
{ "iso-c10", "C10 (ISO/DIN)" },
{ "iso-c2", "C2 (ISO/DIN)" },
{ "iso-c3", "C3 (ISO/DIN)" },
{ "iso-c4", "C4 (ISO/DIN)" },
{ "iso-c5", "C5 (ISO/DIN)" },
{ "iso-c6", "C6 (ISO/DIN)" },
{ "iso-c7", "C7 (ISO/DIN)" },
{ "iso-c8", "C8 (ISO/DIN)" },
{ "iso-c9", "C9 (ISO/DIN)" },
{ "iso-designated-long", "ISO Designated Long" },
{ "italian-envelope", "Italienskt kuvert" },
{ "italy-envelope", "Italienskt kuvert" },
{ "japanese-postcard", "Postcard (JIS)" },
{ "jis-b0", "B0 (JIS)" },
{ "jis-b1", "B1 (JIS)" },
{ "jis-b10", "B10 (JIS)" },
{ "jis-b2", "B2 (JIS)" },
{ "jis-b3", "B3 (JIS)" },
{ "jis-b4", "B4 (JIS)" },
{ "jis-b5", "B5 (JIS)" },
{ "jis-b6", "B6 (JIS)" },
{ "jis-b7", "B7 (JIS)" },
{ "jis-b8", "B8 (JIS)" },
{ "jis-b9", "B9 (JIS)" },
{ "label.bottommargin", "&nederkant" },
{ "label.inches", "(tum)" },
{ "label.info", "Information:" },
{ "label.jobname", "&Utskrift:" },
{ "label.leftmargin", "v&\u00E4nster" },
{ "label.millimetres", "(mm)" },
{ "label.numcopies", "Antal e&xemplar:" },
{ "label.priority", "P&rioritet:" },
{ "label.psname", "&Namn:" },
{ "label.pstype", "Typ:" },
{ "label.rangeto", "Till" },
{ "label.rightmargin", "&h\u00F6ger" },
{ "label.size", "Stor&lek:" },
{ "label.source", "&K\u00E4lla:" },
{ "label.status", "Status:" },
{ "label.topmargin", "&\u00F6verkant" },
{ "label.username", "A&nv\u00E4ndarnamn:" },
{ "large-capacity", "H\u00F6g kapacitet" },
{ "ledger", "Ledger" },
{ "main", "Huvud" },
{ "manual", "Manuell" },
{ "middle", "Mitten" },
{ "monarch-envelope", "Monarch-kuvert" },
{ "na-10x13-envelope", "10x15-kuvert" },
{ "na-10x14-envelope", "10x15-kuvert" },
{ "na-10x15-envelope", "10x15-kuvert" },
{ "na-5x7", "5x7-tumspapper" },
{ "na-6x9-envelope", "6x9-kuvert" },
{ "na-7x9-envelope", "6x7-kuvert" },
{ "na-8x10", "8x10-tumspapper" },
{ "na-9x11-envelope", "9x11-kuvert" },
{ "na-9x12-envelope", "9x12-kuvert" },
{ "na-legal", "Legal" },
{ "na-letter", "Letter" },
{ "na-number-10-envelope", "No. 10-kuvert" },
{ "na-number-11-envelope", "No. 11-kuvert" },
{ "na-number-12-envelope", "No. 12-kuvert" },
{ "na-number-14-envelope", "No. 14-kuvert" },
{ "na-number-9-envelope", "No. 9-kuvert" },
{ "not-accepting-jobs", "Accepterar inte jobb" },
{ "oufuko-postcard", "Double Postcard (JIS)" },
{ "personal-envelope", "Egen kuvertstorlek" },
{ "quarto", "Quarto" },
{ "radiobutton.color", "&F\u00E4rg" },
{ "radiobutton.draftq", "Utka&st" },
{ "radiobutton.duplex", "&Dubbelsidig" },
{ "radiobutton.highq", "&H\u00F6g" },
{ "radiobutton.landscape", "Liggan&de" },
{ "radiobutton.monochrome", "&Monokrom" },
{ "radiobutton.normalq", "&Normal" },
{ "radiobutton.oneside", "&Ensidig" },
{ "radiobutton.portrait", "&St\u00E5ende" },
{ "radiobutton.rangeall", "A&lla" },
{ "radiobutton.rangepages", "Sid&or" },
{ "radiobutton.revlandscape", "Omv\u00E4nt li&ggande" },
{ "radiobutton.revportrait", "Omv\u00E4nt st\u00E5en&de" },
{ "radiobutton.tumble", "&V\u00E4nd" },
{ "side", "Sida" },
{ "tab.appearance", "Fo&rmat" },
{ "tab.general", "&Allm\u00E4nt" },
{ "tab.pagesetup", "&Utskriftsformat" },
{ "tabloid", "Tabloid" },
{ "top", "Topp" },
};
}
}
| 7,961 | Java | .java | 167 | 35.08982 | 109 | 0.451745 | techsaint/ikvm_openjdk | 2 | 1 | 0 | GPL-2.0 | 9/5/2024, 12:07:57 AM (Europe/Amsterdam) | false | false | false | false | true | false | true | true | 7,961 |
1,744,724 | SimpleWebServer.java | flyver_Flyver-Apps/AirQualityMonitorApp/nanohttpd/src/main/java/fi/iki/elonen/SimpleWebServer.java | package fi.iki.elonen;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.StringTokenizer;
public class SimpleWebServer extends NanoHTTPD {
/**
* Common mime type for dynamic content: binary
*/
public static final String MIME_DEFAULT_BINARY = "application/octet-stream";
/**
* Default Index file names.
*/
public static final List<String> INDEX_FILE_NAMES = new ArrayList<String>() {{
add("index.html");
add("index.htm");
}};
/**
* Hashtable mapping (String)FILENAME_EXTENSION -> (String)MIME_TYPE
*/
private static final Map<String, String> MIME_TYPES = new HashMap<String, String>() {{
put("css", "text/css");
put("htm", "text/html");
put("html", "text/html");
put("xml", "text/xml");
put("java", "text/x-java-source, text/java");
put("md", "text/plain");
put("txt", "text/plain");
put("asc", "text/plain");
put("gif", "image/gif");
put("jpg", "image/jpeg");
put("jpeg", "image/jpeg");
put("png", "image/png");
put("mp3", "audio/mpeg");
put("m3u", "audio/mpeg-url");
put("mp4", "video/mp4");
put("ogv", "video/ogg");
put("flv", "video/x-flv");
put("mov", "video/quicktime");
put("swf", "application/x-shockwave-flash");
put("js", "application/javascript");
put("pdf", "application/pdf");
put("doc", "application/msword");
put("ogg", "application/x-ogg");
put("zip", "application/octet-stream");
put("exe", "application/octet-stream");
put("class", "application/octet-stream");
}};
/**
* The distribution licence
*/
private static final String LICENCE =
"Copyright (c) 2012-2013 by Paul S. Hawke, 2001,2005-2013 by Jarno Elonen, 2010 by Konstantinos Togias\n"
+ "\n"
+ "Redistribution and use in source and binary forms, with or without\n"
+ "modification, are permitted provided that the following conditions\n"
+ "are met:\n"
+ "\n"
+ "Redistributions of source code must retain the above copyright notice,\n"
+ "this list of conditions and the following disclaimer. Redistributions in\n"
+ "binary form must reproduce the above copyright notice, this list of\n"
+ "conditions and the following disclaimer in the documentation and/or other\n"
+ "materials provided with the distribution. The name of the author may not\n"
+ "be used to endorse or promote products derived from this software without\n"
+ "specific prior written permission. \n"
+ " \n"
+ "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
+ "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
+ "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
+ "IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
+ "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n"
+ "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n"
+ "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n"
+ "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
+ "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n"
+ "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.";
private static Map<String, WebServerPlugin> mimeTypeHandlers = new HashMap<String, WebServerPlugin>();
private final List<File> rootDirs;
private final boolean quiet;
public SimpleWebServer(String host, int port, File wwwroot, boolean quiet) {
super(host, port);
this.quiet = quiet;
this.rootDirs = new ArrayList<File>();
this.rootDirs.add(wwwroot);
this.init();
}
public SimpleWebServer(String host, int port, List<File> wwwroots, boolean quiet) {
super(host, port);
this.quiet = quiet;
this.rootDirs = new ArrayList<File>(wwwroots);
this.init();
}
/**
* Used to initialize and customize the server.
*/
public void init() {
}
/**
* Starts as a standalone file server and waits for Enter.
*/
public static void main(String[] args) {
// Defaults
int port = 8080;
String host = "127.0.0.1";
List<File> rootDirs = new ArrayList<File>();
boolean quiet = false;
Map<String, String> options = new HashMap<String, String>();
// Parse command-line, with short and long versions of the options.
for (int i = 0; i < args.length; ++i) {
if (args[i].equalsIgnoreCase("-h") || args[i].equalsIgnoreCase("--host")) {
host = args[i + 1];
} else if (args[i].equalsIgnoreCase("-p") || args[i].equalsIgnoreCase("--port")) {
port = Integer.parseInt(args[i + 1]);
} else if (args[i].equalsIgnoreCase("-q") || args[i].equalsIgnoreCase("--quiet")) {
quiet = true;
} else if (args[i].equalsIgnoreCase("-d") || args[i].equalsIgnoreCase("--dir")) {
rootDirs.add(new File(args[i + 1]).getAbsoluteFile());
} else if (args[i].equalsIgnoreCase("--licence")) {
System.out.println(LICENCE + "\n");
} else if (args[i].startsWith("-X:")) {
int dot = args[i].indexOf('=');
if (dot > 0) {
String name = args[i].substring(0, dot);
String value = args[i].substring(dot + 1, args[i].length());
options.put(name, value);
}
}
}
if (rootDirs.isEmpty()) {
rootDirs.add(new File(".").getAbsoluteFile());
}
options.put("host", host);
options.put("port", ""+port);
options.put("quiet", String.valueOf(quiet));
StringBuilder sb = new StringBuilder();
for (File dir : rootDirs) {
if (sb.length() > 0) {
sb.append(":");
}
try {
sb.append(dir.getCanonicalPath());
} catch (IOException ignored) {}
}
options.put("home", sb.toString());
ServiceLoader<WebServerPluginInfo> serviceLoader = ServiceLoader.load(WebServerPluginInfo.class);
for (WebServerPluginInfo info : serviceLoader) {
String[] mimeTypes = info.getMimeTypes();
for (String mime : mimeTypes) {
String[] indexFiles = info.getIndexFilesForMimeType(mime);
if (!quiet) {
System.out.print("# Found plugin for Mime type: \"" + mime + "\"");
if (indexFiles != null) {
System.out.print(" (serving index files: ");
for (String indexFile : indexFiles) {
System.out.print(indexFile + " ");
}
}
System.out.println(").");
}
registerPluginForMimeType(indexFiles, mime, info.getWebServerPlugin(mime), options);
}
}
ServerRunner.executeInstance(new SimpleWebServer(host, port, rootDirs, quiet));
}
protected static void registerPluginForMimeType(String[] indexFiles, String mimeType, WebServerPlugin plugin, Map<String, String> commandLineOptions) {
if (mimeType == null || plugin == null) {
return;
}
if (indexFiles != null) {
for (String filename : indexFiles) {
int dot = filename.lastIndexOf('.');
if (dot >= 0) {
String extension = filename.substring(dot + 1).toLowerCase();
MIME_TYPES.put(extension, mimeType);
}
}
INDEX_FILE_NAMES.addAll(Arrays.asList(indexFiles));
}
mimeTypeHandlers.put(mimeType, plugin);
plugin.initialize(commandLineOptions);
}
private File getRootDir() {
return rootDirs.get(0);
}
private List<File> getRootDirs() {
return rootDirs;
}
private void addWwwRootDir(File wwwroot) {
rootDirs.add(wwwroot);
}
/**
* URL-encodes everything between "/"-characters. Encodes spaces as '%20' instead of '+'.
*/
private String encodeUri(String uri) {
String newUri = "";
StringTokenizer st = new StringTokenizer(uri, "/ ", true);
while (st.hasMoreTokens()) {
String tok = st.nextToken();
if (tok.equals("/"))
newUri += "/";
else if (tok.equals(" "))
newUri += "%20";
else {
try {
newUri += URLEncoder.encode(tok, "UTF-8");
} catch (UnsupportedEncodingException ignored) {
}
}
}
return newUri;
}
public Response serve(IHTTPSession session) {
Map<String, String> header = session.getHeaders();
Map<String, String> parms = session.getParms();
String uri = session.getUri();
if (!quiet) {
System.out.println(session.getMethod() + " '" + uri + "' ");
Iterator<String> e = header.keySet().iterator();
while (e.hasNext()) {
String value = e.next();
System.out.println(" HDR: '" + value + "' = '" + header.get(value) + "'");
}
e = parms.keySet().iterator();
while (e.hasNext()) {
String value = e.next();
System.out.println(" PRM: '" + value + "' = '" + parms.get(value) + "'");
}
}
for (File homeDir : getRootDirs()) {
// Make sure we won't die of an exception later
if (!homeDir.isDirectory()) {
return getInternalErrorResponse("given path is not a directory (" + homeDir + ").");
}
}
return respond(Collections.unmodifiableMap(header), session, uri);
}
private Response respond(Map<String, String> headers, IHTTPSession session, String uri) {
// Remove URL arguments
uri = uri.trim().replace(File.separatorChar, '/');
if (uri.indexOf('?') >= 0) {
uri = uri.substring(0, uri.indexOf('?'));
}
// Prohibit getting out of current directory
if (uri.startsWith("src/main") || uri.endsWith("src/main") || uri.contains("../")) {
return getForbiddenResponse("Won't serve ../ for security reasons.");
}
boolean canServeUri = false;
File homeDir = null;
List<File> roots = getRootDirs();
for (int i = 0; !canServeUri && i < roots.size(); i++) {
homeDir = roots.get(i);
canServeUri = canServeUri(uri, homeDir);
}
if (!canServeUri) {
return getNotFoundResponse();
}
// Browsers get confused without '/' after the directory, send a redirect.
File f = new File(homeDir, uri);
if (f.isDirectory() && !uri.endsWith("/")) {
uri += "/";
Response res = createResponse(Response.Status.REDIRECT, NanoHTTPD.MIME_HTML, "<html><body>Redirected: <a href=\"" +
uri + "\">" + uri + "</a></body></html>");
res.addHeader("Location", uri);
return res;
}
if (f.isDirectory()) {
// First look for index files (index.html, index.htm, etc) and if none found, list the directory if readable.
String indexFile = findIndexFileInDirectory(f);
if (indexFile == null) {
if (f.canRead()) {
// No index file, list the directory if it is readable
return createResponse(Response.Status.OK, NanoHTTPD.MIME_HTML, listDirectory(uri, f));
} else {
return getForbiddenResponse("No directory listing.");
}
} else {
return respond(headers, session, uri + indexFile);
}
}
String mimeTypeForFile = getMimeTypeForFile(uri);
WebServerPlugin plugin = mimeTypeHandlers.get(mimeTypeForFile);
Response response = null;
if (plugin != null) {
response = plugin.serveFile(uri, headers, session, f, mimeTypeForFile);
if (response != null && response instanceof InternalRewrite) {
InternalRewrite rewrite = (InternalRewrite) response;
return respond(rewrite.getHeaders(), session, rewrite.getUri());
}
} else {
response = serveFile(uri, headers, f, mimeTypeForFile);
}
return response != null ? response : getNotFoundResponse();
}
protected Response getNotFoundResponse() {
return createResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT,
"Error 404, file not found.");
}
protected Response getForbiddenResponse(String s) {
return createResponse(Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT, "FORBIDDEN: "
+ s);
}
protected Response getInternalErrorResponse(String s) {
return createResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT,
"INTERNAL ERRROR: " + s);
}
private boolean canServeUri(String uri, File homeDir) {
boolean canServeUri;
File f = new File(homeDir, uri);
canServeUri = f.exists();
if (!canServeUri) {
String mimeTypeForFile = getMimeTypeForFile(uri);
WebServerPlugin plugin = mimeTypeHandlers.get(mimeTypeForFile);
if (plugin != null) {
canServeUri = plugin.canServeUri(uri, homeDir);
}
}
return canServeUri;
}
/**
* Serves file from homeDir and its' subdirectories (only). Uses only URI, ignores all headers and HTTP parameters.
*/
Response serveFile(String uri, Map<String, String> header, File file, String mime) {
Response res;
try {
// Calculate etag
String etag = Integer.toHexString((file.getAbsolutePath() + file.lastModified() + "" + file.length()).hashCode());
// Support (simple) skipping:
long startFrom = 0;
long endAt = -1;
String range = header.get("range");
if (range != null) {
if (range.startsWith("bytes=")) {
range = range.substring("bytes=".length());
int minus = range.indexOf('-');
try {
if (minus > 0) {
startFrom = Long.parseLong(range.substring(0, minus));
endAt = Long.parseLong(range.substring(minus + 1));
}
} catch (NumberFormatException ignored) {
}
}
}
// Change return code and add Content-Range header when skipping is requested
long fileLen = file.length();
if (range != null && startFrom >= 0) {
if (startFrom >= fileLen) {
res = createResponse(Response.Status.RANGE_NOT_SATISFIABLE, NanoHTTPD.MIME_PLAINTEXT, "");
res.addHeader("Content-Range", "bytes 0-0/" + fileLen);
res.addHeader("ETag", etag);
} else {
if (endAt < 0) {
endAt = fileLen - 1;
}
long newLen = endAt - startFrom + 1;
if (newLen < 0) {
newLen = 0;
}
final long dataLen = newLen;
FileInputStream fis = new FileInputStream(file) {
@Override
public int available() throws IOException {
return (int) dataLen;
}
};
fis.skip(startFrom);
res = createResponse(Response.Status.PARTIAL_CONTENT, mime, fis);
res.addHeader("Content-Length", "" + dataLen);
res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
res.addHeader("ETag", etag);
}
} else {
if (etag.equals(header.get("if-none-match")))
res = createResponse(Response.Status.NOT_MODIFIED, mime, "");
else {
res = createResponse(Response.Status.OK, mime, new FileInputStream(file));
res.addHeader("Content-Length", "" + fileLen);
res.addHeader("ETag", etag);
}
}
} catch (IOException ioe) {
res = getForbiddenResponse("Reading file failed.");
}
return res;
}
// Get MIME type from file name extension, if possible
private String getMimeTypeForFile(String uri) {
int dot = uri.lastIndexOf('.');
String mime = null;
if (dot >= 0) {
mime = MIME_TYPES.get(uri.substring(dot + 1).toLowerCase());
}
return mime == null ? MIME_DEFAULT_BINARY : mime;
}
// Announce that the file server accepts partial content requests
private Response createResponse(Response.Status status, String mimeType, InputStream message) {
Response res = new Response(status, mimeType, message);
res.addHeader("Accept-Ranges", "bytes");
return res;
}
// Announce that the file server accepts partial content requests
private Response createResponse(Response.Status status, String mimeType, String message) {
Response res = new Response(status, mimeType, message);
res.addHeader("Accept-Ranges", "bytes");
return res;
}
private String findIndexFileInDirectory(File directory) {
for (String fileName : INDEX_FILE_NAMES) {
File indexFile = new File(directory, fileName);
if (indexFile.exists()) {
return fileName;
}
}
return null;
}
protected String listDirectory(String uri, File f) {
String heading = "Directory " + uri;
StringBuilder msg = new StringBuilder("<html><head><title>" + heading + "</title><style><!--\n" +
"span.dirname { font-weight: bold; }\n" +
"span.filesize { font-size: 75%; }\n" +
"// -->\n" +
"</style>" +
"</head><body><h1>" + heading + "</h1>");
String up = null;
if (uri.length() > 1) {
String u = uri.substring(0, uri.length() - 1);
int slash = u.lastIndexOf('/');
if (slash >= 0 && slash < u.length()) {
up = uri.substring(0, slash + 1);
}
}
List<String> files = Arrays.asList(f.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return new File(dir, name).isFile();
}
}));
Collections.sort(files);
List<String> directories = Arrays.asList(f.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return new File(dir, name).isDirectory();
}
}));
Collections.sort(directories);
if (up != null || directories.size() + files.size() > 0) {
msg.append("<ul>");
if (up != null || directories.size() > 0) {
msg.append("<section class=\"directories\">");
if (up != null) {
msg.append("<li><a rel=\"directory\" href=\"").append(up).append("\"><span class=\"dirname\">..</span></a></b></li>");
}
for (String directory : directories) {
String dir = directory + "/";
msg.append("<li><a rel=\"directory\" href=\"").append(encodeUri(uri + dir)).append("\"><span class=\"dirname\">").append(dir).append("</span></a></b></li>");
}
msg.append("</section>");
}
if (files.size() > 0) {
msg.append("<section class=\"files\">");
for (String file : files) {
msg.append("<li><a href=\"").append(encodeUri(uri + file)).append("\"><span class=\"filename\">").append(file).append("</span></a>");
File curFile = new File(f, file);
long len = curFile.length();
msg.append(" <span class=\"filesize\">(");
if (len < 1024) {
msg.append(len).append(" bytes");
} else if (len < 1024 * 1024) {
msg.append(len / 1024).append(".").append(len % 1024 / 10 % 100).append(" KB");
} else {
msg.append(len / (1024 * 1024)).append(".").append(len % (1024 * 1024) / 10 % 100).append(" MB");
}
msg.append(")</span></li>");
}
msg.append("</section>");
}
msg.append("</ul>");
}
msg.append("</body></html>");
return msg.toString();
}
}
| 22,002 | Java | .java | 494 | 32.668016 | 177 | 0.543684 | flyver/Flyver-Apps | 12 | 8 | 1 | LGPL-3.0 | 9/4/2024, 8:17:04 PM (Europe/Amsterdam) | false | true | true | true | true | true | true | true | 22,002 |
501,839 | FacilityIndicatorImpl.java | RestComm_jss7/isup/isup-impl/src/main/java/org/restcomm/protocols/ss7/isup/impl/message/parameter/FacilityIndicatorImpl.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2012, Telestax Inc and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
/**
* Start time:11:50:01 2009-03-31<br>
* Project: mobicents-isup-stack<br>
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski
* </a>
*
*/
package org.restcomm.protocols.ss7.isup.impl.message.parameter;
import org.restcomm.protocols.ss7.isup.ParameterException;
import org.restcomm.protocols.ss7.isup.message.parameter.FacilityIndicator;
/**
* Start time:11:50:01 2009-03-31<br>
* Project: mobicents-isup-stack<br>
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class FacilityIndicatorImpl extends AbstractISUPParameter implements FacilityIndicator {
private byte facilityIndicator = 0;
public FacilityIndicatorImpl(byte[] b) throws ParameterException {
super();
decode(b);
}
public FacilityIndicatorImpl() {
super();
}
public FacilityIndicatorImpl(byte facilityIndicator) {
super();
this.facilityIndicator = facilityIndicator;
}
public int decode(byte[] b) throws ParameterException {
if (b == null || b.length != 1) {
throw new ParameterException("byte[] must not be null or have different size than 1");
}
this.facilityIndicator = b[0];
return 1;
}
public byte[] encode() throws ParameterException {
byte[] b = { (byte) this.facilityIndicator };
return b;
}
public byte getFacilityIndicator() {
return facilityIndicator;
}
public void setFacilityIndicator(byte facilityIndicator) {
this.facilityIndicator = facilityIndicator;
}
public int getCode() {
return _PARAMETER_CODE;
}
}
| 2,668 | Java | .java | 72 | 32.736111 | 98 | 0.716776 | RestComm/jss7 | 178 | 218 | 47 | AGPL-3.0 | 9/4/2024, 7:07:37 PM (Europe/Amsterdam) | false | false | true | false | false | true | false | true | 2,668 |
3,020,770 | FileChooser.java | Ed-Fernando_lg3d-incubator/src/classes/org/jdesktop/lg3d/apps/presentoire/FileChooser.java | /*
* NewJFrame.java
*
* Created on 19 août 2006, 19:13
*/
package org.jdesktop.lg3d.apps.presentoire;
import java.io.File;
/**
* Undocumented HACK.
* MUST DISAPPEAR AS SOON AS POSSIBLE !
* @author debian
*/
public class FileChooser extends javax.swing.JDialog {
private Presentoire presentoire;
/** Creates new form FileChooser */
public FileChooser(Presentoire app) {
presentoire = app;
//setModal(true); // Do you want to see the LG3D AWT Toolkit failing ? Just remove the comment :)
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE);
jLabel1.setText("File name :");
jTextField1.setText("/home/debian/LG3D/Presentoire/doc.zip");
jButton1.setText("Ok");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE)
.addComponent(jLabel1)
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
presentoire.openDocument(new File(jTextField1.getText()));
//setEnabled(false);
setVisible(false);
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
| 3,366 | Java | .java | 75 | 36 | 160 | 0.678868 | Ed-Fernando/lg3d-incubator | 5 | 3 | 0 | GPL-2.0 | 9/4/2024, 10:42:59 PM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 3,366 |
1,312,902 | TypeHierarchyContentProvider.java | eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyContentProvider.java | /*******************************************************************************
* Copyright (c) 2000, 2014 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.internal.ui.typehierarchy;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.MethodOverrideTester;
import org.eclipse.jdt.ui.IWorkingCopyProvider;
/**
* Base class for content providers for type hierarchy viewers.
* Implementors must override 'getTypesInHierarchy'.
* Java delta processing is also performed by the content provider
*/
public abstract class TypeHierarchyContentProvider implements ITreeContentProvider, IWorkingCopyProvider {
protected static final Object[] NO_ELEMENTS= new Object[0];
protected TypeHierarchyLifeCycle fTypeHierarchy;
protected IMember[] fMemberFilter;
protected TreeViewer fViewer;
private ViewerFilter fWorkingSetFilter;
private MethodOverrideTester fMethodOverrideTester;
private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener;
public TypeHierarchyContentProvider(TypeHierarchyLifeCycle lifecycle) {
fTypeHierarchy= lifecycle;
fMemberFilter= null;
fWorkingSetFilter= null;
fMethodOverrideTester= null;
fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() {
@Override
public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchyProvider, IType[] changedTypes) {
if (changedTypes == null) {
synchronized (this) {
fMethodOverrideTester= null;
}
}
}
};
lifecycle.addChangedListener(fTypeHierarchyLifeCycleListener);
}
/**
* Sets members to filter the hierarchy for. Set to <code>null</code> to disable member filtering.
* When member filtering is enabled, the hierarchy contains only types that contain
* an implementation of one of the filter members and the members themself.
* The hierarchy can be empty as well.
* @param memberFilter the new member filter
*/
public final void setMemberFilter(IMember[] memberFilter) {
fMemberFilter= memberFilter;
}
private boolean initializeMethodOverrideTester(IMethod filterMethod, IType typeToFindIn) {
IType filterType= filterMethod.getDeclaringType();
ITypeHierarchy hierarchy= fTypeHierarchy.getHierarchy();
boolean filterOverrides= JavaModelUtil.isSuperType(hierarchy, typeToFindIn, filterType);
IType focusType= filterOverrides ? filterType : typeToFindIn;
if (fMethodOverrideTester == null || !fMethodOverrideTester.getFocusType().equals(focusType)) {
fMethodOverrideTester= new MethodOverrideTester(focusType, hierarchy);
}
return filterOverrides;
}
private void addCompatibleMethods(IMethod filterMethod, IType typeToFindIn, List<IMember> children) throws JavaModelException {
int flags= filterMethod.getFlags();
if (Flags.isPrivate(flags) || Flags.isStatic(flags) || filterMethod.isConstructor())
return;
synchronized (fTypeHierarchyLifeCycleListener) {
boolean filterMethodOverrides= initializeMethodOverrideTester(filterMethod, typeToFindIn);
for (IMethod m : typeToFindIn.getMethods()) {
flags= m.getFlags();
if (Flags.isPrivate(flags) || Flags.isStatic(flags) || m.isConstructor())
continue;
if (isCompatibleMethod(filterMethod, m, filterMethodOverrides) && !children.contains(m)) {
children.add(m);
}
}
}
}
private boolean hasCompatibleMethod(IMethod filterMethod, IType typeToFindIn) throws JavaModelException {
int flags= filterMethod.getFlags();
if (Flags.isPrivate(flags) || Flags.isStatic(flags) || filterMethod.isConstructor())
return false;
synchronized (fTypeHierarchyLifeCycleListener) {
boolean filterMethodOverrides= initializeMethodOverrideTester(filterMethod, typeToFindIn);
for (IMethod m : typeToFindIn.getMethods()) {
flags= m.getFlags();
if (Flags.isPrivate(flags) || Flags.isStatic(flags) || m.isConstructor())
continue;
if (isCompatibleMethod(filterMethod, m, filterMethodOverrides)) {
return true;
}
}
return false;
}
}
private boolean isCompatibleMethod(IMethod filterMethod, IMethod method, boolean filterOverrides) throws JavaModelException {
if (filterOverrides) {
return fMethodOverrideTester.isSubsignature(filterMethod, method);
} else {
return fMethodOverrideTester.isSubsignature(method, filterMethod);
}
}
/**
* The members to filter or <code>null</code> if member filtering is disabled.
* @return the member filter
*/
public IMember[] getMemberFilter() {
return fMemberFilter;
}
/**
* Sets a filter representing a working set or <code>null</code> if working sets are disabled.
* @param filter the filter
*/
public void setWorkingSetFilter(ViewerFilter filter) {
fWorkingSetFilter= filter;
}
protected final ITypeHierarchy getHierarchy() {
return fTypeHierarchy.getHierarchy();
}
@Override
public boolean providesWorkingCopies() {
return true;
}
/*
* Called for the root element
* @see IStructuredContentProvider#getElements
*/
@Override
public Object[] getElements(Object parent) {
ArrayList<IType> types= new ArrayList<>();
getRootTypes(types);
for (int i= types.size() - 1; i >= 0; i--) {
IType curr= types.get(i);
try {
if (!isInTree(curr)) {
types.remove(i);
}
} catch (JavaModelException e) {
// ignore
}
}
return types.toArray();
}
protected void getRootTypes(List<IType> res) {
ITypeHierarchy hierarchy= getHierarchy();
if (hierarchy != null) {
IType input= hierarchy.getType();
if (input != null) {
res.add(input);
}
// opened on a region: dont show
}
}
/**
* Hook to overwrite. Filter will be applied on the returned types
* @param type the type
* @param res all types in the hierarchy of the given type
*/
protected abstract void getTypesInHierarchy(IType type, List<IType> res);
/**
* Hook to overwrite. Return null if parent is ambiguous.
* @param type the type
* @return the parent type
*/
protected abstract IType getParentType(IType type);
private boolean isInHierarchyOfInputElements(IType type) {
if (fWorkingSetFilter != null && !fWorkingSetFilter.select(null, null, type)) {
return false;
}
IJavaElement[] input= fTypeHierarchy.getInputElements();
if (input == null)
return false;
for (IJavaElement e : input) {
int inputType= e.getElementType();
if (inputType == IJavaElement.TYPE) {
return true;
}
IJavaElement parent= type.getAncestor(inputType);
if (inputType == IJavaElement.PACKAGE_FRAGMENT) {
if (parent == null || parent.getElementName().equals(e.getElementName())) {
return true;
}
} else if (e.equals(parent)) {
return true;
}
}
return false;
}
/*
* Called for the tree children.
* @see ITreeContentProvider#getChildren
*/
@Override
public Object[] getChildren(Object element) {
if (element instanceof IType) {
try {
IType type= (IType)element;
List<IMember> children= new ArrayList<>();
if (fMemberFilter != null) {
addFilteredMemberChildren(type, children);
}
addTypeChildren(type, children);
return children.toArray();
} catch (JavaModelException e) {
// ignore
}
}
return NO_ELEMENTS;
}
/*
* @see ITreeContentProvider#hasChildren
*/
@Override
public boolean hasChildren(Object element) {
if (element instanceof IType) {
try {
IType type= (IType) element;
return hasTypeChildren(type) || (fMemberFilter != null && hasMemberFilterChildren(type));
} catch (JavaModelException e) {
return false;
}
}
return false;
}
private void addFilteredMemberChildren(IType parent, List<IMember> children) throws JavaModelException {
for (IMember member : fMemberFilter) {
if (parent.equals(member.getDeclaringType())) {
if (!children.contains(member)) {
children.add(member);
}
} else if (member instanceof IMethod) {
addCompatibleMethods((IMethod) member, parent, children);
}
}
}
private void addTypeChildren(IType type, List<IMember> children) throws JavaModelException {
ArrayList<IType> types= new ArrayList<>();
getTypesInHierarchy(type, types);
int len= types.size();
for (int i= 0; i < len; i++) {
IType curr= types.get(i);
if (isInTree(curr)) {
children.add(curr);
}
}
}
protected final boolean isInTree(IType type) throws JavaModelException {
if (isInHierarchyOfInputElements(type)) {
if (fMemberFilter != null) {
return hasMemberFilterChildren(type) || hasTypeChildren(type);
} else {
return true;
}
}
return hasTypeChildren(type);
}
private boolean hasMemberFilterChildren(IType type) throws JavaModelException {
for (IMember member : fMemberFilter) {
if (type.equals(member.getDeclaringType())) {
return true;
} else if (member instanceof IMethod) {
if (hasCompatibleMethod((IMethod) member, type)) {
return true;
}
}
}
return false;
}
private boolean hasTypeChildren(IType type) throws JavaModelException {
ArrayList<IType> types= new ArrayList<>();
getTypesInHierarchy(type, types);
int len= types.size();
for (int i= 0; i < len; i++) {
IType curr= types.get(i);
if (isInTree(curr)) {
return true;
}
}
return false;
}
/*
* @see IContentProvider#inputChanged
*/
@Override
public void inputChanged(Viewer part, Object oldInput, Object newInput) {
Assert.isTrue(part instanceof TreeViewer);
fViewer= (TreeViewer)part;
}
/*
* @see IContentProvider#dispose
*/
@Override
public void dispose() {
fTypeHierarchy.removeChangedListener(fTypeHierarchyLifeCycleListener);
}
/*
* @see ITreeContentProvider#getParent
*/
@Override
public Object getParent(Object element) {
if (element instanceof IMember) {
IMember member= (IMember) element;
if (member.getElementType() == IJavaElement.TYPE) {
return getParentType((IType)member);
}
return member.getDeclaringType();
}
return null;
}
protected final boolean isAnonymous(IType type) {
try {
return type.isAnonymous();
} catch (JavaModelException e) {
return false;
}
}
protected final boolean isAnonymousFromInterface(IType type) {
return isAnonymous(type) && fTypeHierarchy.getHierarchy().getSuperInterfaces(type).length != 0;
}
protected final boolean isObject(IType type) {
return "Object".equals(type.getElementName()) && type.getDeclaringType() == null && "java.lang".equals(type.getPackageFragment().getElementName()); //$NON-NLS-1$//$NON-NLS-2$
}
}
| 11,436 | Java | .java | 342 | 30.187135 | 177 | 0.740831 | eclipse-jdt/eclipse.jdt.ui | 35 | 86 | 242 | EPL-2.0 | 9/4/2024, 7:34:16 PM (Europe/Amsterdam) | false | false | false | false | false | true | true | true | 11,436 |
79,186 | HelloServiceStressTest.java | jwpttcg66_NettyGameServer/game-core/src/test/java/com/snowcattle/game/net/client/rpc/stresstest/HelloServiceStressTest.java | package com.snowcattle.game.net.client.rpc.stresstest;
import com.snowcattle.game.TestStartUp;
import com.snowcattle.game.common.enums.BOEnum;
import com.snowcattle.game.common.util.BeanUtil;
import com.snowcattle.game.service.rpc.client.RpcContextHolder;
import com.snowcattle.game.service.rpc.client.RpcContextHolderObject;
import com.snowcattle.game.service.rpc.client.RpcProxyService;
import com.snowcattle.game.service.rpc.service.client.HelloService;
import org.junit.Assert;
/**
* Created by jwp on 2017/3/8.
*/
public class HelloServiceStressTest {
private RpcProxyService rpcProxyService;
public static void main(String[] args) throws Exception {
HelloServiceStressTest helloServiceStressTest = new HelloServiceStressTest();
helloServiceStressTest.init();
helloServiceStressTest.helloTest1();
helloServiceStressTest.setTear();
}
public void init() throws Exception {
TestStartUp.startUpWithSpring();
rpcProxyService = (RpcProxyService) BeanUtil.getBean("rpcProxyService");
}
public void helloTest1() {
int serverId = 9001;
HelloService helloService = rpcProxyService.createProxy(HelloService.class);
// HelloService helloService = rpcProxyService.createRemoteProxy(HelloService.class);
final String result = "Hello! World";
final int test_size = 1_000;
int wrong_size = 0;
int right_size = 0;
long current_time = System.currentTimeMillis();
RpcContextHolderObject rpcContextHolderObject = new RpcContextHolderObject(BOEnum.WORLD, serverId);
RpcContextHolder.setContextHolder(rpcContextHolderObject);
for (int i = 0; i < test_size; i++) {
if(helloService!=null){
String test = helloService.hello("World");
if (test != null && result.equals(test)) {
right_size++;
} else {
wrong_size++;
}
}
}
;
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
System.out.println("------------------------- ------------------------- ");
System.out.println("right_size " + right_size);
System.out.println("wrong_size " + wrong_size);
System.out.println("cost time " + (System.currentTimeMillis() - current_time));
System.out.println("------------------------- ------------------------- ");
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
Assert.assertEquals("Hello! World", result);
}
public void setTear() {
if (rpcProxyService != null) {
try {
rpcProxyService.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| 2,825 | Java | .java | 65 | 35.215385 | 107 | 0.626138 | jwpttcg66/NettyGameServer | 1,597 | 670 | 3 | GPL-3.0 | 9/4/2024, 7:04:55 PM (Europe/Amsterdam) | false | false | false | true | false | false | true | true | 2,825 |
4,373,335 | BuscarReserva.java | eldblack_eng_software2/codigo-fonte/src/interfacelanchonete/BuscarReserva.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package interfacelanchonete;
import bd.ConexaoSQlite;
import classes.Reserva;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
/**
*
* @author pedro
*/
public class BuscarReserva extends javax.swing.JFrame {
/**
* Creates new form BuscarReserva
*/
public BuscarReserva() {
initComponents();
dadosCliente.setVisible(false);
nome.setEditable(false);
txtCpf.setEditable(false);
rg.setEditable(false);
fone.setEditable(false);
end.setEditable(false);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
buscaCpf = new javax.swing.JFormattedTextField();
busca = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
dadosCliente = new javax.swing.JPanel();
nome = new javax.swing.JTextField();
fone = new javax.swing.JTextField();
txtCpf = new javax.swing.JTextField();
rg = new javax.swing.JTextField();
end = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
detalhes = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel3.setBackground(new java.awt.Color(255, 102, 0));
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("Consultar Reserva");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addContainerGap(25, Short.MAX_VALUE))
);
jPanel4.setBackground(new java.awt.Color(255, 255, 255));
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Consultar", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 1, 12))); // NOI18N
jLabel1.setFont(new java.awt.Font("Segoe UI", 1, 12)); // NOI18N
jLabel1.setText("Informe o cpf do cliente ");
try {
buscaCpf.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
busca.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icone/icons8_search_20px.png"))); // NOI18N
busca.setText("Pesquisar");
busca.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buscaActionPerformed(evt);
}
});
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icone/icons8_return_20px_2.png"))); // NOI18N
jButton2.setText("Voltar");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(33, 33, 33)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(buscaCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(busca)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(buscaCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(busca, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
dadosCliente.setBackground(new java.awt.Color(255, 255, 255));
dadosCliente.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Dados do Cliente", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 1, 12))); // NOI18N
nome.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Nome", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 1, 11))); // NOI18N
nome.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nomeActionPerformed(evt);
}
});
fone.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Telefone", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 1, 11))); // NOI18N
fone.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
foneActionPerformed(evt);
}
});
txtCpf.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "CPF", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 1, 11))); // NOI18N
txtCpf.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtCpfActionPerformed(evt);
}
});
rg.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "RG", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 1, 11))); // NOI18N
rg.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
rgActionPerformed(evt);
}
});
end.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Endereço", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 1, 11))); // NOI18N
end.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
endActionPerformed(evt);
}
});
javax.swing.GroupLayout dadosClienteLayout = new javax.swing.GroupLayout(dadosCliente);
dadosCliente.setLayout(dadosClienteLayout);
dadosClienteLayout.setHorizontalGroup(
dadosClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(dadosClienteLayout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(dadosClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(nome, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(dadosClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(fone, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(rg, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(57, 57, 57))
.addGroup(dadosClienteLayout.createSequentialGroup()
.addGap(215, 215, 215)
.addComponent(end, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
dadosClienteLayout.setVerticalGroup(
dadosClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(dadosClienteLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(dadosClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(fone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(dadosClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(rg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(end, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(85, 85, 85))
);
detalhes.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null}
},
new String [] {
"Data", "Hora", "Mesa", "Quantidade de Pessoas", "Numero do Cartão"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(detalhes);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(dadosCliente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(20, 20, 20)
.addComponent(dadosCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void add(String cpf){
Reserva entrega = new Reserva();
ConexaoSQlite conSQLite = new ConexaoSQlite();
conSQLite.conectar();
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
String sql = "SELECT * "
+ " FROM tbl_reserva"
+ " WHERE cpf = ?;";
try {
int i=0;
preparedStatement = conSQLite.criarPreparedStatement(sql);
preparedStatement.setString(1,cpf);
resultSet = preparedStatement.executeQuery();
boolean ver=FALSE;
while(resultSet.next()) {
if(resultSet.getString("cpf").equals(cpf)){
detalhes.setValueAt(resultSet.getString("data"),i, 0);
detalhes.setValueAt(resultSet.getString("hora"),i, 1);
detalhes.setValueAt(resultSet.getInt("numMesa"),i, 2);
detalhes.setValueAt(resultSet.getInt("numPessoa"),i, 3);
detalhes.setValueAt(resultSet.getString("numCartao"),i, 4);
ver = TRUE;
i++;
}
}
if(FALSE == ver){
JOptionPane.showMessageDialog(null, "RESERVA NÃO ENCONTRADA");
}
}catch(SQLException ex) {
JOptionPane.showMessageDialog(null, "RESERVA NÃO ENCONTRADA: "+ex, "ERRO", JOptionPane.ERROR_MESSAGE);
}finally {
try {
resultSet.close();
preparedStatement.close();
conSQLite.desconectar();
}catch(SQLException ex) {
JOptionPane.showMessageDialog(null, "RESERVA NÃO ENCONTRADA: "+ex, "ERRO", JOptionPane.ERROR_MESSAGE);
}
}
}
private void buscaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscaActionPerformed
dadosCliente.setVisible(true);
Reserva entrega = new Reserva();
entrega = entrega.getReserva(buscaCpf.getText());
if(entrega !=null){
nome.setText(entrega.getNome());
fone.setText(entrega.getTelefone());
txtCpf.setText(entrega.getCpf());
rg.setText(entrega.getRg());
end.setText(entrega.getEndereco());
add(entrega.getCpf());
}
}//GEN-LAST:event_buscaActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// Metodos met = new Metodos();
// Funcionario f = met.busca(cpf);
// if (f.getFuncao().equals("Vendedor")) {
// new MenuFuncionario(cpf).show();
// } else {
// new MenuGerente(cpf).show();
// }
this.dispose();
}//GEN-LAST:event_jButton2ActionPerformed
private void nomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nomeActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_nomeActionPerformed
private void foneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_foneActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_foneActionPerformed
private void txtCpfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCpfActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtCpfActionPerformed
private void rgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rgActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_rgActionPerformed
private void endActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_endActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_endActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(BuscarReserva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(BuscarReserva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(BuscarReserva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(BuscarReserva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new BuscarReserva().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton busca;
private javax.swing.JFormattedTextField buscaCpf;
private javax.swing.JPanel dadosCliente;
private javax.swing.JTable detalhes;
private javax.swing.JTextField end;
private javax.swing.JTextField fone;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField nome;
private javax.swing.JTextField rg;
private javax.swing.JTextField txtCpf;
// End of variables declaration//GEN-END:variables
}
| 22,664 | Java | .java | 382 | 47.874346 | 256 | 0.674942 | eldblack/eng_software2 | 2 | 1 | 0 | LGPL-3.0 | 9/5/2024, 12:11:05 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 22,659 |
2,418,772 | TestBlockPosException.java | dotexe1337_bdsm-client-1_16/src/main/java/net/minecraft/test/TestBlockPosException.java | package net.minecraft.test;
import javax.annotation.Nullable;
import net.minecraft.util.math.BlockPos;
public class TestBlockPosException extends TestRuntimeException
{
private final BlockPos field_229455_a_ = null;
private final BlockPos field_229456_b_ = null;
private final long field_229457_c_ = 0L;
public String getMessage()
{
String s = "" + this.field_229455_a_.getX() + "," + this.field_229455_a_.getY() + "," + this.field_229455_a_.getZ() + " (relative: " + this.field_229456_b_.getX() + "," + this.field_229456_b_.getY() + "," + this.field_229456_b_.getZ() + ")";
return super.getMessage() + " at " + s + " (t=" + this.field_229457_c_ + ")";
}
@Nullable
public String func_229458_a_()
{
return super.getMessage() + " here";
}
@Nullable
public BlockPos func_229459_c_()
{
return this.field_229455_a_;
}
private TestBlockPosException()
{
super("Synthetic constructor added by MCP, do not call");
throw new RuntimeException("Synthetic constructor added by MCP, do not call");
}
}
| 1,110 | Java | .java | 29 | 33.068966 | 249 | 0.642791 | dotexe1337/bdsm-client-1.16 | 8 | 1 | 1 | GPL-2.0 | 9/4/2024, 9:22:36 PM (Europe/Amsterdam) | false | false | false | true | true | false | true | true | 1,110 |
4,505,699 | PUT.java | cintix_cintix-application-server/src/dk/cintix/application/server/rest/annotations/PUT.java | /*
*/
package dk.cintix.application.server.rest.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @author cix
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface PUT {
}
| 358 | Java | .java | 15 | 21.333333 | 55 | 0.781711 | cintix/cintix-application-server | 2 | 0 | 0 | GPL-3.0 | 9/5/2024, 12:15:15 AM (Europe/Amsterdam) | false | true | false | false | false | true | true | true | 358 |
735,772 | AbstractSpringContextTest.java | geoserver_geofence/src/services/core/services-impl/src/test/java/org/geoserver/test/AbstractSpringContextTest.java | /* (c) 2014 - 2017 Open Source Geospatial Foundation - all rights reserved
* This code is licensed under the GPL 2.0 license, available at the root
* application directory.
*/
package org.geoserver.test;
import junit.framework.TestCase;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Base class for tests with a spring context loaded from the classpath.
*
* @author Nate Sammons
*/
public abstract class AbstractSpringContextTest extends TestCase {
protected Logger logger = LogManager.getLogger(getClass());
protected ClassPathXmlApplicationContext context = null;
/**
* Get the filename to use for this context.
*/
protected abstract String[] getContextFilenames();
@Override
protected void setUp() throws Exception {
super.setUp();
context = new ClassPathXmlApplicationContext(getContextFilenames());
logger.info("Built test context: " + context);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
logger.info("Closing test context");
context.close();
context = null;
}
}
| 1,243 | Java | .java | 35 | 30.942857 | 76 | 0.7335 | geoserver/geofence | 97 | 55 | 78 | GPL-2.0 | 9/4/2024, 7:08:37 PM (Europe/Amsterdam) | false | false | true | false | false | true | false | true | 1,243 |
2,793,486 | Wait.java | stranck_JavaTimecode/src/main/java/ovh/stranck/javaTimecode/Wait.java | package ovh.stranck.javaTimecode;
public class Wait {
public long ms;
public Wait(){
ms = System.currentTimeMillis();
}
public void sleep(int ms){
long rn = System.currentTimeMillis();
int wait = (int) (ms - (rn - this.ms));
if(wait > 0){
wait(wait);
rn += wait;
}
this.ms = rn;
}
public static void wait(int ms){
try{
Thread.sleep(ms);
} catch(Exception ex){
Thread.currentThread().interrupt();
}
}
}
| 473 | Java | .java | 23 | 16.478261 | 42 | 0.61573 | stranck/JavaTimecode | 6 | 1 | 0 | EPL-2.0 | 9/4/2024, 10:15:27 PM (Europe/Amsterdam) | false | false | false | false | false | false | true | true | 473 |
3,300,035 | XsltProcessingException.java | europeana_metis-sandbox/src/main/java/eu/europeana/metis/sandbox/common/exception/XsltProcessingException.java | package eu.europeana.metis.sandbox.common.exception;
public class XsltProcessingException extends RuntimeException{
private static final long serialVersionUID = -1308555888429284944L;
public XsltProcessingException(String message, Throwable cause) {
super(message, cause);
}
}
| 291 | Java | .java | 7 | 38.571429 | 69 | 0.832143 | europeana/metis-sandbox | 4 | 0 | 3 | EUPL-1.2 | 9/4/2024, 11:11:18 PM (Europe/Amsterdam) | false | true | false | false | false | true | true | true | 291 |
3,983,793 | DateDeserializer.java | r00li_RHome/Android/RHome/lib-src/org/codehaus/jackson/map/deser/DateDeserializer.java | package org.codehaus.jackson.map.deser;
import java.io.IOException;
import java.util.Date;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.DeserializationContext;
/**
* Simple deserializer for handling {@link java.util.Date} values.
*<p>
* One way to customize Date formats accepted is to override method
* {@link DeserializationContext#parseDate} that this basic
* deserializer calls.
*/
public class DateDeserializer
extends StdScalarDeserializer<Date>
{
public DateDeserializer() { super(Date.class); }
@Override
public java.util.Date deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException
{
return _parseDate(jp, ctxt);
}
}
| 804 | Java | .java | 24 | 30.25 | 81 | 0.784974 | r00li/RHome | 2 | 1 | 0 | GPL-3.0 | 9/4/2024, 11:59:09 PM (Europe/Amsterdam) | false | false | true | false | true | true | true | true | 804 |
1,314,866 | Foo.java | eclipse-jdt_eclipse_jdt_ui/org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceIndirection/test14/in/Foo.java | package p0;
class Foo {
// Test adjustment of target method and target type
// because of the intermediary
private void hello() { // <- create indirection in p1.Bar
}
}
| 181 | Java | .java | 7 | 23.142857 | 58 | 0.730539 | 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 | 181 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.