hexsha
stringlengths 40
40
| size
int64 3
1.05M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 5
1.02k
| max_stars_repo_name
stringlengths 4
126
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
sequence | max_stars_count
float64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 5
1.02k
| max_issues_repo_name
stringlengths 4
114
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
sequence | max_issues_count
float64 1
92.2k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 5
1.02k
| max_forks_repo_name
stringlengths 4
136
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
sequence | max_forks_count
float64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2.55
99.9
| max_line_length
int64 3
1k
| alphanum_fraction
float64 0.25
1
| index
int64 0
1M
| content
stringlengths 3
1.05M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e022cff745f3649f98d59fea3a88ca6b694ea24 | 1,734 | java | Java | fotoapparat/src/main/java/io/fotoapparat/routine/StartCameraRoutine.java | alphater/Fotoapparat | 541bd2d7409fc40c1aa0fdc0dba36d93c5f607e4 | [
"Apache-2.0"
] | 1 | 2019-04-12T01:11:49.000Z | 2019-04-12T01:11:49.000Z | fotoapparat/src/main/java/io/fotoapparat/routine/StartCameraRoutine.java | alphater/Fotoapparat | 541bd2d7409fc40c1aa0fdc0dba36d93c5f607e4 | [
"Apache-2.0"
] | null | null | null | fotoapparat/src/main/java/io/fotoapparat/routine/StartCameraRoutine.java | alphater/Fotoapparat | 541bd2d7409fc40c1aa0fdc0dba36d93c5f607e4 | [
"Apache-2.0"
] | 1 | 2019-04-12T01:06:15.000Z | 2019-04-12T01:06:15.000Z | 34.68 | 69 | 0.825836 | 904 | package io.fotoapparat.routine;
import io.fotoapparat.hardware.CameraDevice;
import io.fotoapparat.hardware.orientation.ScreenOrientationProvider;
import io.fotoapparat.parameter.LensPosition;
import io.fotoapparat.parameter.provider.InitialParametersProvider;
import io.fotoapparat.parameter.selector.SelectorFunction;
import io.fotoapparat.view.CameraRenderer;
/**
* Opens camera and starts preview.
*/
public class StartCameraRoutine implements Runnable {
private final CameraDevice cameraDevice;
private final CameraRenderer cameraRenderer;
private final SelectorFunction<LensPosition> lensPositionSelector;
private final ScreenOrientationProvider screenOrientationProvider;
private final InitialParametersProvider initialParametersProvider;
public StartCameraRoutine(CameraDevice cameraDevice,
CameraRenderer cameraRenderer,
SelectorFunction<LensPosition> lensPositionSelector,
ScreenOrientationProvider screenOrientationProvider,
InitialParametersProvider initialParametersProvider) {
this.cameraDevice = cameraDevice;
this.cameraRenderer = cameraRenderer;
this.lensPositionSelector = lensPositionSelector;
this.screenOrientationProvider = screenOrientationProvider;
this.initialParametersProvider = initialParametersProvider;
}
@Override
public void run() {
LensPosition lensPosition = lensPositionSelector.select(
cameraDevice.getAvailableLensPositions()
);
cameraDevice.open(lensPosition);
cameraDevice.updateParameters(
initialParametersProvider.initialParameters()
);
cameraDevice.setDisplayOrientation(
screenOrientationProvider.getScreenRotation()
);
cameraRenderer.attachCamera(cameraDevice);
cameraDevice.startPreview();
}
}
|
3e022d8347a762d8dc13343d9bbf444d426aaeda | 491 | java | Java | platform-pojo-bl/src/main/java/ua/com/fielden/platform/serialisation/exceptions/SerialisationException.java | fieldenms/ | 4efd3b2475877d434a57cbba638b711df95748e7 | [
"MIT"
] | 16 | 2017-03-22T05:42:26.000Z | 2022-01-17T22:38:38.000Z | platform-pojo-bl/src/main/java/ua/com/fielden/platform/serialisation/exceptions/SerialisationException.java | fieldenms/ | 4efd3b2475877d434a57cbba638b711df95748e7 | [
"MIT"
] | 647 | 2017-03-21T07:47:44.000Z | 2022-03-31T13:03:47.000Z | platform-pojo-bl/src/main/java/ua/com/fielden/platform/serialisation/exceptions/SerialisationException.java | fieldenms/ | 4efd3b2475877d434a57cbba638b711df95748e7 | [
"MIT"
] | 8 | 2017-03-21T08:26:56.000Z | 2020-06-27T01:55:09.000Z | 24.55 | 79 | 0.708758 | 905 | package ua.com.fielden.platform.serialisation.exceptions;
/**
* A runtime exception to indicate TG specific serialisation related exception.
*
* @author TG Team
*
*/
public class SerialisationException extends RuntimeException {
private static final long serialVersionUID = 1L;
public SerialisationException(final String msg) {
super(msg);
}
public SerialisationException(final String msg, final Throwable cause) {
super(msg, cause);
}
} |
3e022e63a05024e79f1dafe6c499bcc56989582f | 1,382 | java | Java | actionbarsherlock/src/com/actionbarsherlock/internal/widget/IcsColorDrawable.java | edejong/ActionBarSherlock | 5a718b7848e41ac85e574cb830e02864b8c99ecf | [
"Apache-2.0"
] | 4,348 | 2015-01-01T00:31:29.000Z | 2022-03-29T03:24:23.000Z | actionbarsherlock/src/com/actionbarsherlock/internal/widget/IcsColorDrawable.java | edejong/ActionBarSherlock | 5a718b7848e41ac85e574cb830e02864b8c99ecf | [
"Apache-2.0"
] | 355 | 2015-11-03T09:30:16.000Z | 2022-03-23T11:02:05.000Z | actionbarsherlock/src/com/actionbarsherlock/internal/widget/IcsColorDrawable.java | edejong/ActionBarSherlock | 5a718b7848e41ac85e574cb830e02864b8c99ecf | [
"Apache-2.0"
] | 3,248 | 2015-01-01T11:45:07.000Z | 2022-03-25T07:25:01.000Z | 26.576923 | 85 | 0.636758 | 906 | package com.actionbarsherlock.internal.widget;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
/**
* A version of {@link android.graphics.drawable.ColorDrawable} that respects bounds.
*/
public class IcsColorDrawable extends Drawable {
private int color;
private final Paint paint = new Paint();
public IcsColorDrawable(ColorDrawable drawable) {
Bitmap bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
drawable.draw(c);
this.color = bitmap.getPixel(0, 0);
bitmap.recycle();
}
public IcsColorDrawable(int color) {
this.color = color;
}
@Override public void draw(Canvas canvas) {
if ((color >>> 24) != 0) {
paint.setColor(color);
canvas.drawRect(getBounds(), paint);
}
}
@Override
public void setAlpha(int alpha) {
if (alpha != (color >>> 24)) {
color = (color & 0x00FFFFFF) | (alpha << 24);
invalidateSelf();
}
}
@Override public void setColorFilter(ColorFilter colorFilter) {
//Ignored
}
@Override public int getOpacity() {
return color >>> 24;
}
}
|
3e022fca90f6f5286a6503c0f88ab8fc826a14fd | 5,251 | java | Java | src/DAO/DAORiego.java | Carlos-Caballero/jardineria_183403 | 75f4f7e848a8bb2516d215ed9778d617c661da98 | [
"MIT"
] | null | null | null | src/DAO/DAORiego.java | Carlos-Caballero/jardineria_183403 | 75f4f7e848a8bb2516d215ed9778d617c661da98 | [
"MIT"
] | null | null | null | src/DAO/DAORiego.java | Carlos-Caballero/jardineria_183403 | 75f4f7e848a8bb2516d215ed9778d617c661da98 | [
"MIT"
] | null | null | null | 30.178161 | 103 | 0.544468 | 907 | /*
* 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 DAO;
/**
*
* @author Carlos
*/
import java.util.List;
import java.util.Iterator;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.HibernateException;
import hibernate.Riegos;
import java.util.ArrayList;
import java.util.Date;
public class DAORiego {
public int crearRiego(Riegos riegos) {
SessionFactory sesion = NewHibernateUtil.getSessionFactory();
Session session;
session = sesion.openSession();
int id=-1;
Transaction tx = null;
try {
tx = session.beginTransaction();
id = (Integer)session.save(riegos);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
System.out.println("INSERTADO");
return id;
}
public void deleteRiego(Integer RiegoID) {
SessionFactory sesion = NewHibernateUtil.getSessionFactory();
Session session;
session = sesion.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Riegos dao
= (Riegos) session.get(Riegos.class, RiegoID);
session.delete(dao);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
}
public void updateRiego(Integer RiegoID, Date fecha, int productoID) {
SessionFactory sesion = NewHibernateUtil.getSessionFactory();
Session session;
session = sesion.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Riegos riego
= (Riegos) session.get(Riegos.class, RiegoID);
riego.setProductosId(productoID);
riego.setFecha(fecha);
session.update(riego);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
}
public ArrayList<Riegos> listRiegos() {
SessionFactory sesion = NewHibernateUtil.getSessionFactory();
Session session;
session = sesion.openSession();
Transaction tx = null;
ArrayList<Riegos> riegoss = new ArrayList<Riegos>();
try {
tx = session.beginTransaction();
List employees = session.createQuery("FROM Riegos").list();
for (Iterator iterator
= employees.iterator(); iterator.hasNext();) {
Riegos dao = (Riegos) iterator.next();
riegoss.add(dao);
System.out.print("Fecha:" + dao.getFecha());
System.out.print(" Producto: " + dao.getProductosId());
}
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return riegoss;
}
public Riegos buscarRiego(Integer idRiegos){
Riegos r = null;
SessionFactory sesion = NewHibernateUtil.getSessionFactory();
Session session;
session = sesion.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
r = (Riegos) session.get(Riegos.class, idRiegos);
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return r;
}
public ArrayList<Riegos> listRiegosByProduct(Integer productoId) {
SessionFactory sesion = NewHibernateUtil.getSessionFactory();
Session session;
session = sesion.openSession();
Transaction tx = null;
ArrayList<Riegos> riegoss = new ArrayList<Riegos>();
try {
tx = session.beginTransaction();
List employees = session.createQuery("FROM Riegos where productosId = "+productoId).list();
for (Iterator iterator
= employees.iterator(); iterator.hasNext();) {
Riegos dao = (Riegos) iterator.next();
riegoss.add(dao);
}
tx.commit();
} catch (HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return riegoss;
}
}
|
3e02305a5959ccd6ca3911b9284c189d7129853a | 1,497 | java | Java | src/main/java/com/capgemini/service/ITrainingCourseService.java | ThappetaJyothi/women-empowerment-master | 20263f8273de99a15075c00a0de975d744f16268 | [
"MIT"
] | null | null | null | src/main/java/com/capgemini/service/ITrainingCourseService.java | ThappetaJyothi/women-empowerment-master | 20263f8273de99a15075c00a0de975d744f16268 | [
"MIT"
] | null | null | null | src/main/java/com/capgemini/service/ITrainingCourseService.java | ThappetaJyothi/women-empowerment-master | 20263f8273de99a15075c00a0de975d744f16268 | [
"MIT"
] | null | null | null | 23.390625 | 89 | 0.780895 | 908 | package com.capgemini.service;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.capgemini.model.TrainingCourse;
import com.capgemini.repository.ITrainingCourseRepository;
@Service
public class ITrainingCourseService implements TrainingServices {
private static final Logger LOG = LoggerFactory.getLogger(ITrainingCourseService.class);
@Autowired
ITrainingCourseRepository trainrepo;
@Override
public TrainingCourse addTrainingCourse(TrainingCourse course) {
// if(trainrepo.equals(course.getCourseName())) {
// throw new
// }
return trainrepo.save(course);
//return null;
}
@Override
public TrainingCourse updateTrainingCourse(TrainingCourse course) {
// TODO Auto-generated method stub
return null;
}
@Override
public TrainingCourse viewTrainingCourse(int courseId) {
LOG.info("trainig course");
Optional<TrainingCourse> tcOpt = trainrepo.findById(courseId);
return tcOpt.get();
}
@Override
public List<TrainingCourse> viewAllTrainingCourse() {
// TODO Auto-generated method stub
return null;
}
@Override
public void deleteTrainingCourse(int courseId) {
// TODO Auto-generated method stub
}
@Override
public void viewByTrainingCourseName(String courseName) {
// TODO Auto-generated method stub
}
}
|
3e0230963601118ed012f753f6e77d1701e96968 | 232 | java | Java | core-java-modules/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteUnitTest.java | eas5/tutorials | 4b460a9e25f6f0b0292e98144add0ce631a9e05e | [
"MIT"
] | 32,544 | 2015-01-02T16:59:22.000Z | 2022-03-31T21:04:05.000Z | core-java-modules/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteUnitTest.java | eas5/tutorials | 4b460a9e25f6f0b0292e98144add0ce631a9e05e | [
"MIT"
] | 1,577 | 2015-02-21T17:47:03.000Z | 2022-03-31T14:25:58.000Z | core-java-modules/core-java/src/test/java/com/baeldung/junit4vstestng/SuiteUnitTest.java | eas5/tutorials | 4b460a9e25f6f0b0292e98144add0ce631a9e05e | [
"MIT"
] | 55,853 | 2015-01-01T07:52:09.000Z | 2022-03-31T21:08:15.000Z | 21.090909 | 73 | 0.806034 | 909 | package com.baeldung.junit4vstestng;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ RegistrationUnitTest.class, SignInUnitTest.class })
public class SuiteUnitTest {
}
|
3e02311901d269e77ec667fded98a17c3d458973 | 3,208 | java | Java | src/main/java/net/accelbyte/sdk/api/platform/operations/campaign/ApplyUserRedemption.java | AccelByte/accelbyte-java-sdk | 35086513f8f2acaa9b15a78730498fa5e19769ef | [
"MIT"
] | 1 | 2022-02-26T12:15:52.000Z | 2022-02-26T12:15:52.000Z | src/main/java/net/accelbyte/sdk/api/platform/operations/campaign/ApplyUserRedemption.java | AccelByte/accelbyte-java-sdk | 35086513f8f2acaa9b15a78730498fa5e19769ef | [
"MIT"
] | null | null | null | src/main/java/net/accelbyte/sdk/api/platform/operations/campaign/ApplyUserRedemption.java | AccelByte/accelbyte-java-sdk | 35086513f8f2acaa9b15a78730498fa5e19769ef | [
"MIT"
] | 1 | 2021-12-29T04:01:20.000Z | 2021-12-29T04:01:20.000Z | 28.140351 | 160 | 0.665835 | 910 | /*
* Copyright (c) 2022 AccelByte Inc. All Rights Reserved
* This is licensed software from AccelByte Inc, for limitations
* and restrictions contact your company contract manager.
*
* Code generated. DO NOT EDIT.
*/
package net.accelbyte.sdk.api.platform.operations.campaign;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import net.accelbyte.sdk.api.platform.models.*;
import net.accelbyte.sdk.api.platform.models.RedeemResult;
import net.accelbyte.sdk.api.platform.models.RedeemRequest;
import net.accelbyte.sdk.core.Operation;
import net.accelbyte.sdk.core.util.Helper;
import net.accelbyte.sdk.core.HttpResponseException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* applyUserRedemption
*
* [SERVICE COMMUNICATION ONLY] Redeem code. If the campaign which the code belongs to is INACTIVE, the code couldn't be redeemed even if its status is ACTIVE.
* Other detail info:
*
* * Required permission : resource="ADMIN:NAMESPACE:{namespace}:USER:{userId}:REDEMPTION", action=1 (CREATE)
* * Returns : Redeem result
*/
@Getter
@Setter
public class ApplyUserRedemption extends Operation {
/**
* generated field's value
*/
private String path = "/platform/admin/namespaces/{namespace}/users/{userId}/redemption";
private String method = "POST";
private List<String> consumes = Arrays.asList("application/json");
private List<String> produces = Arrays.asList("application/json");
@Deprecated
private String security = "Bearer";
private String locationQuery = null;
/**
* fields as input parameter
*/
private String namespace;
private String userId;
private RedeemRequest body;
/**
* @param namespace required
* @param userId required
*/
@Builder
public ApplyUserRedemption(
String namespace,
String userId,
RedeemRequest body
)
{
this.namespace = namespace;
this.userId = userId;
this.body = body;
securities.add("Bearer");
}
@Override
public Map<String, String> getPathParams(){
Map<String, String> pathParams = new HashMap<>();
if (this.namespace != null){
pathParams.put("namespace", this.namespace);
}
if (this.userId != null){
pathParams.put("userId", this.userId);
}
return pathParams;
}
@Override
public RedeemRequest getBodyParams(){
return this.body;
}
@Override
public boolean isValid() {
if(this.namespace == null) {
return false;
}
if(this.userId == null) {
return false;
}
return true;
}
public RedeemResult parseResponse(int code, String contentTpe, InputStream payload) throws HttpResponseException, IOException {
String json = Helper.convertInputStreamToString(payload);
if(code == 200){
return new RedeemResult().createFromJson(json);
}
throw new HttpResponseException(code, json);
}
} |
3e023154e11373a36ef2eddf0be03a9af465fa20 | 367 | java | Java | src/main/java/specification/NotSpecification.java | apibol/specification | 9b3f14b4db496ba1367330c8a356b45d1bfe222b | [
"Apache-2.0"
] | null | null | null | src/main/java/specification/NotSpecification.java | apibol/specification | 9b3f14b4db496ba1367330c8a356b45d1bfe222b | [
"Apache-2.0"
] | null | null | null | src/main/java/specification/NotSpecification.java | apibol/specification | 9b3f14b4db496ba1367330c8a356b45d1bfe222b | [
"Apache-2.0"
] | null | null | null | 21.588235 | 67 | 0.784741 | 911 | package specification;
public class NotSpecification<T> extends AbstractSpecification<T> {
private Specification<T> specification1;
public NotSpecification(final Specification<T> specification1) {
super();
this.specification1 = specification1;
}
@Override
public Boolean isSatisfiedBy(T instance) {
return !specification1.isSatisfiedBy(instance);
}
} |
3e02316b254411e91e4b3e59889a47cd87afed6c | 8,158 | java | Java | src/frames/Frame.java | ronaldosvieira/tcc | f87e57fce2d0a4fd7aeaad5db29a365786be4e66 | [
"MIT"
] | 1 | 2017-12-12T11:29:57.000Z | 2017-12-12T11:29:57.000Z | src/frames/Frame.java | ronaldosvieira/beings | f87e57fce2d0a4fd7aeaad5db29a365786be4e66 | [
"MIT"
] | 27 | 2016-11-26T21:12:00.000Z | 2017-11-15T20:08:48.000Z | src/frames/Frame.java | ronaldosvieira/tcc | f87e57fce2d0a4fd7aeaad5db29a365786be4e66 | [
"MIT"
] | null | null | null | 32.373016 | 114 | 0.571586 | 912 | package frames;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import frames.constraint.Constraint;
import frames.constraint.ContainsConstraint;
import frames.constraint.RangeConstraint;
import frames.constraint.TypeConstraint;
import frames.util.ClassTypeAdapterFactory;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public abstract class Frame implements Cloneable {
private String name;
protected FrameRef parent;
protected Map<String, Slot> slots;
public Frame(String name) {
this.name = name;
this.slots = new HashMap<>();
}
public Frame(String name, GenericFrame parent) {
this(name);
this.parent = parent.ref();
}
public Frame(Frame frame) {
this.copy(frame);
}
protected void copy(Frame frame) {
this.name = frame.name;
this.parent = frame.parent;
this.slots = new HashMap<>();
for (String slot : frame.slots.keySet()) {
this.slots.put(slot, new Slot(this, frame.slots.get(slot)));
}
}
public String name() {return this.name;}
public GenericFrame parent() {
return this.parent != null && this.parent.retrieve() != null? (GenericFrame) this.parent.retrieve() : null;
}
public Set<String> slots() {
Set<String> slots = new HashSet<>();
GenericFrame parent = this.parent();
slots.addAll(this.slots.keySet());
if (parent != null) {
slots.addAll(parent.slots());
}
return slots;
}
public void setName(String name) {this.name = name;}
public void setParent(GenericFrame parent) {this.parent = parent.ref();}
public void setParent(FrameRef ref) {this.parent = ref;}
public boolean isA(String type) {
return name().equals(type) || (parent() != null && parent().isA(type));
}
public boolean isA(GenericFrame type) {return this.isA(type.name());}
public boolean contains(String key) {
return slots.containsKey(key);
}
public Slot find(String key) throws NoSuchElementException {
if (this.contains(key))
return slots.get(key);
else if (parent() != null)
return parent().find(key);
else
throw new NoSuchElementException("Slot '" + key
+ "' not found on frame " + name());
}
public Object get(String key) throws NoSuchElementException {
return this.find(key).getValue();
}
public <T> T get(String key, Class<T> type) throws ClassCastException {
Object value = this.get(key);
try {
return type.cast(value);
} catch (ClassCastException e) {
throw new ClassCastException("Slot '" + key + "' is of type "
+ value.getClass().getSimpleName() + ". "
+ type.getSimpleName() + " given.");
}
}
public <T> void set(String key, T value) {
try {
Slot slot = new Slot(this, this.find(key));
slot.setValue(value);
slots.put(key, slot);
} catch (NoSuchElementException e) {
slots.put(key, new Slot(this, value));
}
}
public void ifAdded(String key, Consumer<Object> if_added) {
Slot slot;
try {
slot = new Slot(this, this.find(key));
} catch (NoSuchElementException e) {
slot = new Slot(this);
}
slot.setIfAdded(if_added);
slots.put(key, slot);
}
public void ifNeeded(String key, Function<Frame, Object> if_needed) {
Slot slot;
try {
slot = new Slot(this, this.find(key));
} catch (NoSuchElementException e) {
slot = new Slot(this);
}
slot.setIfNeeded(if_needed);
slots.put(key, slot);
}
public void addConstraint(String key, Constraint constraint) {
Slot slot;
try {
slot = this.find(key);
} catch (NoSuchElementException e) {
slot = new Slot(this);
}
slot.addConstraint(constraint);
slots.put(key, slot);
}
public FrameRef ref() {return new FrameRef(this);}
public String toString() {
StringBuilder s = new StringBuilder("[");
List<Map.Entry<String, Slot>> entries = slots.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getKey))
.collect(Collectors.toList());
for (Map.Entry<String, Slot> entry : entries) {
s.append(" ")
.append(entry.getKey())
.append(": ")
.append(entry.getValue().getValue())
.append(";");
}
return s.append("]").toString();
}
public String toJson() {
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapterFactory(new ClassTypeAdapterFactory());
builder.serializeNulls();
return builder.create().toJson(this);
}
public static Frame fromJson(String json) {
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject frameJson = parser.parse(json).getAsJsonObject();
Frame frame = new GenericFrame(frameJson.get("name").getAsString());
JsonElement parent = frameJson.get("parent");
if (!parent.isJsonNull()) {
frame.setParent(gson.fromJson(parent, FrameRef.class));
}
JsonObject slots = frameJson.get("slots").getAsJsonObject();
for (Map.Entry<String, JsonElement> slot : slots.entrySet()) {
String key = slot.getKey();
JsonObject filler = slot.getValue().getAsJsonObject();
Predicate<JsonElement> exists = el -> el != null && !el.isJsonNull();
JsonElement value = filler.get("value");
JsonElement if_added = filler.get("if-added");
JsonElement if_needed = filler.get("if-needed");
JsonElement constraints = filler.get("constraints");
if (exists.test(value))
frame.set(key, gson.fromJson(filler.get("value"), Object.class));
if (exists.test(if_added))
frame.ifAdded(key, KnowledgeBase.retrieveIfAdded(if_added.getAsString()));
if (exists.test(if_needed))
frame.ifNeeded(key, KnowledgeBase.retrieveIfNeeded(if_needed.getAsString()));
if (exists.test(constraints)) {
for (JsonElement constraint : filler.get("constraints").getAsJsonArray()) {
JsonObject constraintObj = constraint.getAsJsonObject();
String constrType = constraintObj.get("type").getAsString();
Constraint constr;
try {
switch (constrType) {
case "type":
String className = constraintObj.get("class-name").getAsString();
constr = new TypeConstraint(Class.forName(className));
break;
case "contains":
JsonArray accepts = constraintObj.get("accepts").getAsJsonArray();
constr = new ContainsConstraint(gson.fromJson(accepts, ArrayList.class));
break;
case "range":
Comparable lo = (Comparable) gson.fromJson(constraintObj.get("lo"), Object.class);
Comparable hi = (Comparable) gson.fromJson(constraintObj.get("hi"), Object.class);
JsonArray bounds = constraintObj.get("bounds").getAsJsonArray();
String inclusivity = bounds.get(0).getAsString() + bounds.get(1).getAsString();
constr = new RangeConstraint(lo, hi, inclusivity);
break;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
return frame;
}
}
|
3e0231eefe75ac4fa0d332cf741dd3b87b7ce005 | 8,663 | java | Java | modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxImplicitSingleStateImpl.java | mshonichev/ignite | 28a5247d37ba65bdcb6119f97023f32d511b5f1e | [
"CC0-1.0"
] | 1 | 2016-02-03T12:46:25.000Z | 2016-02-03T12:46:25.000Z | modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxImplicitSingleStateImpl.java | mshonichev/ignite | 28a5247d37ba65bdcb6119f97023f32d511b5f1e | [
"CC0-1.0"
] | 6 | 2020-11-16T20:42:48.000Z | 2022-02-01T01:05:33.000Z | modules/core/src/main/java/org/apache/ignite/internal/processors/cache/transactions/IgniteTxImplicitSingleStateImpl.java | mshonichev/ignite | 28a5247d37ba65bdcb6119f97023f32d511b5f1e | [
"CC0-1.0"
] | 1 | 2020-07-11T01:08:38.000Z | 2020-07-11T01:08:38.000Z | 30.719858 | 121 | 0.643426 | 914 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.transactions;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.cluster.ClusterTopologyServerNotFoundException;
import org.apache.ignite.internal.processors.cache.GridCacheContext;
import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTopologyFuture;
import org.apache.ignite.internal.processors.cache.store.CacheStoreManager;
import org.apache.ignite.internal.util.future.GridFutureAdapter;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.jetbrains.annotations.Nullable;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
/**
*
*/
public class IgniteTxImplicitSingleStateImpl extends IgniteTxLocalStateAdapter {
/** */
private GridCacheContext cacheCtx;
/** */
private IgniteTxEntry entry;
/** */
private boolean init;
/** {@inheritDoc} */
@Override public void addActiveCache(GridCacheContext ctx, IgniteTxLocalAdapter tx)
throws IgniteCheckedException {
assert cacheCtx == null : "Cache already set [cur=" + cacheCtx.name() + ", new=" + ctx.name() + ']';
this.cacheCtx = ctx;
tx.activeCachesDeploymentEnabled(cacheCtx.deploymentEnabled());
}
/** {@inheritDoc} */
@Nullable @Override public GridCacheContext singleCacheContext(GridCacheSharedContext cctx) {
return cacheCtx;
}
/** {@inheritDoc} */
@Nullable @Override public Integer firstCacheId() {
return cacheCtx != null ? cacheCtx.cacheId() : null;
}
/** {@inheritDoc} */
@Override public void awaitLastFut(GridCacheSharedContext ctx) {
if (cacheCtx == null)
return;
cacheCtx.cache().awaitLastFut();
}
/** {@inheritDoc} */
@Override public boolean implicitSingle() {
return true;
}
/** {@inheritDoc} */
@Override public IgniteCheckedException validateTopology(GridCacheSharedContext cctx, GridDhtTopologyFuture topFut) {
if (cacheCtx == null)
return null;
Throwable err = topFut.validateCache(cacheCtx);
if (err != null) {
return new IgniteCheckedException("Failed to perform cache operation (cache topology is not valid): " +
U.maskName(cacheCtx.name()));
}
if (CU.affinityNodes(cacheCtx, topFut.topologyVersion()).isEmpty()) {
return new ClusterTopologyServerNotFoundException("Failed to map keys for cache (all " +
"partition nodes left the grid): " + cacheCtx.name());
}
return null;
}
/** {@inheritDoc} */
@Override public boolean sync(GridCacheSharedContext cctx) {
return cacheCtx != null && cacheCtx.config().getWriteSynchronizationMode() == FULL_SYNC;
}
/** {@inheritDoc} */
@Override public boolean hasNearCache(GridCacheSharedContext cctx) {
return cacheCtx != null && cacheCtx.isNear();
}
/** {@inheritDoc} */
@Override public GridDhtTopologyFuture topologyReadLock(GridCacheSharedContext cctx, GridFutureAdapter<?> fut) {
if (cacheCtx == null || cacheCtx.isLocal())
return cctx.exchange().lastTopologyFuture();
cacheCtx.topology().readLock();
if (cacheCtx.topology().stopping()) {
fut.onDone(new IgniteCheckedException("Failed to perform cache operation (cache is stopped): " +
cacheCtx.name()));
return null;
}
return cacheCtx.topology().topologyVersionFuture();
}
/** {@inheritDoc} */
@Override public void topologyReadUnlock(GridCacheSharedContext cctx) {
if (cacheCtx == null || cacheCtx.isLocal())
return;
cacheCtx.topology().readUnlock();
}
/** {@inheritDoc} */
@Override public boolean storeUsed(GridCacheSharedContext cctx) {
if (cacheCtx == null)
return false;
CacheStoreManager store = cacheCtx.store();
return store.configured();
}
/** {@inheritDoc} */
@Override public boolean hasInterceptor(GridCacheSharedContext cctx) {
GridCacheContext ctx0 = cacheCtx;
return ctx0 != null && ctx0.config().getInterceptor() != null;
}
/** {@inheritDoc} */
@Override public Collection<CacheStoreManager> stores(GridCacheSharedContext cctx) {
if (cacheCtx == null)
return null;
CacheStoreManager store = cacheCtx.store();
if (store.configured()) {
HashSet<CacheStoreManager> set = new HashSet<>(3, 0.75f);
set.add(store);
return set;
}
return null;
}
/** {@inheritDoc} */
@Override public void onTxEnd(GridCacheSharedContext cctx, IgniteInternalTx tx, boolean commit) {
if (cacheCtx != null)
onTxEnd(cacheCtx, tx, commit);
}
/** {@inheritDoc} */
@Override public IgniteTxEntry entry(IgniteTxKey key) {
if (entry != null && entry.txKey().equals(key))
return entry;
return null;
}
/** {@inheritDoc} */
@Override public boolean hasWriteKey(IgniteTxKey key) {
return entry != null && entry.txKey().equals(key);
}
/** {@inheritDoc} */
@Override public Set<IgniteTxKey> readSet() {
return Collections.emptySet();
}
/** {@inheritDoc} */
@Override public Set<IgniteTxKey> writeSet() {
if (entry != null) {
HashSet<IgniteTxKey> set = new HashSet<>(3, 0.75f);
set.add(entry.txKey());
return set;
}
else
return Collections.<IgniteTxKey>emptySet();
}
/** {@inheritDoc} */
@Override public Collection<IgniteTxEntry> writeEntries() {
return entry != null ? Arrays.asList(entry) : Collections.<IgniteTxEntry>emptyList();
}
/** {@inheritDoc} */
@Override public Collection<IgniteTxEntry> readEntries() {
return Collections.emptyList();
}
/** {@inheritDoc} */
@Override public Map<IgniteTxKey, IgniteTxEntry> writeMap() {
return entry != null ? F.asMap(entry.txKey(), entry) : Collections.<IgniteTxKey, IgniteTxEntry>emptyMap();
}
/** {@inheritDoc} */
@Override public Map<IgniteTxKey, IgniteTxEntry> readMap() {
return Collections.emptyMap();
}
/** {@inheritDoc} */
@Override public boolean empty() {
return entry == null;
}
/** {@inheritDoc} */
@Override public Collection<IgniteTxEntry> allEntries() {
return entry != null ? Arrays.asList(entry) : Collections.<IgniteTxEntry>emptyList();
}
/** {@inheritDoc} */
@Override public boolean init(int txSize) {
if (!init) {
init = true;
return true;
}
return false;
}
/** {@inheritDoc} */
@Override public boolean initialized() {
return init;
}
/** {@inheritDoc} */
@Override public void addEntry(IgniteTxEntry entry) {
assert this.entry == null : "Entry already set [cur=" + this.entry + ", new=" + entry + ']';
this.entry = entry;
}
/** {@inheritDoc} */
@Override public void seal() {
// No-op.
}
/** {@inheritDoc} */
@Override public IgniteTxEntry singleWrite() {
return entry;
}
/** {@inheritDoc} */
public String toString() {
return S.toString(IgniteTxImplicitSingleStateImpl.class, this);
}
}
|
3e0233b01c462acfd8e2459dfbdda2f6bd7a44a9 | 462 | java | Java | predavanja/primeri-java/src/rs/math/oop1/z090401/anonimneUnutrasnje/z03/geometrijaSortiranje/Tekst.java | MatfOOP/OOP | da14e7bcaf371abf223a1ecc78b24947da2ad1fa | [
"MIT"
] | 5 | 2019-04-09T08:21:02.000Z | 2022-01-03T14:21:00.000Z | predavanja/primeri-java/src/rs/math/oop1/z090401/anonimneUnutrasnje/z03/geometrijaSortiranje/Tekst.java | MatfOOP/OOP | da14e7bcaf371abf223a1ecc78b24947da2ad1fa | [
"MIT"
] | 7 | 2019-05-05T12:02:56.000Z | 2020-04-18T16:44:53.000Z | predavanja/primeri-java/src/rs/math/oop1/z090401/anonimneUnutrasnje/z03/geometrijaSortiranje/Tekst.java | MatfOOP/OOP | da14e7bcaf371abf223a1ecc78b24947da2ad1fa | [
"MIT"
] | null | null | null | 14.903226 | 73 | 0.694805 | 915 | package rs.math.oop1.z090401.anonimneUnutrasnje.z03.geometrijaSortiranje;
import java.awt.Graphics;
public class Tekst extends GeometrijskiObjekat implements Prikaz
{
private String sadrzaj = "tra la la";
public Tekst(String s)
{
sadrzaj= s;
}
public Tekst()
{
}
@Override
public void prikaziSe ()
{
System.out.print("Tekst: " + sadrzaj);
}
@Override
public void prikaziSe ( Graphics g )
{
g.drawString(sadrzaj, 100, 100);
}
}
|
3e023466e5dda2e132b8d6ebd893f840978d5a1d | 3,604 | java | Java | overlap2d/src/com/uwsoft/editor/view/ui/followers/LabelAnchorListener.java | i-Taozi/overlap2d | ce6d7513d5c50bffe70386d7407a1a07512015e6 | [
"Apache-2.0"
] | 930 | 2015-04-02T12:59:09.000Z | 2022-02-04T19:40:55.000Z | overlap2d/src/com/uwsoft/editor/view/ui/followers/LabelAnchorListener.java | i-Taozi/overlap2d | ce6d7513d5c50bffe70386d7407a1a07512015e6 | [
"Apache-2.0"
] | 379 | 2015-04-02T16:58:24.000Z | 2022-02-16T04:46:44.000Z | overlap2d/src/com/uwsoft/editor/view/ui/followers/LabelAnchorListener.java | i-Taozi/overlap2d | ce6d7513d5c50bffe70386d7407a1a07512015e6 | [
"Apache-2.0"
] | 379 | 2015-04-02T13:27:34.000Z | 2022-03-05T23:44:29.000Z | 49.369863 | 135 | 0.703385 | 916 | package com.uwsoft.editor.view.ui.followers;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
/**
* Created by CyberJoe on 6/15/2015.
*/
public class LabelAnchorListener extends AnchorListener {
protected FollowerTransformationListener listenerTransform = new EmptyTransformationListener();
protected FollowerTransformationListener listenerResize = new EmptyTransformationListener();
public LabelAnchorListener(NormalSelectionFollower follower, FollowerTransformationListener listenerResize, int anchorId) {
super(follower, anchorId);
this.listenerResize = listenerResize;
}
public void setListenerTransform(FollowerTransformationListener listener) {
listenerTransform = listenerTransform;
}
@Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
super.touchDown(event, x, y, pointer, button);
if(follower.getMode() == NormalSelectionFollower.SelectionMode.normal) {
listenerResize.anchorDown(follower, anchorId, event.getStageX(), event.getStageY());
}
if(follower.getMode() == NormalSelectionFollower.SelectionMode.transform) {
if(listenerTransform != null) listenerTransform.anchorDown(follower, anchorId, event.getStageX(), event.getStageY());
}
return true;
}
@Override
public void touchDragged (InputEvent event, float x, float y, int pointer) {
if(follower.getMode() == NormalSelectionFollower.SelectionMode.normal) {
listenerResize.anchorDragged(follower, anchorId, event.getStageX(), event.getStageY());
}
if(follower.getMode() == NormalSelectionFollower.SelectionMode.transform) {
if(listenerTransform != null) listenerTransform.anchorDragged(follower, anchorId, event.getStageX(), event.getStageY());
}
}
@Override
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
if(follower.getMode() == NormalSelectionFollower.SelectionMode.normal) {
listenerResize.anchorUp(follower, anchorId, event.getStageX(), event.getStageY());
}
if(follower.getMode() == NormalSelectionFollower.SelectionMode.transform) {
if(listenerTransform != null) listenerTransform.anchorUp(follower, anchorId, event.getStageX(), event.getStageY());
}
}
@Override
public void enter (InputEvent event, float x, float y, int pointer, Actor fromActor) {
super.enter(event, x, y, pointer, fromActor);
if(follower.getMode() == NormalSelectionFollower.SelectionMode.normal) {
listenerResize.anchorMouseEnter(follower, anchorId, event.getStageX(), event.getStageY());
}
if(follower.getMode() == NormalSelectionFollower.SelectionMode.transform) {
if(listenerTransform != null) listenerTransform.anchorMouseEnter(follower, anchorId, event.getStageX(), event.getStageY());
}
}
@Override
public void exit (InputEvent event, float x, float y, int pointer, Actor toActor) {
super.exit(event, x, y, pointer, toActor);
if(follower.getMode() == NormalSelectionFollower.SelectionMode.normal) {
listenerResize.anchorMouseExit(follower, anchorId, event.getStageX(), event.getStageY());
}
if(follower.getMode() == NormalSelectionFollower.SelectionMode.transform) {
if(listenerTransform != null) listenerTransform.anchorMouseExit(follower, anchorId, event.getStageX(), event.getStageY());
}
}
}
|
3e0234a9493ee4f9f8d50c976994c967b5a4af6a | 545 | java | Java | java/MultiThreading/MultiThreadSleep.java | abhilashreddyy/My-internship-work-gitignore | 6040aa7c90dae38d5eb0bb21a1ae8a46e8151ab2 | [
"MIT"
] | null | null | null | java/MultiThreading/MultiThreadSleep.java | abhilashreddyy/My-internship-work-gitignore | 6040aa7c90dae38d5eb0bb21a1ae8a46e8151ab2 | [
"MIT"
] | null | null | null | java/MultiThreading/MultiThreadSleep.java | abhilashreddyy/My-internship-work-gitignore | 6040aa7c90dae38d5eb0bb21a1ae8a46e8151ab2 | [
"MIT"
] | null | null | null | 22.708333 | 93 | 0.653211 | 917 | class Threading1 extends Thread{
public void run() {
for(int i = 0; i < 5; i++) {
try {Thread.sleep(1000);}
catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String[] args) {
Threading1 t1 = new Threading1();
Threading1 t2 = new Threading1();
// if i call run it wont create a separate call stack it runs on main thread
// but start method creates a separate call stack which helps the program too run paralelly
t1.start();
t2.start();
}
}
|
3e02351f52646646eff31aeabe74398965a38a82 | 698 | java | Java | src/main/java/com/jsoniter/fuzzy/MaybeStringIntDecoder.java | alexquilliam/java | 411647c5a9e9fd2cee48cf29e4fed1ec8b29bd29 | [
"MIT"
] | 1,575 | 2016-12-09T12:02:42.000Z | 2022-03-27T05:11:57.000Z | src/main/java/com/jsoniter/fuzzy/MaybeStringIntDecoder.java | alexquilliam/java | 411647c5a9e9fd2cee48cf29e4fed1ec8b29bd29 | [
"MIT"
] | 281 | 2016-12-12T07:34:17.000Z | 2022-03-09T03:14:26.000Z | src/main/java/com/jsoniter/fuzzy/MaybeStringIntDecoder.java | alexquilliam/java | 411647c5a9e9fd2cee48cf29e4fed1ec8b29bd29 | [
"MIT"
] | 600 | 2016-12-12T00:37:25.000Z | 2022-03-25T13:40:17.000Z | 26.846154 | 92 | 0.624642 | 918 | package com.jsoniter.fuzzy;
import com.jsoniter.CodegenAccess;
import com.jsoniter.JsonIterator;
import com.jsoniter.spi.Decoder;
import java.io.IOException;
public class MaybeStringIntDecoder extends Decoder.IntDecoder {
@Override
public int decodeInt(JsonIterator iter) throws IOException {
byte c = CodegenAccess.nextToken(iter);
if (c != '"') {
CodegenAccess.unreadByte(iter);
return iter.readInt();
}
int val = iter.readInt();
c = CodegenAccess.nextToken(iter);
if (c != '"') {
throw iter.reportError("StringIntDecoder", "expect \", but found: " + (char) c);
}
return val;
}
}
|
3e02356649cc944c216789fd1e19d8d74948445a | 1,346 | java | Java | requestor/core/requestor-api/src/main/java/io/reinert/requestor/core/ProviderManager.java | heat/requestor | 1631d4ec9acd1b8420efc60074c8b54cf0a4fe84 | [
"Apache-2.0"
] | 45 | 2015-01-07T20:33:26.000Z | 2022-03-14T22:27:13.000Z | requestor/core/requestor-api/src/main/java/io/reinert/requestor/core/ProviderManager.java | heat/requestor | 1631d4ec9acd1b8420efc60074c8b54cf0a4fe84 | [
"Apache-2.0"
] | 73 | 2015-01-07T14:19:41.000Z | 2022-03-31T13:58:01.000Z | requestor/core/requestor-api/src/main/java/io/reinert/requestor/core/ProviderManager.java | heat/requestor | 1631d4ec9acd1b8420efc60074c8b54cf0a4fe84 | [
"Apache-2.0"
] | 14 | 2015-01-09T12:42:14.000Z | 2022-01-23T20:21:06.000Z | 29.911111 | 88 | 0.683507 | 919 | /*
* Copyright 2015-2021 Danilo Reinert
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reinert.requestor.core;
/**
* A container of {@link Provider}.
*
* @author Danilo Reinert
*/
public interface ProviderManager {
/**
* Register a {@link Provider}.
*
* @param type the type related to the provider
* @param provider the provider to register
*
* @return the {@link Registration} object, capable of cancelling this registration
*/
<T> Registration register(Class<T> type, Provider<T> provider);
/**
* Register a {@link TypeProvider}.
*
* @param provider the provider to register
*
* @return the {@link Registration} object, capable of cancelling this registration
*/
<T> Registration register(TypeProvider<T> provider);
}
|
3e0235b1d231a875b0216a0490fa74a3694e8f62 | 4,871 | java | Java | src/test/java/com/alphawallet/attestation/TestHelper.java | darakhbharat/blockchain-attestation | 5ab6174d3e17f209cca897d0ce91937ccf1d8ba0 | [
"MIT"
] | null | null | null | src/test/java/com/alphawallet/attestation/TestHelper.java | darakhbharat/blockchain-attestation | 5ab6174d3e17f209cca897d0ce91937ccf1d8ba0 | [
"MIT"
] | null | null | null | src/test/java/com/alphawallet/attestation/TestHelper.java | darakhbharat/blockchain-attestation | 5ab6174d3e17f209cca897d0ce91937ccf1d8ba0 | [
"MIT"
] | null | null | null | 45.90566 | 165 | 0.767365 | 920 | package com.alphawallet.attestation;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.alphawallet.attestation.IdentifierAttestation.AttestationType;
import com.alphawallet.attestation.core.AttestationCrypto;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Date;
import org.bouncycastle.asn1.ASN1Boolean;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;
public class TestHelper {
public static final int CHARS_IN_LINE = 65;
// public static KeyPair constructKeys(SecureRandom rand) throws Exception {
// Security.addProvider(new BouncyCastleProvider());
// KeyPairGenerator keyGen = KeyPairGenerator.getInstance(AttestationCrypto.SIGNATURE_ALG, "BC");
// ECGenParameterSpec ecSpec = new ECGenParameterSpec(AttestationCrypto.ECDSA_CURVE);
// keyGen.initialize(ecSpec, rand);
// return keyGen.generateKeyPair();
// }
public static IdentifierAttestation makeUnsignedStandardAtt(AsymmetricKeyParameter key, BigInteger secret) {
IdentifierAttestation att = new IdentifierAttestation("[email protected]", AttestationType.EMAIL, key, secret);
att.setIssuer("CN=ALX");
att.setSerialNumber(1);
Date now = new Date();
att.setNotValidBefore(now);
att.setNotValidAfter(new Date(System.currentTimeMillis() + 3600000)); // Valid for an hour
att.setSmartcontracts(Arrays.asList(42L, 1337L));
assertTrue(att.checkValidity());
assertFalse(att.isValidX509()); // Since the version is wrong, and algorithm is non-standard
return att;
}
/* the unsigned x509 attestation will have a subject of "CN=0x2042424242424564648" */
public static Attestation makeUnsignedx509Att(AsymmetricKeyParameter key) throws IOException {
Attestation att = new Attestation();
att.setVersion(2); // =v3 since counting starts from 0
att.setSerialNumber(42);
att.setSignature("1.2.840.10045.4.3.2"); // ECDSA with SHA256 which is needed for a proper x509
att.setIssuer("CN=ALX");
Date now = new Date();
att.setNotValidBefore(now);
att.setNotValidAfter(new Date(System.currentTimeMillis()+3600000)); // Valid for an hour
att.setSubject("CN=0x2042424242424564648");
SubjectPublicKeyInfo spki = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(key);
spki = new SubjectPublicKeyInfo(new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.2.840.10045.4.3.2")), // ECDSA with SHA256 which is needed for a proper x509
spki.getPublicKeyData());
att.setSubjectPublicKeyInfo(spki);
ASN1EncodableVector extensions = new ASN1EncodableVector();
extensions.add(new ASN1ObjectIdentifier(Attestation.OID_OCTETSTRING));
extensions.add(ASN1Boolean.TRUE);
extensions.add(new DEROctetString("hello world".getBytes()));
// Double Sequence is needed to be compatible with X509V3
att.setExtensions(new DERSequence(new DERSequence(extensions)));
assertTrue(att.isValidX509());
return att;
}
public static Attestation makeMaximalAtt(AsymmetricKeyParameter key) throws IOException {
Attestation att = new Attestation();
att.setVersion(18); // Our initial version
att.setSerialNumber(42);
att.setSignature(AttestationCrypto.OID_SIGNATURE_ALG);
att.setIssuer("CN=ALX");
Date now = new Date();
att.setNotValidBefore(now);
att.setNotValidAfter(new Date(System.currentTimeMillis()+3600000)); // Valid for an hour
att.setSubject("CN=0x2042424242424564648");
SubjectPublicKeyInfo spki = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(key);
att.setSubjectPublicKeyInfo(spki);
att.setSmartcontracts(Arrays.asList(42L, 1337L));
ASN1EncodableVector dataObject = new ASN1EncodableVector();
dataObject.add(new DEROctetString("hello world".getBytes()));
dataObject.add(new ASN1Integer(42));
att.setDataObject(new DERSequence(dataObject));
assertTrue(att.checkValidity());
return att;
}
public static Attestation makeMinimalAtt() {
Attestation att = new Attestation();
att.setVersion(18); // Our initial version
att.setSerialNumber(42);
att.setSignature(AttestationCrypto.OID_SIGNATURE_ALG);
ASN1EncodableVector dataObject = new ASN1EncodableVector();
dataObject.add(new DEROctetString("hello world".getBytes()));
att.setDataObject(new DERSequence(dataObject));
assertTrue(att.checkValidity());
return att;
}
}
|
3e02367b4611ecefa7164309dd14ab93ec3128fe | 3,446 | java | Java | src/main/java/com/cjunn/setool/core/monitor/sql/SQLInfo.java | cjunn/spring_atum | 40b2e3f270e9908817ab99498dbdad199f27f092 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/cjunn/setool/core/monitor/sql/SQLInfo.java | cjunn/spring_atum | 40b2e3f270e9908817ab99498dbdad199f27f092 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/cjunn/setool/core/monitor/sql/SQLInfo.java | cjunn/spring_atum | 40b2e3f270e9908817ab99498dbdad199f27f092 | [
"Apache-2.0"
] | null | null | null | 27.568 | 62 | 0.57632 | 921 | package com.cjunn.setool.core.monitor.sql;
/**
* @ClassName SQLInfo
* @Description TODO
* @Author cjunn
* @Date 2021/3/8 11:09
* @Version
*/
public class SQLInfo {
private String connectionId;
private String statementId;
private String transactionId;
private String executeSqlText;
@Override
public String toString() {
return "SQLInfo{" +
"connectionId='" + connectionId + '\'' +
", statementId='" + statementId + '\'' +
", transactionId='" + transactionId + '\'' +
", executeSqlText='" + executeSqlText + '\'' +
", executeType='" + executeType + '\'' +
", executeTimeNano=" + executeTimeNano +
", executeStartNano=" + executeStartNano +
'}';
}
private String executeType;
private Long executeTimeNano;
private Long executeStartNano;
public static SQLInfo of(String connectionId,
String statementId,
String transactionId,
String executeSqlText,
String executeType,
Long executeTimeNano,
Long executeStartNano){
return new SQLInfo(connectionId,
statementId,
transactionId,
executeSqlText,
executeType,
executeTimeNano,
executeStartNano);
}
public SQLInfo(
String connectionId,
String statementId,
String transactionId,
String executeSqlText,
String executeType,
Long executeTimeNano,
Long executeStartNano) {
this.connectionId = connectionId;
this.statementId = statementId;
this.transactionId = transactionId;
this.executeSqlText = executeSqlText;
this.executeTimeNano = executeTimeNano;
this.executeStartNano = executeStartNano;
this.executeType=executeType;
}
public String getExecuteType() {
return executeType;
}
public void setExecuteType(String executeType) {
this.executeType = executeType;
}
public String getConnectionId() {
return connectionId;
}
public void setConnectionId(String connectionId) {
this.connectionId = connectionId;
}
public String getStatementId() {
return statementId;
}
public void setStatementId(String statementId) {
this.statementId = statementId;
}
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public String getExecuteSqlText() {
return executeSqlText;
}
public void setExecuteSqlText(String executeSqlText) {
this.executeSqlText = executeSqlText;
}
public Long getExecuteTimeNano() {
return executeTimeNano;
}
public void setExecuteTimeNano(Long executeTimeNano) {
this.executeTimeNano = executeTimeNano;
}
public Long getExecuteStartNano() {
return executeStartNano;
}
public void setExecuteStartNano(Long executeStartNano) {
this.executeStartNano = executeStartNano;
}
}
|
3e0236c4f560b455c71222a34c4f564f912b7f75 | 16,482 | java | Java | test/hotspot/jtreg/vmTestbase/nsk/jdi/ObjectReference/invokeMethod/invokemethod008.java | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | 2 | 2018-06-19T05:43:32.000Z | 2018-06-23T10:04:56.000Z | test/hotspot/jtreg/vmTestbase/nsk/jdi/ObjectReference/invokeMethod/invokemethod008.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | null | null | null | test/hotspot/jtreg/vmTestbase/nsk/jdi/ObjectReference/invokeMethod/invokemethod008.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | null | null | null | 44.545946 | 119 | 0.541743 | 922 | /*
* Copyright (c) 2002, 2018, 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 nsk.jdi.ObjectReference.invokeMethod;
import com.sun.jdi.*;
import com.sun.jdi.event.*;
import com.sun.jdi.request.*;
import java.util.*;
import java.io.*;
import nsk.share.*;
import nsk.share.jpda.*;
import nsk.share.jdi.*;
/**
* The test checks that virtual and non-virtual method invocation
* will be performed properly through the JDI method
* <code>com.sun.jdi.ObjectReference.invokeMethod()</code>.<br>
* A debugger part of the test invokes several debuggee methods,
* overriden in an object reference class, but obtained from
* a reference type of its superclass. The debugger calls the
* JDI method without and with the flag <i>ObjectReference.INVOKE_NONVIRTUAL</i>
* sequentially. It is expected, that methods from the object reference
* class instead of from the superclass will be invoked without
* the flag <i>INVOKE_NONVIRTUAL</i> and vise versa otherwise.
*/
public class invokemethod008 {
// debuggee classes
static final String DEBUGGEE_CLASSES[] = {
"nsk.jdi.ObjectReference.invokeMethod.invokemethod008t",
"nsk.jdi.ObjectReference.invokeMethod.invokemethod008tDummySuperClass",
"nsk.jdi.ObjectReference.invokeMethod.invokemethod008tDummySuperSuperClass"
};
// name of debuggee main thread
static final String DEBUGGEE_THRNAME = "invokemethod008tThr";
// debuggee source line where it should be stopped
static final int DEBUGGEE_STOPATLINE = 69;
// debuggee local var used to find needed stack frame
static final String DEBUGGEE_LOCALVAR =
"invokemethod008tdummyCls";
// tested debuggee methods to be invoked, reference type numbers
// and expected return values
static final int METH_NUM = 4;
static final String DEBUGGEE_METHODS[][] = {
{"longProtMeth", "1", "9223372036854775806"},
{"longMeth", "1", "9223372036854775806"},
{"longProtMeth", "2", "9223372036854775805"},
{"longMeth", "2", "9223372036854775805"}
};
static final int TIMEOUT_DELTA = 1000; // in milliseconds
static final String COMMAND_READY = "ready";
static final String COMMAND_GO = "go";
static final String COMMAND_QUIT = "quit";
private ArgumentHandler argHandler;
private Log log;
private IOPipe pipe;
private Debugee debuggee;
private VirtualMachine vm;
private ThreadReference thrRef = null;
private BreakpointRequest BPreq;
private volatile int tot_res = Consts.TEST_PASSED;
private volatile boolean gotEvent = false;
public static void main (String argv[]) {
System.exit(run(argv,System.out) + Consts.JCK_STATUS_BASE);
}
public static int run(String argv[], PrintStream out) {
return new invokemethod008().runIt(argv, out);
}
private int runIt(String args[], PrintStream out) {
argHandler = new ArgumentHandler(args);
log = new Log(out, argHandler);
Binder binder = new Binder(argHandler, log);
String cmd;
int num = 0;
debuggee = binder.bindToDebugee(DEBUGGEE_CLASSES[0]);
pipe = debuggee.createIOPipe();
vm = debuggee.VM();
debuggee.redirectStderr(log, "invokemethod008t.err> ");
debuggee.resume();
cmd = pipe.readln();
if (!cmd.equals(COMMAND_READY)) {
log.complain("TEST BUG: unknown debuggee command: " + cmd);
tot_res = Consts.TEST_FAILED;
return quitDebuggee();
}
if ((thrRef =
debuggee.threadByName(DEBUGGEE_THRNAME)) == null) {
log.complain("TEST FAILURE: Method Debugee.threadByName() returned null for debuggee thread "
+ DEBUGGEE_THRNAME);
tot_res = Consts.TEST_FAILED;
return quitDebuggee();
}
ReferenceType[] rType = new ReferenceType[3];
// reference types of debuggee main & dummy classes
rType[0] = debuggee.classByName(DEBUGGEE_CLASSES[0]);
rType[1] = debuggee.classByName(DEBUGGEE_CLASSES[1]);
rType[2] = debuggee.classByName(DEBUGGEE_CLASSES[2]);
// Check the tested assersion
try {
suspendAtBP(rType[0], DEBUGGEE_STOPATLINE);
ObjectReference objRef = findObjRef(DEBUGGEE_LOCALVAR);
for (int i=0; i<METH_NUM; i++) {
// get reference type # from DEBUGGEE_METHODS[i][1]
int typeIndex = Integer.parseInt(DEBUGGEE_METHODS[i][1]);
// get expected return value from DEBUGGEE_METHODS[i][2]
long expValue = Long.parseLong(DEBUGGEE_METHODS[i][2]);
// get method to be invoked from DEBUGGEE_METHODS[i][0]
List methList = rType[typeIndex].methodsByName(DEBUGGEE_METHODS[i][0]);
if (methList.isEmpty()) {
log.complain("TEST FAILURE: the expected debuggee method \""
+ DEBUGGEE_METHODS[i]
+ "\" not found through the JDI method ReferenceType.methodsByName()");
tot_res = Consts.TEST_FAILED;
continue;
}
Method meth = (Method) methList.get(0);
LinkedList<Value> argList = new LinkedList<Value>();
argList.add(vm.mirrorOf(9223372036854775807L));
try {
log.display("\n\n1) Trying to invoke the method \""
+ meth.name() + " " + meth.signature() + " " + meth
+ "\"\n\tgot from reference type \"" + rType[typeIndex]
+ "\"\n\twith the arguments: " + argList
+ " and without the flag ObjectReference.INVOKE_NONVIRTUAL"
+ "\n\tusing the debuggee object reference \""
+ objRef + "\" ...");
LongValue retVal = (LongValue)
objRef.invokeMethod(thrRef, meth, argList, 0);
if (retVal.value() == 9223372036854775807L) {
log.display("CHECK PASSED: the invoked method returns: " + retVal.value()
+ " as expected");
}
else {
log.complain("TEST FAILED: wrong virtual invocation: the method \""
+ meth.name() + " " + meth.signature()
+ "\"\n\tgot from reference type \"" + rType[typeIndex]
+ "\"\n\tinvoked with the arguments: " + argList
+ " and without the flag ObjectReference.INVOKE_NONVIRTUAL"
+ "\"\n\tusing the debuggee object reference \"" + objRef
+ "\" returned: " + retVal.value()
+ " instead of 9223372036854775807L as expected");
tot_res = Consts.TEST_FAILED;
}
log.display("\n2) Trying to invoke the method \""
+ meth.name() + " " + meth.signature() + " " + meth
+ "\"\n\tgot from reference type \"" + rType[typeIndex]
+ "\"\n\twith the arguments: " + argList
+ " and with the flag ObjectReference.INVOKE_NONVIRTUAL"
+ "\n\tusing the debuggee object reference \""
+ objRef + "\" ...");
LongValue retVal2 = (LongValue)
objRef.invokeMethod(thrRef, meth, argList,
ObjectReference.INVOKE_NONVIRTUAL);
if (retVal2.value() != expValue) {
log.complain("TEST FAILED: wrong non-virtual invocation: the method \""
+ meth.name() + " " + meth.signature()
+ "\"\n\tgot from reference type \"" + rType[typeIndex]
+ "\"\n\tinvoked with the arguments: " + argList
+ " and with the flag ObjectReference.INVOKE_NONVIRTUAL"
+ "\"\n\tusing the debuggee object reference \"" + objRef
+ "\",\n\treturns: " + retVal2.value()
+ " instead of " + expValue + " as expected");
tot_res = Consts.TEST_FAILED;
}
else
log.display("CHECK PASSED: the method invoked with ObjectReference.INVOKE_NONVIRTUAL returns: "
+ retVal2.value() + " as expected");
} catch (Exception ee) {
ee.printStackTrace();
log.complain("TEST FAILED: ObjectReference.invokeMethod(): caught unexpected "
+ ee + "\n\twhen attempted to invoke the method \""
+ meth.name() + " " + meth.signature()
+ "\"\n\tgot from reference type \"" + rType[typeIndex]
+ "\"\n\twith the arguments: " + argList
+ "\"\n\tusing the debuggee object reference \""
+ objRef + "\"");
tot_res = Consts.TEST_FAILED;
}
}
} catch (Exception e) {
e.printStackTrace();
log.complain("TEST FAILURE: caught unexpected exception: " + e);
tot_res = Consts.TEST_FAILED;
}
// Finish the test
return quitDebuggee();
}
private ObjectReference findObjRef(String varName) {
try {
List frames = thrRef.frames();
Iterator iter = frames.iterator();
while (iter.hasNext()) {
StackFrame stackFr = (StackFrame) iter.next();
try {
LocalVariable locVar = stackFr.visibleVariableByName(varName);
if (locVar == null) continue;
// dummy debuggee class
return (ObjectReference)stackFr.getValue(locVar);
} catch(AbsentInformationException e) {
// this is not needed stack frame, ignoring
} catch(NativeMethodException ne) {
// current method is native, also ignoring
}
}
} catch (Exception e) {
e.printStackTrace();
tot_res = Consts.TEST_FAILED;
throw new Failure("findObjRef: caught unexpected exception: " + e);
}
throw new Failure("findObjRef: needed debuggee stack frame not found");
}
private BreakpointRequest setBP(ReferenceType refType, int bpLine) {
EventRequestManager evReqMan =
debuggee.getEventRequestManager();
Location loc;
try {
List locations = refType.allLineLocations();
Iterator iter = locations.iterator();
while (iter.hasNext()) {
loc = (Location) iter.next();
if (loc.lineNumber() == bpLine) {
BreakpointRequest BPreq =
evReqMan.createBreakpointRequest(loc);
log.display("created " + BPreq + "\n\tfor " + refType
+ " ; line=" + bpLine);
return BPreq;
}
}
} catch (Exception e) {
e.printStackTrace();
throw new Failure("setBP: caught unexpected exception: " + e);
}
throw new Failure("setBP: location corresponding debuggee source line "
+ bpLine + " not found");
}
private void suspendAtBP(ReferenceType rType, int bpLine) {
// Class containing a critical section which may lead to time out of the test
class CriticalSection extends Thread {
public volatile boolean waitFor = true;
public void run() {
try {
do {
EventSet eventSet = vm.eventQueue().remove(TIMEOUT_DELTA);
if (eventSet != null) { // it is not a timeout
EventIterator it = eventSet.eventIterator();
while (it.hasNext()) {
Event event = it.nextEvent();
if (event instanceof VMDisconnectEvent) {
log.complain("TEST FAILED: unexpected VMDisconnectEvent");
break;
} else if (event instanceof VMDeathEvent) {
log.complain("TEST FAILED: unexpected VMDeathEvent");
break;
} else if (event instanceof BreakpointEvent) {
if (event.request().equals(BPreq)) {
log.display("expected Breakpoint event occured: "
+ event.toString());
gotEvent = true;
return;
}
} else
log.display("following JDI event occured: "
+ event.toString());
}
}
} while(waitFor);
log.complain("TEST FAILED: no expected Breakpoint event");
tot_res = Consts.TEST_FAILED;
} catch (Exception e) {
e.printStackTrace();
tot_res = Consts.TEST_FAILED;
log.complain("TEST FAILED: caught unexpected exception: " + e);
}
}
}
/////////////////////////////////////////////////////////////////////////////
BPreq = setBP(rType, bpLine);
BPreq.enable();
CriticalSection critSect = new CriticalSection();
log.display("\nStarting potential timed out section:\n\twaiting "
+ (argHandler.getWaitTime())
+ " minute(s) for JDI Breakpoint event ...\n");
critSect.start();
pipe.println(COMMAND_GO);
try {
critSect.join((argHandler.getWaitTime())*60000);
if (critSect.isAlive()) {
critSect.waitFor = false;
throw new Failure("timeout occured while waiting for Breakpoint event");
}
} catch (InterruptedException e) {
critSect.waitFor = false;
throw new Failure("TEST INCOMPLETE: InterruptedException occured while waiting for Breakpoint event");
} finally {
BPreq.disable();
}
log.display("\nPotential timed out section successfully passed\n");
if (gotEvent == false)
throw new Failure("unable to suspend debuggee thread at breakpoint");
}
private int quitDebuggee() {
vm.resume();
pipe.println(COMMAND_QUIT);
debuggee.waitFor();
int debStat = debuggee.getStatus();
if (debStat != (Consts.JCK_STATUS_BASE + Consts.TEST_PASSED)) {
log.complain("TEST FAILED: debuggee process finished with status: "
+ debStat);
tot_res = Consts.TEST_FAILED;
} else
log.display("\nDebuggee process finished with the status: "
+ debStat);
return tot_res;
}
}
|
3e023731659a0ad7f21d70dcf8867792f95387fd | 4,890 | java | Java | Data/Juliet-Java/Juliet-Java-v103/000/132/458/CWE191_Integer_Underflow__long_rand_sub_12.java | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | Data/Juliet-Java/Juliet-Java-v103/000/132/458/CWE191_Integer_Underflow__long_rand_sub_12.java | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | Data/Juliet-Java/Juliet-Java-v103/000/132/458/CWE191_Integer_Underflow__long_rand_sub_12.java | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | 30.185185 | 128 | 0.534765 | 923 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE191_Integer_Underflow__long_rand_sub_12.java
Label Definition File: CWE191_Integer_Underflow.label.xml
Template File: sources-sinks-12.tmpl.java
*/
/*
* @description
* CWE: 191 Integer Underflow
* BadSource: rand Set data to result of rand()
* GoodSource: A hardcoded non-zero, non-min, non-max, even number
* Sinks: sub
* GoodSink: Ensure there will not be an underflow before subtracting 1 from data
* BadSink : Subtract 1 from data, which can cause an Underflow
* Flow Variant: 12 Control flow: if(IO.staticReturnsTrueOrFalse())
*
* */
public class CWE191_Integer_Underflow__long_rand_sub_12 extends AbstractTestCase
{
public void bad() throws Throwable
{
long data;
if(IO.staticReturnsTrueOrFalse())
{
/* POTENTIAL FLAW: Use a random value */
data = (new java.security.SecureRandom()).nextLong();
}
else
{
/* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */
data = 2;
}
if(IO.staticReturnsTrueOrFalse())
{
/* POTENTIAL FLAW: if data == Long.MIN_VALUE, this will overflow */
long result = (long)(data - 1);
IO.writeLine("result: " + result);
}
else
{
/* FIX: Add a check to prevent an overflow from occurring */
if (data > Long.MIN_VALUE)
{
long result = (long)(data - 1);
IO.writeLine("result: " + result);
}
else
{
IO.writeLine("data value is too small to perform subtraction.");
}
}
}
/* goodG2B() - use goodsource and badsink by changing the first "if" so that
* both branches use the GoodSource */
private void goodG2B() throws Throwable
{
long data;
if(IO.staticReturnsTrueOrFalse())
{
/* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */
data = 2;
}
else
{
/* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */
data = 2;
}
if(IO.staticReturnsTrueOrFalse())
{
/* POTENTIAL FLAW: if data == Long.MIN_VALUE, this will overflow */
long result = (long)(data - 1);
IO.writeLine("result: " + result);
}
else
{
/* POTENTIAL FLAW: if data == Long.MIN_VALUE, this will overflow */
long result = (long)(data - 1);
IO.writeLine("result: " + result);
}
}
/* goodB2G() - use badsource and goodsink by changing the second "if" so that
* both branches use the GoodSink */
private void goodB2G() throws Throwable
{
long data;
if(IO.staticReturnsTrueOrFalse())
{
/* POTENTIAL FLAW: Use a random value */
data = (new java.security.SecureRandom()).nextLong();
}
else
{
/* POTENTIAL FLAW: Use a random value */
data = (new java.security.SecureRandom()).nextLong();
}
if(IO.staticReturnsTrueOrFalse())
{
/* FIX: Add a check to prevent an overflow from occurring */
if (data > Long.MIN_VALUE)
{
long result = (long)(data - 1);
IO.writeLine("result: " + result);
}
else
{
IO.writeLine("data value is too small to perform subtraction.");
}
}
else
{
/* FIX: Add a check to prevent an overflow from occurring */
if (data > Long.MIN_VALUE)
{
long result = (long)(data - 1);
IO.writeLine("result: " + result);
}
else
{
IO.writeLine("data value is too small to perform subtraction.");
}
}
}
public void good() throws Throwable
{
goodG2B();
goodB2G();
}
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
|
3e0237e411aa398d24575070c70ed031b591c422 | 9,951 | java | Java | work/decompile-e0c6d16a/net/minecraft/world/entity/monster/EntitySkeletonAbstract.java | jacobo-mc/spigot_1.18 | 03d238eebaeab66357e75987e8fb4403e0c85960 | [
"MIT"
] | null | null | null | work/decompile-e0c6d16a/net/minecraft/world/entity/monster/EntitySkeletonAbstract.java | jacobo-mc/spigot_1.18 | 03d238eebaeab66357e75987e8fb4403e0c85960 | [
"MIT"
] | null | null | null | work/decompile-e0c6d16a/net/minecraft/world/entity/monster/EntitySkeletonAbstract.java | jacobo-mc/spigot_1.18 | 03d238eebaeab66357e75987e8fb4403e0c85960 | [
"MIT"
] | null | null | null | 41.635983 | 225 | 0.707869 | 924 | package net.minecraft.world.entity.monster;
import java.time.LocalDate;
import java.time.temporal.ChronoField;
import javax.annotation.Nullable;
import net.minecraft.core.BlockPosition;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.sounds.SoundEffect;
import net.minecraft.sounds.SoundEffects;
import net.minecraft.world.DifficultyDamageScaler;
import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.entity.EntityCreature;
import net.minecraft.world.entity.EntityLiving;
import net.minecraft.world.entity.EntityPose;
import net.minecraft.world.entity.EntitySize;
import net.minecraft.world.entity.EntityTypes;
import net.minecraft.world.entity.EnumItemSlot;
import net.minecraft.world.entity.EnumMobSpawn;
import net.minecraft.world.entity.EnumMonsterType;
import net.minecraft.world.entity.GroupDataEntity;
import net.minecraft.world.entity.ai.attributes.AttributeProvider;
import net.minecraft.world.entity.ai.attributes.GenericAttributes;
import net.minecraft.world.entity.ai.goal.PathfinderGoalAvoidTarget;
import net.minecraft.world.entity.ai.goal.PathfinderGoalBowShoot;
import net.minecraft.world.entity.ai.goal.PathfinderGoalFleeSun;
import net.minecraft.world.entity.ai.goal.PathfinderGoalLookAtPlayer;
import net.minecraft.world.entity.ai.goal.PathfinderGoalMeleeAttack;
import net.minecraft.world.entity.ai.goal.PathfinderGoalRandomLookaround;
import net.minecraft.world.entity.ai.goal.PathfinderGoalRandomStrollLand;
import net.minecraft.world.entity.ai.goal.PathfinderGoalRestrictSun;
import net.minecraft.world.entity.ai.goal.target.PathfinderGoalHurtByTarget;
import net.minecraft.world.entity.ai.goal.target.PathfinderGoalNearestAttackableTarget;
import net.minecraft.world.entity.animal.EntityIronGolem;
import net.minecraft.world.entity.animal.EntityTurtle;
import net.minecraft.world.entity.animal.EntityWolf;
import net.minecraft.world.entity.player.EntityHuman;
import net.minecraft.world.entity.projectile.EntityArrow;
import net.minecraft.world.entity.projectile.ProjectileHelper;
import net.minecraft.world.item.ItemProjectileWeapon;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.World;
import net.minecraft.world.level.WorldAccess;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.IBlockData;
public abstract class EntitySkeletonAbstract extends EntityMonster implements IRangedEntity {
private final PathfinderGoalBowShoot<EntitySkeletonAbstract> bowGoal = new PathfinderGoalBowShoot<>(this, 1.0D, 20, 15.0F);
private final PathfinderGoalMeleeAttack meleeGoal = new PathfinderGoalMeleeAttack(this, 1.2D, false) {
@Override
public void stop() {
super.stop();
EntitySkeletonAbstract.this.setAggressive(false);
}
@Override
public void start() {
super.start();
EntitySkeletonAbstract.this.setAggressive(true);
}
};
protected EntitySkeletonAbstract(EntityTypes<? extends EntitySkeletonAbstract> entitytypes, World world) {
super(entitytypes, world);
this.reassessWeaponGoal();
}
@Override
protected void registerGoals() {
this.goalSelector.addGoal(2, new PathfinderGoalRestrictSun(this));
this.goalSelector.addGoal(3, new PathfinderGoalFleeSun(this, 1.0D));
this.goalSelector.addGoal(3, new PathfinderGoalAvoidTarget<>(this, EntityWolf.class, 6.0F, 1.0D, 1.2D));
this.goalSelector.addGoal(5, new PathfinderGoalRandomStrollLand(this, 1.0D));
this.goalSelector.addGoal(6, new PathfinderGoalLookAtPlayer(this, EntityHuman.class, 8.0F));
this.goalSelector.addGoal(6, new PathfinderGoalRandomLookaround(this));
this.targetSelector.addGoal(1, new PathfinderGoalHurtByTarget(this, new Class[0]));
this.targetSelector.addGoal(2, new PathfinderGoalNearestAttackableTarget<>(this, EntityHuman.class, true));
this.targetSelector.addGoal(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityIronGolem.class, true));
this.targetSelector.addGoal(3, new PathfinderGoalNearestAttackableTarget<>(this, EntityTurtle.class, 10, true, false, EntityTurtle.BABY_ON_LAND_SELECTOR));
}
public static AttributeProvider.Builder createAttributes() {
return EntityMonster.createMonsterAttributes().add(GenericAttributes.MOVEMENT_SPEED, 0.25D);
}
@Override
protected void playStepSound(BlockPosition blockposition, IBlockData iblockdata) {
this.playSound(this.getStepSound(), 0.15F, 1.0F);
}
abstract SoundEffect getStepSound();
@Override
public EnumMonsterType getMobType() {
return EnumMonsterType.UNDEAD;
}
@Override
public void aiStep() {
boolean flag = this.isSunBurnTick();
if (flag) {
ItemStack itemstack = this.getItemBySlot(EnumItemSlot.HEAD);
if (!itemstack.isEmpty()) {
if (itemstack.isDamageableItem()) {
itemstack.setDamageValue(itemstack.getDamageValue() + this.random.nextInt(2));
if (itemstack.getDamageValue() >= itemstack.getMaxDamage()) {
this.broadcastBreakEvent(EnumItemSlot.HEAD);
this.setItemSlot(EnumItemSlot.HEAD, ItemStack.EMPTY);
}
}
flag = false;
}
if (flag) {
this.setSecondsOnFire(8);
}
}
super.aiStep();
}
@Override
public void rideTick() {
super.rideTick();
if (this.getVehicle() instanceof EntityCreature) {
EntityCreature entitycreature = (EntityCreature) this.getVehicle();
this.yBodyRot = entitycreature.yBodyRot;
}
}
@Override
protected void populateDefaultEquipmentSlots(DifficultyDamageScaler difficultydamagescaler) {
super.populateDefaultEquipmentSlots(difficultydamagescaler);
this.setItemSlot(EnumItemSlot.MAINHAND, new ItemStack(Items.BOW));
}
@Nullable
@Override
public GroupDataEntity finalizeSpawn(WorldAccess worldaccess, DifficultyDamageScaler difficultydamagescaler, EnumMobSpawn enummobspawn, @Nullable GroupDataEntity groupdataentity, @Nullable NBTTagCompound nbttagcompound) {
groupdataentity = super.finalizeSpawn(worldaccess, difficultydamagescaler, enummobspawn, groupdataentity, nbttagcompound);
this.populateDefaultEquipmentSlots(difficultydamagescaler);
this.populateDefaultEquipmentEnchantments(difficultydamagescaler);
this.reassessWeaponGoal();
this.setCanPickUpLoot(this.random.nextFloat() < 0.55F * difficultydamagescaler.getSpecialMultiplier());
if (this.getItemBySlot(EnumItemSlot.HEAD).isEmpty()) {
LocalDate localdate = LocalDate.now();
int i = localdate.get(ChronoField.DAY_OF_MONTH);
int j = localdate.get(ChronoField.MONTH_OF_YEAR);
if (j == 10 && i == 31 && this.random.nextFloat() < 0.25F) {
this.setItemSlot(EnumItemSlot.HEAD, new ItemStack(this.random.nextFloat() < 0.1F ? Blocks.JACK_O_LANTERN : Blocks.CARVED_PUMPKIN));
this.armorDropChances[EnumItemSlot.HEAD.getIndex()] = 0.0F;
}
}
return groupdataentity;
}
public void reassessWeaponGoal() {
if (this.level != null && !this.level.isClientSide) {
this.goalSelector.removeGoal(this.meleeGoal);
this.goalSelector.removeGoal(this.bowGoal);
ItemStack itemstack = this.getItemInHand(ProjectileHelper.getWeaponHoldingHand(this, Items.BOW));
if (itemstack.is(Items.BOW)) {
byte b0 = 20;
if (this.level.getDifficulty() != EnumDifficulty.HARD) {
b0 = 40;
}
this.bowGoal.setMinAttackInterval(b0);
this.goalSelector.addGoal(4, this.bowGoal);
} else {
this.goalSelector.addGoal(4, this.meleeGoal);
}
}
}
@Override
public void performRangedAttack(EntityLiving entityliving, float f) {
ItemStack itemstack = this.getProjectile(this.getItemInHand(ProjectileHelper.getWeaponHoldingHand(this, Items.BOW)));
EntityArrow entityarrow = this.getArrow(itemstack, f);
double d0 = entityliving.getX() - this.getX();
double d1 = entityliving.getY(0.3333333333333333D) - entityarrow.getY();
double d2 = entityliving.getZ() - this.getZ();
double d3 = Math.sqrt(d0 * d0 + d2 * d2);
entityarrow.shoot(d0, d1 + d3 * 0.20000000298023224D, d2, 1.6F, (float) (14 - this.level.getDifficulty().getId() * 4));
this.playSound(SoundEffects.SKELETON_SHOOT, 1.0F, 1.0F / (this.getRandom().nextFloat() * 0.4F + 0.8F));
this.level.addFreshEntity(entityarrow);
}
protected EntityArrow getArrow(ItemStack itemstack, float f) {
return ProjectileHelper.getMobArrow(this, itemstack, f);
}
@Override
public boolean canFireProjectileWeapon(ItemProjectileWeapon itemprojectileweapon) {
return itemprojectileweapon == Items.BOW;
}
@Override
public void readAdditionalSaveData(NBTTagCompound nbttagcompound) {
super.readAdditionalSaveData(nbttagcompound);
this.reassessWeaponGoal();
}
@Override
public void setItemSlot(EnumItemSlot enumitemslot, ItemStack itemstack) {
super.setItemSlot(enumitemslot, itemstack);
if (!this.level.isClientSide) {
this.reassessWeaponGoal();
}
}
@Override
protected float getStandingEyeHeight(EntityPose entitypose, EntitySize entitysize) {
return 1.74F;
}
@Override
public double getMyRidingOffset() {
return -0.6D;
}
public boolean isShaking() {
return this.isFullyFrozen();
}
}
|
3e023926b5a940277ea06be05fe228b485dae94f | 1,283 | java | Java | snaker-core/src/main/java/org/snaker/engine/impl/DefaultNoGenerator.java | f3226912/snaker | 68b2ad62721087dc33bdc7c83f8d7cfa5ccc652d | [
"Apache-2.0"
] | null | null | null | snaker-core/src/main/java/org/snaker/engine/impl/DefaultNoGenerator.java | f3226912/snaker | 68b2ad62721087dc33bdc7c83f8d7cfa5ccc652d | [
"Apache-2.0"
] | null | null | null | snaker-core/src/main/java/org/snaker/engine/impl/DefaultNoGenerator.java | f3226912/snaker | 68b2ad62721087dc33bdc7c83f8d7cfa5ccc652d | [
"Apache-2.0"
] | null | null | null | 29.837209 | 75 | 0.740452 | 925 | /* Copyright 2013-2015 www.snakerflow.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.snaker.engine.impl;
import java.io.Serializable;
import java.util.Random;
import org.joda.time.DateTime;
import org.snaker.engine.INoGenerator;
import org.snaker.engine.model.ProcessModel;
/**
* 默认的流程实例编号生成器
* 编号生成规则为:yyyyMMdd-HH:mm:ss-SSS-random
* @author yuqs
* @since 1.0
*/
public class DefaultNoGenerator implements INoGenerator,Serializable {
/**
*
*/
private static final long serialVersionUID = 1264032817553607213L;
public String generate(ProcessModel model) {
DateTime dateTime = new DateTime();
String time = dateTime.toString("yyyyMMdd-HH:mm:ss-SSS");
Random random = new Random();
return time + "-" + random.nextInt(1000);
}
}
|
3e0239854299c916ab9981969e90a04aed2bf86b | 3,127 | java | Java | icecp-node/src/test/java/com/intel/icecp/node/utils/JarUtilsTest.java | epylar/icecp | d5a6f5a52dfd8008cbd6f9c57481f9edaf49d92c | [
"Apache-2.0"
] | 5 | 2017-07-12T19:50:48.000Z | 2021-05-06T09:22:07.000Z | icecp-node/src/test/java/com/intel/icecp/node/utils/JarUtilsTest.java | epylar/icecp | d5a6f5a52dfd8008cbd6f9c57481f9edaf49d92c | [
"Apache-2.0"
] | null | null | null | icecp-node/src/test/java/com/intel/icecp/node/utils/JarUtilsTest.java | epylar/icecp | d5a6f5a52dfd8008cbd6f9c57481f9edaf49d92c | [
"Apache-2.0"
] | 4 | 2017-04-03T14:55:24.000Z | 2021-11-11T22:48:06.000Z | 37.22619 | 211 | 0.709946 | 926 | /*
* Copyright (c) 2017 Intel Corporation
*
* 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.intel.icecp.node.utils;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.lang.reflect.Array;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import com.intel.icecp.node.management.JarUtils;
/**
*/
public class JarUtilsTest {
private static final Logger LOGGER = LogManager.getLogger();
@Test
public void testGetClassByteCode() throws IOException {
byte[] byteCode = JarUtils.getClassByteCode(JarUtilsTest.class);
String byteCodeAsString = new String(byteCode);
LOGGER.debug("Generated byte code: {}", byteCodeAsString);
String classNameAsByteCode = 'L' + JarUtilsTest.class.getCanonicalName().replace('.', '/') + ';'; // see http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.3.2
assertTrue(new String(byteCode).contains(classNameAsByteCode));
}
@Test
public void testGetClassByteCodeOfInnerClass() throws IOException {
byte[] byteCode = JarUtils.getClassByteCode(X.class);
String byteCodeAsString = new String(byteCode);
LOGGER.debug("Generated byte code: {}", byteCodeAsString);
String classNameAsByteCode = 'L' + JarUtilsTest.class.getCanonicalName().replace('.', '/') + '$' + X.class.getSimpleName(); // see http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.3.2
assertTrue(byteCodeAsString.contains(classNameAsByteCode));
}
@Test
public void testBuildJar() throws IOException {
byte[] bytes = JarUtils.buildJar(JarUtilsTest.class, JarUtils.class, IOException.class);
String jarBytesAsString = new String(bytes);
LOGGER.debug("Generated byte code: {}", jarBytesAsString);
assertTrue(jarBytesAsString.contains(JarUtilsTest.class.getSimpleName()));
assertTrue(jarBytesAsString.contains(JarUtils.class.getSimpleName()));
assertTrue(jarBytesAsString.contains(IOException.class.getSimpleName()));
}
@Test
public void testBuildJarClassesWithNullEntriesDoesNotThrowNullPointerException() throws IOException {
Class<String>[] classArray = (Class<String>[]) Array.newInstance(Class.class, 10);
Class<String> clazz = String.class;
classArray[0] = clazz;
JarUtils.buildJar(classArray);
// no assert needed; if we get through this, we haven't thrown an NPE
}
private class X {
// do nothing
}
}
|
3e023ad01a36eeab4201df7588a594208349a101 | 553 | java | Java | src/main/java/io/dactilo/sumbawa/spring/ical/converter/api/attendees/ICalEventChair.java | Dactilo/spring-ical | 4a8d258e3fed2442c3f9de348eeeaf5a5dea3532 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/dactilo/sumbawa/spring/ical/converter/api/attendees/ICalEventChair.java | Dactilo/spring-ical | 4a8d258e3fed2442c3f9de348eeeaf5a5dea3532 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/dactilo/sumbawa/spring/ical/converter/api/attendees/ICalEventChair.java | Dactilo/spring-ical | 4a8d258e3fed2442c3f9de348eeeaf5a5dea3532 | [
"Apache-2.0"
] | null | null | null | 27.65 | 75 | 0.804702 | 927 | package io.dactilo.sumbawa.spring.ical.converter.api.attendees;
import io.dactilo.sumbawa.spring.ical.converter.api.ICalendarEvent;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Specifies which getter represents the chair of an {@link ICalendarEvent}
*/
@Retention(value = RUNTIME)
@Target(value = {METHOD})
@Documented
public @interface ICalEventChair {
} |
3e023c4ae87c6c5f5b10cf18685d94e9bc8beb0b | 16,686 | java | Java | duct/src/main/java/com/salesforce/pyplyn/duct/etl/extract/argus/ArgusExtractProcessor.java | archbobo/pyplyn | 1787882801594db40fe8fef30445c4b708032956 | [
"BSD-3-Clause"
] | 17 | 2017-01-27T18:24:01.000Z | 2019-08-15T08:39:19.000Z | duct/src/main/java/com/salesforce/pyplyn/duct/etl/extract/argus/ArgusExtractProcessor.java | archbobo/pyplyn | 1787882801594db40fe8fef30445c4b708032956 | [
"BSD-3-Clause"
] | 4 | 2017-05-11T15:58:35.000Z | 2018-08-11T03:09:21.000Z | duct/src/main/java/com/salesforce/pyplyn/duct/etl/extract/argus/ArgusExtractProcessor.java | salesforce/pyplyn | e70aab598245766642328bb4923f756603e8f39e | [
"BSD-3-Clause"
] | 6 | 2017-05-11T15:58:07.000Z | 2019-10-16T05:53:28.000Z | 47.135593 | 173 | 0.552319 | 928 | /*
* Copyright (c) 2016-2017, Salesforce.com, Inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see the LICENSE.txt file in repo root
* or https://opensource.org/licenses/BSD-3-Clause
*/
package com.salesforce.pyplyn.duct.etl.extract.argus;
import static com.salesforce.pyplyn.util.FormatUtils.*;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
import java.text.ParseException;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.Timer;
import com.google.common.collect.Iterables;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.salesforce.argus.ArgusClient;
import com.salesforce.argus.model.MetricResponse;
import com.salesforce.pyplyn.cache.Cache;
import com.salesforce.pyplyn.client.UnauthorizedException;
import com.salesforce.pyplyn.duct.app.ShutdownHook;
import com.salesforce.pyplyn.duct.connector.AppConnectors;
import com.salesforce.pyplyn.model.ImmutableTransmutation;
import com.salesforce.pyplyn.model.Transmutation;
import com.salesforce.pyplyn.processor.AbstractMeteredExtractProcessor;
/**
* Extracts data from Argus endpoints
* <p/>Annotated as Singleton as there should only be one instance of this class in operation.
*
* @author Mihai Bojin <[email protected]>
* @since 3.0
*/
@Singleton
public class ArgusExtractProcessor extends AbstractMeteredExtractProcessor<Argus> {
private static final Logger logger = LoggerFactory.getLogger(ArgusExtractProcessor.class);
private final AppConnectors appConnectors;
private final ShutdownHook shutdownHook;
@Inject
public ArgusExtractProcessor(AppConnectors appConnectors, ShutdownHook shutdownHook) {
this.appConnectors = appConnectors;
this.shutdownHook = shutdownHook;
}
/**
* @return a list of metrics returned by executing the passed Argus expressions
*/
@Override
public List<List<Transmutation>> process(List<Argus> data) {
// prepare a map of the datapoints that can be cached
final Map<String, Integer> cacheSettings = data.stream().filter(argus -> argus.cacheMillis() > 0).collect(Collectors.toMap(Argus::cacheKey, Argus::cacheMillis));
// prepare a map of default values, in case no data is found for some of the expressions
final Map<String, Double> defaultValueMap = data.stream().filter(argus -> nonNull(argus.defaultValue())).collect(Collectors.toMap(Argus::name, Argus::defaultValue));
// stream of metrics to be loaded from the endpoints or from cache
return data.stream()
// separate each metric by endpoint
.collect(Collectors.groupingBy(Argus::endpoint))
// then process each endpoint in parallel
.entrySet().parallelStream()
// process expressions for each endpoint
.map(endpointExpressions -> {
final String endpointId = endpointExpressions.getKey();
// retrieve Argus client and cache for the specified endpoint
AppConnectors.ClientAndCache<ArgusClient, MetricResponse> cc = appConnectors.retrieveOrBuildClient(endpointId, ArgusClient.class, MetricResponse.class);
final ArgusClient client = cc.client();
final Cache<MetricResponse> endpointCache = cc.cache();
// TODO: move this someplace better
try {
client.authenticate();
} catch (UnauthorizedException e) {
// log auth failure if this exception type was thrown
authenticationFailure();
failed();
// stop here if we cannot authenticate
logger.warn("", e);
return null;
}
// first load the cached responses
final List<MetricResponse> cachedResponses = endpointExpressions.getValue().stream()
.map(s -> endpointCache.isCached(s.cacheKey()))
.filter(Objects::nonNull)
.collect(Collectors.toList());
// prepare Argus expressions as strings
List<String> expressions = endpointExpressions.getValue().stream()
// only processes expressions that aren't already cached
.filter(s -> isNull(endpointCache.isCached(s.cacheKey())))
// always alias the expression with the expected name,
// in order to be able to identify it in the response
.map(ArgusExtractProcessor::aliasExpression)
.collect(Collectors.toList());
try {
// short circuit if app was shutdown
if (shutdownHook.isShutdown()) {
return null;
}
// retrieve metrics from Argus endpoint, only if we have expressions to retrieve
List<MetricResponse> metricResponses;
if (!expressions.isEmpty()) {
try (Timer.Context context = systemStatus.timer(meterName(), "get-metrics." + endpointId).time()) {
metricResponses = client.getMetrics(expressions);
}
// determine if the retrieval failed; stop here if that's the case
if (isNull(metricResponses)) {
failed();
return null;
}
// cache expressions that should be cached, based on their cacheMillis() settings mapped in canCache
metricResponses.stream()
// we are not caching results with no data
.filter(ArgusExtractProcessor::responseHasDatapoints)
.forEach(result -> tryCache(endpointCache, result, cacheSettings));
} else {
metricResponses = Collections.emptyList();
}
// mark successful operation and continue processing
succeeded();
// log cache debugging data
logger.info("{} metrics loaded from cache, {} from endpoint {}",
cachedResponses.size(), metricResponses.size(), endpointId);
// check all metrics with noData and populate with defaults, if required
return Stream.concat(cachedResponses.stream(), metricResponses.stream())
// if there is missing data, add default datapoints
.map(result -> {
// nothing to do if the response already has datapoints
if (responseHasDatapoints(result)) {
logger.info("Loaded data for {}, endpoint {}", result.metric(), endpointId);
return mapDatapointsAsResults(result, endpointId);
}
// if the response does not have any datapoints and a default value was not specified
Double defaultValue = defaultValueMap.get(result.metric());
if (isNull(defaultValue)) {
// log no-data events
logger.warn("No data for {}, endpoint {}", result.metric(), endpointId);
noData();
// stop here, cannot create a Transmutation from no points
return null;
}
// creates a default datapoint, based on the specified defaultValueMap
final Map.Entry<String, String> defaultMetricEntry = createDefaultDatapoint(defaultValue);
// tags the result with a message, to denote that this is a default value and not extracted from the endpoint
final String defaultValueMessage =
generateDefaultValueMessage(result.metric(), defaultValue);
// return the default value, tagged with
return Optional.ofNullable(
// attempt to create a result
createResult(defaultMetricEntry.getKey(),
defaultMetricEntry.getValue(),
result.metric(),
endpointId))
// tag each datapoint with the originating MetricResponse object
.map(transmutation -> addOriginalDatapoint(transmutation, result))
// add a default message
.map(transResult -> {
logger.info("Default data provided for {}={}, endpoint {}", result.metric(), transResult.value(), endpointId);
return ImmutableTransmutation.builder().from(transResult)
.metadata(ImmutableTransmutation.Metadata.builder()
.from(transResult.metadata())
.addMessages(defaultValueMessage)
.build())
.build();
})
// and map to a list, which is the expected return type
.map(Collections::singletonList)
// or return an empty collection, for any failures
.orElse(null);
})
// filter out any errors due to no-data or when creating the default response
.filter(Objects::nonNull)
.collect(Collectors.toList());
// catch any endpoint failures
} catch (UnauthorizedException e) {
logger.error("Could not complete request for {}; failed expressions={}; due to {}", endpointId, expressions, e.getMessage());
failed();
}
// if we end up here, it means something failed
return null;
})
// filter failures and return as List<MetricResponse>
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
/**
* Maps datapoints returned by Argus as a {@link Transmutation} matrix
*/
private List<Transmutation> mapDatapointsAsResults(MetricResponse metricResponse, String endpointId) {
// store metric name, as it's the same for all data points
final String metricName = metricResponse.metric();
// map each datapoint to a Transmutation object
return metricResponse.datapoints().entrySet().stream()
// create TransformResultStage object
.map(metricEntry -> createResult(metricEntry.getKey(), metricEntry.getValue(), metricName, endpointId))
// filter any failures and collect
.filter(Objects::nonNull)
// tag each datapoint with the originating MetricResponse object
.map(result -> addOriginalDatapoint(result, metricResponse))
.collect(Collectors.toList());
}
/**
* Adds a reference to the original datapoint in the {@link Transmutation}'s metadata
*/
private Transmutation addOriginalDatapoint(Transmutation input, Object source) {
return ImmutableTransmutation.builder().from(input)
.metadata(ImmutableTransmutation.Metadata.builder()
.from(input.metadata())
// TODO: do this for Refocus too, and/or define global flag for skipping this step
// alternatively, either specify this flag per configuration (+1) or detect if it will be required (based on some annotation
// implemented by Transforms - i.e.: @RequiresSourceObject
.source(source)
.build())
.build();
}
/**
* Creates a datapoint map, containing a single result
* <p/>Creates one point marked at the current time with the value specified in the defaultValueMap object
*
* @return returns a Map.Entry containing the time and value of the default point
*/
private Map.Entry<String, String> createDefaultDatapoint(Double defaultValue) {
SortedMap<String, String> defaultDatapoint = new TreeMap<>();
// init time and value and add to map
String time = Long.toString(Instant.now().toEpochMilli());
String value = formatNumber(defaultValue);
defaultDatapoint.put(time, value);
return Iterables.getOnlyElement(defaultDatapoint.entrySet());
}
/**
* Aliases a specified expression so the result can be identified (in a batch)
*
* @param argus Configuration parameter that holds the expression to load and its name
*/
static String aliasExpression(Argus argus) {
return String.format("ALIAS(%s,#%s#,#literal#)", argus.expression(), argus.name());
}
/**
* Checks that returned metric response has datapoints
* <p/>This method is used to determine if the result should be cached.
*/
static boolean responseHasDatapoints(MetricResponse response) {
return !response.datapoints().isEmpty();
}
/**
* Creates an extract result
*
* @param time time of data point
* @param value value of data point
* @param metric name of data point
* @return Null if either time or value could not be parsed
*/
private Transmutation createResult(String time, String value, String metric, String endpointId) {
try {
ZonedDateTime parsedTime = parseUTCTime(time);
Number parsedNumber = parseNumber(value);
return ImmutableTransmutation.of(parsedTime, metric, parsedNumber, parsedNumber,
ImmutableTransmutation.Metadata.builder().build());
} catch (DateTimeParseException |ParseException e) {
logger.warn("No data for {}, endpoint {}; invalid time or value: {}", metric, endpointId, e.getMessage());
noData();
return null;
}
}
/**
* Attempts to cache getMetrics responses, if they are registered for caching
*
* @param endpointCache
* @param metric MetricResponse to cache
* @param howLongToCacheFor Cache duration map, per each cacheable metric key
*/
private void tryCache(Cache<MetricResponse> endpointCache, MetricResponse metric, Map<String, Integer> howLongToCacheFor) {
if (howLongToCacheFor.containsKey(metric.cacheKey())) {
// retrieves the MetricResponse cache object and caches the specified metric for the specified duration
endpointCache.cache(metric, howLongToCacheFor.get(metric.cacheKey()));
}
}
@Override
public Class<Argus> filteredType() {
return Argus.class;
}
@Override
protected String meterName() {
return "Argus";
}
}
|
3e023c624e465b1830ff31efdc7bcc05abe5d37b | 4,621 | java | Java | webk8055/src/io/milkyway/k8055/App.java | jvmvik/k8055 | ae1ea48cc29cea2473f0d5b46e6407f0119b937f | [
"Apache-2.0"
] | 2 | 2016-10-31T14:56:50.000Z | 2022-03-04T17:49:14.000Z | webk8055/src/io/milkyway/k8055/App.java | jvmvik/k8055 | ae1ea48cc29cea2473f0d5b46e6407f0119b937f | [
"Apache-2.0"
] | null | null | null | webk8055/src/io/milkyway/k8055/App.java | jvmvik/k8055 | ae1ea48cc29cea2473f0d5b46e6407f0119b937f | [
"Apache-2.0"
] | null | null | null | 28.88125 | 141 | 0.648994 | 929 | package io.milkyway.k8055;
import groovy.util.logging.Log4j;
import io.milkyway.framework.exception.RouterException;
import io.milkyway.framework.json.gson.GsonFail;
import io.milkyway.framework.json.gson.GsonOk;
import io.milkyway.framework.json.smart.JsonOk;
import io.milkyway.framework.utils.Config;
import io.milkyway.netty.console.WebBrowser;
import io.milkyway.netty.core.Server;
import io.milkyway.netty.exception.RestException;
import io.milkyway.netty.exception.SessionException;
import io.milkyway.netty.webserver.RestRequestHandler;
import io.milkyway.netty.webserver.ViewRequestHandler;
import io.milkyway.netty.webserver.WebServer;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.apache.log4j.BasicConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
/**
* @author vicben01
*/
public class App extends Server
{
static WebServer server;
static AppController controller;
Logger log = LoggerFactory.getLogger(App.class);
public static void main(String[] args) throws InterruptedException
{
BasicConfigurator.configure();
App app = new App();
app.start();
//WebBrowser.start();
}
@Override
public void start() throws InterruptedException
{
server = new WebServer();
// Local instance of config
Config c = Config.getOrCreate();
c.setPort(8080);
c.set(Config.WEB_APP, "web/");
//c.enableTemplate();
controller = new AppController();
route();
server.start();
log.info("Application started..");
}
void route()
{
try
{
server.addRequestHandler("/", new ViewRequestHandler()
{
@Override
public void handle(ChannelHandlerContext ctx, HttpRequest req, Map<String, String> params) throws SessionException, RestException
{
render(ctx, "index", new HashMap<String, Object>());
}
});
server.addRequestHandler("/isConnected", new RestRequestHandler()
{
@Override
public void handle(ChannelHandlerContext ctx, HttpRequest request, Map<String, String> params) throws SessionException, RestException
{
JsonOk ok = new JsonOk();
ok.put("isConnected", controller.isConnected());
render(ctx, ok.toJSONString(), HttpResponseStatus.OK);
}
});
server.addRequestHandler("/connect", new RestRequestHandler()
{
@Override
public void handle(ChannelHandlerContext ctx, HttpRequest req, Map<String, String> params) throws SessionException, RestException
{
if (controller.connect())
{
render(ctx, new GsonOk().toJson(), HttpResponseStatus.OK);
}
else
{
GsonFail fail = new GsonFail("Connection failed");
render(ctx, fail.toJson(), HttpResponseStatus.OK);
}
}
});
server.addRequestHandler("/disconnect", new RestRequestHandler()
{
@Override
public void handle(ChannelHandlerContext ctx, HttpRequest req, Map<String, String> params) throws SessionException, RestException
{
if (controller.disconnect())
{
render(ctx, new GsonOk().toJson(), HttpResponseStatus.OK);
}
else
{
GsonFail fail = new GsonFail("Cannot close the connection failed");
render(ctx, fail.toJson(), HttpResponseStatus.OK);
}
}
});
server.addRequestHandler("/apply", new RestRequestHandler()
{
@Override
public void handle(ChannelHandlerContext ctx, HttpRequest req, Map<String, String> params) throws SessionException, RestException
{
if (controller.apply(params.get("q")))
{
render(ctx, new GsonOk().toJson(), HttpResponseStatus.OK);
}
else
{
render(ctx, new GsonFail("Oups apply failed...").toJson(), HttpResponseStatus.NOT_FOUND);
}
}
});
server.addRequestHandler("/read", new RestRequestHandler()
{
@Override
public void handle(ChannelHandlerContext ctx, HttpRequest req, Map<String, String> params) throws SessionException, RestException
{
render(ctx, controller.read().toString(), HttpResponseStatus.OK);
}
});
}
catch (RouterException e)
{
e.printStackTrace();
}
}
@Override
public void stop()
{
server.stop();
}
}
|
3e023d3f8cde323f9a849e4fb24c62f38e79361e | 4,873 | java | Java | src/com/framework/RestAssuredHelpers.java | virag8/Auto-Framework-Java | 83d03e27f865a28f622b25d5d9b9d4e8d70183e5 | [
"MIT"
] | null | null | null | src/com/framework/RestAssuredHelpers.java | virag8/Auto-Framework-Java | 83d03e27f865a28f622b25d5d9b9d4e8d70183e5 | [
"MIT"
] | null | null | null | src/com/framework/RestAssuredHelpers.java | virag8/Auto-Framework-Java | 83d03e27f865a28f622b25d5d9b9d4e8d70183e5 | [
"MIT"
] | null | null | null | 23.427885 | 110 | 0.69567 | 930 | package com.framework;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.everit.json.schema.Schema;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.testng.annotations.Ignore;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
public class RestAssuredHelpers {
@Test
@Ignore
public void openweathermap() {
RestAssured.get(
"https://samples.openweathermap.org/data/2.5/forecast?id=524901&appid=b1b15e88fa797225412429c1c50c122a1")
.then().statusCode(200);
}
@Test
@Ignore
public void echo_jsontest() {
RestAssured.baseURI = "http://echo.jsontest.com";
RequestSpecification rs = RestAssured.given();
Response res = rs.get("Key1/value/Key2/two");
System.out.println(res.getBody().asString().toString());
System.out.println(res.getBody().jsonPath().getString("value").toString());
}
@Test
@Ignore
public void ip_jsontest_POJO() {
RestAssured.baseURI = "http://ip.jsontest.com";
RequestSpecification rs = RestAssured.given();
Response res = rs.get();
System.out.println(res.getBody().asString());
Machine machine = res.getBody().as(Machine.class);
System.out.println(machine.getIp());
System.out.println(res.getBody().jsonPath().getString("ip").toString());
}
@Test
@Ignore
public void ip_jsonvalidate_POJO() throws IOException {
RestAssured.baseURI = "http://validate.jsontest.com";
RequestSpecification rs = RestAssured.given();
rs.queryParam("json", "{\"key\":\"value\"}");
Response res = rs.get();
System.out.println(res.getBody().asString());
Validate validate = res.getBody().as(Validate.class);
// System.out.println(validate.isEmpty1());
// System.out.println(res.getBody().jsonPath().getString("empty1"));
File initialFile = new File("resources/schema.json");
InputStream targetStream = new FileInputStream(initialFile);
JSONObject jsonSchema = new JSONObject(new JSONTokener(targetStream));
JSONObject jsonSubject = new JSONObject(new JSONTokener(res.getBody().asInputStream()));
Schema schema = SchemaLoader.load(jsonSchema);
schema.validate(jsonSubject);
}
@Test
public void jsonplaceholder_typicode() throws IOException {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com/photos";
RequestSpecification rs = RestAssured.given();
Response res = rs.get();
// System.out.println(res.getBody().asString());
List<Photos> photos = res.getBody().jsonPath().getList("", Photos.class);
// List<Photos> photos1 = res.getBody().jsonPath().getObject("photos",
// Photos[].class);
for (Photos photos2 : photos) {
}
System.out.println(photos.size());
System.out.println(res.getBody().jsonPath().getString("url"));
}
}
class Photos {
private int albumId;
private int id;
private String title;
private String url;
private String thumbnailUrl;
public int getAlbumId() {
return albumId;
}
public void setAlbumId(int albumId) {
this.albumId = albumId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
}
final class Machine {
private String ip1;
public String getIp() {
return ip1;
}
public void setIp(String ip) {
this.ip1 = ip;
}
}
final class Validate {
private int size;
private long parse_time_nanoseconds;
private String object_or_array;
private boolean validate;
private boolean empty;
public boolean isEmpty() {
return empty;
}
public void setEmpty(boolean empty) {
this.empty = empty;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public long getParse_time_nanoseconds() {
return parse_time_nanoseconds;
}
public void setParse_time_nanoseconds(long parse_time_nanoseconds) {
this.parse_time_nanoseconds = parse_time_nanoseconds;
}
public String getObject_or_array() {
return object_or_array;
}
public void setObject_or_array(String object_or_array) {
this.object_or_array = object_or_array;
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
this.validate = validate;
}
}
|
3e023db679d1aa72aaed087c0e89f18c72fde8bd | 30,147 | java | Java | sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/DoFn.java | acidburn0zzz/beam | 92540d0ecd98125e4f6fe13917dca46a77af52f0 | [
"Apache-2.0"
] | 3 | 2018-12-04T14:44:37.000Z | 2021-07-07T09:23:54.000Z | sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/DoFn.java | eljefe6a/incubator-beam | 8b540d2dd43af2a0495884d8152472a7ebff8a8e | [
"Apache-2.0"
] | 13 | 2019-11-13T03:56:36.000Z | 2021-12-14T21:12:07.000Z | sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/DoFn.java | eljefe6a/incubator-beam | 8b540d2dd43af2a0495884d8152472a7ebff8a8e | [
"Apache-2.0"
] | 2 | 2017-09-23T14:41:17.000Z | 2018-08-29T02:57:03.000Z | 40.249666 | 100 | 0.687531 | 931 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.transforms;
import com.google.auto.value.AutoValue;
import java.io.Serializable;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.annotations.Experimental;
import org.apache.beam.sdk.annotations.Experimental.Kind;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.state.State;
import org.apache.beam.sdk.state.StateSpec;
import org.apache.beam.sdk.state.TimeDomain;
import org.apache.beam.sdk.state.Timer;
import org.apache.beam.sdk.state.TimerSpec;
import org.apache.beam.sdk.transforms.display.DisplayData;
import org.apache.beam.sdk.transforms.display.HasDisplayData;
import org.apache.beam.sdk.transforms.splittabledofn.HasDefaultTracker;
import org.apache.beam.sdk.transforms.splittabledofn.RestrictionTracker;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.transforms.windowing.PaneInfo;
import org.apache.beam.sdk.transforms.windowing.Window;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.sdk.values.TupleTag;
import org.apache.beam.sdk.values.TypeDescriptor;
import org.joda.time.Duration;
import org.joda.time.Instant;
/**
* The argument to {@link ParDo} providing the code to use to process
* elements of the input
* {@link org.apache.beam.sdk.values.PCollection}.
*
* <p>See {@link ParDo} for more explanation, examples of use, and
* discussion of constraints on {@code DoFn}s, including their
* serializability, lack of access to global shared mutable state,
* requirements for failure tolerance, and benefits of optimization.
*
* <p>{@code DoFn}s can be tested in a particular
* {@code Pipeline} by running that {@code Pipeline} on sample input
* and then checking its output. Unit testing of a {@code DoFn},
* separately from any {@code ParDo} transform or {@code Pipeline},
* can be done via the {@link DoFnTester} harness.
*
* <p>Implementations must define a method annotated with {@link ProcessElement}
* that satisfies the requirements described there. See the {@link ProcessElement}
* for details.
*
* <p>Example usage:
*
* <pre><code>
* {@literal PCollection<String>} lines = ... ;
* {@literal PCollection<String>} words =
* {@literal lines.apply(ParDo.of(new DoFn<String, String>())} {
* {@literal @ProcessElement}
* public void processElement(ProcessContext c, BoundedWindow window) {
* ...
* }}));
* </code></pre>
*
* @param <InputT> the type of the (main) input elements
* @param <OutputT> the type of the (main) output elements
*/
public abstract class DoFn<InputT, OutputT> implements Serializable, HasDisplayData {
/**
* Information accessible while within the {@link StartBundle} method.
*/
public abstract class StartBundleContext {
/**
* Returns the {@code PipelineOptions} specified with the {@link
* org.apache.beam.sdk.PipelineRunner} invoking this {@code DoFn}. The {@code
* PipelineOptions} will be the default running via {@link DoFnTester}.
*/
public abstract PipelineOptions getPipelineOptions();
}
/**
* Information accessible while within the {@link FinishBundle} method.
*/
public abstract class FinishBundleContext {
/**
* Returns the {@code PipelineOptions} specified with the {@link
* org.apache.beam.sdk.PipelineRunner} invoking this {@code DoFn}. The {@code
* PipelineOptions} will be the default running via {@link DoFnTester}.
*/
public abstract PipelineOptions getPipelineOptions();
/**
* Adds the given element to the main output {@code PCollection} at the given
* timestamp in the given window.
*
* <p>Once passed to {@code output} the element should not be modified in
* any way.
*
* <p><i>Note:</i> A splittable {@link DoFn} is not allowed to output from the
* {@link FinishBundle} method.
*/
public abstract void output(OutputT output, Instant timestamp, BoundedWindow window);
/**
* Adds the given element to the output {@code PCollection} with the given tag at the given
* timestamp in the given window.
*
* <p>Once passed to {@code output} the element should not be modified in any way.
*
* <p><i>Note:</i> A splittable {@link DoFn} is not allowed to output from the {@link
* FinishBundle} method.
*/
public abstract <T> void output(
TupleTag<T> tag, T output, Instant timestamp, BoundedWindow window);
}
/**
* Information accessible to all methods in this {@link DoFn} where the context is in some window.
*/
public abstract class WindowedContext {
/**
* Returns the {@code PipelineOptions} specified with the {@link
* org.apache.beam.sdk.PipelineRunner} invoking this {@code DoFn}. The {@code
* PipelineOptions} will be the default running via {@link DoFnTester}.
*/
public abstract PipelineOptions getPipelineOptions();
/**
* Adds the given element to the main output {@code PCollection}.
*
* <p>Once passed to {@code output} the element should not be modified in
* any way.
*
* <p>If invoked from {@link ProcessElement}, the output
* element will have the same timestamp and be in the same windows
* as the input element passed to the method annotated with
* {@code @ProcessElement}.
*
* <p>If invoked from {@link StartBundle} or {@link FinishBundle},
* this will attempt to use the
* {@link org.apache.beam.sdk.transforms.windowing.WindowFn}
* of the input {@code PCollection} to determine what windows the element
* should be in, throwing an exception if the {@code WindowFn} attempts
* to access any information about the input element. The output element
* will have a timestamp of negative infinity.
*
* <p><i>Note:</i> A splittable {@link DoFn} is not allowed to output from
* {@link StartBundle} or {@link FinishBundle} methods.
*/
public abstract void output(OutputT output);
/**
* Adds the given element to the main output {@code PCollection},
* with the given timestamp.
*
* <p>Once passed to {@code outputWithTimestamp} the element should not be
* modified in any way.
*
* <p>If invoked from {@link ProcessElement}), the timestamp
* must not be older than the input element's timestamp minus
* {@link DoFn#getAllowedTimestampSkew}. The output element will
* be in the same windows as the input element.
*
* <p>If invoked from {@link StartBundle} or {@link FinishBundle},
* this will attempt to use the
* {@link org.apache.beam.sdk.transforms.windowing.WindowFn}
* of the input {@code PCollection} to determine what windows the element
* should be in, throwing an exception if the {@code WindowFn} attempts
* to access any information about the input element except for the
* timestamp.
*
* <p><i>Note:</i> A splittable {@link DoFn} is not allowed to output from
* {@link StartBundle} or {@link FinishBundle} methods.
*/
public abstract void outputWithTimestamp(OutputT output, Instant timestamp);
/**
* Adds the given element to the output {@code PCollection} with the
* given tag.
*
* <p>Once passed to {@code output} the element should not be modified
* in any way.
*
* <p>The caller of {@code ParDo} uses {@link ParDo.SingleOutput#withOutputTags} to
* specify the tags of outputs that it consumes. Non-consumed
* outputs, e.g., outputs for monitoring purposes only, don't necessarily
* need to be specified.
*
* <p>The output element will have the same timestamp and be in the same
* windows as the input element passed to {@link ProcessElement}).
*
* <p>If invoked from {@link StartBundle} or {@link FinishBundle},
* this will attempt to use the
* {@link org.apache.beam.sdk.transforms.windowing.WindowFn}
* of the input {@code PCollection} to determine what windows the element
* should be in, throwing an exception if the {@code WindowFn} attempts
* to access any information about the input element. The output element
* will have a timestamp of negative infinity.
*
* <p><i>Note:</i> A splittable {@link DoFn} is not allowed to output from
* {@link StartBundle} or {@link FinishBundle} methods.
*
* @see ParDo.SingleOutput#withOutputTags
*/
public abstract <T> void output(TupleTag<T> tag, T output);
/**
* Adds the given element to the specified output {@code PCollection},
* with the given timestamp.
*
* <p>Once passed to {@code outputWithTimestamp} the element should not be
* modified in any way.
*
* <p>If invoked from {@link ProcessElement}), the timestamp
* must not be older than the input element's timestamp minus
* {@link DoFn#getAllowedTimestampSkew}. The output element will
* be in the same windows as the input element.
*
* <p>If invoked from {@link StartBundle} or {@link FinishBundle},
* this will attempt to use the
* {@link org.apache.beam.sdk.transforms.windowing.WindowFn}
* of the input {@code PCollection} to determine what windows the element
* should be in, throwing an exception if the {@code WindowFn} attempts
* to access any information about the input element except for the
* timestamp.
*
* <p><i>Note:</i> A splittable {@link DoFn} is not allowed to output from
* {@link StartBundle} or {@link FinishBundle} methods.
*
* @see ParDo.SingleOutput#withOutputTags
*/
public abstract <T> void outputWithTimestamp(
TupleTag<T> tag, T output, Instant timestamp);
}
/**
* Information accessible when running a {@link DoFn.ProcessElement} method.
*/
public abstract class ProcessContext extends WindowedContext {
/**
* Returns the input element to be processed.
*
* <p>The element will not be changed -- it is safe to cache, etc.
* without copying.
*/
public abstract InputT element();
/**
* Returns the value of the side input.
*
* @throws IllegalArgumentException if this is not a side input
* @see ParDo.SingleOutput#withSideInputs
*/
public abstract <T> T sideInput(PCollectionView<T> view);
/**
* Returns the timestamp of the input element.
*
* <p>See {@link Window} for more information.
*/
public abstract Instant timestamp();
/**
* Returns information about the pane within this window into which the
* input element has been assigned.
*
* <p>Generally all data is in a single, uninteresting pane unless custom
* triggering and/or late data has been explicitly requested.
* See {@link Window} for more information.
*/
public abstract PaneInfo pane();
/**
* Gives the runner a (best-effort) lower bound about the timestamps of future output associated
* with the current element.
*
* <p>If the {@link DoFn} has multiple outputs, the watermark applies to all of them.
*
* <p>Only splittable {@link DoFn DoFns} are allowed to call this method. It is safe to call
* this method from a different thread than the one running {@link ProcessElement}, but
* all calls must finish before {@link ProcessElement} returns.
*/
public abstract void updateWatermark(Instant watermark);
}
/**
* Information accessible when running a {@link DoFn.OnTimer} method.
*/
public abstract class OnTimerContext extends WindowedContext {
/**
* Returns the timestamp of the current timer.
*/
public abstract Instant timestamp();
/**
* Returns the window in which the timer is firing.
*/
public abstract BoundedWindow window();
/**
* Returns the time domain of the current timer.
*/
public abstract TimeDomain timeDomain();
}
/**
* Returns the allowed timestamp skew duration, which is the maximum duration that timestamps can
* be shifted backward in {@link WindowedContext#outputWithTimestamp}.
*
* <p>The default value is {@code Duration.ZERO}, in which case timestamps can only be shifted
* forward to future. For infinite skew, return {@code Duration.millis(Long.MAX_VALUE)}.
*
* @deprecated This method permits a {@link DoFn} to emit elements behind the watermark. These
* elements are considered late, and if behind the
* {@link Window#withAllowedLateness(Duration) allowed lateness} of a downstream
* {@link PCollection} may be silently dropped. See
* https://issues.apache.org/jira/browse/BEAM-644 for details on a replacement.
*
*/
@Deprecated
public Duration getAllowedTimestampSkew() {
return Duration.ZERO;
}
/////////////////////////////////////////////////////////////////////////////
/**
* Returns a {@link TypeDescriptor} capturing what is known statically
* about the input type of this {@code DoFn} instance's most-derived
* class.
*
* <p>See {@link #getOutputTypeDescriptor} for more discussion.
*/
public TypeDescriptor<InputT> getInputTypeDescriptor() {
return new TypeDescriptor<InputT>(getClass()) {};
}
/**
* Returns a {@link TypeDescriptor} capturing what is known statically
* about the output type of this {@code DoFn} instance's
* most-derived class.
*
* <p>In the normal case of a concrete {@code DoFn} subclass with
* no generic type parameters of its own (including anonymous inner
* classes), this will be a complete non-generic type, which is good
* for choosing a default output {@code Coder<O>} for the output
* {@code PCollection<O>}.
*/
public TypeDescriptor<OutputT> getOutputTypeDescriptor() {
return new TypeDescriptor<OutputT>(getClass()) {};
}
/** Receives values of the given type. */
public interface OutputReceiver<T> {
void output(T output);
}
/////////////////////////////////////////////////////////////////////////////
/**
* Annotation for declaring and dereferencing state cells.
*
* <p>To declare a state cell, create a field of type {@link StateSpec} annotated with a
* {@link StateId}. To use the cell during processing, add a parameter of the appropriate {@link
* State} subclass to your {@link ProcessElement @ProcessElement} or {@link OnTimer @OnTimer}
* method, and annotate it with {@link StateId}. See the following code for an example:
*
* <pre><code>{@literal new DoFn<KV<Key, Foo>, Baz>()} {
*
* {@literal @StateId("my-state-id")}
* {@literal private final StateSpec<ValueState<MyState>>} myStateSpec =
* StateSpecs.value(new MyStateCoder());
*
* {@literal @ProcessElement}
* public void processElement(
* ProcessContext c,
* {@literal @StateId("my-state-id") ValueState<MyState> myState}) {
* myState.read();
* myState.write(...);
* }
* }
* </code></pre>
*
* <p>State is subject to the following validity conditions:
*
* <ul>
* <li>Each state ID must be declared at most once.
* <li>Any state referenced in a parameter must be declared with the same state type.
* <li>State declarations must be final.
* </ul>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Experimental(Kind.STATE)
public @interface StateId {
/** The state ID. */
String value();
}
/**
* Annotation for declaring and dereferencing timers.
*
* <p>To declare a timer, create a field of type {@link TimerSpec} annotated with a {@link
* TimerId}. To use the cell during processing, add a parameter of the type {@link Timer} to your
* {@link ProcessElement @ProcessElement} or {@link OnTimer @OnTimer} method, and annotate it with
* {@link TimerId}. See the following code for an example:
*
* <pre><code>{@literal new DoFn<KV<Key, Foo>, Baz>()} {
* {@literal @TimerId("my-timer-id")}
* private final TimerSpec myTimer = TimerSpecs.timerForDomain(TimeDomain.EVENT_TIME);
*
* {@literal @ProcessElement}
* public void processElement(
* ProcessContext c,
* {@literal @TimerId("my-timer-id") Timer myTimer}) {
* myTimer.offset(Duration.standardSeconds(...)).setRelative();
* }
*
* {@literal @OnTimer("my-timer-id")}
* public void onMyTimer() {
* ...
* }
* }</code></pre>
*
* <p>Timers are subject to the following validity conditions:
*
* <ul>
* <li>Each timer must have a distinct id.
* <li>Any timer referenced in a parameter must be declared.
* <li>Timer declarations must be final.
* <li>All declared timers must have a corresponding callback annotated with {@link
* OnTimer @OnTimer}.
* </ul>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Experimental(Kind.TIMERS)
public @interface TimerId {
/** The timer ID. */
String value();
}
/**
* Annotation for registering a callback for a timer.
*
* <p>See the javadoc for {@link TimerId} for use in a full example.
*
* <p>The method annotated with {@code @OnTimer} may have parameters according to the same logic
* as {@link ProcessElement}, but limited to the {@link BoundedWindow}, {@link State} subclasses,
* and {@link Timer}. State and timer parameters must be annotated with their {@link StateId} and
* {@link TimerId} respectively.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Experimental(Kind.TIMERS)
public @interface OnTimer {
/** The timer ID. */
String value();
}
/**
* Annotation for the method to use to prepare an instance for processing bundles of elements. The
* method annotated with this must satisfy the following constraints
* <ul>
* <li>It must have zero arguments.
* </ul>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Setup {
}
/**
* Annotation for the method to use to prepare an instance for processing a batch of elements.
* The method annotated with this must satisfy the following constraints:
* <ul>
* <li>It must have exactly zero or one arguments.
* <li>If it has any arguments, its only argument must be a {@link DoFn.StartBundleContext}.
* </ul>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface StartBundle {}
/**
* Annotation for the method to use for processing elements. A subclass of {@link DoFn} must have
* a method with this annotation.
*
* <p>The signature of this method must satisfy the following constraints:
*
* <ul>
* <li>Its first argument must be a {@link DoFn.ProcessContext}.
* <li>If one of its arguments is a subtype of {@link RestrictionTracker}, then it is a <a
* href="https://s.apache.org/splittable-do-fn">splittable</a> {@link DoFn} subject to the
* separate requirements described below. Items below are assuming this is not a splittable
* {@link DoFn}.
* <li>If one of its arguments is a subtype of {@link BoundedWindow} then it will
* be passed the window of the current element. When applied by {@link ParDo} the subtype
* of {@link BoundedWindow} must match the type of windows on the input {@link PCollection}.
* If the window is not accessed a runner may perform additional optimizations.
* <li>It must return {@code void}.
* </ul>
*
* <h2>Splittable DoFn's</h2>
*
* <p>A {@link DoFn} is <i>splittable</i> if its {@link ProcessElement} method has a parameter
* whose type is a subtype of {@link RestrictionTracker}. This is an advanced feature and an
* overwhelming majority of users will never need to write a splittable {@link DoFn}.
*
* <p>Not all runners support Splittable DoFn. See the
* <a href="https://beam.apache.org/documentation/runners/capability-matrix/">capability
* matrix</a>.
*
* <p>See <a href="https://s.apache.org/splittable-do-fn">the proposal</a> for an overview of the
* involved concepts (<i>splittable DoFn</i>, <i>restriction</i>, <i>restriction tracker</i>).
*
* <p>If a {@link DoFn} is splittable, the following constraints must be respected:
*
* <ul>
* <li>It <i>must</i> define a {@link GetInitialRestriction} method.
* <li>It <i>may</i> define a {@link SplitRestriction} method.
* <li>It <i>may</i> define a {@link NewTracker} method returning the same type as the type of
* the {@link RestrictionTracker} argument of {@link ProcessElement}, which in turn must be a
* subtype of {@code RestrictionTracker<R>} where {@code R} is the restriction type returned
* by {@link GetInitialRestriction}. This method is optional in case the restriction type
* returned by {@link GetInitialRestriction} implements {@link HasDefaultTracker}.
* <li>It <i>may</i> define a {@link GetRestrictionCoder} method.
* <li>The type of restrictions used by all of these methods must be the same.
* <li>Its {@link ProcessElement} method <i>may</i> return a {@link ProcessContinuation} to
* indicate whether there is more work to be done for the current element.
* <li>Its {@link ProcessElement} method <i>must not</i> use any extra context parameters, such as
* {@link BoundedWindow}.
* <li>The {@link DoFn} itself <i>may</i> be annotated with {@link BoundedPerElement} or
* {@link UnboundedPerElement}, but not both at the same time. If it's not annotated with
* either of these, it's assumed to be {@link BoundedPerElement} if its {@link
* ProcessElement} method returns {@code void} and {@link UnboundedPerElement} if it
* returns a {@link ProcessContinuation}.
* </ul>
*
* <p>A non-splittable {@link DoFn} <i>must not</i> define any of these methods.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ProcessElement {}
/**
* Annotation for the method to use to finish processing a batch of elements.
* The method annotated with this must satisfy the following constraints:
* <ul>
* <li>It must have exactly zero or one arguments.
* <li>If it has any arguments, its only argument must be a {@link DoFn.FinishBundleContext}.
* </ul>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface FinishBundle {}
/**
* Annotation for the method to use to clean up this instance after processing bundles of
* elements. No other method will be called after a call to the annotated method is made.
* The method annotated with this must satisfy the following constraint:
* <ul>
* <li>It must have zero arguments.
* </ul>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Teardown {
}
/**
* Annotation for the method that maps an element to an initial restriction for a <a
* href="https://s.apache.org/splittable-do-fn">splittable</a> {@link DoFn}.
*
* <p>Signature: {@code RestrictionT getInitialRestriction(InputT element);}
*
* <p>TODO: Make the InputT parameter optional.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Experimental(Kind.SPLITTABLE_DO_FN)
public @interface GetInitialRestriction {}
/**
* Annotation for the method that returns the coder to use for the restriction of a <a
* href="https://s.apache.org/splittable-do-fn">splittable</a> {@link DoFn}.
*
* <p>If not defined, a coder will be inferred using standard coder inference rules and the
* pipeline's {@link Pipeline#getCoderRegistry coder registry}.
*
* <p>This method will be called only at pipeline construction time.
*
* <p>Signature: {@code Coder<RestrictionT> getRestrictionCoder();}
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Experimental(Kind.SPLITTABLE_DO_FN)
public @interface GetRestrictionCoder {}
/**
* Annotation for the method that splits restriction of a <a
* href="https://s.apache.org/splittable-do-fn">splittable</a> {@link DoFn} into multiple parts to
* be processed in parallel.
*
* <p>Signature: {@code List<RestrictionT> splitRestriction( InputT element, RestrictionT
* restriction);}
*
* <p>Optional: if this method is omitted, the restriction will not be split (equivalent to
* defining the method and returning {@code Collections.singletonList(restriction)}).
*
* <p>TODO: Introduce a parameter for controlling granularity of splitting, e.g. numParts. TODO:
* Make the InputT parameter optional.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Experimental(Kind.SPLITTABLE_DO_FN)
public @interface SplitRestriction {}
/**
* Annotation for the method that creates a new {@link RestrictionTracker} for the restriction of
* a <a href="https://s.apache.org/splittable-do-fn">splittable</a> {@link DoFn}.
*
* <p>Signature: {@code MyRestrictionTracker newTracker(RestrictionT restriction);} where {@code
* MyRestrictionTracker} must be a subtype of {@code RestrictionTracker<RestrictionT>}.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Experimental(Kind.SPLITTABLE_DO_FN)
public @interface NewTracker {}
/**
* Annotation on a <a href="https://s.apache.org/splittable-do-fn">splittable</a> {@link DoFn}
* specifying that the {@link DoFn} performs a bounded amount of work per input element, so
* applying it to a bounded {@link PCollection} will produce also a bounded {@link PCollection}.
* It is an error to specify this on a non-splittable {@link DoFn}.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Experimental(Kind.SPLITTABLE_DO_FN)
public @interface BoundedPerElement {}
/**
* Annotation on a <a href="https://s.apache.org/splittable-do-fn">splittable</a> {@link DoFn}
* specifying that the {@link DoFn} performs an unbounded amount of work per input element, so
* applying it to a bounded {@link PCollection} will produce an unbounded {@link PCollection}. It
* is an error to specify this on a non-splittable {@link DoFn}.
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Experimental(Kind.SPLITTABLE_DO_FN)
public @interface UnboundedPerElement {}
// This can't be put into ProcessContinuation itself due to the following problem:
// http://ternarysearch.blogspot.com/2013/07/static-initialization-deadlock.html
private static final ProcessContinuation PROCESS_CONTINUATION_STOP =
new AutoValue_DoFn_ProcessContinuation(false, Duration.ZERO);
/**
* When used as a return value of {@link ProcessElement}, indicates whether there is more work to
* be done for the current element.
*
* <p>If the {@link ProcessElement} call completes because of a failed {@code tryClaim()} call
* on the {@link RestrictionTracker}, then the call MUST return {@link #stop()}.
*/
@Experimental(Kind.SPLITTABLE_DO_FN)
@AutoValue
public abstract static class ProcessContinuation {
/** Indicates that there is no more work to be done for the current element. */
public static ProcessContinuation stop() {
return PROCESS_CONTINUATION_STOP;
}
/** Indicates that there is more work to be done for the current element. */
public static ProcessContinuation resume() {
return new AutoValue_DoFn_ProcessContinuation(true, Duration.ZERO);
}
/**
* If false, the {@link DoFn} promises that there is no more work remaining for the current
* element, so the runner should not resume the {@link ProcessElement} call.
*/
public abstract boolean shouldResume();
/**
* A minimum duration that should elapse between the end of this {@link ProcessElement} call and
* the {@link ProcessElement} call continuing processing of the same element. By default, zero.
*/
public abstract Duration resumeDelay();
/** Builder method to set the value of {@link #resumeDelay()}. */
public ProcessContinuation withResumeDelay(Duration resumeDelay) {
return new AutoValue_DoFn_ProcessContinuation(shouldResume(), resumeDelay);
}
}
/**
* Finalize the {@link DoFn} construction to prepare for processing.
* This method should be called by runners before any processing methods.
*
* @deprecated use {@link Setup} or {@link StartBundle} instead. This method will be removed in a
* future release.
*/
@Deprecated
public final void prepareForProcessing() {}
/**
* {@inheritDoc}
*
* <p>By default, does not register any display data. Implementors may override this method
* to provide their own display data.
*/
@Override
public void populateDisplayData(DisplayData.Builder builder) {
}
}
|
3e023ed35923bfd8efe71e13bf0b04333ef84c3e | 3,089 | java | Java | trunk/adhoc-solr/src/main/java/org/apache/lucene/search/spans/SpanPositionRangeQuery.java | yblucky/mdrill | 8621180ac977e670a8e50a16053d4fce2b1c6a3e | [
"ICU",
"Apache-2.0"
] | 1,104 | 2015-01-01T07:45:27.000Z | 2022-03-31T04:09:24.000Z | trunk/adhoc-solr/src/main/java/org/apache/lucene/search/spans/SpanPositionRangeQuery.java | jwpttcg66/mdrill | 3acf33cfa72527fc1d949e933cc87fba340f2524 | [
"ICU",
"Apache-2.0"
] | 7 | 2015-05-04T10:29:01.000Z | 2019-01-07T05:38:55.000Z | trunk/adhoc-solr/src/main/java/org/apache/lucene/search/spans/SpanPositionRangeQuery.java | jwpttcg66/mdrill | 3acf33cfa72527fc1d949e933cc87fba340f2524 | [
"ICU",
"Apache-2.0"
] | 579 | 2015-01-04T06:40:10.000Z | 2022-03-28T11:53:15.000Z | 29.419048 | 127 | 0.687925 | 932 | package org.apache.lucene.search.spans;
/**
* 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.
*/
import org.apache.lucene.util.ToStringUtils;
import java.io.IOException;
/**
* Checks to see if the {@link #getMatch()} lies between a start and end position
*
* @see org.apache.lucene.search.spans.SpanFirstQuery for a derivation that is optimized for the case where start position is 0
*/
public class SpanPositionRangeQuery extends SpanPositionCheckQuery {
protected int start = 0;
protected int end;
public SpanPositionRangeQuery(SpanQuery match, int start, int end) {
super(match);
this.start = start;
this.end = end;
}
@Override
protected AcceptStatus acceptPosition(Spans spans) throws IOException {
assert spans.start() != spans.end();
if (spans.start() >= end)
return AcceptStatus.NO_AND_ADVANCE;
else if (spans.start() >= start && spans.end() <= end)
return AcceptStatus.YES;
else
return AcceptStatus.NO;
}
/**
* @return The minimum position permitted in a match
*/
public int getStart() {
return start;
}
/**
* @return the maximum end position permitted in a match.
*/
public int getEnd() {
return end;
}
@Override
public String toString(String field) {
StringBuilder buffer = new StringBuilder();
buffer.append("spanPosRange(");
buffer.append(match.toString(field));
buffer.append(", ").append(start).append(", ");
buffer.append(end);
buffer.append(")");
buffer.append(ToStringUtils.boost(getBoost()));
return buffer.toString();
}
@Override
public Object clone() {
SpanPositionRangeQuery result = new SpanPositionRangeQuery((SpanQuery) match.clone(), start, end);
result.setBoost(getBoost());
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SpanPositionRangeQuery)) return false;
SpanPositionRangeQuery other = (SpanPositionRangeQuery)o;
return this.end == other.end && this.start == other.start
&& this.match.equals(other.match)
&& this.getBoost() == other.getBoost();
}
@Override
public int hashCode() {
int h = match.hashCode();
h ^= (h << 8) | (h >>> 25); // reversible
h ^= Float.floatToRawIntBits(getBoost()) ^ end ^ start;
return h;
}
} |
3e023f47d9a234a3a9d98d30b17a5c9c652ff705 | 598 | java | Java | transactions/src/main/java/br/com/zup/transactions/transactionsconsumer/Establishment.java | GiovaniFavero/orange-talents-01-template-transacao | 96deee69a5c2db2314ecfc4367ad3ae033946cda | [
"Apache-2.0"
] | null | null | null | transactions/src/main/java/br/com/zup/transactions/transactionsconsumer/Establishment.java | GiovaniFavero/orange-talents-01-template-transacao | 96deee69a5c2db2314ecfc4367ad3ae033946cda | [
"Apache-2.0"
] | null | null | null | transactions/src/main/java/br/com/zup/transactions/transactionsconsumer/Establishment.java | GiovaniFavero/orange-talents-01-template-transacao | 96deee69a5c2db2314ecfc4367ad3ae033946cda | [
"Apache-2.0"
] | null | null | null | 17.588235 | 68 | 0.623746 | 933 | package br.com.zup.transactions.transactionsconsumer;
import javax.persistence.*;
@Embeddable
public class Establishment {
private String name;
private String city;
private String address;
public Establishment(String name, String city, String address) {
this.name = name;
this.city = city;
this.address = address;
}
@Deprecated
public Establishment() {
}
public String getName() {
return name;
}
public String getCity() {
return city;
}
public String getAddress() {
return address;
}
}
|
3e024050f670c7db332260e0f610312270ff561b | 817 | java | Java | array/ReverseWordsInString.java | mukilkrishnan/leetcode | f5e674c4f0734103809334648eb53d55856a9d8c | [
"MIT"
] | null | null | null | array/ReverseWordsInString.java | mukilkrishnan/leetcode | f5e674c4f0734103809334648eb53d55856a9d8c | [
"MIT"
] | null | null | null | array/ReverseWordsInString.java | mukilkrishnan/leetcode | f5e674c4f0734103809334648eb53d55856a9d8c | [
"MIT"
] | null | null | null | 34.041667 | 78 | 0.563035 | 934 | import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReverseWordsInString {
public String reverseWords(String s) {
s = s.trim();
final String pattern = "[ ]{2,}"; // find 2 or more adjacent spaces
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(s);
s = m.replaceAll(" ");
String[] words = s.split (" ");
StringBuilder temp = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
temp.append (words[i]);
if (i != 0) temp.append(" ");
}
return temp.toString();
}
public static void main (String[] args) {
ReverseWordsInString test = new ReverseWordsInString ();
System.out.println (test.reverseWords (" Am I insane?"));
}
} |
3e02420d3b76066ef4518b5e439f061eed5130bd | 7,190 | java | Java | src/main/java/com/irurueta/ar/sfm/KnownBaselineSparseReconstructor.java | albertoirurueta/irurueta-ar | 6333a9a732837150937cf0ea7e4153ade8358b0e | [
"Apache-2.0"
] | 1 | 2021-04-21T15:03:49.000Z | 2021-04-21T15:03:49.000Z | src/main/java/com/irurueta/ar/sfm/KnownBaselineSparseReconstructor.java | albertoirurueta/irurueta-ar | 6333a9a732837150937cf0ea7e4153ade8358b0e | [
"Apache-2.0"
] | null | null | null | src/main/java/com/irurueta/ar/sfm/KnownBaselineSparseReconstructor.java | albertoirurueta/irurueta-ar | 6333a9a732837150937cf0ea7e4153ade8358b0e | [
"Apache-2.0"
] | null | null | null | 44.677019 | 117 | 0.685528 | 936 | /*
* Copyright (C) 2017 Alberto Irurueta Carro ([email protected])
*
* 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.irurueta.ar.sfm;
import com.irurueta.geometry.MetricTransformation3D;
import com.irurueta.geometry.PinholeCamera;
import com.irurueta.geometry.Point3D;
import java.util.ArrayList;
import java.util.List;
/**
* Class in charge of estimating cameras and 3D reconstructed points from sparse
* image point correspondences from multiple views and known initial camera baseline
* (camera separation), so that cameras and reconstructed points are obtained with
* exact scale.
*/
public class KnownBaselineSparseReconstructor extends
BaseSparseReconstructor<KnownBaselineSparseReconstructorConfiguration,
KnownBaselineSparseReconstructor, KnownBaselineSparseReconstructorListener> {
/**
* Constructor.
*
* @param configuration configuration for this re-constructor.
* @param listener listener in charge of handling events.
* @throws NullPointerException if listener or configuration is not
* provided.
*/
public KnownBaselineSparseReconstructor(
final KnownBaselineSparseReconstructorConfiguration configuration,
final KnownBaselineSparseReconstructorListener listener) {
super(configuration, listener);
}
/**
* Constructor with default configuration.
*
* @param listener listener in charge of handling events.
* @throws NullPointerException if listener is not provided.
*/
public KnownBaselineSparseReconstructor(
final KnownBaselineSparseReconstructorListener listener) {
this(new KnownBaselineSparseReconstructorConfiguration(), listener);
}
/**
* Called when processing one frame is successfully finished. This can be done to estimate scale on those
* implementations where scale can be measured or is already known.
*
* @param isInitialPairOfViews true if initial pair of views is being processed, false otherwise.
* @return true if post processing succeeded, false otherwise.
*/
@SuppressWarnings("DuplicatedCode")
@Override
protected boolean postProcessOne(final boolean isInitialPairOfViews) {
try {
final PinholeCamera metricCamera1 = mPreviousMetricEstimatedCamera.getCamera();
final PinholeCamera metricCamera2 = mCurrentMetricEstimatedCamera.getCamera();
metricCamera1.decompose();
metricCamera2.decompose();
final double scale;
if (isInitialPairOfViews) {
// reconstruction succeeded, so we update scale of cameras and
// reconstructed points
final double baseline = mConfiguration.getBaseline();
final Point3D center1 = metricCamera1.getCameraCenter();
final Point3D center2 = metricCamera2.getCameraCenter();
final double estimatedBaseline = center1.distanceTo(center2);
scale = mCurrentScale = baseline / estimatedBaseline;
} else {
scale = mCurrentScale;
}
final double sqrScale = scale * scale;
final MetricTransformation3D scaleTransformation =
new MetricTransformation3D(scale);
// update scale of cameras
final PinholeCamera euclideanCamera1 = scaleTransformation.transformAndReturnNew(metricCamera1);
final PinholeCamera euclideanCamera2 = scaleTransformation.transformAndReturnNew(metricCamera2);
mPreviousEuclideanEstimatedCamera = new EstimatedCamera();
mPreviousEuclideanEstimatedCamera.setCamera(euclideanCamera1);
mPreviousEuclideanEstimatedCamera.setViewId(mPreviousMetricEstimatedCamera.getViewId());
mPreviousEuclideanEstimatedCamera.setQualityScore(mPreviousMetricEstimatedCamera.getQualityScore());
if (mPreviousMetricEstimatedCamera.getCovariance() != null) {
mPreviousEuclideanEstimatedCamera.setCovariance(
mPreviousMetricEstimatedCamera.getCovariance().multiplyByScalarAndReturnNew(sqrScale));
}
mCurrentEuclideanEstimatedCamera = new EstimatedCamera();
mCurrentEuclideanEstimatedCamera.setCamera(euclideanCamera2);
mCurrentEuclideanEstimatedCamera.setViewId(mCurrentMetricEstimatedCamera.getViewId());
mCurrentEuclideanEstimatedCamera.setQualityScore(mCurrentMetricEstimatedCamera.getQualityScore());
if (mCurrentMetricEstimatedCamera.getCovariance() != null) {
mCurrentEuclideanEstimatedCamera.setCovariance(
mCurrentMetricEstimatedCamera.getCovariance().multiplyByScalarAndReturnNew(sqrScale));
}
// update scale of reconstructed points
final int numPoints = mActiveMetricReconstructedPoints.size();
final List<Point3D> metricReconstructedPoints3D = new ArrayList<>();
for (ReconstructedPoint3D activeMetricReconstructedPoint : mActiveMetricReconstructedPoints) {
metricReconstructedPoints3D.add(activeMetricReconstructedPoint.
getPoint());
}
final List<Point3D> euclideanReconstructedPoints3D = scaleTransformation.transformPointsAndReturnNew(
metricReconstructedPoints3D);
// set scaled points into result
mActiveEuclideanReconstructedPoints = new ArrayList<>();
ReconstructedPoint3D euclideanPoint;
ReconstructedPoint3D metricPoint;
for (int i = 0; i < numPoints; i++) {
metricPoint = mActiveMetricReconstructedPoints.get(i);
euclideanPoint = new ReconstructedPoint3D();
euclideanPoint.setId(metricPoint.getId());
euclideanPoint.setPoint(euclideanReconstructedPoints3D.get(i));
euclideanPoint.setInlier(metricPoint.isInlier());
euclideanPoint.setQualityScore(metricPoint.getQualityScore());
if (metricPoint.getCovariance() != null) {
euclideanPoint.setCovariance(metricPoint.getCovariance().multiplyByScalarAndReturnNew(sqrScale));
}
euclideanPoint.setColorData(metricPoint.getColorData());
mActiveEuclideanReconstructedPoints.add(euclideanPoint);
}
return true;
} catch (final Exception e) {
mFailed = true;
mListener.onFail(this);
return false;
}
}
}
|
3e024232ddb3a950db009bc1043138b8b9a8fe7b | 911 | java | Java | src/main/java/me/zbl/reactive/rxjava/Just.java | JamesZBL/reactive-java | c6b9dc79e44d3a0a660b4ed5ab7b71925df8a5b8 | [
"Apache-2.0"
] | 6 | 2019-05-01T12:44:22.000Z | 2021-06-13T07:50:09.000Z | src/main/java/me/zbl/reactive/rxjava/Just.java | JamesZBL/reactive-java | c6b9dc79e44d3a0a660b4ed5ab7b71925df8a5b8 | [
"Apache-2.0"
] | null | null | null | src/main/java/me/zbl/reactive/rxjava/Just.java | JamesZBL/reactive-java | c6b9dc79e44d3a0a660b4ed5ab7b71925df8a5b8 | [
"Apache-2.0"
] | null | null | null | 28.46875 | 75 | 0.688255 | 937 | /*
* Copyright 2019 ZHENG BAO LE
*
* 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 me.zbl.reactive.rxjava;
import io.reactivex.Observable;
/**
* @author ZHENG BAO LE
* @since 2019-05-01
*/
public class Just {
public static void main(String[] args) {
Observable.just("Hello, ReactiveX! ")
.doOnNext(System.out::println)
.subscribe();
}
}
|
3e02431536798eb96ebcd0f2c005886b0b1d57f5 | 4,060 | java | Java | Main.java | SenaOzcn/Ucak-Bileti-Hesaplama | 83be8913f08193d7e35ae10aed2b8ef3069ecd47 | [
"MIT"
] | null | null | null | Main.java | SenaOzcn/Ucak-Bileti-Hesaplama | 83be8913f08193d7e35ae10aed2b8ef3069ecd47 | [
"MIT"
] | null | null | null | Main.java | SenaOzcn/Ucak-Bileti-Hesaplama | 83be8913f08193d7e35ae10aed2b8ef3069ecd47 | [
"MIT"
] | null | null | null | 47.764706 | 152 | 0.590148 | 938 | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
double mesafeMaliyeti, normalTutar, yasIndirimiCocuk, yasIndirimiGenc, yasIndirimiYasli, yasIndirimMaliyeti, gidisGonusBiletIndirimi, toplamTutar;
int mesafe, yas, select;
Scanner input = new Scanner(System.in);
mesafeMaliyeti = 0.1;
yasIndirimiCocuk = 0.5;
yasIndirimiGenc = 0.1;
yasIndirimiYasli = 0.3;
gidisGonusBiletIndirimi = 0.2;
System.out.println("Lütfen Uçuş Mesafesini Giriniz: ");
mesafe = input.nextInt();
if (mesafe >= 0) {
normalTutar = mesafe * mesafeMaliyeti;
System.out.print("Lütfen Yaşınızı Giriniz: ");
yas = input.nextInt();
if ((yas >= 0) && (yas <= 12)) {
yasIndirimMaliyeti = normalTutar - (normalTutar * yasIndirimiCocuk);
System.out.println("Lütfen Yolculuk Tipini Seçiniz: ");
System.out.println("1-Tek Yön\n2-Gidiş-Dönüş");
select = input.nextInt();
if (select == 1) {
toplamTutar = yasIndirimMaliyeti;
System.out.println("Toplam Ödemeniz Gereken Tutar: " + toplamTutar + " TL'dir.");
} else if (select == 2) {
toplamTutar = (yasIndirimMaliyeti - (yasIndirimMaliyeti * gidisGonusBiletIndirimi)) * 2;
System.out.println("Toplam Ödemeniz Gereken Tutar: " + toplamTutar + " TL'dir.");
} else {
System.out.println("Geçersiz bir numara girdiniz. Lütfen tekrar deneyin.");
}
} else if ((yas >= 13) && (yas <= 24)) {
yasIndirimMaliyeti = normalTutar - (normalTutar * yasIndirimiGenc);
System.out.println("Lütfen Yolculuk Tipini Seçiniz: ");
System.out.println("1-Tek Yön\n2-Gidiş-Dönüş");
select = input.nextInt();
if (select == 1) {
toplamTutar = yasIndirimMaliyeti;
System.out.println("Toplam Ödemeniz Gereken Tutar: " + toplamTutar + " TL'dir.");
} else if (select == 2) {
toplamTutar = (yasIndirimMaliyeti - (yasIndirimMaliyeti * gidisGonusBiletIndirimi)) * 2;
System.out.println("Toplam Ödemeniz Gereken Tutar: " + toplamTutar + " TL'dir.");
} else {
System.out.println("Geçersiz bir numara girdiniz. Lütfen tekrar deneyin.");
}
} else if ((yas >= 25) && (yas <= 64)) {
System.out.println("Lütfen Yolculuk Tipini Seçiniz: ");
System.out.println("1-Tek Yön\n2-Gidiş-Dönüş");
select = input.nextInt();
if (select == 1) {
toplamTutar = normalTutar;
System.out.println("Toplam Ödemeniz Gereken Tutar: " + toplamTutar + " TL'dir.");
} else if (select == 2) {
toplamTutar = (normalTutar - (normalTutar * gidisGonusBiletIndirimi)) * 2;
System.out.println("Toplam Ödemeniz Gereken Tutar: " + toplamTutar + " TL'dir.");
} else {
System.out.println("Geçersiz bir numara girdiniz. Lütfen tekrar deneyin.");
}
} else if ((yas > 64) && (yas < 128)) {
yasIndirimMaliyeti = normalTutar - (normalTutar * yasIndirimiYasli);
System.out.println("Lütfen Yolculuk Tipini Seçiniz: ");
System.out.println("1-Tek Yön\n2-Gidiş-Dönüş");
select = input.nextInt();
if (select == 1) {
toplamTutar = yasIndirimMaliyeti;
System.out.println("Toplam Ödemeniz Gereken Tutar: " + toplamTutar + " TL'dir.");
} else if (select == 2) {
toplamTutar = (yasIndirimMaliyeti - (yasIndirimMaliyeti * gidisGonusBiletIndirimi)) * 2;
System.out.println("Toplam Ödemeniz Gereken Tutar: " + toplamTutar + " TL'dir.");
} else {
System.out.println("Geçersiz bir numara girdiniz. Lütfen tekrar deneyin.");
}
} else {
System.out.println("Geçersiz bir numara girdiniz. Lütfen tekrar deneyin.");
}
} else {
System.out.println("Geçersiz bir numara girdiniz.");
}
}
}
|
3e024354948ad32fa89f14f5ddc58690ea9b4207 | 2,132 | java | Java | runescape-client/src/main/java/WorldMapSectionType.java | umer-rs/runelite | 8ec3d5397a35ffd3a1acb5b0d5af2b4378729934 | [
"BSD-2-Clause"
] | 4 | 2022-03-11T19:45:58.000Z | 2022-03-27T20:29:20.000Z | runescape-client/src/main/java/WorldMapSectionType.java | umer-rs/runelite | 8ec3d5397a35ffd3a1acb5b0d5af2b4378729934 | [
"BSD-2-Clause"
] | 5 | 2022-02-24T14:32:28.000Z | 2022-03-15T15:07:44.000Z | runescape-client/src/main/java/WorldMapSectionType.java | umer-rs/runelite | 8ec3d5397a35ffd3a1acb5b0d5af2b4378729934 | [
"BSD-2-Clause"
] | 11 | 2022-02-19T06:06:38.000Z | 2022-03-22T23:42:11.000Z | 23.955056 | 101 | 0.695591 | 939 | import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("hn")
@Implements("WorldMapSectionType")
public enum WorldMapSectionType implements MouseWheel {
@ObfuscatedName("o")
@ObfuscatedSignature(
descriptor = "Lhn;"
)
@Export("WORLDMAPSECTIONTYPE0")
WORLDMAPSECTIONTYPE0(1, (byte)0),
@ObfuscatedName("q")
@ObfuscatedSignature(
descriptor = "Lhn;"
)
@Export("WORLDMAPSECTIONTYPE1")
WORLDMAPSECTIONTYPE1(3, (byte)1),
@ObfuscatedName("l")
@ObfuscatedSignature(
descriptor = "Lhn;"
)
@Export("WORLDMAPSECTIONTYPE2")
WORLDMAPSECTIONTYPE2(0, (byte)2),
@ObfuscatedName("k")
@ObfuscatedSignature(
descriptor = "Lhn;"
)
@Export("WORLDMAPSECTIONTYPE3")
WORLDMAPSECTIONTYPE3(2, (byte)3);
@ObfuscatedName("hg")
@ObfuscatedGetter(
intValue = -156777687
)
static int field2828;
@ObfuscatedName("a")
@ObfuscatedGetter(
intValue = -1514256887
)
@Export("type")
final int type;
@ObfuscatedName("m")
@Export("id")
final byte id;
WorldMapSectionType(int var3, byte var4) {
this.type = var3; // L: 17
this.id = var4; // L: 18
} // L: 19
@ObfuscatedName("o")
@ObfuscatedSignature(
descriptor = "(B)I",
garbageValue = "30"
)
@Export("rsOrdinal")
public int rsOrdinal() {
return this.id; // L: 23
}
@ObfuscatedName("o")
@ObfuscatedSignature(
descriptor = "(II)Lfm;",
garbageValue = "-1177052487"
)
@Export("getNpcDefinition")
public static NPCComposition getNpcDefinition(int var0) {
NPCComposition var1 = (NPCComposition)NPCComposition.NpcDefinition_cached.get((long)var0); // L: 65
if (var1 != null) { // L: 66
return var1;
} else {
byte[] var2 = NPCComposition.NpcDefinition_archive.takeFile(9, var0); // L: 67
var1 = new NPCComposition(); // L: 68
var1.id = var0; // L: 69
if (var2 != null) { // L: 70
var1.decode(new Buffer(var2));
}
var1.postDecode(); // L: 71
NPCComposition.NpcDefinition_cached.put(var1, (long)var0); // L: 72
return var1; // L: 73
}
}
}
|
3e0244012ea998e2870e22db15a2efe9352ca688 | 6,816 | java | Java | itsnatdroid/src/main/java/org/itsnat/droid/impl/browser/HttpResourceDownloader.java | jmarranz/itsnat_droid | 6b4e350ce6a52d82634b157a64395cffd090643c | [
"Apache-2.0"
] | 15 | 2015-09-16T04:47:26.000Z | 2018-04-19T08:08:18.000Z | itsnatdroid/src/main/java/org/itsnat/droid/impl/browser/HttpResourceDownloader.java | jmarranz/itsnat_droid | 6b4e350ce6a52d82634b157a64395cffd090643c | [
"Apache-2.0"
] | null | null | null | itsnatdroid/src/main/java/org/itsnat/droid/impl/browser/HttpResourceDownloader.java | jmarranz/itsnat_droid | 6b4e350ce6a52d82634b157a64395cffd090643c | [
"Apache-2.0"
] | 7 | 2015-09-16T04:48:14.000Z | 2020-09-22T09:44:44.000Z | 45.139073 | 225 | 0.637471 | 940 | package org.itsnat.droid.impl.browser;
import org.itsnat.droid.impl.dom.ParsedResource;
import org.itsnat.droid.impl.dom.ParsedResourceXMLDOM;
import org.itsnat.droid.impl.dom.ResourceDescRemote;
import org.itsnat.droid.impl.dom.XMLDOM;
import org.itsnat.droid.impl.domparser.XMLDOMParser;
import org.itsnat.droid.impl.domparser.XMLDOMParserContext;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Created by jmarranz on 12/11/14.
*/
public class HttpResourceDownloader
{
protected final String pageURLBase;
protected final HttpRequestData httpRequestData;
protected final String itsNatServerVersion;
protected final Map<String,ParsedResource> urlResDownloadedMap;
protected final XMLDOMParserContext xmlDOMParserContext;
public HttpResourceDownloader(String pageURLBase,HttpRequestData httpRequestData, String itsNatServerVersion,Map<String,ParsedResource> urlResDownloadedMap,XMLDOMParserContext xmlDOMParserContext)
{
this.pageURLBase = pageURLBase;
this.httpRequestData = httpRequestData;
this.itsNatServerVersion = itsNatServerVersion;
this.urlResDownloadedMap = urlResDownloadedMap;
this.xmlDOMParserContext = xmlDOMParserContext;
}
public List<HttpRequestResultOKImpl> downloadResources(List<ResourceDescRemote> resDescRemoteList) throws Exception
{
List<HttpRequestResultOKImpl> resultList = Collections.synchronizedList(new ArrayList<HttpRequestResultOKImpl>()); // Necesario synchronizedList(), pues se comparte entre hilos
downloadResources(resDescRemoteList,resultList);
return resultList;
}
private void downloadResources(List<ResourceDescRemote> resDescRemoteList,List<HttpRequestResultOKImpl> resultList) throws Exception
{
int len = resDescRemoteList.size();
ResourceDescRemote[] resDescRemoteArray = resDescRemoteList.toArray(new ResourceDescRemote[len]);
final Thread[] threadArray = new Thread[len];
final Exception[] exList = new Exception[len];
int cores;
try { cores = Runtime.getRuntime().availableProcessors(); } // Un Nexus 4 devuelve 4 processors = cores
catch(Exception ex) { cores = 8; }
if (cores < 1) cores = 8; // Pase lo que pase ponemos un valor coherente
int threadsPerCore = 5; // Para evitar demasiados hilos concurrentes a la vez, sobre t_odo por el tema de la memoria
int maxThreads = cores * threadsPerCore;
int threadConcurrentGroups = len / maxThreads + 1; // El +1 es para redondear hacia arriba, el if (j2 >= len) j2 = len; ya ajustará el valor exacto
int j1;
int j2;
for(int i = 0; i < threadConcurrentGroups; i++)
{
j1 = i * maxThreads;
j2 = j1 + maxThreads;
if (j1 >= len) break; // Sobra pero para que quede claro
if (j2 >= len) j2 = len;
final boolean[] stop = new boolean[1];
for (int k = j1; k < j2; k++)
{
ResourceDescRemote resourceDesc = resDescRemoteArray[k];
Runnable task = createTaskToDownloadResource(resourceDesc, stop, k, resultList, exList);
Thread thread = new Thread(task);
thread.start(); // Alternativa: ThreadPoolExecutor, aunque realmente el que asigna cores a threads es Linux a bajo nivel
threadArray[k] = thread;
}
for (int k = j1; k < j2; k++)
{
threadArray[k].join();
}
for (int k = j1; k < j2; k++)
{
if (exList[k] != null) throw exList[k]; // La primera que encontremos (es raro que haya más de una)
}
}
}
private Runnable createTaskToDownloadResource(final ResourceDescRemote resourceDesc, final boolean[] stop, final int i, final List<HttpRequestResultOKImpl> resultList, final Exception[] exList) throws Exception
{
Runnable task = new Runnable()
{
public void run()
{
if (stop[0]) return;
try
{
String resourceMime = resourceDesc.getResourceMime();
String absURL = HttpUtil.composeAbsoluteURL(resourceDesc.getLocation(xmlDOMParserContext), pageURLBase);
ParsedResource parsedResource;
synchronized(urlResDownloadedMap)
{
// El objetivo de esto es evitar cargar el mismo recurso (ej archivo XML) muchas veces durante el mismo proceso de carga en hilos no UI, más aun cuando en un archivo "values" ha referencias recursivas
parsedResource = urlResDownloadedMap.get(absURL);
}
if (parsedResource != null)
{
resourceDesc.setParsedResource(parsedResource.copy());
return;
}
HttpRequestResultOKImpl resultResource = HttpUtil.httpGet(absURL, httpRequestData, null, resourceMime);
processHttpRequestResultResource(absURL,resourceDesc, resultResource, resultList);
}
catch (Exception ex)
{
exList[i] = ex;
stop[0] = true;
}
}
};
return task;
}
private void processHttpRequestResultResource(String absURL,ResourceDescRemote resourceDesc, HttpRequestResultOKImpl resultRes, List<HttpRequestResultOKImpl> resultList) throws Exception
{
// Método llamado en multihilo
resultList.add(resultRes);
ParsedResource resource = XMLDOMParser.parseResourceDescRemote(resourceDesc, resultRes, xmlDOMParserContext);
synchronized(urlResDownloadedMap)
{
urlResDownloadedMap.put(absURL,resource); // No pasa nada si dos hilos con el mismo absURL-resource hacen put seguidos
}
if (resource instanceof ParsedResourceXMLDOM)
{
XMLDOM xmlDOM = ((ParsedResourceXMLDOM)resource).getXMLDOM();
String absURLContainer = HttpUtil.composeAbsoluteURL(resourceDesc.getLocation(xmlDOMParserContext), pageURLBase);
String pageURLBaseContainer = HttpUtil.getBasePathOfURL(absURLContainer);
XMLDOMDownloader downloader = XMLDOMDownloader.createXMLDOMDownloader(xmlDOM,pageURLBaseContainer, httpRequestData, itsNatServerVersion,urlResDownloadedMap,xmlDOMParserContext);
downloader.downloadRemoteResources();
}
}
}
|
3e02441eb4d225f4561824025ed7c1efa6885e42 | 2,609 | java | Java | common/src/main/java/com/wildbeeslabs/sensiblemetrics/diffy/common/executor/impl/AbstractTask.java | AlexRogalskiy/Comparalyzer | 42a03c14d639663387e7b796dca41cb1300ad36b | [
"MIT"
] | 1 | 2019-02-27T00:28:14.000Z | 2019-02-27T00:28:14.000Z | common/src/main/java/com/wildbeeslabs/sensiblemetrics/diffy/common/executor/impl/AbstractTask.java | AlexRogalskiy/Comparalyzer | 42a03c14d639663387e7b796dca41cb1300ad36b | [
"MIT"
] | 8 | 2019-11-13T09:02:17.000Z | 2021-12-09T20:49:03.000Z | common/src/main/java/com/wildbeeslabs/sensiblemetrics/diffy/common/executor/impl/AbstractTask.java | AlexRogalskiy/Diffy | 42a03c14d639663387e7b796dca41cb1300ad36b | [
"MIT"
] | 1 | 2019-02-01T08:48:24.000Z | 2019-02-01T08:48:24.000Z | 33.883117 | 80 | 0.696819 | 941 | /*
* The MIT License
*
* Copyright 2019 WildBees Labs, Inc.
*
* 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.
*/
package com.wildbeeslabs.sensiblemetrics.diffy.common.executor.impl;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
/**
* Abstract {@link Callable} task implementation
*
* @param <T> type of task item
*/
public abstract class AbstractTask<T> implements Callable<T> {
/**
* Stores the executor service to be destroyed at the end.
*/
private final ExecutorService executorService;
/**
* Creates a new instance of {@code InitializationTask} and initializes
* it with the {@code ExecutorService} to be destroyed at the end.
*
* @param executorService the {@code ExecutorService}
*/
public AbstractTask(final ExecutorService executorService) {
this.executorService = executorService;
}
/**
* Initiates initialization and returns the result.
*
* @return the result object
* @throws Exception if an error occurs
*/
@Override
public T call() throws Exception {
try {
return initialize();
} finally {
if (Objects.nonNull(this.executorService)) {
this.executorService.shutdown();
}
}
}
/**
* Returns result {@code T} by processing current task
*
* @return result {@code T}
* @throws Exception if current task initializes exceptionally
*/
protected abstract T initialize() throws Exception;
}
|
3e024580a4c58043e9895cd6f6012e694fda0584 | 2,392 | java | Java | lansidemo/src/main/java/com/ls/common/filter/HttpLogFilter.java | zheng-zy/spring-boot | 3b005e56b94edf9e45363e4d9213a2c32e1a0776 | [
"Apache-2.0"
] | null | null | null | lansidemo/src/main/java/com/ls/common/filter/HttpLogFilter.java | zheng-zy/spring-boot | 3b005e56b94edf9e45363e4d9213a2c32e1a0776 | [
"Apache-2.0"
] | null | null | null | lansidemo/src/main/java/com/ls/common/filter/HttpLogFilter.java | zheng-zy/spring-boot | 3b005e56b94edf9e45363e4d9213a2c32e1a0776 | [
"Apache-2.0"
] | null | null | null | 39.229508 | 151 | 0.641036 | 942 | package com.ls.common.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* <p>请求记录</p>
* Created by [email protected] on 2017/2/7.
*/
//@WebFilter(filterName = "httpFilter", urlPatterns = "/*")
public class HttpLogFilter extends OncePerRequestFilter {
private Logger logger = LoggerFactory.getLogger(getClass());
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
ByteHttpServletRequestWrapper requestWrapper;
//碰到这个URL直接跳过过滤
Assert.notNull(request, "request must not null!");
String uri = request.getRequestURI();
if (uri.startsWith("/druid/") || uri.startsWith("/static/") || uri.startsWith("/favicon")) {
chain.doFilter(request, response);
return;
}
requestWrapper = new ByteHttpServletRequestWrapper(request);
ResponseWrapper responseWrapper = new ResponseWrapper(response);
try {
chain.doFilter(requestWrapper, responseWrapper);
if (!response.isCommitted()) {
ServletOutputStream outputStream = response.getOutputStream();
byte[] responseData = responseWrapper.getBytes();
if (responseData != null && responseData.length > 0) {
outputStream.write(responseData);
outputStream.flush();
outputStream.close();
}
// else{} 什么都不做,因为会重定定向到别的视图,如404视图,不可以现在关闭
}
} catch (Exception e) {
logger.error("url: {}, result msg: {}", requestWrapper.getRequestURL(), e.getMessage());
} finally {
logger.info("url: {}?{}, req: {}, resp: {}",
requestWrapper.getRequestURL(),
requestWrapper.getQueryString() == null ? "" : requestWrapper.getQueryString(),
requestWrapper.getResult(),
responseWrapper.getResult());
}
}
}
|
3e0245980bec4f1efd2405b479cdb2e39321856e | 2,335 | java | Java | 09.1.MVC-Persistence-Exercise-I/App/app/src/main/controllers/UserController.java | kostadinlambov/Java-Web-Development-Basics-May-2018 | 8985c6eabd62a37d280d6307dbdbb88080f418be | [
"MIT"
] | 2 | 2019-02-15T01:10:17.000Z | 2019-04-07T23:23:45.000Z | 09.1.MVC-Persistence-Exercise-I/App/app/src/main/controllers/UserController.java | kostadinlambov/Java-Web-Development-Basics-May-2018 | 8985c6eabd62a37d280d6307dbdbb88080f418be | [
"MIT"
] | null | null | null | 09.1.MVC-Persistence-Exercise-I/App/app/src/main/controllers/UserController.java | kostadinlambov/Java-Web-Development-Basics-May-2018 | 8985c6eabd62a37d280d6307dbdbb88080f418be | [
"MIT"
] | null | null | null | 30.324675 | 107 | 0.688651 | 943 | package controllers;
import entities.User;
import models.binding.UserLoginBindingModel;
import models.binding.UserRegisterBindingModel;
import org.softuni.broccolina.solet.HttpSoletRequest;
import org.softuni.javache.http.HttpSession;
import org.softuni.javache.http.HttpSessionImpl;
import org.softuni.summermvc.api.Controller;
import org.softuni.summermvc.api.GetMapping;
import org.softuni.summermvc.api.PostMapping;
import repositories.UserRepository;
@Controller
public class UserController {
private UserRepository userRepository;
public UserController() { this.userRepository = new UserRepository(); }
@GetMapping(route = "/login")
public String login() {
return "template:login";
}
@PostMapping(route = "/login")
public String loginConfirm(HttpSoletRequest request, UserLoginBindingModel userLoginBindingModel) {
if(request.getSession() != null) {
return "redirect:/home";
}
User user = this.userRepository.findByUsername(userLoginBindingModel.getUsername());
if(user == null || !user.getPassword().equals(userLoginBindingModel.getPassword())) {
return "redirect:/login";
}
request.setSession(new HttpSessionImpl());
request.getSession().addAttribute("user-id", user.getId());
request.getSession().addAttribute("username", user.getUsername());
return "redirect:/home";
}
@GetMapping(route = "/register")
public String register() {
return "template:register";
}
@PostMapping(route = "/register")
public String registerConfirm(UserRegisterBindingModel userRegisterBindingModel) {
if(!userRegisterBindingModel.getPassword().equals(userRegisterBindingModel.getConfirmPassword())) {
return "redirect:/register";
}
User user = new User();
user.setUsername(userRegisterBindingModel.getUsername());
user.setPassword(userRegisterBindingModel.getPassword());
this.userRepository.saveUser(user);
return "redirect:/login";
}
@GetMapping(route = "/logout")
public String logout(HttpSoletRequest request) {
if(request.getSession() == null) {
return "redirect:/login";
}
request.getSession().invalidate();
return "redirect:/";
}
}
|
3e02462056d51e88b136dc653c6675d0dbd2a1b6 | 690 | java | Java | userInterface/src/main/java/org/mifos/ui/core/controller/UploadedFileFormBean.java | sureshkrishnamoorthy/suresh-mifos | 88e7df964688ca3955b38125213090297d4171a4 | [
"Apache-2.0"
] | 7 | 2016-06-23T12:50:58.000Z | 2020-12-21T18:39:55.000Z | userInterface/src/main/java/org/mifos/ui/core/controller/UploadedFileFormBean.java | sureshkrishnamoorthy/suresh-mifos | 88e7df964688ca3955b38125213090297d4171a4 | [
"Apache-2.0"
] | 8 | 2019-02-04T14:15:49.000Z | 2022-02-01T01:04:00.000Z | userInterface/src/main/java/org/mifos/ui/core/controller/UploadedFileFormBean.java | sureshkrishnamoorthy/suresh-mifos | 88e7df964688ca3955b38125213090297d4171a4 | [
"Apache-2.0"
] | 20 | 2015-02-11T06:31:19.000Z | 2020-03-04T15:24:52.000Z | 22.258065 | 70 | 0.710145 | 944 | package org.mifos.ui.core.controller;
import java.io.Serializable;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
public class UploadedFileFormBean implements Serializable {
private static final long serialVersionUID = 6766656607918159631L;
private CommonsMultipartFile file;
private String description;
public CommonsMultipartFile getFile() {
return file;
}
public void setFile(CommonsMultipartFile file) {
this.file = file;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
3e02465d948e5bc26729dcad4198376beb7da6ac | 739 | java | Java | apps/mobility/src/main/java/org/onosproject/mobility/package-info.java | tohotforice/onos | 02f4c0eb0a193bfd22ca43767cffe68b54f22148 | [
"Apache-2.0"
] | 1,091 | 2015-01-06T11:10:40.000Z | 2022-03-30T09:09:05.000Z | apps/mobility/src/main/java/org/onosproject/mobility/package-info.java | tohotforice/onos | 02f4c0eb0a193bfd22ca43767cffe68b54f22148 | [
"Apache-2.0"
] | 39 | 2015-02-13T19:58:32.000Z | 2022-03-02T02:38:07.000Z | apps/mobility/src/main/java/org/onosproject/mobility/package-info.java | tohotforice/onos | 02f4c0eb0a193bfd22ca43767cffe68b54f22148 | [
"Apache-2.0"
] | 914 | 2015-01-05T19:42:35.000Z | 2022-03-30T09:25:18.000Z | 35.190476 | 77 | 0.746955 | 945 | /*
* Copyright 2014-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Sample application that provides simple form of end-station host mobility.
*/
package org.onosproject.mobility;
|
3e024690a9bf5498f8e4e828f7805456455ade24 | 1,647 | java | Java | src/io/github/riesenpilz/nmsUtilities/packet/playIn/PacketPlayInItemNameEvent.java | Riesenpilz/NMSUtilities | 883fc61e576787cc3c7c9106c0e18c213748602c | [
"Apache-2.0"
] | 3 | 2021-10-09T12:01:29.000Z | 2022-01-25T12:57:07.000Z | src/io/github/riesenpilz/nmsUtilities/packet/playIn/PacketPlayInItemNameEvent.java | Riesenpilz/NMSUtilities | 883fc61e576787cc3c7c9106c0e18c213748602c | [
"Apache-2.0"
] | null | null | null | src/io/github/riesenpilz/nmsUtilities/packet/playIn/PacketPlayInItemNameEvent.java | Riesenpilz/NMSUtilities | 883fc61e576787cc3c7c9106c0e18c213748602c | [
"Apache-2.0"
] | null | null | null | 25.338462 | 87 | 0.746205 | 946 | package io.github.riesenpilz.nmsUtilities.packet.playIn;
import org.apache.commons.lang.Validate;
import org.bukkit.entity.Player;
import net.minecraft.server.v1_16_R3.Packet;
import net.minecraft.server.v1_16_R3.PacketListenerPlayIn;
import net.minecraft.server.v1_16_R3.PacketPlayInItemName;
/**
* https://wiki.vg/Protocol#Name_Item
* <p>
* Sent as a player is renaming an item in an anvil (each keypress in the anvil
* UI sends a new Name Item packet). If the new name is empty, then the item
* loses its custom name (this is different from setting the custom name to the
* normal name of the item). The item name may be no longer than 35 characters
* long, and if it is longer than that, then the rename is silently ignored.
* <p>
* Packet ID: 0x20<br>
* State: Play<br>
* Bound To: Server
*
* @author Martin
*
*/
public class PacketPlayInItemNameEvent extends PacketPlayInEvent {
/**
* The new name of the item. (32767 chars max)
*/
private String itemName;
public PacketPlayInItemNameEvent(Player injectedPlayer, PacketPlayInItemName packet) {
super(injectedPlayer);
Validate.notNull(packet);
itemName = packet.b();
}
public PacketPlayInItemNameEvent(Player injectedPlayer, String itemName) {
super(injectedPlayer);
Validate.notNull(itemName);
this.itemName = itemName;
}
public String getItemName() {
return itemName;
}
@Override
public Packet<PacketListenerPlayIn> getNMS() {
return new PacketPlayInItemName(itemName);
}
@Override
public int getPacketID() {
return 0x20;
}
@Override
public String getProtocolURLString() {
return "https://wiki.vg/Protocol#Name_Item";
}
}
|
3e0246d321445df7e8b6acdaed1d80b9eb0c0f89 | 263 | java | Java | src/main/java/ro/siit/session12/MainEx.java | fiatfilip/java-national-7 | 65dad6c5f732d8779b665c2b59ca7ad4f35296f7 | [
"Apache-2.0"
] | 1 | 2021-08-06T19:10:30.000Z | 2021-08-06T19:10:30.000Z | src/main/java/ro/siit/session12/MainEx.java | fiatfilip/java-national-7 | 65dad6c5f732d8779b665c2b59ca7ad4f35296f7 | [
"Apache-2.0"
] | null | null | null | src/main/java/ro/siit/session12/MainEx.java | fiatfilip/java-national-7 | 65dad6c5f732d8779b665c2b59ca7ad4f35296f7 | [
"Apache-2.0"
] | null | null | null | 21.916667 | 56 | 0.56654 | 947 | package ro.siit.session12;
public class MainEx {
public static void main(String[] args) {
try{
System.out.println(args[0]);
} catch (Exception exception){
System.out.println("Nu ati dat argumente!");
}
}
}
|
3e0247f92c7d35baea258a473835da373447309f | 1,042 | java | Java | java8/java8-ch07/src/main/java/com/hz/pojo/App.java | we-are-familys/javacore | 57bea9b7ecde7c5e2e26ede7d9e7100de423d6a7 | [
"Apache-2.0"
] | 1 | 2020-05-03T16:00:22.000Z | 2020-05-03T16:00:22.000Z | java8/java8-ch07/src/main/java/com/hz/pojo/App.java | we-are-familys/javacore | 57bea9b7ecde7c5e2e26ede7d9e7100de423d6a7 | [
"Apache-2.0"
] | null | null | null | java8/java8-ch07/src/main/java/com/hz/pojo/App.java | we-are-familys/javacore | 57bea9b7ecde7c5e2e26ede7d9e7100de423d6a7 | [
"Apache-2.0"
] | null | null | null | 33.612903 | 97 | 0.676583 | 948 | package com.hz.pojo;
import java.util.function.Function;
/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) {
// System.out.println("cmd: " + measureSumPerf(ParallelStreams::cmdSum, 10_000_000));
// System.out.println("seq: " + measureSumPerf(ParallelStreams::sequentialSum, 10_000_000));
// System.out.println("par: " + measureSumPerf(ParallelStreams::parellelSum, 10_000_000));
// System.out.println("ran: " + measureSumPerf(ParallelStreams::rangedSum, 10_000_000));
System.out.println("prs: " + measureSumPerf(ParallelStreams::parallelRangedSum, 10_000_000L));
}
//对前n个自然数求和耗时[性能测试]
public static long measureSumPerf(Function<Long, Long> adder, long n) {
long fastest = Long.MAX_VALUE;
for (int i = 0; i < 10; i++) {
long start = System.nanoTime();
long sum = adder.apply(n);
long duration = (System.nanoTime() - start) / 1_000_000;
System.out.println("Result: " + sum);
if (duration < fastest) fastest = duration;
}
return fastest;
}
}
|
3e024956407e587931cd2ddafb07870fbf16fd72 | 1,284 | java | Java | src/main/java/de/netbeacon/xenia/bot/commands/chat/structure/admin/GROUPAdmin.java | Horstexplorer/Xenia | d073a393c8687e89b2ce25956a6fc5012f945f27 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/netbeacon/xenia/bot/commands/chat/structure/admin/GROUPAdmin.java | Horstexplorer/Xenia | d073a393c8687e89b2ce25956a6fc5012f945f27 | [
"Apache-2.0"
] | 22 | 2020-10-22T14:36:43.000Z | 2021-09-20T01:16:17.000Z | src/main/java/de/netbeacon/xenia/bot/commands/chat/structure/admin/GROUPAdmin.java | Horstexplorer/Xenia | d073a393c8687e89b2ce25956a6fc5012f945f27 | [
"Apache-2.0"
] | 1 | 2020-12-04T18:23:34.000Z | 2020-12-04T18:23:34.000Z | 32.1 | 75 | 0.744548 | 949 | /*
* Copyright 2020 Horstexplorer @ https://www.netbeacon.de
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.netbeacon.xenia.bot.commands.chat.structure.admin;
import de.netbeacon.xenia.bot.commands.chat.objects.CommandGroup;
/**
* Contains all commands providing some admin features to the developer
*/
public class GROUPAdmin extends CommandGroup{
public GROUPAdmin(){
super(null, "admin", false);
addChildCommand(new CMDEval());
addChildCommand(new CMDInfo());
addChildCommand(new CMDPing());
addChildCommand(new CMDClientIdentify());
addChildCommand(new CMDGlobalInfo());
addChildCommand(new CMDChatlog());
addChildCommand(new CMDD43Z1());
addChildCommand(new CMDD43Z1Stats());
addChildCommand(new CMDBurger());
}
}
|
3e024a57e8f2dfae93838dad69f3c5e42cd9d82f | 11,144 | java | Java | graphx-pagerank/src/main/java/com/github/chen0040/spark/sga/services/SkillRuleMinerImpl.java | chen0040/spring-boot-spark-integration-demo | 8ddbd3d89d03118d17ccd5a58ecad4debcd2eef4 | [
"MIT"
] | 16 | 2018-06-05T04:41:26.000Z | 2022-02-22T02:37:20.000Z | graphx-pagerank/src/main/java/com/github/chen0040/spark/sga/services/SkillRuleMinerImpl.java | chen0040/spring-boot-spark-integration-demo | 8ddbd3d89d03118d17ccd5a58ecad4debcd2eef4 | [
"MIT"
] | null | null | null | graphx-pagerank/src/main/java/com/github/chen0040/spark/sga/services/SkillRuleMinerImpl.java | chen0040/spring-boot-spark-integration-demo | 8ddbd3d89d03118d17ccd5a58ecad4debcd2eef4 | [
"MIT"
] | 9 | 2019-08-31T23:37:41.000Z | 2021-12-19T15:08:56.000Z | 35.603834 | 178 | 0.595388 | 950 | package com.github.chen0040.spark.sga.services;
import com.github.chen0040.data.commons.consts.SparkGraphMinerFilePath;
import com.github.chen0040.data.commons.models.CoPair;
import com.github.chen0040.data.commons.models.OneToManyToOneAssociation;
import com.github.chen0040.data.sga.services.SkillAssocService;
import com.github.chen0040.lang.commons.utils.CollectionUtil;
import com.github.chen0040.lang.commons.utils.StringUtils;
import com.github.chen0040.spark.sga.graph.GraphPageRanker;
import com.github.chen0040.spark.sga.graph.LabelPropagationCommunityFinder;
import com.github.chen0040.spark.sga.components.HadoopClient;
import com.google.common.base.Optional;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import scala.Tuple2;
import java.io.*;
import java.util.*;
/**
* Created by xschen on 9/2/2017.
*/
@Service
public class SkillRuleMinerImpl implements SkillRuleMiner {
private static final Logger logger = LoggerFactory.getLogger(CompanyRuleMinerImpl.class);
@Value("${mine.debug}")
private boolean debugMode;
@Value("${mine.bigdata.hdfs.enabled}")
private boolean hadoopEnabled;
@Autowired
private HadoopClient hadoopClient;
@Autowired
private SkillAssocService skillAssocService;
@Override public String getVertexFilePath() {
return SparkGraphMinerFilePath.SkillVertexFilePath;
}
@Override public String getEdgeFilePath() {
return SparkGraphMinerFilePath.SkillEdgeFilePath;
}
@Override public String getRankFilePath() {
return SparkGraphMinerFilePath.SkillRankFilePath;
}
@Override public String getClusterFilePath() { return SparkGraphMinerFilePath.SkillClusterFilePath; }
@Override public void run(JavaSparkContext context, JavaPairRDD<String, String> skillCompanyRdd, int partitionCount) throws IOException {
JavaPairRDD<String, String> companySkillRdd = skillCompanyRdd.mapToPair(entry -> {
String skill = entry._1();
String companyName = entry._2();
return new Tuple2<>(companyName, skill);
}).coalesce(partitionCount).cache();
long count = companySkillRdd.count();
logger.info("company-skill: {}", count);
JavaPairRDD<String, Tuple2<String, Optional<String>>> rdd1 = (JavaPairRDD<String, Tuple2<String, Optional<String>>>)companySkillRdd.leftOuterJoin(companySkillRdd);
rdd1 = rdd1.coalesce(partitionCount).cache();
count = rdd1.count();
logger.info("left outer join for company-skill pair result: {}", count);
JavaPairRDD<String, List<OneToManyToOneAssociation>> rdd2 = rdd1
.mapToPair(entry -> {
String company = entry._1();
Tuple2<String, Optional<String>> skillPair = entry._2();
String skill1 = skillPair._1();
String skill2 = skillPair._2().or("");
Set<String> companies = new HashSet<>();
companies.add(company);
return new Tuple2<>(new CoPair(skill1, skill2), companies);
})
.filter(entry -> !StringUtils.isEmpty(entry._1().getItem1()) && !StringUtils.isEmpty(entry._1().getItem2()) && !entry._1().getItem1().equals(entry._1().getItem2()))
.reduceByKey((a, b) -> {
Set<String> c = new HashSet<>(a);
c.addAll(b);
return c;
})
.mapToPair(entry -> {
CoPair pair = entry._1();
Set<String> companies = entry._2();
String skill1 = pair.getItem1();
String skill2 = pair.getItem2();
OneToManyToOneAssociation csa = new OneToManyToOneAssociation(skill2, companies);
return new Tuple2<>(skill1, csa);
})
.combineByKey(a -> {
List<OneToManyToOneAssociation> result = new ArrayList<>();
result.add(a);
return result;
}, (csa, a) -> {
List<OneToManyToOneAssociation> result = new ArrayList<>(csa);
boolean merged = false;
for(int i=0; i < result.size(); ++i) {
OneToManyToOneAssociation item = result.get(i);
if(item.getEntity2().equals(a.getEntity2())){
item.addLinks(a.getLinks());
merged =true;
break;
}
}
if(!merged) {
result.add(a);
if (result.size() > 10) {
result.sort((a1, a2) -> Integer.compare(a2.getCount(), a1.getCount()));
result = CollectionUtil.subList(result, 0, 10);
}
}
return result;
}, (csa1, csa2) -> {
List<OneToManyToOneAssociation> result = new ArrayList<>(csa1);
result.addAll(csa2);
if(result.size() > 10){
result.sort((a1, a2) -> Integer.compare(a2.getCount(), a1.getCount()));
result = CollectionUtil.subList(result, 0, 10);
}
return result;
}).mapValues(entry -> {
List<OneToManyToOneAssociation> result = new ArrayList<>();
for(int i=0; i < entry.size(); ++i){
OneToManyToOneAssociation item = entry.get(i);
item.getLinks().clear();
result.add(item);
}
result.sort((a1, a2) -> Integer.compare(a2.getCount(), a1.getCount()));
return result;
});
Map<String, List<OneToManyToOneAssociation>> result = rdd2.collectAsMap();
rdd1.unpersist();
BufferedWriter vertexWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(getVertexFilePath())));
BufferedWriter edgeWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(getEdgeFilePath())));
int maxMinCount = 0;
Map<String, Integer> vertexIds = new HashMap<>();
for(Map.Entry<String, List<OneToManyToOneAssociation>> entry : result.entrySet()) {
String name = entry.getKey();
if(!vertexIds.containsKey(name)){
vertexIds.put(name, vertexIds.size());
}
List<OneToManyToOneAssociation> list = entry.getValue();
OneToManyToOneAssociation last = list.get(list.size()-1);
maxMinCount = Math.max(maxMinCount, last.getCount());
}
for(Map.Entry<String, List<OneToManyToOneAssociation>> entry : result.entrySet()) {
logger.info("skill: {}", entry.getKey());
vertexWriter.write(entry.getKey() + "\t" + vertexIds.get(entry.getKey()) + "\r\n");
List<OneToManyToOneAssociation> assocs = entry.getValue();
List<OneToManyToOneAssociation> refined = new ArrayList<>();
for(int j=0; j < assocs.size(); ++j) {
OneToManyToOneAssociation csa = assocs.get(j);
String associated = csa.getEntity2();
if(j != 0) {
csa.truncateLinks(maxMinCount);
}
if(csa.getCount() == 0) {
break;
}
refined.add(csa);
if(debugMode) {
logger.info("\t{} ({})", associated, csa.getCount());
}
if(entry.getKey().compareTo(associated) < 0){
edgeWriter.write(vertexIds.get(entry.getKey()) + "\t" + vertexIds.get(associated) + "\t" + csa.getCount() + "\r\n");
}
}
skillAssocService.saveSimilarSkills(entry.getKey(), refined);
try {
Thread.sleep(10L);
}
catch (InterruptedException e) {
logger.error("sleep interrupted");
}
}
vertexWriter.close();
edgeWriter.close();
String fPrefix;
if(hadoopEnabled) {
fPrefix = hadoopClient.getHadoopUri();
hadoopClient.copyFromLocalToHdfs(getVertexFilePath());
hadoopClient.copyFromLocalToHdfs(getEdgeFilePath());
} else {
fPrefix = "file://";
}
GraphPageRanker.run(context.sc(), fPrefix + getVertexFilePath(), fPrefix + getEdgeFilePath(), getRankFilePath());
saveRanking();
LabelPropagationCommunityFinder.run(context.sc(), fPrefix + getVertexFilePath(), fPrefix + getEdgeFilePath(),getClusterFilePath());
saveClustering();
}
private void saveClustering() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(getClusterFilePath())));
String line;
Map<Long, Long> mapper = new HashMap<>();
while((line = reader.readLine()) != null) {
String[] parts = line.split("\t");
String skill = parts[0];
long clusterId = StringUtils.parseLong(parts[1]);
if(mapper.containsKey(clusterId)){
clusterId = mapper.get(clusterId);
} else {
long mappedId = mapper.size()+1;
mapper.put(clusterId, mappedId);
clusterId = mappedId;
}
skillAssocService.saveClusterId(skill, clusterId);
}
reader.close();
if(hadoopEnabled) {
hadoopClient.copyFromLocalToHdfs(getClusterFilePath());
}
logger.info("db net-stat information on skill ranking: {}", skillAssocService.countNetStats());
}
private void saveRanking() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(getRankFilePath())));
String line;
while((line = reader.readLine()) != null) {
String[] parts = line.split("\t");
String skill = parts[0];
double rank = StringUtils.parseDouble(parts[1]);
skillAssocService.saveRank(skill, rank);
}
reader.close();
if(hadoopEnabled) {
hadoopClient.copyFromLocalToHdfs(getRankFilePath());
}
logger.info("db net-stat information on skill ranking: {}", skillAssocService.countNetStats());
}
@Override public void cleanUp() {
if(!debugMode) {
String[] paths = getFiles();
for (int i = 0; i < paths.length; ++i) {
String filePath = paths[i];
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
}
}
}
private String[] getFiles(){
return new String[] {getEdgeFilePath(), getRankFilePath(), getVertexFilePath(), getClusterFilePath()};
}
@Override public void setUp() {
if(hadoopEnabled) {
String[] paths = getFiles();
for (int i = 0; i < paths.length; ++i) {
String filePath = paths[i];
hadoopClient.delete(filePath);
}
}
}
}
|
3e024a95747106991319d7f8f91808cbda73d0a4 | 1,921 | java | Java | deps/alterrs/jode/expr/ThisOperator.java | clienthax/Deobfuscator | d63a29f2fed9098e0a0a7e962dca11866d8e77fd | [
"MIT"
] | 18 | 2015-05-27T18:34:37.000Z | 2021-06-11T22:34:31.000Z | deps/alterrs/jode/expr/ThisOperator.java | AlterRS/Deobfuscator | d63a29f2fed9098e0a0a7e962dca11866d8e77fd | [
"MIT"
] | null | null | null | deps/alterrs/jode/expr/ThisOperator.java | AlterRS/Deobfuscator | d63a29f2fed9098e0a0a7e962dca11866d8e77fd | [
"MIT"
] | 14 | 2015-05-21T21:24:43.000Z | 2021-09-19T05:30:33.000Z | 28.671642 | 78 | 0.743363 | 951 | /* ThisOperator Copyright (C) 1998-2002 Jochen Hoenicke.
*
* 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 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 Lesser General Public License
* along with this program; see the file COPYING.LESSER. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id: ThisOperator.java,v 1.2.4.1 2002/05/28 17:34:06 hoenicke Exp $
*/
package alterrs.jode.expr;
import alterrs.jode.bytecode.ClassInfo;
import alterrs.jode.decompiler.Scope;
import alterrs.jode.decompiler.TabbedPrintWriter;
import alterrs.jode.type.Type;
public class ThisOperator extends NoArgOperator {
boolean isInnerMost;
ClassInfo classInfo;
public ThisOperator(ClassInfo classInfo, boolean isInnerMost) {
super(Type.tClass(classInfo));
this.classInfo = classInfo;
this.isInnerMost = isInnerMost;
}
public ThisOperator(ClassInfo classInfo) {
this(classInfo, false);
}
public ClassInfo getClassInfo() {
return classInfo;
}
public int getPriority() {
return 1000;
}
public String toString() {
return classInfo + ".this";
}
public boolean opEquals(Operator o) {
return (o instanceof ThisOperator && ((ThisOperator) o).classInfo
.equals(classInfo));
}
public void dumpExpression(TabbedPrintWriter writer)
throws java.io.IOException {
if (!isInnerMost) {
writer.print(writer.getClassString(classInfo, Scope.AMBIGUOUSNAME));
writer.print(".");
}
writer.print("this");
}
}
|
3e024a9f8bccad3fd5f6dd1db4e5911e6c2f47e3 | 2,468 | java | Java | integration/java/src/main/java/org/artificer/integration/java/model/JavaModel.java | brmeyer/s-ramp | cfe42dfa539fb60de1b964153bc82b30d05917c2 | [
"Apache-2.0"
] | 1 | 2015-04-11T21:09:12.000Z | 2015-04-11T21:09:12.000Z | integration/java/src/main/java/org/artificer/integration/java/model/JavaModel.java | brmeyer/s-ramp | cfe42dfa539fb60de1b964153bc82b30d05917c2 | [
"Apache-2.0"
] | null | null | null | integration/java/src/main/java/org/artificer/integration/java/model/JavaModel.java | brmeyer/s-ramp | cfe42dfa539fb60de1b964153bc82b30d05917c2 | [
"Apache-2.0"
] | null | null | null | 45 | 89 | 0.762424 | 952 | /*
* Copyright 2013 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.artificer.integration.java.model;
/**
* Information about the java model defined by the java artifact builder(s).
*
* @author [email protected]
*/
public class JavaModel {
public static final String TYPE_ARCHIVE = "JavaArchive";
public static final String TYPE_WEB_APPLICATION = "JavaWebApplication";
public static final String TYPE_ENTERPRISE_APPLICATION = "JavaEnterpriseApplication";
public static final String TYPE_BEANS_XML = "BeanArchiveDescriptor";
public static final String TYPE_JAVA_CLASS = "JavaClass";
public static final String TYPE_JAVA_INTERFACE = "JavaInterface";
public static final String TYPE_JAVA_ENUM = "JavaEnum";
public static final String PROP_PACKAGE_NAME = "packageName";
public static final String PROP_CLASS_NAME = "className";
//maven info
public static final String TYPE_MAVEN_POM_XML = "MavenPom";
public static final String PROP_MAVEN_PROPERTY = "maven.property.";
public static final String PROP_MAVEN_ARTIFACT_ID = "maven.artifactId";
public static final String PROP_MAVEN_GROUP_ID = "maven.groupId";
public static final String PROP_MAVEN_VERSION = "maven.version";
public static final String PROP_MAVEN_TYPE = "maven.type";
public static final String PROP_MAVEN_CLASSIFIER = "maven.classifier";
public static final String PROP_MAVEN_PACKAGING = "maven.packaging";
public static final String PROP_MAVEN_PARENT_ARTIFACT_ID = "maven.parent.artifactId";
public static final String PROP_MAVEN_PARENT_GROUP_ID = "maven.parent.groupId";
public static final String PROP_MAVEN_PARENT_VERSION = "maven.parent.version";
public static final String PROP_MAVEN_HASH_MD5 = "maven.hash.md5";
public static final String PROP_MAVEN_HASH_SHA1 = "maven.hash.sha1";
public static final String PROP_MAVEN_SNAPSHOT_ID = "maven.snapshot.id";
}
|
3e024bfd185224b111fd6d3cd656f5fde15973a2 | 1,936 | java | Java | src/it/alma/ecrypt/api/EncryptApi.java | alotronto/encryptSetting | d2777680c8b1f62b6f2fed098e29e3f1d86c768f | [
"Apache-2.0"
] | null | null | null | src/it/alma/ecrypt/api/EncryptApi.java | alotronto/encryptSetting | d2777680c8b1f62b6f2fed098e29e3f1d86c768f | [
"Apache-2.0"
] | null | null | null | src/it/alma/ecrypt/api/EncryptApi.java | alotronto/encryptSetting | d2777680c8b1f62b6f2fed098e29e3f1d86c768f | [
"Apache-2.0"
] | null | null | null | 30.730159 | 119 | 0.753099 | 953 | package it.alma.ecrypt.api;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import it.alma.ecrypt.util.Encrypter;
/**
* Servlet implementation class EncryptApi
*/
@WebServlet("/encryptapi")
public class EncryptApi extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public EncryptApi() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter printWriter = response.getWriter();
response.setContentType("text/html");
if (request.getParameter("setting") != null) {
String setting = request.getParameter("setting");
System.out.println("EncryptAPI ClearText::"+setting);
String encryptedSetting = Encrypter.encrypt(setting);
System.out.println("EncryptAPI EncryptedText::"+encryptedSetting);
String encryptedSettingURL= URLEncoder.encode(encryptedSetting);
System.out.println("EncryptAPI EncryptedText URL::"+encryptedSettingURL);
printWriter.println(encryptedSettingURL);// URLEncoder.encode(encryptedSetting));
}
else {
printWriter.println("setting null");
System.out.println("EncryptAPI::"+"setting null");
}
}
}
|
3e024c0ca2f5869084222f9f5347907aa5940ea1 | 3,375 | java | Java | SVIEngine/src/com/github/sviengine/unittest/SceneNodeTestWindow.java | Samsung/SVIEngine | 36964f5b296317a3b7b2825137fef921a8c94973 | [
"Apache-2.0"
] | 27 | 2015-04-24T07:14:55.000Z | 2020-01-24T16:16:37.000Z | SVIEngine/src/com/github/sviengine/unittest/SceneNodeTestWindow.java | teeraporn39/SVIEngine | 87e379a1e1906025660e9de8da8ff908faf0a976 | [
"Apache-2.0"
] | null | null | null | SVIEngine/src/com/github/sviengine/unittest/SceneNodeTestWindow.java | teeraporn39/SVIEngine | 87e379a1e1906025660e9de8da8ff908faf0a976 | [
"Apache-2.0"
] | 15 | 2015-12-08T14:46:19.000Z | 2020-01-21T19:26:41.000Z | 26.162791 | 142 | 0.679407 | 954 | package com.github.sviengine.unittest;
import com.github.sviengine.slide.SVISlide;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
public class SceneNodeTestWindow extends PlatformWindow{
public SceneNodeTestWindow(Context context) {
super(context);
mMsgHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
sendEmptyMessageDelayed(0, 200);
}
};
buildSlideTree();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// TODO Auto-generated method stub
super.surfaceChanged(holder, format, w, h);
}
public void onConfigurationChanged(int rotation) {
}
@Override
public void onPause(){
SVISlide mainSlide = getMainSlide();
if (mainSlide != null){
mainSlide.setCapture(false);
if (mMsgHandler != null){
mMsgHandler.removeMessages(0);
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
if( event.getAction() == MotionEvent.ACTION_DOWN){
long time = System.currentTimeMillis();
if( (time - mClickTime) < 1000 ) {
//mLeftSlide.removeSceneNode();
//mRightSlide.removeSceneNode();
//mRemove = true;
}
mClickTime = time;
if(mFlag == false) {
/// set model position animation
//mLeftSlide.setModelPosition(70.0f, 0.0f, 0.0f, 500);
//mRightSlide.setModelPosition(0.0f, 100.0f, 0.0f, 500);
// set model rotation animation
//mLeftSlide.setModelRotation(0.0f, 0.0f, 180.0f, 500);
//mRightSlide.setModelRotation(0.0f, 0.0f, 180.0f, 500);
/// set model scale animation
//mLeftSlide.setModelScale(2.0f, 2.0f, 2.0f, 500);
//mRightSlide.setModelScale(2.0f, 2.0f, 2.0f, 500);
mFlag = true;
}
else {
/// set model position animation
//mLeftSlide.setModelPosition(0.0f, 0.0f, 0.0f, 500);
//mRightSlide.setModelPosition(0.0f, 0.0f, 0.0f, 500);
/// set model rotation animation
//mLeftSlide.setModelRotation(0.0f, 0.0f, 0.0f, 500);
//mRightSlide.setModelRotation(0.0f, 0.0f, 0.0f, 500);
/// set model scale animation
//mLeftSlide.setModelScale(1.0f, 1.0f, 1.0f, 1000);
//mRightSlide.setModelScale(1.0f, 1.0f, 1.0f, 1000);
mFlag = false;
}
}
return true;
}
protected void buildSlideTree() {
super.buildSubSlide();
float color[] = { 1.0f, 1.0f, 1.0f, 1.0f };
mMainSlide = getMainSlide();
//SVISize mainSize = mMainSlide.getRegion().mSize;
mMainSlide.setBackgroundColor(color);
//float width = mainSize.mWidth / 2.0f;
//float height = mainSize.mHeight;
//mLeftSlide = new SVISlide(0, mMainSlide.getNativeSlideHandle(), 0, 0, width, height, color);
//mRightSlide = new SVISlide(0, mMainSlide.getNativeSlideHandle(), width + width / 4.0f, height / 4.0f, width / 2.0f, height / 2.0f, color);
//SVISceneNode node = SVISceneNode.createSceneNodeFromModelFile("parent.bsa");
//mRightSlide.setSceneNode(node);
//mLeftSlide.setSceneNode(node);
}
private Handler mMsgHandler;
private SVISlide mMainSlide;
//private SVISlide mLeftSlide;
//private SVISlide mRightSlide;
private boolean mFlag = false;
//private boolean mRemove = false;
private long mClickTime = 0;
}
|
3e024d6f5cf7d3adadb5b644646ebd62488ba167 | 2,703 | java | Java | support/cas-server-support-webauthn-ldap/src/test/java/org/apereo/cas/webauthn/OpenLdapWebAuthnCredentialRepositoryTests.java | chulei926/cas | 2ad43ec75016fb43fff98b37922c2daecefffeb9 | [
"Apache-2.0"
] | 8,772 | 2016-05-08T04:44:50.000Z | 2022-03-31T06:02:13.000Z | support/cas-server-support-webauthn-ldap/src/test/java/org/apereo/cas/webauthn/OpenLdapWebAuthnCredentialRepositoryTests.java | chulei926/cas | 2ad43ec75016fb43fff98b37922c2daecefffeb9 | [
"Apache-2.0"
] | 2,911 | 2016-05-07T23:07:52.000Z | 2022-03-31T15:09:08.000Z | support/cas-server-support-webauthn-ldap/src/test/java/org/apereo/cas/webauthn/OpenLdapWebAuthnCredentialRepositoryTests.java | chulei926/cas | 2ad43ec75016fb43fff98b37922c2daecefffeb9 | [
"Apache-2.0"
] | 3,675 | 2016-05-08T04:45:46.000Z | 2022-03-31T09:34:54.000Z | 37.027397 | 112 | 0.706992 | 955 | package org.apereo.cas.webauthn;
import org.apereo.cas.adaptors.ldap.LdapIntegrationTestsOperations;
import org.apereo.cas.config.LdapWebAuthnConfiguration;
import org.apereo.cas.util.junit.EnabledIfPortOpen;
import org.apereo.cas.webauthn.storage.BaseWebAuthnCredentialRepositoryTests;
import com.unboundid.ldap.sdk.LDAPConnection;
import lombok.Cleanup;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.val;
import org.junit.jupiter.api.Tag;
import org.ldaptive.BindConnectionInitializer;
import org.ldaptive.Credential;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.TestPropertySource;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
/**
* This is {@link OpenLdapWebAuthnCredentialRepositoryTests}.
*
* @author Misagh Moayyed
* @since 6.3.0
*/
@TestPropertySource(
properties = {
"cas.authn.mfa.web-authn.ldap.ldap-url=ldap://localhost:11389",
"cas.authn.mfa.web-authn.ldap.base-dn=ou=people,dc=example,dc=org",
"cas.authn.mfa.web-authn.ldap.search-filter=cn={0}",
"cas.authn.mfa.web-authn.ldap.account-attribute-name=description",
"cas.authn.mfa.web-authn.ldap.bind-dn=cn=admin,dc=example,dc=org",
"cas.authn.mfa.web-authn.ldap.bind-credential=P@ssw0rd",
"cas.authn.mfa.web-authn.ldap.trust-manager=ANY"
})
@Tag("Ldap")
@EnabledIfPortOpen(port = 11636)
@Getter
@Import(LdapWebAuthnConfiguration.class)
public class OpenLdapWebAuthnCredentialRepositoryTests extends BaseWebAuthnCredentialRepositoryTests {
@SneakyThrows
@Override
protected String getUsername() {
val uid = super.getUsername();
val bindInit = new BindConnectionInitializer("cn=admin,dc=example,dc=org", new Credential("P@ssw0rd"));
@Cleanup
val connection = new LDAPConnection("localhost", 11389,
bindInit.getBindDn(), bindInit.getBindCredential().getString());
val rs = new ByteArrayInputStream(getLdif(uid).getBytes(StandardCharsets.UTF_8));
LdapIntegrationTestsOperations.populateEntries(connection, rs, "ou=people,dc=example,dc=org", bindInit);
return uid;
}
protected String getLdif(final String user) {
val baseDn = casProperties.getAuthn().getMfa().getWebAuthn().getLdap().getBaseDn();
return String.format("dn: cn=%s,%s%n"
+ "objectClass: top%n"
+ "objectClass: person%n"
+ "objectClass: organizationalPerson%n"
+ "objectClass: inetOrgPerson%n"
+ "cn: %s%n"
+ "userPassword: 123456%n"
+ "sn: %s%n"
+ "uid: %s%n", user, baseDn, user, user, user);
}
}
|
3e0250bfcdd3e30f11aa0801a85adcd906ff3f0e | 2,606 | java | Java | ServerWebSockets/src/pt/uminho/sd/pi/Server.java | miguelcobain/ColabOT-Server | 07126ad2d3a0eeedc6efd6bb97b97ac7a44532d0 | [
"MIT"
] | null | null | null | ServerWebSockets/src/pt/uminho/sd/pi/Server.java | miguelcobain/ColabOT-Server | 07126ad2d3a0eeedc6efd6bb97b97ac7a44532d0 | [
"MIT"
] | null | null | null | ServerWebSockets/src/pt/uminho/sd/pi/Server.java | miguelcobain/ColabOT-Server | 07126ad2d3a0eeedc6efd6bb97b97ac7a44532d0 | [
"MIT"
] | null | null | null | 22.084746 | 100 | 0.666155 | 956 | package pt.uminho.sd.pi;
import java.io.IOException;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Server extends WebSocketServer{
/**
* @param args
*
*/
HashMap<Integer, Document> docs;
public Server(int port){
super(port);
System.out.println("Servidor iniciado na porta:"+ port);
docs = new HashMap<Integer, Document>();
docs.put(1, new Document());
start();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Server server = new Server(8000);
}
@Override
public void onClientOpen(WebSocket conn) {
// TODO Auto-generated method stub
}
@Override
public void onClientClose(WebSocket conn) {
// TODO Auto-generated method stub
}
@Override
public void onClientMessage(WebSocket conn, String message) {
// TODO Auto-generated method stub
System.out.println("Nova Mensagem:" + message);
try {
conn.send(message);
parser(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void parser(String json){
try {
//Get the message
JSONObject j = new JSONObject(json);
JSONArray op = j.getJSONArray("msg");
JSONObject operationsObj = op.getJSONObject(0) ;
JSONObject stateobj = op.getJSONObject(1);
JSONArray operations = operationsObj.getJSONArray("operation");
Document doc = docs.get(1);
for(int i=0; i<operations.length();i++){
//Get all operations
JSONObject operation = operations.getJSONObject(i);
String opname = operation.getString("_type");
JSONArray args = operation.getJSONArray("_args");
if(opname.compareTo("add")==0){
int index = args.getInt(0);
String insert = args.getString(1);
doc.add(index, insert);
System.out.println("Operation:"+opname+" Position:"+index+" String:"+insert);
}else if(opname.compareTo("del")==0){
int index = args.getInt(0);
int length = args.getInt(1);
doc.remove(index, length);
System.out.println("Operation:"+opname+" Position:"+index+" Length:"+length);
}else if(opname.compareTo("rep")==0){
int index = args.getInt(0);
int length = args.getInt(1);
String insert = args.getString(2);
doc.replace(index, length, insert);
System.out.println("Operation:"+opname+" Position:"+index+" Length:"+length+" String:"+insert);
}
else{
System.out.println("give exception - no operation");
}
}
} catch (JSONException e) {System.out.println("Error on message inside json!! "+ e);}
}
}
|
3e02511c93678d32dd252223dbf290b94d900e55 | 10,988 | java | Java | Corpus/birt/2018.java | JamesCao2048/BlizzardData | a524bec4f0d297bb748234eeb1c2fcdee3dce7d7 | [
"MIT"
] | 1 | 2022-01-15T02:47:45.000Z | 2022-01-15T02:47:45.000Z | Corpus/birt/2018.java | JamesCao2048/BlizzardData | a524bec4f0d297bb748234eeb1c2fcdee3dce7d7 | [
"MIT"
] | null | null | null | Corpus/birt/2018.java | JamesCao2048/BlizzardData | a524bec4f0d297bb748234eeb1c2fcdee3dce7d7 | [
"MIT"
] | null | null | null | 27.333333 | 130 | 0.558791 | 957 | /*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.core.script.bre;
import junit.framework.TestCase;
import org.eclipse.birt.core.script.CoreJavaScriptInitializer;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
/**
*
*/
public class BirtCompTest extends TestCase
{
private Context cx;
private Scriptable scope;
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#setUp()
*/
public void setUp( ) throws Exception
{
/*
* Creates and enters a Context. The Context stores information about
* the execution environment of a script.
*/
cx = Context.enter( );
/*
* Initialize the standard objects (Object, Function, etc.) This must be
* done before scripts can be executed. Returns a scope object that we
* use in later calls.
*/
scope = cx.initStandardObjects( );
new CoreJavaScriptInitializer().initialize( cx, scope );
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#tearDown()
*/
public void tearDown( )
{
Context.exit( );
}
/**
*
*
*/
public void testAnyOf()
{
/*String script1 = "var array = new Array(4);array[0] = 100; array[1] = \"ABC\"; array[2] = \"1999-11-10\"; array[3] = null;";*/
String script2 = "BirtComp.anyOf(100,100,\"ABC\", \"1999-11-10\",null);";
String script3 = "BirtComp.anyOf(null,100,\"ABC\", \"1999-11-10\",null)";
String script4 = "BirtComp.anyOf(\"ABC\",100,\"ABC\", \"1999-11-10\",null)";
String script5 = "BirtComp.anyOf(new Date(99,10,10),100,\"ABC\", \"1999-11-10\",null)";
String script6 = "BirtComp.anyOf(\"1999-11-10\",100,\"ABC\", \"1999-11-10\",null)";
String script7 = "BirtComp.anyOf(20,100,\"ABC\", \"1999-11-10\",null)";
String script8 = "array = new Array(3);array[0]=0;array[1]=1;array[2]=2;BirtComp.anyOf(1,array);";
String script9 = "array = new Array(3);array[0]=0;array[1]=1;array[2]=2;BirtComp.anyOf(4,array);";
assertTrue( ( (Boolean) cx.evaluateString( scope,
script2,
"inline",
1,
null ) ).booleanValue( ) );
assertTrue( ( (Boolean) cx.evaluateString( scope,
script3,
"inline",
1,
null ) ).booleanValue( ) );
assertTrue( ( (Boolean) cx.evaluateString( scope,
script4,
"inline",
1,
null ) ).booleanValue( ) );
assertTrue( ( (Boolean) cx.evaluateString( scope,
script5,
"inline",
1,
null ) ).booleanValue( ) );
assertTrue( ( (Boolean) cx.evaluateString( scope,
script6,
"inline",
1,
null ) ).booleanValue( ) );
assertFalse( ( (Boolean) cx.evaluateString( scope,
script7,
"inline",
1,
null ) ).booleanValue( ) );
assertTrue( ( (Boolean) cx.evaluateString( scope,
script8,
"inline",
1,
null ) ).booleanValue( ) );
assertFalse( ( (Boolean) cx.evaluateString( scope,
script9,
"inline",
1,
null ) ).booleanValue( ) );
}
public void testBetween()
{
String script1 = "BirtComp.between(\"1923-10-11\",new Date(10,11,11),new Date(33,11,11))";
assertTrue( ( (Boolean) cx.evaluateString( scope,
script1,
"inline",
1,
null ) ).booleanValue( ) );
String script2 = "BirtComp.between(100,101,102)";
assertFalse( ( (Boolean) cx.evaluateString( scope,
script2,
"inline",
1,
null ) ).booleanValue( ) );
}
/**
*
*
*/
public void testNotBetween()
{
String script1 = "BirtComp.notBetween(\"1923-10-11\",new Date(10,11,11),new Date(33,11,11))";
assertFalse( ( (Boolean) cx.evaluateString( scope,
script1,
"inline",
1,
null ) ).booleanValue( ) );
String script2 = "BirtComp.notBetween(100,101,102)";
assertTrue( ( (Boolean) cx.evaluateString( scope,
script2,
"inline",
1,
null ) ).booleanValue( ) );
}
/**
*
*
*/
public void testCompare()
{
String[] script = new String[]{
//Equal to
"BirtComp.equalTo(100,100);",
"BirtComp.equalTo(null,null)",
"BirtComp.equalTo(\"ABC\",\"ABC\")",
"BirtComp.equalTo(new Date(99,10,10),\"1999-11-10\")",
"BirtComp.equalTo(\"1999-11-10\",new Date(99,10,10))",
"BirtComp.equalTo(20,100)",
"BirtComp.equalTo( new java.sql.Time(10,10,10), \"10:10:10.000\")",
"BirtComp.equalTo( new java.sql.Date(80,9,9), \"1980-10-9 12:14:25\")",
//NotEqual to
"BirtComp.notEqual(100,100);",
"BirtComp.notEqual(null,null)",
"BirtComp.notEqual(\"ABC\",\"ABC\")",
"BirtComp.notEqual(new Date(99,10,10),\"1999-11-10\")",
"BirtComp.notEqual(\"1999-11-10\",new Date(99,10,10))",
"BirtComp.notEqual(20,100)",
//greater than
"BirtComp.greaterThan(100,10);",
"BirtComp.greaterThan(null,null)",
"BirtComp.greaterThan(\"aBC\",\"ABC\")",
"BirtComp.greaterThan(new Date(99,9,10),\"1999-11-10\")",
"BirtComp.greaterThan(\"1999-11-10\",new Date(99,9,10))",
"BirtComp.greaterThan(20,100)",
//greater than or equal to
"BirtComp.greaterOrEqual(100,10);",
"BirtComp.greaterOrEqual(null,null)",
"BirtComp.greaterOrEqual(\"aBC\",\"ABC\")",
"BirtComp.greaterOrEqual(new Date(99,9,10),\"1999-11-10\")",
"BirtComp.greaterOrEqual(\"1999-11-10\",new Date(99,9,10))",
"BirtComp.greaterOrEqual(20,100)",
//Less than
"BirtComp.lessThan(10,100);",
"BirtComp.lessThan(null,null)",
"BirtComp.lessThan(\"aBC\",\"ABC\")",
"BirtComp.lessThan(new Date(99,9,10),\"1999-11-10\")",
"BirtComp.lessThan(\"1999-11-10\",new Date(99,9,10))",
"BirtComp.lessThan(20,100)",
//greater than or equal to
"BirtComp.lessOrEqual(100,10);",
"BirtComp.lessOrEqual(null,null)",
"BirtComp.lessOrEqual(\"aBC\",\"ABC\")",
"BirtComp.lessOrEqual(new Date(99,9,10),\"1999-11-10\")",
"BirtComp.lessOrEqual(\"1999-11-10\",new Date(99,9,10))",
"BirtComp.lessOrEqual(100,100)",
};
boolean[] result = new boolean[] { true, true, true, true, true, false,true,true,
false,false,false,false,false,true,
true, false, false, false, true, false,
true, true, false, false, true, false,
true, false, true, true, false, true,
false, true, true, true, false, true};
for( int i = 0; i < script.length; i++ )
{
assertTrue( ( (Boolean) cx.evaluateString( scope,
script[i],
"inline",
1,
null ) ).booleanValue( ) == result[i]);
}
}
/**
*
*
*/
public void testMatch()
{
String[] script = new String[]{
//Equal to
"BirtComp.match(\"x 99:02:03\",\".*[0-9]*:[0-9]*:[0-9]*\");",
"BirtComp.match(\"x 99::03\",\".*[0-9]*:[0-9]*:[0-9]*\");",
"BirtComp.match(\"x 99:02:03\",\"x [0-9]*:[0-9]*:[0-9]*\");",
"BirtComp.match(\"x 99:02:03\",\".*99*:[0-9]*:[0-9]*\");",
"BirtComp.match(\"x 99:02:03\",\".*[0-9]*.[0-9]*:[0-9]*\");",
"BirtComp.match(\"x 99:02:03\",\".*[0-9]*:[0-9]*:[0-9]*3.\");",
};
boolean[] result = new boolean[] { true, true, true, true, true, false};
for( int i = 0; i < script.length; i++ )
{
assertTrue( ( (Boolean) cx.evaluateString( scope,
script[i],
"inline",
1,
null ) ).booleanValue( ) == result[i]);
}
}
/**
*
*
*/
public void testLike()
{
String[] script = new String[]{
//Equal to
"BirtComp.like(\"x 99:02:03\",\"%:0_:03\");",
"BirtComp.like(\"x 99::003\",\"%9_::__3\");",
"BirtComp.like(\"x 99:02:03\",\"%99:02_03\");",
"BirtComp.like(\"x 99:02:03\",\"x 99%0_\");",
"BirtComp.like(\"x 99:02:03\",\"_ 99%03\");",
"BirtComp.like(\"x 99:02:03\",\"%:0_:__3\");",
"BirtComp.like(\"x 99:02:03\",\"%:0\\\\_03\");",
"BirtComp.like(\"x 99:02_03\",\"%:0\\\\_03\");",
"BirtComp.like(\"x 99:02_03\",\"%:02\\\\_03\");",
"BirtComp.like(\"x 99:02_03\",\"\\\\%:02\\\\_03\");",
"BirtComp.like(\"x 99%:02_03\",\"%\\\\%:02\\\\_03\");",
"BirtComp.like(\"x 99%:02_03\",\"\\\\\\\\%\\\\%:02\\\\_03\");",
"BirtComp.like(\"x \\\\99%:02_03\",\"_ \\\\\\\\99\\\\%:02\\\\_03\");"
};
boolean[] result = new boolean[]{
true,
true,
true,
true,
true,
false,
false,
false,
true,
false,
true,
false,
true
};
for( int i = 0; i < script.length; i++ )
{
assertEquals( result[i], ( (Boolean) cx.evaluateString( scope,
script[i],
"inline",
1,
null ) ).booleanValue( ) );
}
}
/**
*
*
*/
public void testNotLike()
{
String[] script = new String[]{
//Equal to
"BirtComp.notLike(\"x 99:02:03\",\"%:0_:03\");",
"BirtComp.notLike(\"x 99::003\",\"%9_::__3\");",
"BirtComp.notLike(\"x 99:02:03\",\"%99:02_03\");",
"BirtComp.notLike(\"x 99:02:03\",\"x 99%0_\");",
"BirtComp.notLike(\"x 99:02:03\",\"_ 99%03\");",
"BirtComp.notLike(\"x 99:02:03\",\"%:0_:__3\");",
"BirtComp.notLike(\"x 99:02:03\",\"%:0\\\\_03\");",
"BirtComp.notLike(\"x 99:02_03\",\"%:0\\\\_03\");",
"BirtComp.notLike(\"x 99:02_03\",\"%:02\\\\_03\");",
"BirtComp.notLike(\"x 99:02_03\",\"\\\\%:02\\\\_03\");",
"BirtComp.notLike(\"x 99%:02_03\",\"%\\\\%:02\\\\_03\");",
"BirtComp.notLike(\"x 99%:02_03\",\"\\\\\\\\%\\\\%:02\\\\_03\");",
"BirtComp.notLike(\"x \\\\99%:02_03\",\"_ \\\\\\\\99\\\\%:02\\\\_03\");"
};
boolean[] result = new boolean[]{
false,
false,
false,
false,
false,
true,
true,
true,
false,
true,
false,
true,
false
};
for( int i = 0; i < script.length; i++ )
{
assertEquals( result[i], ( (Boolean) cx.evaluateString( scope,
script[i],
"inline",
1,
null ) ).booleanValue( ) );
}
}
/**
* Test BirtComp.compareString function
*
*/
public void testCompareString( )
{
String[] script = new String[]{
"BirtComp.compareString(null,null)",
"BirtComp.compareString(null,\"abc\")",
"BirtComp.compareString(\"abc\",null);",
"BirtComp.compareString(\"ABC\",\"ABC\")",
"BirtComp.compareString(\"abc\",\"ABC\")",
"BirtComp.compareString(\"ABC\",\"DEF\")",
"BirtComp.compareString(\"abc\",\"ABC\",true)",
"BirtComp.compareString(\"abc \",\"ABC\",true)",
"BirtComp.compareString(\"abc \",\"ABC\",true,true)",
"BirtComp.compareString(\"abc \",\"ABC\",false,true)",
};
boolean[] result = new boolean[] { true, false, false, true, false, false, true, false, true, false };
for ( int i = 0; i < script.length; i++ )
{
assertTrue( (Boolean) cx.evaluateString( scope,
script[i],
"inline",
1,
null ) == result[i] );
System.out.println( i );
}
}
}
|
3e025195901744a9b1553ac36944d8a17f24799e | 1,022 | java | Java | data/account/delete/account-delete-java-apachehttpclient.java | filethis/ft-test-account-manager | e074782793b95ab3e7b2267635c7a72fe992dc17 | [
"Apache-2.0"
] | null | null | null | data/account/delete/account-delete-java-apachehttpclient.java | filethis/ft-test-account-manager | e074782793b95ab3e7b2267635c7a72fe992dc17 | [
"Apache-2.0"
] | null | null | null | data/account/delete/account-delete-java-apachehttpclient.java | filethis/ft-test-account-manager | e074782793b95ab3e7b2267635c7a72fe992dc17 | [
"Apache-2.0"
] | null | null | null | 31.9375 | 89 | 0.720157 | 958 | import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import java.io.IOException;
import static com.jayway.jsonpath.matchers.JsonPathMatchers.hasJsonPath;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class TestClass
{
@Test
public void testHttpCall() throws IOException
{
// Build request
HttpDelete request = new HttpDelete("{{SERVER}}/api/v1/accounts/{{ACCOUNT_ID}}");
request.add("Authorization", "Basic {{API_CREDENTIALS}}");
// Send request
HttpResponse response = HttpClientBuilder.create().build().execute(request);
// Extract response
HttpEntity entity = response.getEntity();
String jsonString = EntityUtils.toString(entity);
assertThat(jsonString, hasJsonPath("$.status", is("OK")));
}
} |
3e025314f938473388dd2842f6ebe904fe022ea3 | 2,792 | java | Java | proFL-plugin-2.0.3/org/mudebug/prapr/reloc/commons/lang3/ArchUtils.java | ycj123/Research-Project | 08296e0075ba0c13204944b1bc1a96a7b8d2f023 | [
"MIT"
] | null | null | null | proFL-plugin-2.0.3/org/mudebug/prapr/reloc/commons/lang3/ArchUtils.java | ycj123/Research-Project | 08296e0075ba0c13204944b1bc1a96a7b8d2f023 | [
"MIT"
] | null | null | null | proFL-plugin-2.0.3/org/mudebug/prapr/reloc/commons/lang3/ArchUtils.java | ycj123/Research-Project | 08296e0075ba0c13204944b1bc1a96a7b8d2f023 | [
"MIT"
] | null | null | null | 34.04878 | 117 | 0.655802 | 959 | //
// Decompiled by Procyon v0.5.36
//
package org.mudebug.prapr.reloc.commons.lang3;
import java.util.HashMap;
import org.mudebug.prapr.reloc.commons.lang3.arch.Processor;
import java.util.Map;
public class ArchUtils
{
private static final Map<String, Processor> ARCH_TO_PROCESSOR;
private static void init() {
init_X86_32Bit();
init_X86_64Bit();
init_IA64_32Bit();
init_IA64_64Bit();
init_PPC_32Bit();
init_PPC_64Bit();
}
private static void init_X86_32Bit() {
final Processor processor = new Processor(Processor.Arch.BIT_32, Processor.Type.X86);
addProcessors(processor, "x86", "i386", "i486", "i586", "i686", "pentium");
}
private static void init_X86_64Bit() {
final Processor processor = new Processor(Processor.Arch.BIT_64, Processor.Type.X86);
addProcessors(processor, "x86_64", "amd64", "em64t", "universal");
}
private static void init_IA64_32Bit() {
final Processor processor = new Processor(Processor.Arch.BIT_32, Processor.Type.IA_64);
addProcessors(processor, "ia64_32", "ia64n");
}
private static void init_IA64_64Bit() {
final Processor processor = new Processor(Processor.Arch.BIT_64, Processor.Type.IA_64);
addProcessors(processor, "ia64", "ia64w");
}
private static void init_PPC_32Bit() {
final Processor processor = new Processor(Processor.Arch.BIT_32, Processor.Type.PPC);
addProcessors(processor, "ppc", "power", "powerpc", "power_pc", "power_rs");
}
private static void init_PPC_64Bit() {
final Processor processor = new Processor(Processor.Arch.BIT_64, Processor.Type.PPC);
addProcessors(processor, "ppc64", "power64", "powerpc64", "power_pc64", "power_rs64");
}
private static void addProcessor(final String key, final Processor processor) throws IllegalStateException {
if (!ArchUtils.ARCH_TO_PROCESSOR.containsKey(key)) {
ArchUtils.ARCH_TO_PROCESSOR.put(key, processor);
return;
}
final String msg = "Key " + key + " already exists in processor map";
throw new IllegalStateException(msg);
}
private static void addProcessors(final Processor processor, final String... keys) throws IllegalStateException {
for (final String key : keys) {
addProcessor(key, processor);
}
}
public static Processor getProcessor() {
return getProcessor(SystemUtils.OS_ARCH);
}
public static Processor getProcessor(final String value) {
return ArchUtils.ARCH_TO_PROCESSOR.get(value);
}
static {
ARCH_TO_PROCESSOR = new HashMap<String, Processor>();
init();
}
}
|
3e02539bcbd4163e86a6f9ed514caf6d08ae7734 | 3,731 | java | Java | src/main/java/br/com/muryllo/jmailer/Mailer.java | MurylloEx/JMailer | 8dbaf3de40983a77970ace37d4e87668f38889e7 | [
"MIT"
] | 1 | 2021-07-30T17:23:43.000Z | 2021-07-30T17:23:43.000Z | src/main/java/br/com/muryllo/jmailer/Mailer.java | MurylloEx/JMailer | 8dbaf3de40983a77970ace37d4e87668f38889e7 | [
"MIT"
] | null | null | null | src/main/java/br/com/muryllo/jmailer/Mailer.java | MurylloEx/JMailer | 8dbaf3de40983a77970ace37d4e87668f38889e7 | [
"MIT"
] | null | null | null | 28.480916 | 91 | 0.669258 | 960 | package br.com.muryllo.jmailer;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;
import okhttp3.RequestBody;
import okhttp3.MediaType;
public class Mailer {
private static final String SMTP_API_URL = "https://api.smtp2go.com/v3/";
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private String m_SecretKey = "";
private String m_SenderName = "";
private String m_SenderEmail = "";
private ArrayList<String> m_Recipients = new ArrayList<>();
private String m_SubjectText = "";
private String m_TextBody = "";
private String m_HtmlBody = "";
/**
* Define a chave da api de envio de emails.
*
* @param seckey A chave da API SMTP2GO usada para enviar os emails.
* @return A instância do Mailer.
*/
public Mailer key(String seckey){
this.m_SecretKey = seckey;
return this;
}
/**
* Define quem enviou o email.
* Perceba que essa campo pode ser forjado, você pode enviar o email sendo quem quiser.
*
* @param senderName O nome do remetente.
* @param senderEmail O eendereço de email do remetente
* @return A instância do Mailer.
*/
public Mailer from(String senderName, String senderEmail){
this.m_SenderName = senderName;
this.m_SenderEmail = senderEmail;
return this;
}
/**
* Define para quem será enviado o email.
*
* @param recipientName O nome do destinatário.
* @param recipientEmail O endereço de email do destinatário.
* @return A instância do Mailer.
*/
public Mailer to(String recipientName, String recipientEmail){
this.m_Recipients.add(
String.format("%s <%s>", recipientName, recipientEmail));
return this;
}
/**
* Define o título do email (assunto).
*
* @param text O título do email que aparecerá para o destinatário.
* @return A instância do Mailer.
*/
public Mailer subject(String text){
this.m_SubjectText = text;
return this;
}
/**
* Define o corpo do texto do email a ser enviado.
*
* @param text O corpo do texto do email.
* @return A instância do Mailer.
*/
public Mailer textBody(String text){
this.m_TextBody = text;
return this;
}
/**
* Define o corpo HTML do email a ser enviado.
* É possível enviar emails estilizados com html e css.
*
* @param html O corpo HTML do email. Ele deve ser feito em padrão HTML5.
* @return A instância do Mailer.
*/
public Mailer htmlBody(String html){
this.m_HtmlBody = html;
return this;
}
/**
* Envia o email para o destinatário solicitado de forma síncrona.
*
* @return Retorna a resposta do servidor SMTP em formato JSON.
*/
public MailerResponse send(){
try{
Envelope envelope = new Envelope()
.setApiKey(this.m_SecretKey)
.setTo(this.m_Recipients)
.setSender(String.format("%s <%s>", this.m_SenderName, this.m_SenderEmail))
.setSubject(this.m_SubjectText)
.setTextBody(this.m_TextBody)
.setHtmlBody(this.m_HtmlBody);
String envelopeJson = JsonService.stringify(envelope, Envelope.class);
RequestBody reqBody = RequestBody.Companion.create(envelopeJson, JSON);
Map<String, String> queryString = new Hashtable<String, String>();
Map<String, String> headers = new Hashtable<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
String response = RequestService.post(
SMTP_API_URL + "/email/send",
reqBody,
headers,
queryString);
return JsonService.parse(response, MailerResponse.class);
} catch(Exception exception){
return new MailerResponse();
}
}
}
|
3e02540afa1158b4b1b749c201f6453173fb0c14 | 1,206 | java | Java | geo-backend/src/main/java/com/zenika/back/controller/UserControllerImpl.java | RomainVernoux/GeoStack | 2f007c674770c0d8123de0a19c67d15014e59540 | [
"MIT"
] | 2 | 2016-10-09T18:48:42.000Z | 2020-11-05T10:08:08.000Z | geo-backend/src/main/java/com/zenika/back/controller/UserControllerImpl.java | RomainVernoux/GeoStack | 2f007c674770c0d8123de0a19c67d15014e59540 | [
"MIT"
] | null | null | null | geo-backend/src/main/java/com/zenika/back/controller/UserControllerImpl.java | RomainVernoux/GeoStack | 2f007c674770c0d8123de0a19c67d15014e59540 | [
"MIT"
] | null | null | null | 32.810811 | 91 | 0.769357 | 961 | package com.zenika.back.controller;
import com.zenika.back.controller.base.UserController;
import com.zenika.back.message.GcmToken;
import com.zenika.back.service.base.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* User controller.
*
* Created by Romain Vernoux ([email protected]) on 10/01/2016.
*/
@RestController
public class UserControllerImpl implements UserController {
private static final Logger logger = LoggerFactory.getLogger(UserControllerImpl.class);
@Autowired
private UserService userService;
/**
* {@inheritDoc}
*/
@Override
@RequestMapping(method = RequestMethod.POST, value = "/user")
public void updateGcmToken(@RequestBody(required = true) GcmToken gcmToken) {
logger.info("GCM token update received for user {}", gcmToken.getUserId());
userService.updateGcmToken(gcmToken);
}
}
|
3e025472b2b5f4d96848dec12ef228348ab13ebf | 1,761 | java | Java | spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileURLStreamHandler.java | nosan/spring-boot | 30815cc0e0ace7c849fc58c61a079545c9805fd5 | [
"Apache-2.0"
] | 66,985 | 2015-01-01T14:37:10.000Z | 2022-03-31T21:00:10.000Z | spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileURLStreamHandler.java | nosan/spring-boot | 30815cc0e0ace7c849fc58c61a079545c9805fd5 | [
"Apache-2.0"
] | 27,513 | 2015-01-01T03:27:09.000Z | 2022-03-31T19:03:12.000Z | spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/classloader/ClassLoaderFileURLStreamHandler.java | nosan/spring-boot | 30815cc0e0ace7c849fc58c61a079545c9805fd5 | [
"Apache-2.0"
] | 42,709 | 2015-01-02T01:08:50.000Z | 2022-03-31T20:26:44.000Z | 25.897059 | 92 | 0.757524 | 962 | /*
* Copyright 2012-2020 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
*
* https://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.boot.devtools.restart.classloader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
/**
* {@link URLStreamHandler} for the contents of a {@link ClassLoaderFile}.
*
* @author Phillip Webb
* @since 1.5.0
*/
public class ClassLoaderFileURLStreamHandler extends URLStreamHandler {
private final ClassLoaderFile file;
public ClassLoaderFileURLStreamHandler(ClassLoaderFile file) {
this.file = file;
}
@Override
protected URLConnection openConnection(URL url) throws IOException {
return new Connection(url);
}
private class Connection extends URLConnection {
Connection(URL url) {
super(url);
}
@Override
public void connect() throws IOException {
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(ClassLoaderFileURLStreamHandler.this.file.getContents());
}
@Override
public long getLastModified() {
return ClassLoaderFileURLStreamHandler.this.file.getLastModified();
}
}
}
|
3e0256cdfb8a049f78d33c4d2d7e6f74b36df60f | 1,068 | java | Java | NewGenerator/src/main/java/com/sf/dao/CarMapper.java | dz147/Distribution | 644627ba6799a083a6b0dbfd011d63da87e66b8c | [
"MIT"
] | 1 | 2020-12-16T13:19:41.000Z | 2020-12-16T13:19:41.000Z | NewGenerator/src/main/java/com/sf/dao/CarMapper.java | dz147/Distribution | 644627ba6799a083a6b0dbfd011d63da87e66b8c | [
"MIT"
] | null | null | null | NewGenerator/src/main/java/com/sf/dao/CarMapper.java | dz147/Distribution | 644627ba6799a083a6b0dbfd011d63da87e66b8c | [
"MIT"
] | 1 | 2020-03-05T04:14:25.000Z | 2020-03-05T04:14:25.000Z | 23.217391 | 56 | 0.631086 | 963 | package com.sf.dao;
import com.sf.model.Car;
import java.util.List;
public interface CarMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table car
*
* @mbg.generated
*/
int deleteByPrimaryKey(String carID);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table car
*
* @mbg.generated
*/
int insert(Car record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table car
*
* @mbg.generated
*/
Car selectByPrimaryKey(String carID);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table car
*
* @mbg.generated
*/
List<Car> selectAll();
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table car
*
* @mbg.generated
*/
int updateByPrimaryKey(Car record);
} |
3e0256fe3b0aa4f0898a2e6413f05ed53f65df6b | 3,552 | java | Java | eagle-jpm/eagle-jpm-mr-history/src/main/java/org/apache/eagle/jpm/mr/history/metrics/JobExecutionMetricsCreationListener.java | DadanielZ/eagle | 14f7f3fa3c08abab9babe72387cbb4d36dc383d3 | [
"Apache-2.0"
] | 322 | 2016-12-29T03:52:22.000Z | 2022-01-13T03:18:24.000Z | eagle-jpm/eagle-jpm-mr-history/src/main/java/org/apache/eagle/jpm/mr/history/metrics/JobExecutionMetricsCreationListener.java | DadanielZ/eagle | 14f7f3fa3c08abab9babe72387cbb4d36dc383d3 | [
"Apache-2.0"
] | 141 | 2016-12-27T23:19:22.000Z | 2020-04-19T20:36:08.000Z | eagle-jpm/eagle-jpm-mr-history/src/main/java/org/apache/eagle/jpm/mr/history/metrics/JobExecutionMetricsCreationListener.java | DadanielZ/eagle | 14f7f3fa3c08abab9babe72387cbb4d36dc383d3 | [
"Apache-2.0"
] | 128 | 2016-12-28T07:52:34.000Z | 2022-01-24T07:22:24.000Z | 41.302326 | 124 | 0.659628 | 964 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.eagle.jpm.mr.history.metrics;
import org.apache.eagle.jpm.mr.historyentity.JobExecutionAPIEntity;
import org.apache.eagle.jpm.util.Constants;
import org.apache.eagle.jpm.util.MRJobTagName;
import org.apache.eagle.jpm.util.metrics.AbstractMetricsCreationListener;
import org.apache.eagle.log.entity.GenericMetricEntity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JobExecutionMetricsCreationListener extends AbstractMetricsCreationListener<JobExecutionAPIEntity> {
@Override
public List<GenericMetricEntity> generateMetrics(JobExecutionAPIEntity entity) {
List<GenericMetricEntity> metrics = new ArrayList<>();
if (entity != null) {
Long timeStamp = entity.getTimestamp();
Map<String, String> tags = entity.getTags();
metrics.add(metricWrapper(timeStamp,
Constants.JOB_EXECUTION_TIME,
new double[]{entity.getDurationTime()},
tags));
metrics.add(metricWrapper(
timeStamp,
Constants.MAP_COUNT_RATIO,
new double[]{entity.getNumTotalMaps(), 1.0 * entity.getNumFailedMaps() / entity.getNumTotalMaps()},
tags));
metrics.add(metricWrapper(
timeStamp,
Constants.REDUCE_COUNT_RATIO,
new double[]{entity.getNumTotalReduces(), 1.0 * entity.getNumFailedReduces() / entity.getNumTotalReduces()},
tags));
org.apache.eagle.jpm.util.jobcounter.JobCounters jobCounters = entity.getJobCounters();
if (jobCounters != null && jobCounters.getCounters() != null) {
for (Map<String, Long> metricGroup : jobCounters.getCounters().values()) {
for (Map.Entry<String, Long> entry : metricGroup.entrySet()) {
String metricName = entry.getKey().toLowerCase();
metrics.add(metricWrapper(timeStamp, metricName, new double[]{entry.getValue()}, tags));
}
}
}
//generate Constants.JOB_COUNT_PER_HOUR data
Map<String, String> baseTags = new HashMap<>(tags);
baseTags.put(MRJobTagName.JOB_STATUS.toString(), entity.getCurrentState());
metrics.add(metricWrapper(timeStamp / 3600000 * 3600000,
Constants.JOB_COUNT_PER_HOUR,
new double[]{1},
baseTags));
}
return metrics;
}
@Override
public String buildMetricName(String field) {
return String.format(Constants.HADOOP_HISTORY_TOTAL_METRIC_FORMAT, Constants.JOB_LEVEL, field);
}
}
|
3e025768fc48edebf386c33ffccc475f3ec98d93 | 6,149 | java | Java | jdk11/openj9.sharedclasses/com/ibm/oti/shared/SharedClassPermission.java | 1446554749/jdk_11_src_read | b9c070d7232ee3cf5f2f6270e748ada74cbabb3f | [
"Apache-2.0"
] | null | null | null | jdk11/openj9.sharedclasses/com/ibm/oti/shared/SharedClassPermission.java | 1446554749/jdk_11_src_read | b9c070d7232ee3cf5f2f6270e748ada74cbabb3f | [
"Apache-2.0"
] | null | null | null | jdk11/openj9.sharedclasses/com/ibm/oti/shared/SharedClassPermission.java | 1446554749/jdk_11_src_read | b9c070d7232ee3cf5f2f6270e748ada74cbabb3f | [
"Apache-2.0"
] | null | null | null | 31.533333 | 135 | 0.653277 | 965 | package com.ibm.oti.shared;
import java.security.BasicPermission;
import java.security.Permission;
import java.security.PermissionCollection;
import java.util.StringTokenizer;
/*******************************************************************************
* Copyright (c) 1998, 2017 IBM Corp. 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/
* or the Apache License, Version 2.0 which accompanies this distribution and
* is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following
* Secondary Licenses when the conditions for such availability set
* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
* General Public License, version 2 with the GNU Classpath
* Exception [1] and GNU General Public License, version 2 with the
* OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
/**
* SharedClassPermission provides security permission to govern ClassLoader access to the shared class cache.
* <p>
* <b>Usage:</b> To grant permission to a ClassLoader, add permission in the java.policy file.<br>
* For example, com.ibm.oti.shared.SharedClassPermission "classloaders.myClassLoader", "read,write";
* <p>
* "read" allows a ClassLoader to load classes from the shared cache.<br>
* "write" allows a ClassLoader to add classes to the shared cache.
* <p>
*/
public class SharedClassPermission extends BasicPermission {
private static final long serialVersionUID = -3867544018716468265L;
transient private boolean read, write;
/**
* Constructs a new instance of this class.
* <p>
* @param loader java.lang.ClassLoader.
* The ClassLoader requiring the permission.
* @param actions java.lang.String.
* The actions which are applicable to it.
*/
public SharedClassPermission(ClassLoader loader, String actions) {
this(loader.getClass().getName(), actions);
}
/**
* Constructs a new instance of this class.
* <p>
* @param classLoaderClassName java.lang.String.
* The className of the ClassLoader requiring the permission.
* @param actions java.lang.String.
* The actions which are applicable to it.
*/
public SharedClassPermission(String classLoaderClassName, String actions) {
super(classLoaderClassName);
decodeActions(actions);
}
private void decodeActions(String actions) {
StringTokenizer tokenizer =
new StringTokenizer(actions.toLowerCase(), " \t\n\r,"); //$NON-NLS-1$
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (token.equals("read")) //$NON-NLS-1$
read = true;
else if (token.equals("write")) //$NON-NLS-1$
write = true;
else
throw new IllegalArgumentException();
}
if (!read && !write) throw new IllegalArgumentException();
}
/**
* Compares the argument to the receiver, and answers <code>true</code>
* if they represent the <em>same</em> object using a class
* specific comparison. In this case, the receiver must be
* for the same property as the argument, and must have the
* same actions.
* <p>
* @param o The object to compare with this object
* @return <code>true</code>
* If the object is the same as this object
* <code>false</code>
* If it is different from this object
* @see #hashCode
*/
@Override
public boolean equals(Object o) {
if (super.equals(o)) {
SharedClassPermission pp = (SharedClassPermission) o;
return (read == pp.read) && (write == pp.write);
}
return false;
}
/**
* Answers a new PermissionCollection for holding permissions
* of this class. Answer null if any permission collection can
* be used.
* <p>
* @return A new PermissionCollection or null
*
* @see java.security.PermissionCollection
*/
@Override
public PermissionCollection newPermissionCollection() {
return new SharedClassPermissionCollection();
}
/**
* Answers an integer hash code for the receiver. Any two
* objects which answer <code>true</code> when passed to
* <code>equals</code> must answer the same value for this
* method.
* <p>
* @return The receiver's hash
*
* @see #equals
*/
@Override
public int hashCode() {
return super.hashCode();
}
/**
* Answers the actions associated with the receiver.
* The result will be either "read", "write", or
* "read,write".
* <p>
* @return String.
* The actions associated with the receiver.
*/
@Override
public String getActions() {
return read ? (write ? "read,write" : "read") : "write"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
/* Truth table for implies method:
*
* property implies
* p1 read p1 write p2 read p2 write result
* 0 0 0 0 0
* 0 0 0 1 0
* 0 0 1 0 0
* 0 0 1 1 0
* 0 1 0 0 1
* 0 1 0 1 1
* 0 1 1 0 0
* 0 1 1 1 0
* 1 0 0 0 1
* 1 0 0 1 0
* 1 0 1 0 1
* 1 0 1 1 0
* 1 1 0 0 1
* 1 1 0 1 1
* 1 1 1 0 1
* 1 1 1 1 1
*/
/**
* Indicates whether the argument permission is implied
* by the receiver.
* <p>
* @return boolean
* <code>true</code> if the argument permission
* is implied by the receiver,
* and <code>false</code> if it is not.
* @param permission java.security.Permission.
* The permission to check
*/
@Override
public boolean implies(Permission permission) {
if (super.implies(permission)) {
SharedClassPermission pp = (SharedClassPermission) permission;
boolean result = (read && write) ||
(write && !pp.read) ||
(read && !pp.write);
return result;
}
return false;
}
}
|
3e0257bca40a24d6521db542362467c5d2d17fd4 | 10,832 | java | Java | app/src/main/java/com/manga/tubes/mangaeden/tubes03/Chapterlist.java | shafiralucu/tubes3_haha | 30f7ef72018527ad9be8844fbd018ddb1c9e7066 | [
"MIT"
] | null | null | null | app/src/main/java/com/manga/tubes/mangaeden/tubes03/Chapterlist.java | shafiralucu/tubes3_haha | 30f7ef72018527ad9be8844fbd018ddb1c9e7066 | [
"MIT"
] | null | null | null | app/src/main/java/com/manga/tubes/mangaeden/tubes03/Chapterlist.java | shafiralucu/tubes3_haha | 30f7ef72018527ad9be8844fbd018ddb1c9e7066 | [
"MIT"
] | null | null | null | 44.576132 | 266 | 0.59555 | 966 | package com.manga.tubes.mangaeden.tubes03;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.tonyodev.fetch.Fetch;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
public class Chapterlist extends AppCompatActivity implements ChapterAdapter.viewchapter, ChapterAdapter.DownloadCHapter {
private String url = "https://www.mangaeden.com/api/manga/";
ProgressDialog gress;
RecyclerView recyclerView;
ImageView img;
ChapterAdapter adapter;
ProgressDialog bar;
ArrayList<String> chapNo = new ArrayList<>();
ArrayList<String> chapId = new ArrayList<>();
static final int WRITE_PERMISSION = 1001;
ArrayAdapter<String> adapter1;
static ArrayList<String> imagelist = new ArrayList<>();
TextView genre;
// GridView listView;
String msgdescription = "";
CoordinatorLayout coordinatorLayout;
Fetch fetch;
TextView title, total_chapter, author, artist, released;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_chapterlist);
bar = new ProgressDialog(this);
bar.setIndeterminate(true);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator);
img = (ImageView) findViewById(R.id.imageView);
title = (TextView) findViewById(R.id.textView);
genre = (TextView) findViewById(R.id.category2);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView2);
adapter = new ChapterAdapter(chapNo);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
recyclerView.addItemDecoration(
new HorizontalDividerItemDecoration.Builder(this)
.color(Color.parseColor("#BBBBBB"))
.sizeResId(R.dimen.divider)
.build());
recyclerView.setAdapter(adapter);
total_chapter = (TextView) findViewById(R.id.textView6);
author = (TextView) findViewById(R.id.textView2);
artist = (TextView) findViewById(R.id.textView7);
released = (TextView) findViewById(R.id.textView4);
url = url + getIntent().getStringExtra("ID");
volleyCall();
gress = new ProgressDialog(this);
gress.setMessage("Loding Chapter List...");
gress.setIndeterminate(true);
fetch = Fetch.newInstance(getApplicationContext());
new Fetch.Settings(getApplicationContext()).setConcurrentDownloadsLimit(2).apply();
ChapterAdapter.setChapterlist(this);
ChapterAdapter.setDownloadListener(this);
gress.show();
}
private void volleyCall() {
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Gson gson = new Gson();
ChapterDetail chapter = new ChapterDetail();
chapter = gson.fromJson(response.toString(), ChapterDetail.class);
Glide.with(getApplicationContext()).load("https://cdn.mangaeden.com/mangasimg/" + chapter.getImage())
.apply(new RequestOptions()
.override(154,250).centerCrop().placeholder(R.drawable.placeholder).error(R.drawable.error))
.into(img);
title.setText(chapter.getTitle());
total_chapter.setText(chapter.getChapters_len() + " chapters");
author.setText("Author: " + chapter.getAuthor());
artist.setText("Artist: " + chapter.getArtist());
released.setText("Released: " + chapter.getReleased());
msgdescription = chapter.getDescription();
TextView textView = (TextView) findViewById(R.id.description);
textView.setText(msgdescription);
StringBuffer stringBuffer = new StringBuffer();
for (String catgry : chapter.getCategories()) {
stringBuffer.append(catgry + " | ");
}
genre.setText(stringBuffer.toString());
Object ov[] = chapter.getChapters().toArray();
for (Object d : ov) {
Log.d("URL", d.toString() + 'd');
String red = d.toString().replace("[", "");
red = red.replace("]", "");
String newarray[] = red.split(",");
chapNo.add(newarray[0]);
chapId.add(newarray[newarray.length - 1]);
}
adapter.notifyDataSetChanged();
gress.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
gress.dismiss();
}
});
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
}
@Override
public void viewChap(int position) {
chapNo.get(position);
Intent i = new Intent(getApplicationContext(), MangaViewer.class);
i.putExtra("ID", chapId.get(position));
startActivity(i);
}
@Override
public void DownloadChap(int position) {
if (checkPermission()) {
callvolley(position);
}
}
private void DownloadImages(final ArrayList<String> imagelist1, final int position) {
Snackbar.make(coordinatorLayout, "Saved to sdcard/MangaTrend .", Snackbar.LENGTH_LONG).show();
for (final String imgurl : imagelist1) {
String PATH = Environment.getExternalStorageDirectory() + "/" + "MangaTrend" + "/";
final File folder = new File(PATH);
if (!folder.exists()) {
folder.mkdir();//If there is no folder it will be created.
}
com.tonyodev.fetch.request.Request request = new com.tonyodev.fetch.request.Request("https://cdn.mangaeden.com/mangasimg/" + imgurl.trim(), folder.toString() + "/" + title.getText().toString() + "/" + chapNo.get(position) + "/", imgurl.replace("/", ""));
final long downloadId = fetch.enqueue(request);
if (downloadId != Fetch.ENQUEUE_ERROR_ID) {
//Download was successfully queued for download.
}
}
}
private boolean checkPermission() {
int writestoragepermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (writestoragepermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
WRITE_PERMISSION);
} else {
//permission granted download
return true;
}
return false;
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[], @NonNull int[] grantResults) {
switch (requestCode) {
case WRITE_PERMISSION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// download task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "Please Accept The Sd card permission.", Toast.LENGTH_SHORT).show();
}
}
}
}
private void callvolley(final int pos) {
if (bar.isShowing()) {
bar.dismiss();
}
bar.setMessage("Downloading..");
bar.show();
final ArrayList<String> listimg = new ArrayList<>();
String urlsd = "https://www.mangaeden.com/api/chapter/";
listimg.clear();
urlsd = urlsd + chapId.get(pos).trim() + "/";
StringRequest req = new StringRequest(Request.Method.GET, urlsd, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Gson gson = new Gson();
ImageModel model = gson.fromJson(response.toString(), ImageModel.class);
for (Object obj : model.getImages()) {
String i = obj.toString().replace("[", "");
i = i.replace("]", "");
String url[] = i.split(",");
listimg.add(url[1]);
}
Collections.reverse(listimg);
DownloadImages(listimg, pos);
bar.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "" + error.getMessage(), Toast.LENGTH_SHORT).show();
bar.dismiss();
}
});
MySingleton.getInstance(this).addToRequestQueue(req);
}
}
|
3e02586f3aa088a9556f5c266b7fd4dea840b819 | 3,413 | java | Java | src/client/AdminLandingPage.java | ekanshsinghal/Marketplace | 0fa0458eb427b219068a9827445266e267e583c2 | [
"MIT"
] | null | null | null | src/client/AdminLandingPage.java | ekanshsinghal/Marketplace | 0fa0458eb427b219068a9827445266e267e583c2 | [
"MIT"
] | 2 | 2021-11-02T19:01:47.000Z | 2021-11-07T13:52:54.000Z | src/client/AdminLandingPage.java | ekanshsinghal/Marketplace | 0fa0458eb427b219068a9827445266e267e583c2 | [
"MIT"
] | 5 | 2021-11-02T15:56:57.000Z | 2021-11-05T15:35:53.000Z | 35.185567 | 115 | 0.594785 | 967 | package client;
import server.entity.User;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AdminLandingPage extends JFrame implements ActionListener {
private JPanel mainMenuPanel;
private JLabel adminLandingBar;
private JComboBox menuCombo;
private User user;
public void selectMenuOption(User user) {
this.user = user;
this.setTitle("Welcome to marketplace");
this.setPreferredSize(new Dimension(500, 500));
this.setResizable(false);
server.constants.MenuOptions[] menuOptions = server.constants.MenuOptions.values();
menuCombo = new JComboBox(menuOptions);
menuCombo.addActionListener(this);
adminLandingBar = new JLabel("Welcome to marketplace " + user.getUserName());
mainMenuPanel.setLayout(new BoxLayout(mainMenuPanel, BoxLayout.Y_AXIS));
mainMenuPanel.add(adminLandingBar);
mainMenuPanel.add(menuCombo);
this.add(mainMenuPanel);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == menuCombo) {
server.constants.MenuOptions selectedItem = (server.constants.MenuOptions) menuCombo.getSelectedItem();
assert selectedItem != null;
performMenuOperation(selectedItem);
}
}
private void performMenuOperation(server.constants.MenuOptions menuOption) {
int menuId = menuOption.getMenuId();
switch(menuId)
{
case 1 :
// add brand with admin user
BrandCreation brandCreation = new BrandCreation();
brandCreation.showFormForInput(user);
this.setVisible(false);
break;
case 2 :
// add customer with admin user
CustomerCreation customerCreation = new CustomerCreation();
customerCreation.showFormForInput(user);
this.setVisible(false);
break;
case 3 :
// show brand info
ShowBrandInfo showBrandInfo = new ShowBrandInfo();
showBrandInfo.showBrandInfo(user);
this.setVisible(false);
break;
case 4 :
// show customer info
ShowCustomerInfo showCustomerInfo = new ShowCustomerInfo();
showCustomerInfo.showCustomerInfo(user);
this.setVisible(false);
break;
case 5 :
// add activity type
ActivityTypeCreation activityTypeCreation = new ActivityTypeCreation();
activityTypeCreation.showFormForInput(user);
this.setVisible(false);
break;
case 6 :
// add reward type
RewardTypeCreation rewardTypeCreation = new RewardTypeCreation();
rewardTypeCreation.showFormForInput(user);
this.setVisible(false);
break;
case 7 :
Homepage homepage = new Homepage();
homepage.showHomePage();
this.setVisible(false);
break;
}
}
}
|
3e0259b9ab1ff376b90209411ffce8c8c72b27da | 1,608 | java | Java | core/api/src/main/java/org/qi4j/api/injection/scope/Invocation.java | arvidhuss/qi4j-sdk | b49eca6201e702ebcdae810c45fe0bcba3a74773 | [
"Apache-2.0"
] | 1 | 2017-08-08T03:09:29.000Z | 2017-08-08T03:09:29.000Z | core/api/src/main/java/org/qi4j/api/injection/scope/Invocation.java | bwzhang2011/qi4j-sdk | be5f91e61a3b02e21f8f236fbaf85747f7f993ae | [
"Apache-2.0"
] | null | null | null | core/api/src/main/java/org/qi4j/api/injection/scope/Invocation.java | bwzhang2011/qi4j-sdk | be5f91e61a3b02e21f8f236fbaf85747f7f993ae | [
"Apache-2.0"
] | 1 | 2022-01-22T10:59:44.000Z | 2022-01-22T10:59:44.000Z | 32.16 | 85 | 0.746891 | 968 | /*
* Copyright (c) 2007, Rickard Öberg. All Rights Reserved.
* Copyright (c) 2007, Niclas Hedhman. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.qi4j.api.injection.scope;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.qi4j.api.injection.InjectionScope;
/**
* Annotation to denote the injection of a
* invocation specific resource.
* These include:
* <pre><code>
* - The Method being invoked.
*
* - An AnnotationElement with annotations
* from both mixin type, mixin
* implementation.
*
* - An Annotation of a specific type
* </code></pre>
* Examples:
* <code><pre>
* @Invocation Method theInvokedMethod
* @Invocation AnnotationElement annotations
* @Invocation Matches matchesAnnotation
* </pre></code>
*/
@Retention( RetentionPolicy.RUNTIME )
@Target( { ElementType.FIELD, ElementType.PARAMETER } )
@Documented
@InjectionScope
public @interface Invocation
{
} |
3e025a3f8694e2d733f3e05b4db6e4fb9bc4b6a2 | 264 | java | Java | language/src/main/java/ch/epfl/vlsc/truffle/cal/parser/utils/NamespaceElementsToCallTarget.java | streamblocks/streamblocks-graalvm | b4c172c3c519c6104a3f83eeca7673c658a3b220 | [
"UPL-1.0"
] | 15 | 2021-08-29T06:52:39.000Z | 2022-01-07T05:59:17.000Z | language/src/main/java/ch/epfl/vlsc/truffle/cal/parser/utils/NamespaceElementsToCallTarget.java | streamblocks/streamblocks-graalvm | b4c172c3c519c6104a3f83eeca7673c658a3b220 | [
"UPL-1.0"
] | 57 | 2021-09-01T14:20:38.000Z | 2021-12-27T07:12:56.000Z | language/src/main/java/ch/epfl/vlsc/truffle/cal/parser/utils/NamespaceElementsToCallTarget.java | streamblocks/streamblocks-graalvm | b4c172c3c519c6104a3f83eeca7673c658a3b220 | [
"UPL-1.0"
] | 2 | 2021-07-14T11:46:40.000Z | 2021-08-13T13:28:31.000Z | 24 | 49 | 0.791667 | 969 | package ch.epfl.vlsc.truffle.cal.parser.utils;
import com.oracle.truffle.api.RootCallTarget;
import java.util.Map;
public class NamespaceElementsToCallTarget {
public Map<String, RootCallTarget> entities;
public Map<String, RootCallTarget> functions;
}
|
3e025a5825097d4d9e22a8740f4e6c084afce7de | 4,953 | java | Java | fluent/src/main/java/io/kubernetes/client/openapi/models/V1StatusDetailsFluent.java | luke-zhang580/java | edd203cdb4f8a9ab2cb80e5391501a72bcf5b92b | [
"Apache-2.0"
] | 2,389 | 2017-05-13T16:11:07.000Z | 2022-03-31T07:06:17.000Z | fluent/src/main/java/io/kubernetes/client/openapi/models/V1StatusDetailsFluent.java | luke-zhang580/java | edd203cdb4f8a9ab2cb80e5391501a72bcf5b92b | [
"Apache-2.0"
] | 2,128 | 2017-05-10T17:53:06.000Z | 2022-03-30T22:21:15.000Z | fluent/src/main/java/io/kubernetes/client/openapi/models/V1StatusDetailsFluent.java | luke-zhang580/java | edd203cdb4f8a9ab2cb80e5391501a72bcf5b92b | [
"Apache-2.0"
] | 1,112 | 2017-05-10T03:45:57.000Z | 2022-03-31T10:02:03.000Z | 51.59375 | 212 | 0.797496 | 970 | package io.kubernetes.client.openapi.models;
import io.kubernetes.client.fluent.VisitableBuilder;
import com.google.gson.annotations.SerializedName;
import io.kubernetes.client.fluent.Fluent;
import io.kubernetes.client.fluent.Nested;
import java.util.ArrayList;
import java.lang.String;
import java.util.function.Predicate;
import java.lang.Integer;
import java.lang.Deprecated;
import java.util.Iterator;
import java.util.Collection;
import java.util.List;
import java.lang.Boolean;
/**
* Generated
*/
public interface V1StatusDetailsFluent<A extends io.kubernetes.client.openapi.models.V1StatusDetailsFluent<A>> extends io.kubernetes.client.fluent.Fluent<A>{
public A addToCauses(java.lang.Integer index,io.kubernetes.client.openapi.models.V1StatusCause item);
public A setToCauses(java.lang.Integer index,io.kubernetes.client.openapi.models.V1StatusCause item);
public A addToCauses(io.kubernetes.client.openapi.models.V1StatusCause... items);
public A addAllToCauses(java.util.Collection<io.kubernetes.client.openapi.models.V1StatusCause> items);
public A removeFromCauses(io.kubernetes.client.openapi.models.V1StatusCause... items);
public A removeAllFromCauses(java.util.Collection<io.kubernetes.client.openapi.models.V1StatusCause> items);
public A removeMatchingFromCauses(java.util.function.Predicate<io.kubernetes.client.openapi.models.V1StatusCauseBuilder> predicate);
/**
* This method has been deprecated, please use method buildCauses instead.
* @return The buildable object.
*/
@java.lang.Deprecated
public java.util.List<io.kubernetes.client.openapi.models.V1StatusCause> getCauses();
public java.util.List<io.kubernetes.client.openapi.models.V1StatusCause> buildCauses();
public io.kubernetes.client.openapi.models.V1StatusCause buildCause(java.lang.Integer index);
public io.kubernetes.client.openapi.models.V1StatusCause buildFirstCause();
public io.kubernetes.client.openapi.models.V1StatusCause buildLastCause();
public io.kubernetes.client.openapi.models.V1StatusCause buildMatchingCause(java.util.function.Predicate<io.kubernetes.client.openapi.models.V1StatusCauseBuilder> predicate);
public java.lang.Boolean hasMatchingCause(java.util.function.Predicate<io.kubernetes.client.openapi.models.V1StatusCauseBuilder> predicate);
public A withCauses(java.util.List<io.kubernetes.client.openapi.models.V1StatusCause> causes);
public A withCauses(io.kubernetes.client.openapi.models.V1StatusCause... causes);
public java.lang.Boolean hasCauses();
public io.kubernetes.client.openapi.models.V1StatusDetailsFluent.CausesNested<A> addNewCause();
public io.kubernetes.client.openapi.models.V1StatusDetailsFluent.CausesNested<A> addNewCauseLike(io.kubernetes.client.openapi.models.V1StatusCause item);
public io.kubernetes.client.openapi.models.V1StatusDetailsFluent.CausesNested<A> setNewCauseLike(java.lang.Integer index,io.kubernetes.client.openapi.models.V1StatusCause item);
public io.kubernetes.client.openapi.models.V1StatusDetailsFluent.CausesNested<A> editCause(java.lang.Integer index);
public io.kubernetes.client.openapi.models.V1StatusDetailsFluent.CausesNested<A> editFirstCause();
public io.kubernetes.client.openapi.models.V1StatusDetailsFluent.CausesNested<A> editLastCause();
public io.kubernetes.client.openapi.models.V1StatusDetailsFluent.CausesNested<A> editMatchingCause(java.util.function.Predicate<io.kubernetes.client.openapi.models.V1StatusCauseBuilder> predicate);
public java.lang.String getGroup();
public A withGroup(java.lang.String group);
public java.lang.Boolean hasGroup();
/**
* Method is deprecated. use withGroup instead.
*/
@java.lang.Deprecated
public A withNewGroup(java.lang.String original);
public java.lang.String getKind();
public A withKind(java.lang.String kind);
public java.lang.Boolean hasKind();
/**
* Method is deprecated. use withKind instead.
*/
@java.lang.Deprecated
public A withNewKind(java.lang.String original);
public java.lang.String getName();
public A withName(java.lang.String name);
public java.lang.Boolean hasName();
/**
* Method is deprecated. use withName instead.
*/
@java.lang.Deprecated
public A withNewName(java.lang.String original);
public java.lang.Integer getRetryAfterSeconds();
public A withRetryAfterSeconds(java.lang.Integer retryAfterSeconds);
public java.lang.Boolean hasRetryAfterSeconds();
public java.lang.String getUid();
public A withUid(java.lang.String uid);
public java.lang.Boolean hasUid();
/**
* Method is deprecated. use withUid instead.
*/
@java.lang.Deprecated
public A withNewUid(java.lang.String original);
public interface CausesNested<N> extends io.kubernetes.client.fluent.Nested<N>,io.kubernetes.client.openapi.models.V1StatusCauseFluent<io.kubernetes.client.openapi.models.V1StatusDetailsFluent.CausesNested<N>>{
public N and();
public N endCause();
}
} |
3e025b225d38e504099a9c889cda2208dfd6a04a | 252 | java | Java | src/com/simplechain/network/server/NetworkServerConnectionHandler.java | mlalma/SimpleChain | 41fbd1737b1a93734984e92165e574776b71d905 | [
"Apache-2.0"
] | null | null | null | src/com/simplechain/network/server/NetworkServerConnectionHandler.java | mlalma/SimpleChain | 41fbd1737b1a93734984e92165e574776b71d905 | [
"Apache-2.0"
] | 5 | 2019-02-08T21:16:35.000Z | 2019-02-11T14:41:38.000Z | src/com/simplechain/network/server/NetworkServerConnectionHandler.java | mlalma/SimpleChain | 41fbd1737b1a93734984e92165e574776b71d905 | [
"Apache-2.0"
] | null | null | null | 28 | 64 | 0.81746 | 971 | package com.simplechain.network.server;
// Interface for handling network server connections
public interface NetworkServerConnectionHandler {
// Called when connection is closed
void connectionClosed(NetworkServerInConnection connection);
}
|
3e025b687cbad6ba2674cdc63649f8566d1c006c | 11,727 | java | Java | design-synthesis/existing-services/marketingmanager/src/main/java/org/choreos/services/MarketingManagerImpl.java | sesygroup/choreography-synthesis-enactment | 6eb43ea97203853c40f8e447597570f21ea5f52f | [
"Apache-2.0"
] | null | null | null | design-synthesis/existing-services/marketingmanager/src/main/java/org/choreos/services/MarketingManagerImpl.java | sesygroup/choreography-synthesis-enactment | 6eb43ea97203853c40f8e447597570f21ea5f52f | [
"Apache-2.0"
] | null | null | null | design-synthesis/existing-services/marketingmanager/src/main/java/org/choreos/services/MarketingManagerImpl.java | sesygroup/choreography-synthesis-enactment | 6eb43ea97203853c40f8e447597570f21ea5f52f | [
"Apache-2.0"
] | 1 | 2020-11-11T16:27:05.000Z | 2020-11-11T16:27:05.000Z | 40.860627 | 280 | 0.654302 | 972 | package org.choreos.services;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jws.WebService;
import org.choreos.services.client.marketingapplication.MarketingApplication;
import org.choreos.services.client.marketingapplication.MarketingApplicationService;
import org.choreos.services.client.marketingapplication.Offer;
import org.choreos.services.monitor.MonitorLogger;
import org.choreos.services.monitor.MonitorLoggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.chorevolution.idm.common.types.ArtifactType;
import eu.chorevolution.idm.common.types.EventType;
@WebService(endpointInterface = "org.choreos.services.MarketingManager")
public class MarketingManagerImpl implements MarketingManager {
private static Logger logger = LoggerFactory.getLogger(MarketingManagerImpl.class);
private static MonitorLogger monitorLogger = new MonitorLoggerImpl();
private static final String ROLE_MARKETINGAPPLICATION = "marketingapplication";
protected Map<String, String> address = new HashMap<String, String>();
public void scenarioSetup() {
monitorLogger.sendToMonitor();
}
public void setEndpointAddress(String address) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void setInvocationAddress(String role, String name, List<String> endpoints) {
logger.info("PERFORM -- setInvocationAddress - parameters: role: " + (role.isEmpty() ? "isEmpty parameter" : role) + " - name: " + (name.isEmpty() ? "isEmpty parameter" : name) + " - endpoints[0]: " + (endpoints.get(0).isEmpty() ? "isEmpty parameter" : endpoints.get(0)));
if (address.containsKey(role)) {
address.remove(role);
}
address.put(role, endpoints.get(0));
}
public void putEstimationReq(String sessionId, EstimationNeedAlert estimationNeedAlert) throws ScenarioException_Exception {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void requestPrivateOffer(String sessionId, Product product) throws ScenarioException_Exception {
monitorLogger.sendEventData("WP7", Long.parseLong(sessionId), "MarketingManager", ArtifactType.SERVICE, "MarketingManager", "S34","S35", "requestPrivateOffer", null, EventType.RECEIVING_REQUEST, System.currentTimeMillis());
logger.info("PERFORM -- MarketingManager.requestPrivateOffer(String sessionId, Product product)");
//SLEEP FOR SIMULATING REAL INTERACTION
try {
int running = Integer.parseInt(Configuration.get("running_number"));
switch (running) {
case 0:
Thread.sleep(100);
break;
case 1:
Thread.sleep(200);
break;
case 2:
Thread.sleep(400);
break;
case 3:
Thread.sleep(600);
break;
case 4:
Thread.sleep(800);
break;
case 5:
Thread.sleep(1000);
break;
case 6:
Thread.sleep(1200);
break;
case 7:
Thread.sleep(1400);
break;
case 8:
Thread.sleep(1600);
break;
case 9:
Thread.sleep(1800);
break;
case 10:
Thread.sleep(2000);
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
org.choreos.services.client.marketingapplication.Product marketingapplicationProduct = new org.choreos.services.client.marketingapplication.Product();
marketingapplicationProduct.setName(product.getName());
marketingapplicationProduct.setBarcode(product.getBarcode());
marketingapplicationProduct.setBrand(product.getBrand());
Offer offer = new Offer();
offer.setItem(marketingapplicationProduct);
offer.setDiscount(0);
boolean confirmed = true;
ManageCallPrivateOfferConfirmationOfMarketingApplication manageCallPrivateOfferConfirmationOfMarketingApplication = new ManageCallPrivateOfferConfirmationOfMarketingApplication(sessionId, offer, confirmed);
Thread threadManageCallPrivateOfferConfirmationOfMarketingApplication = new Thread(manageCallPrivateOfferConfirmationOfMarketingApplication);
threadManageCallPrivateOfferConfirmationOfMarketingApplication.start();
monitorLogger.sendEventData("WP7", Long.parseLong(sessionId), "MarketingManager", ArtifactType.SERVICE, "MarketingManager", "S34","S35", "requestPrivateOffer", null, EventType.REPLY_RESPONSE, System.currentTimeMillis());
}
public void requestPublicOffer(String sessionId) throws ScenarioException_Exception {
monitorLogger.sendEventData("WP7", Long.parseLong(sessionId), "MarketingManager", ArtifactType.SERVICE, "MarketingManager", "S41","S42", "requestPublicOffer", null, EventType.RECEIVING_REQUEST, System.currentTimeMillis());
logger.info("PERFORM -- MarketingManager.requestPublicOffer(String sessionId)");
//SLEEP FOR SIMULATING REAL INTERACTION
try {
int running = Integer.parseInt(Configuration.get("running_number"));
switch (running) {
case 0:
Thread.sleep(100);
break;
case 1:
Thread.sleep(200);
break;
case 2:
Thread.sleep(400);
break;
case 3:
Thread.sleep(600);
break;
case 4:
Thread.sleep(800);
break;
case 5:
Thread.sleep(1000);
break;
case 6:
Thread.sleep(1200);
break;
case 7:
Thread.sleep(1400);
break;
case 8:
Thread.sleep(1600);
break;
case 9:
Thread.sleep(1800);
break;
case 10:
Thread.sleep(2000);
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
Offer offer = new Offer();
offer.setDiscount(0);
offer.setItem(new org.choreos.services.client.marketingapplication.Product());
boolean confirmed = true;
ManageCallPublicOfferConfirmationOfMarketingApplication manageCallPublicOfferConfirmationOfMarketingApplication = new ManageCallPublicOfferConfirmationOfMarketingApplication(sessionId, offer, confirmed);
Thread threadManageCallPublicOfferConfirmationOfMarketingApplication = new Thread(manageCallPublicOfferConfirmationOfMarketingApplication);
threadManageCallPublicOfferConfirmationOfMarketingApplication.start();
monitorLogger.sendEventData("WP7", Long.parseLong(sessionId), "MarketingManager", ArtifactType.SERVICE, "MarketingManager", "S41","S42", "requestPublicOffer", null, EventType.REPLY_RESPONSE, System.currentTimeMillis());
}
private class ManageCallPublicOfferConfirmationOfMarketingApplication implements Runnable {
private String sessionId;
private Offer offer;
private boolean confirmed;
public ManageCallPublicOfferConfirmationOfMarketingApplication() {
}
public ManageCallPublicOfferConfirmationOfMarketingApplication(String sessionId, Offer offer, boolean confirmed) {
this.sessionId = sessionId;
this.offer = offer;
this.confirmed = confirmed;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public Offer getOffer() {
return offer;
}
public void setOffer(Offer offer) {
this.offer = offer;
}
public boolean isConfirmed() {
return confirmed;
}
public void setConfirmed(boolean confirmed) {
this.confirmed = confirmed;
}
@Override
public void run() {
// call marketingApplication.publicOfferConfirmation(sessionId, offer, confirmed)
try {
MarketingApplicationService marketingApplicationService = new MarketingApplicationService(new URL(address.get(ROLE_MARKETINGAPPLICATION)));
MarketingApplication marketingApplication = marketingApplicationService.getMarketingApplicationPort();
monitorLogger.sendEventData("WP7", Long.parseLong(sessionId), "MarketingManager", ArtifactType.SERVICE, "MarketingManager", "S42","S39", "publicOfferConfirmation", null, EventType.SENDING_REQUEST, System.currentTimeMillis());
marketingApplication.publicOfferConfirmation(sessionId, offer, confirmed);
monitorLogger.sendEventData("WP7", Long.parseLong(sessionId), "MarketingManager", ArtifactType.SERVICE, "MarketingManager", "S42","S39", "publicOfferConfirmation", null, EventType.RECEIVING_RESPONSE, System.currentTimeMillis());
} catch (Exception e) {
logger.error("Error detected:", e);
}
}
}
private class ManageCallPrivateOfferConfirmationOfMarketingApplication implements Runnable {
private String sessionId;
private Offer offer;
private boolean confirmed;
public ManageCallPrivateOfferConfirmationOfMarketingApplication() {
}
public ManageCallPrivateOfferConfirmationOfMarketingApplication(String sessionId, Offer offer, boolean confirmed) {
this.sessionId = sessionId;
this.offer = offer;
this.confirmed = confirmed;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public Offer getOffer() {
return offer;
}
public void setOffer(Offer offer) {
this.offer = offer;
}
public boolean isConfirmed() {
return confirmed;
}
public void setConfirmed(boolean confirmed) {
this.confirmed = confirmed;
}
@Override
public void run() {
// call marketingApplication.privateOfferConfirmation(sessionId, offer, confirmed)
try {
MarketingApplicationService marketingApplicationService = new MarketingApplicationService(new URL(address.get(ROLE_MARKETINGAPPLICATION)));
MarketingApplication marketingApplication = marketingApplicationService.getMarketingApplicationPort();
//monitorLogger.log("S35","S27",SendingRequest)
monitorLogger.sendEventData("WP7", Long.parseLong(sessionId), "MarketingManager", ArtifactType.SERVICE, "MarketingManager", "S35","S27", "privateOfferConfirmation", null, EventType.SENDING_REQUEST, System.currentTimeMillis());
marketingApplication.privateOfferConfirmation(sessionId, offer, confirmed);
monitorLogger.sendEventData("WP7", Long.parseLong(sessionId), "MarketingManager", ArtifactType.SERVICE, "MarketingManager", "S35","S27", "privateOfferConfirmation", null, EventType.RECEIVING_RESPONSE, System.currentTimeMillis());
} catch (Exception e) {
logger.error("Error detected:", e);
}
}
}
}
|
3e025b7f0fcae23a88f1972fb30a92363b5a5d2c | 2,283 | java | Java | Study_2021/Study_Old/JavaStudy/src/main/java/thread/piped/ConnectionManager.java | henghengya/ComputerWorld | 162bb1d1b4bd389cb993194e01488a322323fa6e | [
"MulanPSL-1.0"
] | 2 | 2020-08-14T09:45:34.000Z | 2022-01-01T06:17:53.000Z | Study_2021/Study_Old/JavaStudy/src/main/java/thread/piped/ConnectionManager.java | henghengya/ComputerWorld | 162bb1d1b4bd389cb993194e01488a322323fa6e | [
"MulanPSL-1.0"
] | 18 | 2020-12-03T13:26:40.000Z | 2022-01-01T06:17:39.000Z | Study_2021/Study_Old/JavaStudy/src/main/java/thread/piped/ConnectionManager.java | henghengya/ComputerWorld | 162bb1d1b4bd389cb993194e01488a322323fa6e | [
"MulanPSL-1.0"
] | null | null | null | 31.708333 | 86 | 0.664477 | 973 | package thread.pisd;
import thread.piped.ThreadA;
import thread.piped.ThreadB;
import thread.piped.ThreadC;
import thread.piped.ThreadD;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
/**
* Create Date 2020/11/03 16:41:22 <br>
* Created by lan-mao.top <br>
* 管道管理 <br>
*/
public class ConnectionManager {
//TA - Object -> TB
static private PipedInputStream pisA2B = new PipedInputStream();
static private PipedOutputStream posA2B = new PipedOutputStream();
static private ObjectInputStream oisA2B;
//TB - Primitives -> TA
static private PipedInputStream pisB2A = new PipedInputStream();
static private PipedOutputStream posB2A = new PipedOutputStream();
//TB - Object -> TC
static private PipedInputStream pisB2C = new PipedInputStream();
static private PipedOutputStream posB2C = new PipedOutputStream();
//TC - Object -> TA
static private PipedInputStream pisC2A = new PipedInputStream();
static private PipedOutputStream posC2A = new PipedOutputStream();
//TC - Object -> TB
static private PipedInputStream pisC2B = new PipedInputStream();
static private PipedOutputStream posC2B = new PipedOutputStream();
//TD - Primitives -> TA
static private PipedInputStream pisD2A = new PipedInputStream();
static private PipedOutputStream posD2A = new PipedOutputStream();
public static void main(String[] args) {
try {
System.out.println("System start");
pisA2B.connect(posA2B);
pisB2A.connect(posB2A);
pisB2C.connect(posB2C);
pisC2A.connect(posC2A);
pisC2B.connect(posC2B);
pisD2A.connect(posD2A);
ThreadA threadA = new ThreadA("Thread A", posA2B, pisB2A, pisC2A, pisD2A);
ThreadB threadB = new ThreadB("Thread B", pisA2B, pisC2B, posB2A, posB2C);
ThreadC threadC = new ThreadC("Thread C", pisB2C, posC2A, posC2B);
ThreadD threadD = new ThreadD("Thread D", posD2A);
threadA.start();
threadB.start();
threadC.start();
threadD.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
3e025c506e731a735faeae28f77c9c47de7b134b | 6,453 | java | Java | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-catalog/hadoop-yarn-applications-catalog-webapp/src/main/java/org/apache/hadoop/yarn/appcatalog/model/Application.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-catalog/hadoop-yarn-applications-catalog-webapp/src/main/java/org/apache/hadoop/yarn/appcatalog/model/Application.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-catalog/hadoop-yarn-applications-catalog-webapp/src/main/java/org/apache/hadoop/yarn/appcatalog/model/Application.java | dmgerman/hadoop | 70c015914a8756c5440cd969d70dac04b8b6142b | [
"Apache-2.0"
] | null | null | null | 15.437799 | 813 | 0.800403 | 974 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
DECL|package|org.apache.hadoop.yarn.appcatalog.model
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|appcatalog
operator|.
name|model
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Objects
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|xml
operator|.
name|bind
operator|.
name|annotation
operator|.
name|XmlRootElement
import|;
end_import
begin_import
import|import
name|com
operator|.
name|fasterxml
operator|.
name|jackson
operator|.
name|annotation
operator|.
name|JsonIgnoreProperties
import|;
end_import
begin_import
import|import
name|com
operator|.
name|fasterxml
operator|.
name|jackson
operator|.
name|annotation
operator|.
name|JsonInclude
import|;
end_import
begin_import
import|import
name|com
operator|.
name|fasterxml
operator|.
name|jackson
operator|.
name|annotation
operator|.
name|JsonProperty
import|;
end_import
begin_import
import|import
name|com
operator|.
name|fasterxml
operator|.
name|jackson
operator|.
name|annotation
operator|.
name|JsonPropertyOrder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|service
operator|.
name|api
operator|.
name|records
operator|.
name|Service
import|;
end_import
begin_comment
comment|/** * Data model of display recommended applications and descriptions. */
end_comment
begin_class
annotation|@
name|XmlRootElement
annotation|@
name|JsonInclude
argument_list|(
name|JsonInclude
operator|.
name|Include
operator|.
name|NON_NULL
argument_list|)
annotation|@
name|JsonIgnoreProperties
argument_list|(
name|ignoreUnknown
operator|=
literal|true
argument_list|)
annotation|@
name|JsonPropertyOrder
argument_list|(
block|{
literal|"organization"
block|,
literal|"name"
block|,
literal|"description"
block|,
literal|"icon"
block|}
argument_list|)
DECL|class|Application
specifier|public
class|class
name|Application
extends|extends
name|Service
block|{
DECL|field|serialVersionUID
specifier|private
specifier|static
specifier|final
name|long
name|serialVersionUID
init|=
operator|-
literal|1776203219305414248L
decl_stmt|;
DECL|field|organization
specifier|private
name|String
name|organization
decl_stmt|;
DECL|field|description
specifier|private
name|String
name|description
decl_stmt|;
DECL|field|icon
specifier|private
name|String
name|icon
decl_stmt|;
annotation|@
name|JsonProperty
argument_list|(
literal|"organization"
argument_list|)
DECL|method|getOrganization ()
specifier|public
name|String
name|getOrganization
parameter_list|()
block|{
return|return
name|organization
return|;
block|}
DECL|method|setOrganization (String organization)
specifier|public
name|void
name|setOrganization
parameter_list|(
name|String
name|organization
parameter_list|)
block|{
name|this
operator|.
name|organization
operator|=
name|organization
expr_stmt|;
block|}
annotation|@
name|JsonProperty
argument_list|(
literal|"description"
argument_list|)
DECL|method|getDescription ()
specifier|public
name|String
name|getDescription
parameter_list|()
block|{
return|return
name|description
return|;
block|}
DECL|method|setDescription (String description)
specifier|public
name|void
name|setDescription
parameter_list|(
name|String
name|description
parameter_list|)
block|{
name|this
operator|.
name|description
operator|=
name|description
expr_stmt|;
block|}
annotation|@
name|JsonProperty
argument_list|(
literal|"icon"
argument_list|)
DECL|method|getIcon ()
specifier|public
name|String
name|getIcon
parameter_list|()
block|{
return|return
name|icon
return|;
block|}
DECL|method|setIcon (String icon)
specifier|public
name|void
name|setIcon
parameter_list|(
name|String
name|icon
parameter_list|)
block|{
name|this
operator|.
name|icon
operator|=
name|icon
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|equals (final Object obj)
specifier|public
name|boolean
name|equals
parameter_list|(
specifier|final
name|Object
name|obj
parameter_list|)
block|{
if|if
condition|(
name|obj
operator|==
name|this
condition|)
block|{
return|return
literal|true
return|;
block|}
elseif|else
if|if
condition|(
operator|(
name|obj
operator|instanceof
name|Application
operator|)
condition|)
block|{
if|if
condition|(
operator|(
operator|(
name|Application
operator|)
name|obj
operator|)
operator|.
name|getName
argument_list|()
operator|.
name|equals
argument_list|(
name|this
operator|.
name|getName
argument_list|()
argument_list|)
operator|&&
operator|(
operator|(
name|Application
operator|)
name|obj
operator|)
operator|.
name|getVersion
argument_list|()
operator|.
name|equals
argument_list|(
name|this
operator|.
name|getVersion
argument_list|()
argument_list|)
operator|&&
operator|(
operator|(
name|Application
operator|)
name|obj
operator|)
operator|.
name|getOrganization
argument_list|()
operator|.
name|equals
argument_list|(
name|this
operator|.
name|getOrganization
argument_list|()
argument_list|)
condition|)
block|{
return|return
literal|true
return|;
block|}
block|}
return|return
literal|false
return|;
block|}
annotation|@
name|Override
DECL|method|hashCode ()
specifier|public
name|int
name|hashCode
parameter_list|()
block|{
return|return
name|Objects
operator|.
name|hash
argument_list|(
name|this
operator|.
name|getName
argument_list|()
operator|+
name|this
operator|.
name|getVersion
argument_list|()
operator|+
name|this
operator|.
name|getOrganization
argument_list|()
argument_list|)
return|;
block|}
block|}
end_class
end_unit
|
3e025c9f764aba527974301a6d335be7d9a28446 | 368 | java | Java | Java OOP Exercises/src/JavaAdvanced/DefiningClasses_13/Exercise/CatLady_9/Cat/Cat.java | DenislavVelichkov/Java-Advanced-And-OOP | 2bce655d016f64b911ff1df1143647a3b8efacd1 | [
"MIT"
] | null | null | null | Java OOP Exercises/src/JavaAdvanced/DefiningClasses_13/Exercise/CatLady_9/Cat/Cat.java | DenislavVelichkov/Java-Advanced-And-OOP | 2bce655d016f64b911ff1df1143647a3b8efacd1 | [
"MIT"
] | null | null | null | Java OOP Exercises/src/JavaAdvanced/DefiningClasses_13/Exercise/CatLady_9/Cat/Cat.java | DenislavVelichkov/Java-Advanced-And-OOP | 2bce655d016f64b911ff1df1143647a3b8efacd1 | [
"MIT"
] | null | null | null | 19.368421 | 68 | 0.619565 | 975 | package JavaAdvanced.DefiningClasses_13.Exercise.CatLady_9.Cat;
public abstract class Cat {
private String name;
public Cat(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
@Override
public String toString() {
return this.getClass().getTypeName() + " " + this.getName();
}
}
|
3e025cdab4536c4f638a01150a51941aaaae8469 | 1,133 | java | Java | kool/src/main/java/org/davidmoten/kool/internal/operators/stream/Skip.java | davidmoten/kool | b78b93d60a8e71a0a04ea04a0692e43b7ffeb519 | [
"Apache-2.0"
] | 7 | 2018-10-01T15:48:29.000Z | 2022-03-15T12:00:37.000Z | kool/src/main/java/org/davidmoten/kool/internal/operators/stream/Skip.java | davidmoten/kool | b78b93d60a8e71a0a04ea04a0692e43b7ffeb519 | [
"Apache-2.0"
] | 20 | 2020-11-02T20:18:24.000Z | 2022-03-29T09:21:28.000Z | kool/src/main/java/org/davidmoten/kool/internal/operators/stream/Skip.java | davidmoten/kool | b78b93d60a8e71a0a04ea04a0692e43b7ffeb519 | [
"Apache-2.0"
] | 1 | 2018-12-09T09:35:25.000Z | 2018-12-09T09:35:25.000Z | 22.215686 | 64 | 0.481024 | 976 | package org.davidmoten.kool.internal.operators.stream;
import org.davidmoten.kool.Stream;
import org.davidmoten.kool.StreamIterator;
public final class Skip<T> implements Stream<T> {
private final int count;
private final Stream<T> source;
public Skip(int count, Stream<T> source) {
this.count = count;
this.source = source;
}
@Override
public StreamIterator<T> iterator() {
return new StreamIterator<T>() {
StreamIterator<T> it = source.iteratorNullChecked();
int n = count;
@Override
public boolean hasNext() {
skip();
return it.hasNext();
}
@Override
public T next() {
skip();
return it.nextNullChecked();
}
@Override
public void dispose() {
it.dispose();
}
private void skip() {
while (n > 0 && it.hasNext()) {
it.nextNullChecked();
n--;
}
}
};
}
}
|
3e025e0e637f0bb5526f7caba6133e6d1f9a9df2 | 5,880 | java | Java | webapp/src/main/java/org/entrystore/rowstore/store/impl/PgRowStore.java | MetaSolutionsAB/rowstore | 8a8274cbedc0c9104adae0a684ff8c7e7d49162b | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2015-09-03T19:53:49.000Z | 2015-09-03T19:53:49.000Z | webapp/src/main/java/org/entrystore/rowstore/store/impl/PgRowStore.java | MetaSolutionsAB/rowstore | 8a8274cbedc0c9104adae0a684ff8c7e7d49162b | [
"ECL-2.0",
"Apache-2.0"
] | 20 | 2015-09-04T07:53:11.000Z | 2021-12-11T08:24:30.000Z | webapp/src/main/java/org/entrystore/rowstore/store/impl/PgRowStore.java | MetaSolutionsAB/rowstore | 8a8274cbedc0c9104adae0a684ff8c7e7d49162b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 30.174359 | 119 | 0.731645 | 977 | /*
* Copyright (c) 2011-2015 MetaSolutions AB <[email protected]>
*
* 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.entrystore.rowstore.store.impl;
import org.entrystore.rowstore.etl.EtlProcessor;
import org.entrystore.rowstore.store.Datasets;
import org.entrystore.rowstore.store.RowStore;
import org.entrystore.rowstore.store.RowStoreConfig;
import org.postgresql.ds.PGPoolingDataSource;
import org.postgresql.ds.PGSimpleDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
/**
* A PostgreSQL-specific implementation of the RowStore interface.
*
* @author Hannes Ebner
* @see RowStore
*/
public class PgRowStore implements RowStore {
private final static Logger log = LoggerFactory.getLogger(PgRowStore.class);
final DataSource datasource;
DataSource queryDatasource;
Datasets datasets;
EtlProcessor etlProcessor;
RowStoreConfig config;
public PgRowStore(RowStoreConfig config) {
if (config == null) {
throw new IllegalArgumentException("Configuration must not be null");
}
this.config = config;
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
log.error(e.getMessage());
}
datasource = initializeDataSource(new PGSimpleDataSource(), config.getDatabase());
/* if (config.getDatabase().getConnectionPoolInit() > 0 && config.getDatabase().getConnectionPoolMax() > 0) {
datasource = initializeDataSource(new PGPoolingDataSource(), config.getDatabase());
} else {
datasource = initializeDataSource(new PGSimpleDataSource(), config.getDatabase());
} */
if (config.getDatabase() == config.getQueryDatabase()) {
queryDatasource = datasource;
} else {
if (config.getQueryDatabase().getConnectionPoolInit() > 0 && config.getQueryDatabase().getConnectionPoolMax() > 0) {
queryDatasource = initializeDataSource(new PGPoolingDataSource(), config.getQueryDatabase());
((PGPoolingDataSource) queryDatasource).setReadOnly(true);
} else {
queryDatasource = initializeDataSource(new PGSimpleDataSource(), config.getQueryDatabase());
((PGSimpleDataSource) queryDatasource).setReadOnly(true);
}
}
etlProcessor = new EtlProcessor(this);
}
private DataSource initializeDataSource(DataSource dataSource, RowStoreConfig.Database dbConfig) {
if (dataSource == null || dbConfig == null) {
throw new IllegalArgumentException("Parameters must not be null");
}
if (dataSource instanceof PGSimpleDataSource) {
PGSimpleDataSource ds = (PGSimpleDataSource) dataSource;
ds.setUser(dbConfig.getUser());
ds.setPassword(dbConfig.getPassword());
ds.setServerName(dbConfig.getHost());
ds.setDatabaseName(dbConfig.getName());
ds.setPortNumber(dbConfig.getPort());
ds.setSsl(dbConfig.getSsl());
if (ds.getSsl()) {
ds.setSslMode("require");
}
ds.setLogUnclosedConnections(log.isDebugEnabled());
} else if (dataSource instanceof PGPoolingDataSource) {
PGPoolingDataSource ds = (PGPoolingDataSource) dataSource;
ds.setPreparedStatementCacheQueries(100);
ds.setInitialConnections(dbConfig.getConnectionPoolInit());
ds.setMaxConnections(dbConfig.getConnectionPoolMax());
ds.setUser(dbConfig.getUser());
ds.setPassword(dbConfig.getPassword());
ds.setServerName(dbConfig.getHost());
ds.setDatabaseName(dbConfig.getName());
ds.setPortNumber(dbConfig.getPort());
ds.setSsl(dbConfig.getSsl());
if (ds.getSsl()) {
ds.setSslMode("require");
}
ds.setLogUnclosedConnections(log.isDebugEnabled());
}
return dataSource;
}
/**
* @see RowStore#getConnection()
*/
@Override
public Connection getConnection() throws SQLException {
return datasource.getConnection();
}
/**
* @see RowStore#getQueryConnection()
*/
@Override
public Connection getQueryConnection() throws SQLException {
return queryDatasource.getConnection();
}
/**
* @see RowStore#getEtlProcessor()
*/
@Override
public EtlProcessor getEtlProcessor() {
return etlProcessor;
}
public Datasets getDatasets() {
synchronized (datasource) {
if (datasets == null) {
this.datasets = new PgDatasets(this);
}
}
return this.datasets;
}
/**
* @see RowStore#getConfig()
*/
@Override
public RowStoreConfig getConfig() {
return config;
}
/**
* @see RowStore#shutdown()
*/
@Override
public void shutdown() {
log.info("Shutting down RowStore");
etlProcessor.shutdown();
// Deregister JDBC driver that were loaded by this webapp
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver driver = drivers.nextElement();
if (driver.getClass().getClassLoader() == cl) {
// This driver was registered by the webapp's ClassLoader, so deregister it
try {
log.info("Deregistering JDBC driver: {}", driver);
DriverManager.deregisterDriver(driver);
} catch (SQLException ex) {
log.error("An error occured when deregistering JDBC driver: {}", driver, ex);
}
} else {
log.trace("Not deregistering JDBC driver {} as it does not belong to this webapp's ClassLoader", driver);
}
}
log.info("Shutdown complete");
}
} |
3e025e7e271dce30fca974389c584d972b6123c0 | 2,110 | java | Java | gateway-server/src/test/java/org/apache/knox/gateway/websockets/EchoSocket.java | nxverma/knox | bd24b537b722b98b7dec7ec00b5af7d795ae196b | [
"Apache-2.0"
] | 153 | 2015-01-16T08:01:43.000Z | 2022-03-31T11:42:15.000Z | gateway-server/src/test/java/org/apache/knox/gateway/websockets/EchoSocket.java | nxverma/knox | bd24b537b722b98b7dec7ec00b5af7d795ae196b | [
"Apache-2.0"
] | 758 | 2018-09-10T12:00:48.000Z | 2022-02-28T03:33:51.000Z | gateway-server/src/test/java/org/apache/knox/gateway/websockets/EchoSocket.java | isabella232/knox-2 | 2c45bbd37a80a7c7030c5c0c52017171a93a4d73 | [
"Apache-2.0"
] | 227 | 2015-04-01T19:21:03.000Z | 2022-03-31T11:42:17.000Z | 29.305556 | 75 | 0.704265 | 978 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.knox.gateway.websockets;
import java.io.IOException;
import org.eclipse.jetty.io.RuntimeIOException;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.websocket.api.BatchMode;
import org.eclipse.jetty.websocket.api.RemoteEndpoint;
import org.eclipse.jetty.websocket.api.WebSocketAdapter;
/**
* A simple Echo socket
*/
public class EchoSocket extends WebSocketAdapter {
@Override
public void onWebSocketBinary(byte[] payload, int offset, int len) {
if (isNotConnected()) {
return;
}
try {
RemoteEndpoint remote = getRemote();
remote.sendBytes(BufferUtil.toBuffer(payload, offset, len), null);
if (remote.getBatchMode() == BatchMode.ON) {
remote.flush();
}
} catch (IOException x) {
throw new RuntimeIOException(x);
}
}
@Override
public void onWebSocketError(Throwable cause) {
throw new RuntimeException(cause);
}
@Override
public void onWebSocketText(String message) {
if (isNotConnected()) {
return;
}
try {
RemoteEndpoint remote = getRemote();
remote.sendString(message, null);
if (remote.getBatchMode() == BatchMode.ON) {
remote.flush();
}
} catch (IOException x) {
throw new RuntimeIOException(x);
}
}
}
|
3e025ed9fa6f100db9a3d122bc68d98d3e8663eb | 6,214 | java | Java | tests/acceptance-test/src/test/java/com/quorum/tessera/test/rest/PrivacyGroupIT.java | PuneetGoel80/tessera-fork | 36df042c1f113511833a9b57d52a2edadb73d2b8 | [
"Apache-2.0"
] | 128 | 2018-08-15T15:39:11.000Z | 2020-08-18T19:39:41.000Z | tests/acceptance-test/src/test/java/com/quorum/tessera/test/rest/PrivacyGroupIT.java | PuneetGoel80/tessera-fork | 36df042c1f113511833a9b57d52a2edadb73d2b8 | [
"Apache-2.0"
] | 617 | 2018-08-15T16:08:01.000Z | 2020-08-24T14:08:09.000Z | tests/acceptance-test/src/test/java/com/quorum/tessera/test/rest/PrivacyGroupIT.java | PuneetGoel80/tessera-fork | 36df042c1f113511833a9b57d52a2edadb73d2b8 | [
"Apache-2.0"
] | 99 | 2018-08-15T16:15:32.000Z | 2020-07-21T10:06:31.000Z | 41.986486 | 100 | 0.713711 | 979 | package com.quorum.tessera.test.rest;
import static org.assertj.core.api.Assertions.*;
import com.quorum.tessera.test.Party;
import com.quorum.tessera.test.PartyHelper;
import jakarta.json.Json;
import jakarta.json.JsonArray;
import jakarta.json.JsonObject;
import jakarta.json.JsonString;
import jakarta.ws.rs.client.Entity;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.io.StringReader;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;
public class PrivacyGroupIT {
private final PartyHelper partyHelper = PartyHelper.create();
private final PrivacyGroupTestUtil privacyGroupTestUtil = new PrivacyGroupTestUtil();
@Test
public void testCreate() {
final String output = privacyGroupTestUtil.create("A", "B");
final JsonObject jsonObj = Json.createReader(new StringReader(output)).readObject();
assertThat(jsonObj.getString("privacyGroupId").length()).isEqualTo(44);
assertThat(jsonObj.getString("name")).isEqualTo("Organisation [A, B]");
assertThat(jsonObj.getString("description"))
.isEqualTo("Contains members of Organisation [A, B]");
assertThat(jsonObj.getString("type")).isEqualTo("PANTHEON");
final List<String> members =
jsonObj.getJsonArray("members").getValuesAs(JsonString.class).stream()
.map(JsonString::getString)
.collect(Collectors.toList());
assertThat(members)
.containsExactlyInAnyOrder(
partyHelper.findByAlias("A").getPublicKey(),
partyHelper.findByAlias("B").getPublicKey());
}
@Test
public void testRetrieve() {
final String output = privacyGroupTestUtil.create("C", "D");
final JsonObject jsonObj = Json.createReader(new StringReader(output)).readObject();
final String privacyGroupId = jsonObj.getString("privacyGroupId");
final String nodeCResult = privacyGroupTestUtil.retrieve("C", privacyGroupId);
final JsonObject nodeCJson = Json.createReader(new StringReader(nodeCResult)).readObject();
assertThat(nodeCJson.getString("privacyGroupId")).isEqualTo(privacyGroupId);
assertThat(nodeCJson.getString("name")).isEqualTo("Organisation [C, D]");
assertThat(nodeCJson.getString("description"))
.isEqualTo("Contains members of Organisation [C, D]");
assertThat(nodeCJson.getString("type")).isEqualTo("PANTHEON");
final List<String> members =
nodeCJson.getJsonArray("members").getValuesAs(JsonString.class).stream()
.map(JsonString::getString)
.collect(Collectors.toList());
assertThat(members)
.containsExactlyInAnyOrder(
partyHelper.findByAlias("C").getPublicKey(),
partyHelper.findByAlias("D").getPublicKey());
final String nodeDResult = privacyGroupTestUtil.retrieve("D", privacyGroupId);
final JsonObject nodeDJson = Json.createReader(new StringReader(nodeDResult)).readObject();
assertThat(nodeDJson).isEqualTo(nodeCJson);
// Retrieve will fail on node A as it's not a member
assertThatThrownBy(() -> privacyGroupTestUtil.retrieve("A", privacyGroupId))
.isInstanceOf(AssertionError.class)
.hasMessageContaining("404");
}
@Test
public void testFind() {
String pg1 = privacyGroupTestUtil.create("A", "B", "D");
final JsonObject output1 = Json.createReader(new StringReader(pg1)).readObject();
String pg2 = privacyGroupTestUtil.create("D", "B", "A");
final JsonObject output2 = Json.createReader(new StringReader(pg2)).readObject();
String resultA = privacyGroupTestUtil.find("A", "A", "B", "D");
final JsonArray nodeAJson = Json.createReader(new StringReader(resultA)).readArray();
assertThat(nodeAJson.size()).isEqualTo(2);
assertThat(nodeAJson.getValuesAs(JsonObject.class)).containsExactlyInAnyOrder(output1, output2);
String resultB = privacyGroupTestUtil.find("B", "A", "B", "D");
final JsonArray nodeBJson = Json.createReader(new StringReader(resultB)).readArray();
assertThat(nodeBJson.size()).isEqualTo(2);
assertThat(nodeBJson.getValuesAs(JsonObject.class)).containsExactlyInAnyOrder(output1, output2);
String resultC = privacyGroupTestUtil.find("C", "A", "B", "D");
final JsonArray nodeCJson = Json.createReader(new StringReader(resultC)).readArray();
assertThat(nodeCJson.size()).isEqualTo(0);
String resultD = privacyGroupTestUtil.find("D", "A", "B", "D");
final JsonArray nodeDJson = Json.createReader(new StringReader(resultD)).readArray();
assertThat(nodeDJson.size()).isEqualTo(2);
assertThat(nodeDJson.getValuesAs(JsonObject.class)).containsExactlyInAnyOrder(output1, output2);
}
@Test
public void testDelete() {
final String output = privacyGroupTestUtil.create("C", "A", "B", "D");
final JsonObject jsonObj = Json.createReader(new StringReader(output)).readObject();
final String privacyGroupId = jsonObj.getString("privacyGroupId");
final Party sender = partyHelper.findByAlias("C");
privacyGroupTestUtil.retrieve("A", privacyGroupId);
privacyGroupTestUtil.retrieve("B", privacyGroupId);
privacyGroupTestUtil.retrieve("C", privacyGroupId);
privacyGroupTestUtil.retrieve("D", privacyGroupId);
JsonObject json =
Json.createObjectBuilder()
.add("from", sender.getPublicKey())
.add("privacyGroupId", privacyGroupId)
.build();
final Response response =
sender
.getRestClient()
.target(sender.getQ2TUri())
.path("/deletePrivacyGroup")
.request()
.post(Entity.entity(json, MediaType.APPLICATION_JSON));
assertThat(response.getStatus()).isEqualTo(200);
assertThatThrownBy(() -> privacyGroupTestUtil.retrieve("A", privacyGroupId))
.isInstanceOf(AssertionError.class);
assertThatThrownBy(() -> privacyGroupTestUtil.retrieve("B", privacyGroupId))
.isInstanceOf(AssertionError.class);
assertThatThrownBy(() -> privacyGroupTestUtil.retrieve("C", privacyGroupId))
.isInstanceOf(AssertionError.class);
assertThatThrownBy(() -> privacyGroupTestUtil.retrieve("D", privacyGroupId))
.isInstanceOf(AssertionError.class);
}
}
|
3e025f20bc91022a7b75a15181a7fe2309595156 | 2,980 | java | Java | cwms_radar_api/src/test/java/cwms/radar/formatters/JsonV1Test.java | DanielTOsborne/cwms-radar-api | b52d735e3250b6273aed13b890ef4c57c7c54afa | [
"MIT"
] | 3 | 2021-01-16T17:28:19.000Z | 2022-03-15T21:40:41.000Z | cwms_radar_api/src/test/java/cwms/radar/formatters/JsonV1Test.java | DanielTOsborne/cwms-radar-api | b52d735e3250b6273aed13b890ef4c57c7c54afa | [
"MIT"
] | 62 | 2021-03-26T13:58:36.000Z | 2022-03-31T23:37:49.000Z | cwms_radar_api/src/test/java/cwms/radar/formatters/JsonV1Test.java | DanielTOsborne/cwms-radar-api | b52d735e3250b6273aed13b890ef4c57c7c54afa | [
"MIT"
] | 3 | 2021-05-14T17:10:32.000Z | 2021-08-12T20:48:30.000Z | 22.748092 | 100 | 0.689933 | 980 | package cwms.radar.formatters;
import java.util.ArrayList;
import java.util.List;
import cwms.radar.data.dto.LocationCategory;
import cwms.radar.data.dto.LocationGroup;
import cwms.radar.data.dto.Office;
import cwms.radar.formatters.json.JsonV1;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class JsonV1Test
{
@Test
void singleOfficeFormat()
{
Office office = new Office("name_here", "long_name_next", "office_type_third", "reports_to_last");
JsonV1 v1 = new JsonV1();
String result = v1.format(office);
assertNotNull(result);
assertTrue(result.contains("offices"));
}
@Test
void listOfficeFormat()
{
List<Office> offices = buildOffices();
JsonV1 v1 = new JsonV1();
String result = v1.format(offices);
assertNotNull(result);
assertTrue(result.contains("offices"));
}
private List<Office> buildOffices()
{
String name = "name";
String longName = "long_name";
String officeType = "office_type";
String reportsTo = "reports_to";
List<Office> offices = new ArrayList<>();
for(int i = 0; i < 4; i++)
{
Office office = new Office(name + i, longName + i, officeType + i, reportsTo + i);
offices.add(office);
}
return offices;
}
@Test
void singleLocCatFormat()
{
LocationCategory cat = new LocationCategory("catOfficeId", "id", "catDesc");
JsonV1 v1 = new JsonV1();
String result = v1.format(cat);
assertNotNull(result);
assertTrue(result.contains("catOfficeId"));
}
@Test
void listCatsFormat()
{
List<LocationCategory> cats = buildCats();
JsonV1 v1 = new JsonV1();
String result = v1.format(cats);
assertNotNull(result);
assertTrue(result.contains("catOfficeId"));
}
private List<LocationCategory> buildCats()
{
List<LocationCategory> cats = new ArrayList<>();
for(int i = 0; i < 4; i++)
{
LocationCategory cat = new LocationCategory("catOfficeId" + i, "id" + i, "catDesc");
cats.add(cat);
}
return cats;
}
@Test
void singleLocGroFormat()
{
LocationCategory cat = new LocationCategory("catOfficeId", "id", "catDesc");
final Double locGroupAttribute = null;
LocationGroup grp = new LocationGroup(cat, "grpOfficeId", "id", "grpDesc", "sharedLocAliasId",
"sharedRefLocationId", locGroupAttribute);
JsonV1 v1 = new JsonV1();
String result = v1.format(cat);
assertNotNull(result);
assertTrue(result.contains("catOfficeId"));
}
@Test
void listGrpsFormat()
{
List<LocationGroup> cats = buildGrps();
JsonV1 v1 = new JsonV1();
String result = v1.format(cats);
assertNotNull(result);
assertTrue(result.contains("catOfficeId"));
}
private List<LocationGroup> buildGrps()
{
List<LocationGroup> cats = new ArrayList<>();
for(int i = 0; i < 4; i++)
{
LocationCategory cat = new LocationCategory("catOfficeId", "id", "catDesc");
LocationGroup grp = new LocationGroup(cat, "grpOfficeId" + i, "id" + i, "grpDesc", null,
null, null);
cats.add(grp);
}
return cats;
}
}
|
3e025f35d63510ba5b253317a64a6e5459058901 | 2,980 | java | Java | javajokes/src/main/java/com/bduverneay/JokeProvider.java | duvernea/BuildItBigger | 3379faf7c72dfd959eaed6caa5ab4ad25afac36d | [
"Apache-2.0"
] | null | null | null | javajokes/src/main/java/com/bduverneay/JokeProvider.java | duvernea/BuildItBigger | 3379faf7c72dfd959eaed6caa5ab4ad25afac36d | [
"Apache-2.0"
] | null | null | null | javajokes/src/main/java/com/bduverneay/JokeProvider.java | duvernea/BuildItBigger | 3379faf7c72dfd959eaed6caa5ab4ad25afac36d | [
"Apache-2.0"
] | null | null | null | 47.301587 | 104 | 0.560403 | 981 | package com.bduverneay;
import java.util.Random;
public class JokeProvider {
public Joke getJoke() {
// Get a random joke from the string array
Random rand = new Random();
int randomNum = rand.nextInt((jokeArray.length));
return jokeArray[randomNum];
}
private static Joke[] jokeArray = {
new Joke("A guy walks into a bar and asks for 1.014 root beers.\n\n" +
"The bartender says, \"I\'ll have to charge you extra, that's a root beer float\"",
"So the guy says, \"In that case, better make it a double.\""),
new Joke("There are 10 kinds of people in this world." ,
"Those who understand binary, those who don't"),
new Joke("An SEO expert walks into a bar, pub, public house, inn, restaurant, club." ,
"That's the joke"),
new Joke("Why is it that women find C to be more attractive than Java?" ,
"Because C doesn’t treat them like objects."),
new Joke("In Canadian hexadecimal, why is 6 afraid of 7?" ,
"Because 7 8 9 A?"),
new Joke("Why aren’t octal jokes funny?",
"Because 7 10 11."),
new Joke("Why do Java programmers wear glasses?",
"Because they don’t C#!"),
new Joke("Why did the programmer quit his job?",
"Because he didn’t get arrays."),
new Joke("What do you call it when a programmer throws up at IHOP?",
"A stack overflow."),
new Joke("What do you get if you divide the circumference of a jack-o-lantern by its diameter?",
"Pumpkin Pi"),
new Joke("Why couldn't the angle get a loan?",
"His parents wouldn't Cosine"),
new Joke("Why is beer never served at a math party?",
"Because you can't drink and derive."),
new Joke("Why didn't the number 4 get into the nightclub?",
"Because he is 2 square"),
new Joke("Why did the obtuse angle go to the beach?",
"Because it was over 90 degrees"),
new Joke("What do you call a man who spent all summer at the beach?",
"A Tangent"),
new Joke("How do you know the moon is going broke?",
"It's down to it's last quarter"),
new Joke("Why can't you trust atoms?",
"They make up everything"),
new Joke("A neutron walks into a bar, and asks the bartender \"How much for a drink?\"",
"For you, no charge"),
new Joke("What does a subatomic duck say?" ,
"Quark"),
new Joke("What do you call an educated tube?" ,
"A graduated cylinder"),
new Joke("What do you call a Divinely Shaped Wave?" ,
"A Sine from God"),
new Joke("Do you know any good jokes about Sodium?" ,
"Na"),
new Joke("Tell me a joke about Potassium." ,
"K"),
};
}
|
3e02609ba0c7b13119719931e724d3f29cf29e98 | 4,621 | java | Java | jtransc-rt/src/java/time/Instant.java | jayvdb/jtransc | 960f6bf22cbb0a6be830bf2622385995b20a85b8 | [
"Apache-2.0"
] | 625 | 2016-02-08T21:20:19.000Z | 2022-03-28T13:03:16.000Z | jtransc-rt/src/java/time/Instant.java | jayvdb/jtransc | 960f6bf22cbb0a6be830bf2622385995b20a85b8 | [
"Apache-2.0"
] | 257 | 2016-02-10T13:33:14.000Z | 2021-09-13T12:12:30.000Z | jtransc-rt/src/java/time/Instant.java | jayvdb/jtransc | 960f6bf22cbb0a6be830bf2622385995b20a85b8 | [
"Apache-2.0"
] | 78 | 2016-02-24T14:11:08.000Z | 2021-08-13T12:47:00.000Z | 26.866279 | 101 | 0.765419 | 982 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.time;
import java.io.Serializable;
import java.time.temporal.*;
import static java.time._TimeConsts.*;
public final class Instant implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable {
public static final Instant EPOCH = new Instant(0, 0);
public static final Instant MIN = Instant.ofEpochSecond(-31557014167219200L, 0);
public static final Instant MAX = Instant.ofEpochSecond(31556889864403199L, 999_999_999);
private final long seconds;
private final int nanos;
private Instant(long seconds, int nanos) {
this.seconds = seconds;
this.nanos = nanos;
}
public static Instant now() {
return Clock.systemUTC().instant();
}
public static Instant now(Clock clock) {
return clock.instant();
}
public static Instant ofEpochSecond(long epochSecond) {
return new Instant(epochSecond, 0);
}
public static Instant ofEpochSecond(long epochSecond, long nanoAdjustment) {
return new Instant(
epochSecond + nanoAdjustment / NANOSECONDS_IN_SECOND,
(int) (nanoAdjustment % NANOSECONDS_IN_SECOND)
);
}
public static Instant ofEpochMilli(long epochMilli) {
return ofEpochSecond(epochMilli / MILLISECONDS_IN_SECOND, epochMilli * NANOSECONDS_IN_MILLISECOND);
}
native public static Instant from(TemporalAccessor temporal);
native public static Instant parse(final CharSequence text);
@Override
native public boolean isSupported(TemporalField field);
@Override
native public boolean isSupported(TemporalUnit unit);
@Override // override for Javadoc
native public ValueRange range(TemporalField field);
@Override
native public long getLong(TemporalField field);
public long getEpochSecond() {
return seconds;
}
public int getNano() {
return nanos;
}
@Override
native public Instant with(TemporalAdjuster adjuster);
@Override
native public Instant with(TemporalField field, long newValue);
native public Instant truncatedTo(TemporalUnit unit);
@Override
native public Instant plus(TemporalAmount amountToAdd);
private Instant _plus(long secondsToAdd, long nanosToAdd) {
return ofEpochSecond(this.seconds + secondsToAdd, this.nanos + nanosToAdd);
}
private Instant _minus(long secondsToAdd, long nanosToAdd) {
return ofEpochSecond(this.seconds - secondsToAdd, this.nanos - nanosToAdd);
}
@Override
native public Instant plus(long amountToAdd, TemporalUnit unit);
public Instant plusSeconds(long delta) {
return _plus(delta, 0);
}
public Instant plusMillis(long delta) {
return _plus(0, delta * NANOSECONDS_IN_MILLISECOND);
}
public Instant plusNanos(long delta) {
return _plus(0, delta);
}
@Override
native public Instant minus(TemporalAmount amountToSubtract);
@Override
native public Instant minus(long amountToSubtract, TemporalUnit unit);
public Instant minusSeconds(long delta) {
return _minus(delta, 0);
}
public Instant minusMillis(long delta) {
return _minus(0, delta * NANOSECONDS_IN_MILLISECOND);
}
public Instant minusNanos(long delta) {
return _minus(0, delta);
}
@SuppressWarnings("unchecked")
@Override
native public <R> R query(TemporalQuery<R> query);
@Override
native public Temporal adjustInto(Temporal temporal);
@Override
native public long until(Temporal endExclusive, TemporalUnit unit);
native public OffsetDateTime atOffset(ZoneOffset offset);
native public ZonedDateTime atZone(ZoneId zone);
public long toEpochMilli() {
return (seconds * 1000) + (nanos / NANOSECONDS_IN_MILLISECOND);
}
@Override
native public int compareTo(Instant otherInstant);
native public boolean isAfter(Instant otherInstant);
native public boolean isBefore(Instant otherInstant);
@Override
native public boolean equals(Object otherInstant);
@Override
native public int hashCode();
@Override
native public String toString();
}
|
3e0260c82afcd2095f55031811eb35abb9675459 | 5,638 | java | Java | tlc-commons-project/tlc-io-x937/src/main/java/com/thelastcheck/io/x937/records/base/X937CheckDetailAddendumARecordBase.java | jerrybowman/tlc.open.java | 60269438a4d45c186c9799a015ddccf07389f747 | [
"Apache-2.0"
] | 5 | 2015-11-17T22:39:26.000Z | 2020-05-15T07:36:04.000Z | tlc-commons-project/tlc-io-x937/src/main/java/com/thelastcheck/io/x937/records/base/X937CheckDetailAddendumARecordBase.java | jerrybowman/tlc.open.java | 60269438a4d45c186c9799a015ddccf07389f747 | [
"Apache-2.0"
] | 19 | 2015-10-31T03:34:50.000Z | 2021-09-26T19:08:49.000Z | tlc-commons-project/tlc-io-x937/src/main/java/com/thelastcheck/io/x937/records/base/X937CheckDetailAddendumARecordBase.java | jerrybowman/tlc.open.java | 60269438a4d45c186c9799a015ddccf07389f747 | [
"Apache-2.0"
] | 5 | 2015-11-17T22:40:02.000Z | 2021-09-24T12:37:31.000Z | 31.322222 | 90 | 0.719227 | 983 | /*******************************************************************************
* Copyright (c) 2009-2015 The Last Check, LLC, All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.thelastcheck.io.x937.records.base;
import java.util.Date;
import com.thelastcheck.io.x937.records.X937CheckDetailAddendumARecord;
import com.thelastcheck.commons.base.exception.InvalidDataException;
import com.thelastcheck.commons.base.fields.OnUsField;
import com.thelastcheck.commons.base.fields.RoutingNumber;
import com.thelastcheck.commons.buffer.ByteArray;
import com.thelastcheck.io.base.exception.InvalidStandardLevelException;
import com.thelastcheck.io.x9.X9RecordImpl;
public abstract class X937CheckDetailAddendumARecordBase extends X9RecordImpl
implements X937CheckDetailAddendumARecord {
/*
* X937CheckDetailAddendumARecordBase
*/
public X937CheckDetailAddendumARecordBase() {
super();
recordType(TYPE_CHECK_DETAIL_ADDENDUM_A);
}
public X937CheckDetailAddendumARecordBase(int stdLevel) {
super(TYPE_CHECK_DETAIL_ADDENDUM_A, stdLevel);
}
public X937CheckDetailAddendumARecordBase(String encoding, int stdLevel) {
super(TYPE_CHECK_DETAIL_ADDENDUM_A, encoding, stdLevel);
}
public X937CheckDetailAddendumARecordBase(ByteArray record, int stdLevel) {
super(record, stdLevel);
}
public String checkDetailAddendumARecordNumber() {
throw new InvalidStandardLevelException();
}
public X937CheckDetailAddendumARecord checkDetailAddendumARecordNumber(String value) {
throw new InvalidStandardLevelException();
}
public int checkDetailAddendumARecordNumberAsInt()
throws InvalidDataException {
throw new InvalidStandardLevelException();
}
public X937CheckDetailAddendumARecord checkDetailAddendumARecordNumber(int value) {
throw new InvalidStandardLevelException();
}
public RoutingNumber BOFDRoutingNumber() {
throw new InvalidStandardLevelException();
}
public X937CheckDetailAddendumARecord BOFDRoutingNumber(RoutingNumber value) {
throw new InvalidStandardLevelException();
}
public String BOFDRoutingNumberAsString() {
throw new InvalidStandardLevelException();
}
public X937CheckDetailAddendumARecord BOFDRoutingNumber(String value) {
throw new InvalidStandardLevelException();
}
public Date BOFDBusinessDate()
throws InvalidDataException {
throw new InvalidStandardLevelException();
}
public X937CheckDetailAddendumARecord BOFDBusinessDate(Date value) {
throw new InvalidStandardLevelException();
}
public String BOFDBusinessDateAsString() {
throw new InvalidStandardLevelException();
}
public X937CheckDetailAddendumARecord BOFDBusinessDate(String value) {
throw new InvalidStandardLevelException();
}
public String BOFDItemSequenceNumber() {
throw new InvalidStandardLevelException();
}
public X937CheckDetailAddendumARecord BOFDItemSequenceNumber(String value) {
throw new InvalidStandardLevelException();
}
public String depositAccountNumberAtBOFD() {
throw new InvalidStandardLevelException();
}
public X937CheckDetailAddendumARecord depositAccountNumberAtBOFD(String value) {
throw new InvalidStandardLevelException();
}
public String BOFDDepositBranch() {
throw new InvalidStandardLevelException();
}
public X937CheckDetailAddendumARecord BOFDDepositBranch(String value) {
throw new InvalidStandardLevelException();
}
public String payeeName() {
throw new InvalidStandardLevelException();
}
public X937CheckDetailAddendumARecord payeeName(String value) {
throw new InvalidStandardLevelException();
}
public String truncationIndicator() {
throw new InvalidStandardLevelException();
}
public X937CheckDetailAddendumARecord truncationIndicator(String value) {
throw new InvalidStandardLevelException();
}
public String BOFDConversionIndicator() {
throw new InvalidStandardLevelException();
}
public X937CheckDetailAddendumARecord BOFDConversionIndicator(String value) {
throw new InvalidStandardLevelException();
}
public String BOFDCorrectionIndicator() {
throw new InvalidStandardLevelException();
}
public X937CheckDetailAddendumARecord BOFDCorrectionIndicator(String value) {
throw new InvalidStandardLevelException();
}
public String userField() {
throw new InvalidStandardLevelException();
}
public X937CheckDetailAddendumARecord userField(String value) {
throw new InvalidStandardLevelException();
}
public String reserved() {
throw new InvalidStandardLevelException();
}
public X937CheckDetailAddendumARecord reserved(String value) {
throw new InvalidStandardLevelException();
}
}
|
3e0260e4f1f1ef692e21d131d9a127c74a07e3d3 | 4,581 | java | Java | xdef-transform-xsd/src/test/java/test/schema2xd/suite/CollectionSchema2XdTest.java | Syntea/xdef-transform | be50186742a71b087235b05513c0c209dfc8c854 | [
"Apache-2.0"
] | null | null | null | xdef-transform-xsd/src/test/java/test/schema2xd/suite/CollectionSchema2XdTest.java | Syntea/xdef-transform | be50186742a71b087235b05513c0c209dfc8c854 | [
"Apache-2.0"
] | null | null | null | xdef-transform-xsd/src/test/java/test/schema2xd/suite/CollectionSchema2XdTest.java | Syntea/xdef-transform | be50186742a71b087235b05513c0c209dfc8c854 | [
"Apache-2.0"
] | null | null | null | 26.947059 | 78 | 0.568435 | 984 | package test.schema2xd.suite;
import org.junit.jupiter.api.Test;
import test.schema2xd.AbstractSchema2XdTransformSuite;
import java.util.Collections;
/**
* @author smid
* @since 2021-05-28
*/
public class CollectionSchema2XdTest extends AbstractSchema2XdTransformSuite {
public static final String SUITE_NAME = "collection";
@Test
public void xdPool_t011() {
initTestCaseDirs(SUITE_NAME, "t011");
convertXsd2XdPoolNoRef(
"t011",
Collections.singletonList("t011"),
null);
}
@Test
public void xdPool_t012() {
initTestCaseDirs(SUITE_NAME, "t012");
convertXsd2XdPoolNoRef(
"t012",
Collections.singletonList("t012"),
null);
}
@Test
public void xdPool_t013() {
initTestCaseDirs(SUITE_NAME, "t013");
convertXsd2XdPoolNoRef(
"t013",
Collections.singletonList("t013"),
null);
}
@Test
public void xdPool_t014() {
initTestCaseDirs(SUITE_NAME, "t014");
convertXsd2XdPoolNoRef(
"t014",
Collections.singletonList("t014"),
null);
}
@Test
public void xdPool_t015() {
initTestCaseDirs(SUITE_NAME, "t015");
convertXsd2XdPoolNoRef(
"t015",
Collections.singletonList("t015"),
null);
}
@Test
public void xdPool_t018() {
initTestCaseDirs(SUITE_NAME, "t018");
convertXsd2XdPoolNoRef(
"t018",
Collections.singletonList("t018"),
null);
}
@Test
public void xdPool_Namespace_1() {
initTestCaseDirs(SUITE_NAME, "namespaceTest2");
convertXsd2XdPoolNoRef(
"namespaceTest2",
Collections.singletonList("namespaceTest2_valid_1"),
null);
}
@Test
public void xdPool_Namespace_2() {
initTestCaseDirs(SUITE_NAME, "namespaceTest3");
convertXsd2XdPoolNoRef(
"namespaceTest3",
Collections.singletonList("namespaceTest3_valid_1"),
null);
}
@Test
public void xdPool_Namespace_3() {
initTestCaseDirs(SUITE_NAME, "namespaceTest4");
convertXsd2XdPoolNoRef(
"namespaceTest4",
Collections.singletonList("namespaceTest4_valid_1"),
null);
}
@Test
public void xdPool_MultipleXDef_1() {
initTestCaseDirs(SUITE_NAME, "multiXdefTest");
convertXsd2XdPoolNoRef(
"multiXdefTest",
Collections.singletonList("multiXdefTest_valid_1"),
null);
}
@Test
public void xdPool_MultipleXDef_2() {
initTestCaseDirs(SUITE_NAME, "multiXdefTest2");
convertXsd2XdPoolNoRef(
"multiXdefTest2",
Collections.singletonList("multiXdefTest2_valid_1"),
null);
}
@Test
public void xdPool_MultipleXDef_3() {
initTestCaseDirs(SUITE_NAME, "multiXdefTest3");
convertXsd2XdPoolNoRef(
"multiXdefTest3",
Collections.singletonList("multiXdefTest3_valid_1"),
null);
}
@Test
public void xdPool_Reference_1() {
initTestCaseDirs(SUITE_NAME, "refTest1");
convertXsd2XdPoolNoRef(
"refTest1",
Collections.singletonList("refTest1_valid_1"),
null);
}
@Test
public void xdPool_Reference_2() {
initTestCaseDirs(SUITE_NAME, "refTest2");
convertXsd2XdPoolNoRef(
"refTest2",
Collections.singletonList("refTest2_valid_1"),
null);
}
@Test
public void xdPool_Reference_3() {
initTestCaseDirs(SUITE_NAME, "refTest3");
convertXsd2XdPoolNoRef(
"refTest3",
Collections.singletonList("refTest3_valid_1"),
null);
}
@Test
public void xdPool_Sisma() {
initTestCaseDirs(SUITE_NAME, "sisma");
convertXsd2XdPoolNoRef(
"sisma",
Collections.singletonList("sisma"),
null);
}
@Test
public void xdPool_Sisma_RegistraceSU() {
initTestCaseDirs(SUITE_NAME, "Sisma_RegistraceSU");
convertXsd2XdPoolNoRef(
"Sisma_RegistraceSU",
Collections.singletonList("Sisma_RegistraceSU"),
null);
}
}
|
3e026104f9ce98e4ff7d6487bab171cfde38e8a9 | 853 | java | Java | clover-gateway/clover-gateway-service/src/main/java/com/clover/gateway/config/RestAccessDeniedHandler.java | Mnxj/clover-blog | ad7402ba468fb6df21119718e412451b101a9de6 | [
"MIT"
] | null | null | null | clover-gateway/clover-gateway-service/src/main/java/com/clover/gateway/config/RestAccessDeniedHandler.java | Mnxj/clover-blog | ad7402ba468fb6df21119718e412451b101a9de6 | [
"MIT"
] | null | null | null | clover-gateway/clover-gateway-service/src/main/java/com/clover/gateway/config/RestAccessDeniedHandler.java | Mnxj/clover-blog | ad7402ba468fb6df21119718e412451b101a9de6 | [
"MIT"
] | null | null | null | 40.619048 | 145 | 0.825322 | 985 | package com.clover.gateway.config;
import com.clover.common.domain.RestResponse;
import com.clover.gateway.common.util.HttpUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RestAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex) throws IOException, ServletException {
RestResponse restResponse = new RestResponse(HttpStatus.FORBIDDEN.value(),"没有权限");
HttpUtil.writerError(restResponse,response);
}
}
|
3e02621fed7143277e1352db6974727cacc4a78a | 1,177 | java | Java | Mage.Sets/src/mage/cards/s/StandardBearer.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,444 | 2015-01-02T00:25:38.000Z | 2022-03-31T13:57:18.000Z | Mage.Sets/src/mage/cards/s/StandardBearer.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 6,180 | 2015-01-02T19:10:09.000Z | 2022-03-31T21:10:44.000Z | Mage.Sets/src/mage/cards/s/StandardBearer.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,001 | 2015-01-01T01:15:20.000Z | 2022-03-30T20:23:04.000Z | 29.425 | 165 | 0.728122 | 986 |
package mage.cards.s;
import mage.MageInt;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.common.ruleModifying.TargetsHaveToTargetPermanentIfAbleEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import java.util.UUID;
/**
* @author LevelX2
*/
public final class StandardBearer extends CardImpl {
public StandardBearer(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{W}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.FLAGBEARER);
this.power = new MageInt(1);
this.toughness = new MageInt(1);
// While choosing targets as part of casting a spell or activating an ability, your opponents must choose at least one Flagbearer on the battlefield if able.
this.addAbility(new SimpleStaticAbility(new TargetsHaveToTargetPermanentIfAbleEffect()));
}
private StandardBearer(final StandardBearer card) {
super(card);
}
@Override
public StandardBearer copy() {
return new StandardBearer(this);
}
}
|
3e026371fefc1f5ba0575c568bfcf99c6a1d5028 | 1,831 | java | Java | java-zh-addres-parse/src/main/java/com/github/daihy8759/util/db/SqliteUtil.java | daihy8759/zh-address-parse | 2ce74c815fdd4a940324c3cb8ba99d0d5a77506f | [
"MIT"
] | null | null | null | java-zh-addres-parse/src/main/java/com/github/daihy8759/util/db/SqliteUtil.java | daihy8759/zh-address-parse | 2ce74c815fdd4a940324c3cb8ba99d0d5a77506f | [
"MIT"
] | null | null | null | java-zh-addres-parse/src/main/java/com/github/daihy8759/util/db/SqliteUtil.java | daihy8759/zh-address-parse | 2ce74c815fdd4a940324c3cb8ba99d0d5a77506f | [
"MIT"
] | null | null | null | 32.122807 | 119 | 0.705625 | 987 | package com.github.daihy8759.util.db;
import com.github.daihy8759.util.model.Area;
import com.zaxxer.hikari.HikariDataSource;
import java.util.List;
import javax.sql.DataSource;
import lombok.SneakyThrows;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
public class SqliteUtil {
private SqliteUtil() {
}
public static HikariDataSource dataSource = new HikariDataSource();
static {
dataSource.setDriverClassName("org.sqlite.JDBC");
dataSource.setJdbcUrl("jdbc:sqlite::resource:data.db");
}
public static DataSource getDataSource() {
return dataSource;
}
@SneakyThrows
public static List<Area> getArea(String parentCode, String nameLike, int level) {
if (parentCode == null || "".equals(parentCode)) {
return getArea(nameLike, level);
}
QueryRunner qr = new QueryRunner(getDataSource());
return qr
.query("select code,name,parent_code as parentCode from area where level = ? and parentCode=? and name like ?",
new BeanListHandler<>(Area.class),
level, parentCode, nameLike + "%");
}
@SneakyThrows
private static List<Area> getArea(String nameLike, int level) {
QueryRunner qr = new QueryRunner(getDataSource());
return qr
.query("select code,name,parent_code as parentCode from area where level = ? and name like ?",
new BeanListHandler<>(Area.class), level, nameLike + "%");
}
@SneakyThrows
public static Area getAreaSingle(String code, int level) {
QueryRunner qr = new QueryRunner(getDataSource());
return qr
.query("select code,name,parent_code as parentCode from area where level = ? and code = ?",
new BeanHandler<>(Area.class), level, code);
}
}
|
3e02638f4a4873811fbe17f540013a971fdf1528 | 1,365 | java | Java | acm-common/src/main/java/com/wisdom/webservice/contract/entity/GetContractListByCode.java | daiqingsong2021/ord_project | a8167cee2fbdc79ea8457d706ec1ccd008f2ceca | [
"Apache-2.0"
] | null | null | null | acm-common/src/main/java/com/wisdom/webservice/contract/entity/GetContractListByCode.java | daiqingsong2021/ord_project | a8167cee2fbdc79ea8457d706ec1ccd008f2ceca | [
"Apache-2.0"
] | null | null | null | acm-common/src/main/java/com/wisdom/webservice/contract/entity/GetContractListByCode.java | daiqingsong2021/ord_project | a8167cee2fbdc79ea8457d706ec1ccd008f2ceca | [
"Apache-2.0"
] | null | null | null | 22.016129 | 108 | 0.616117 | 988 |
package com.wisdom.webservice.contract.entity;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>anonymous complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="contrctCode" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"contrctCode"
})
@XmlRootElement(name = "GetContractListByCode")
public class GetContractListByCode {
protected String contrctCode;
/**
* 获取contrctCode属性的值。
*
* @return
* possible object is
* {@link String }
*
*/
public String getContrctCode() {
return contrctCode;
}
/**
* 设置contrctCode属性的值。
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContrctCode(String value) {
this.contrctCode = value;
}
}
|
3e02652b3b3d2697ea9398cd7fb0d4ded9ac51c3 | 1,573 | java | Java | jpa/eclipselink.jpa.wdf.test/src/org/eclipse/persistence/testing/models/wdf/jpa1/employee/EmbeddedFieldAccess.java | marschall/eclipselink.runtime | 3d59eaa9e420902d5347b9fb60fbe6c92310894b | [
"BSD-3-Clause"
] | null | null | null | jpa/eclipselink.jpa.wdf.test/src/org/eclipse/persistence/testing/models/wdf/jpa1/employee/EmbeddedFieldAccess.java | marschall/eclipselink.runtime | 3d59eaa9e420902d5347b9fb60fbe6c92310894b | [
"BSD-3-Clause"
] | 2 | 2021-03-24T17:58:46.000Z | 2021-12-14T20:59:52.000Z | jpa/eclipselink.jpa.wdf.test/src/org/eclipse/persistence/testing/models/wdf/jpa1/employee/EmbeddedFieldAccess.java | marschall/eclipselink.runtime | 3d59eaa9e420902d5347b9fb60fbe6c92310894b | [
"BSD-3-Clause"
] | null | null | null | 30.25 | 87 | 0.647171 | 989 | /*******************************************************************************
* Copyright (c) 2005, 2015 SAP. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* SAP - initial API and implementation
******************************************************************************/
package org.eclipse.persistence.testing.models.wdf.jpa1.employee;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Embeddable;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Embeddable
public class EmbeddedFieldAccess {
@Temporal(TemporalType.TIMESTAMP)
protected Date date; // embedded reference type (mutable)
@Basic
protected long time; // embedded primitive type
public EmbeddedFieldAccess() {
}
// getter and setter for testing purposes renamed to
// make them invisible for the implementation
final public Date retrieveDate() {
return date;
}
final public void changeDate(final Date aDate) {
date = aDate;
}
final public long retrieveTime() {
return time;
}
final public void changeTime(final long aTime) {
time = aTime;
}
}
|
3e0266a22ad1510f0c92fc3f6f25d16002e71b35 | 2,556 | java | Java | src/main/java/com/boyarsky/dapos/core/service/message/MessageServiceImpl.java | AndrewBoyarsky/DPoSBlockchain | 2376035bd9bf7518e4e55b5f16e5c15b659481fe | [
"Apache-2.0"
] | 2 | 2020-08-05T08:14:35.000Z | 2021-11-11T13:22:26.000Z | src/main/java/com/boyarsky/dapos/core/service/message/MessageServiceImpl.java | AndrewBoyarsky/DPoSBlockchain | 2376035bd9bf7518e4e55b5f16e5c15b659481fe | [
"Apache-2.0"
] | 1 | 2020-05-30T13:50:16.000Z | 2020-05-30T13:50:16.000Z | src/main/java/com/boyarsky/dapos/core/service/message/MessageServiceImpl.java | AndrewBoyarsky/DPoSBlockchain | 2376035bd9bf7518e4e55b5f16e5c15b659481fe | [
"Apache-2.0"
] | 1 | 2021-11-11T13:22:28.000Z | 2021-11-11T13:22:28.000Z | 36.514286 | 205 | 0.66784 | 990 | package com.boyarsky.dapos.core.service.message;
import com.boyarsky.dapos.core.model.account.AccountId;
import com.boyarsky.dapos.core.model.message.MessageEntity;
import com.boyarsky.dapos.core.repository.message.MessageRepository;
import com.boyarsky.dapos.core.tx.Transaction;
import com.boyarsky.dapos.core.tx.type.attachment.impl.MessageAttachment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class MessageServiceImpl implements MessageService {
private MessageRepository repo;
@Autowired
public MessageServiceImpl(MessageRepository repo) {
this.repo = repo;
}
@Override
public void handle(MessageAttachment attachment, Transaction tx) {
MessageEntity entity = new MessageEntity(tx.getTxId(), attachment.getEncryptedData(), tx.getSender(), attachment.isToSelf() ? null : tx.getRecipient(), attachment.isCompressed());
entity.setHeight(tx.getHeight());
repo.save(entity);
}
@Override
public List<MessageEntity> getChat(AccountId acc1, AccountId acc2) {
return repo.getWith(acc1, acc2);
}
@Override
public List<MessageEntity> getChats(AccountId acc1) {
List<MessageEntity> allChats = repo.getAllChats(acc1);
Map<AccountId, MessageEntity> chats = new HashMap<>();
for (MessageEntity allChat : allChats) {
AccountId checkKey;
if (allChat.isToSelf()) {
checkKey = allChat.getSender();
} else {
if (allChat.getSender().equals(acc1)) {
checkKey = allChat.getRecipient();
} else {
checkKey = allChat.getSender();
}
}
MessageEntity currentValue = chats.get(checkKey);
if (currentValue == null) {
chats.put(checkKey, allChat);
} else if (currentValue.getHeight() < allChat.getHeight()) {
chats.put(checkKey, allChat);
}
}
List<MessageEntity> resultChats = chats.entrySet().stream().sorted(Map.Entry.comparingByValue(Comparator.comparing(MessageEntity::getHeight))).map(Map.Entry::getValue).collect(Collectors.toList());
return resultChats;
}
@Override
public List<MessageEntity> getToSelfNotes(AccountId id) {
return repo.getToSelf(id);
}
}
|
3e0266e02f7040d0b843d5f3bcc0052bc01c62c8 | 7,052 | java | Java | ScalarApiSampleApp/app/src/main/java/com/google/android/apps/forscience/scalarapisample/AllNativeSensorProvider.java | Malik-Saifullah/science-journal | 67e15e4538611f30d9d7ff7a74cd0301aae4445f | [
"Apache-2.0"
] | 550 | 2016-08-17T15:57:29.000Z | 2020-12-13T09:15:20.000Z | ScalarApiSampleApp/app/src/main/java/com/google/android/apps/forscience/scalarapisample/AllNativeSensorProvider.java | lizlooney/science-journal | 73222ba6f538f3c2fa7ce3821f5004ff362b4752 | [
"Apache-2.0"
] | 60 | 2016-09-07T22:11:52.000Z | 2020-12-10T02:59:11.000Z | ScalarApiSampleApp/app/src/main/java/com/google/android/apps/forscience/scalarapisample/AllNativeSensorProvider.java | lizlooney/science-journal | 73222ba6f538f3c2fa7ce3821f5004ff362b4752 | [
"Apache-2.0"
] | 181 | 2016-08-20T04:56:05.000Z | 2020-12-13T09:23:09.000Z | 35.616162 | 100 | 0.693279 | 991 | /*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.forscience.scalarapisample;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import androidx.annotation.NonNull;
import com.google.android.apps.forscience.whistlepunk.api.scalarinput.AdvertisedDevice;
import com.google.android.apps.forscience.whistlepunk.api.scalarinput.AdvertisedSensor;
import com.google.android.apps.forscience.whistlepunk.api.scalarinput.ScalarSensorService;
import com.google.android.apps.forscience.whistlepunk.api.scalarinput.SensorAppearanceResources;
import com.google.android.apps.forscience.whistlepunk.api.scalarinput.SensorBehavior;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
public class AllNativeSensorProvider extends ScalarSensorService {
public static final String DEVICE_ID = "onlyDevice";
/**
* If true, only allow Google-built versions of Science Journal to access these sensors. Edit to
* false in your local version if you want to allow custom apps or open-source Science Journal to
* connect.
*
* <p>But beware, if this is left as false in a publicly-released service, a malicious third-party
* client app could use this service to get access to device sensors without permission.
*/
private static final boolean ONLY_ALLOW_SCIENCE_JOURNAL = true;
@Override
protected boolean shouldCheckBinderSignature() {
return ONLY_ALLOW_SCIENCE_JOURNAL;
}
@Override
protected List<? extends AdvertisedDevice> getDevices() {
return Lists.newArrayList(
new AdvertisedDevice(DEVICE_ID, "Phone native sensors") {
@Override
public List<AdvertisedSensor> getSensors() {
return buildSensors();
}
});
}
private List<AdvertisedSensor> buildSensors() {
List<AdvertisedSensor> sensors = new ArrayList<>();
final List<Sensor> deviceSensors = getSensorManager().getSensorList(Sensor.TYPE_ALL);
for (final Sensor sensor : deviceSensors) {
final SensorAppearanceResources appearance = new SensorAppearanceResources();
String name = sensor.getName();
final SensorBehavior behavior = new SensorBehavior();
behavior.loggingId = name;
behavior.settingsIntent =
DeviceSettingsPopupActivity.getPendingIntent(AllNativeSensorProvider.this, sensor);
final int sensorType = sensor.getType();
if (sensorType == Sensor.TYPE_ACCELEROMETER) {
appearance.iconId = android.R.drawable.ic_media_ff;
appearance.units = "ms/2";
appearance.shortDescription = "Not really a 3-axis accelerometer";
behavior.shouldShowSettingsOnConnect = true;
}
if (isTemperature(sensorType)) {
appearance.iconId = android.R.drawable.star_on;
String unitString =
TemperatureSettingsPopupActivity.getUnitString(AllNativeSensorProvider.this);
appearance.units = unitString;
appearance.shortDescription = "Ambient temperature (settings to change units!)";
behavior.settingsIntent =
TemperatureSettingsPopupActivity.getPendingIntent(AllNativeSensorProvider.this, sensor);
}
String sensorAddress = "" + sensorType;
sensors.add(
new AdvertisedSensor(sensorAddress, name) {
private SensorEventListener mSensorEventListener;
@Override
protected SensorAppearanceResources getAppearance() {
return appearance;
}
@Override
protected SensorBehavior getBehavior() {
return behavior;
}
@Override
protected boolean connect() throws Exception {
unregister();
return true;
}
@Override
protected void streamData(final DataConsumer c) {
final int index =
DeviceSettingsPopupActivity.getIndexForSensorType(
sensorType, AllNativeSensorProvider.this);
mSensorEventListener = new HardwareEventListener(sensorType, index, c);
getSensorManager()
.registerListener(mSensorEventListener, sensor, SensorManager.SENSOR_DELAY_UI);
}
@Override
protected void disconnect() {
unregister();
}
private void unregister() {
if (mSensorEventListener != null) {
getSensorManager().unregisterListener(mSensorEventListener);
mSensorEventListener = null;
}
}
});
}
return sensors;
}
@Override
@NonNull
protected String getDiscovererName() {
return "AllNative";
}
private boolean isTemperature(int sensorType) {
return sensorType == Sensor.TYPE_AMBIENT_TEMPERATURE || isNexus6pThermometer(sensorType);
}
private boolean isNexus6pThermometer(int sensorType) {
return isNexus6p() && sensorType == 65536;
}
private boolean isNexus6p() {
return Build.MODEL.equals("angler") || Build.MODEL.equals("Nexus 6P");
}
private SensorManager getSensorManager() {
return (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
private class HardwareEventListener implements SensorEventListener {
private final int mSensorType;
private final int mSensorValueIndex;
private final AdvertisedSensor.DataConsumer mDataConsumer;
HardwareEventListener(
int sensorType, int sensorValueIndex, AdvertisedSensor.DataConsumer dataConsumer) {
mSensorType = sensorType;
mSensorValueIndex = sensorValueIndex;
mDataConsumer = dataConsumer;
}
@Override
public void onSensorChanged(SensorEvent event) {
if (mDataConsumer.isReceiving()) {
long timestamp = System.currentTimeMillis();
float value = event.values[mSensorValueIndex];
mDataConsumer.onNewData(timestamp, maybeModify(value));
}
}
private float maybeModify(float value) {
if (isTemperature(mSensorType)
&& !TemperatureSettingsPopupActivity.isCelsius(AllNativeSensorProvider.this)) {
return value * 1.8f + 32f;
}
return value;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// do nothing
}
}
}
|
3e026745b11431ed17dc68bd0648d94639e49ba4 | 1,530 | java | Java | app/src/main/java/org/andengine/examples/game/snake/entity/AnimatedCellEntity.java | LGD2009/AndEngineExample | c4478e45f6554faf415af23c38961961f4c0950f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/org/andengine/examples/game/snake/entity/AnimatedCellEntity.java | LGD2009/AndEngineExample | c4478e45f6554faf415af23c38961961f4c0950f | [
"Apache-2.0"
] | null | null | null | app/src/main/java/org/andengine/examples/game/snake/entity/AnimatedCellEntity.java | LGD2009/AndEngineExample | c4478e45f6554faf415af23c38961961f4c0950f | [
"Apache-2.0"
] | null | null | null | 30.6 | 207 | 0.771242 | 992 | package org.andengine.examples.game.snake.entity;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.examples.game.snake.util.constants.SnakeConstants;
import org.andengine.opengl.texture.region.TiledTextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 17:13:44 - 09.07.2010
*/
public abstract class AnimatedCellEntity extends AnimatedSprite implements SnakeConstants, ICellEntity {
protected int mCellX;
protected int mCellY;
public AnimatedCellEntity(final int pCellX, final int pCellY, final int pWidth, final int pHeight, final TiledTextureRegion pTiledTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager) {
super(pCellX * CELL_WIDTH, pCellY * CELL_HEIGHT, pWidth, pHeight, pTiledTextureRegion, pVertexBufferObjectManager);
this.mCellX = pCellX;
this.mCellY = pCellY;
}
public int getCellX() {
return this.mCellX;
}
public int getCellY() {
return this.mCellY;
}
public void setCell(final ICellEntity pCellEntity) {
this.setCell(pCellEntity.getCellX(), pCellEntity.getCellY());
}
public void setCell(final int pCellX, final int pCellY) {
this.mCellX = pCellX;
this.mCellY = pCellY;
this.setPosition(this.mCellX * CELL_WIDTH, this.mCellY * CELL_HEIGHT);
}
@Override
public boolean isInSameCell(final ICellEntity pCellEntity) {
return this.mCellX == pCellEntity.getCellX() && this.mCellY == pCellEntity.getCellY();
}
}
|
3e0268515ef0b0d798636ed553cb0c3b1bb3e77c | 1,507 | java | Java | polardbx-parser/src/test/java/com/alibaba/polardbx/druid/bvt/sql/mysql/show/MySqlShowTest_createtable.java | arkbriar/galaxysql | df28f91eab772839e5df069739a065ac01c0a26e | [
"Apache-2.0"
] | 480 | 2021-10-16T06:00:00.000Z | 2022-03-28T05:54:49.000Z | polardbx-parser/src/test/java/com/alibaba/polardbx/druid/bvt/sql/mysql/show/MySqlShowTest_createtable.java | arkbriar/galaxysql | df28f91eab772839e5df069739a065ac01c0a26e | [
"Apache-2.0"
] | 31 | 2021-10-20T02:59:55.000Z | 2022-03-29T03:38:33.000Z | polardbx-parser/src/test/java/com/alibaba/polardbx/druid/bvt/sql/mysql/show/MySqlShowTest_createtable.java | arkbriar/galaxysql | df28f91eab772839e5df069739a065ac01c0a26e | [
"Apache-2.0"
] | 96 | 2021-10-17T14:19:49.000Z | 2022-03-23T09:25:37.000Z | 38.641026 | 94 | 0.754479 | 993 | /*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.polardbx.druid.bvt.sql.mysql.show;
import com.alibaba.polardbx.druid.sql.MysqlTest;
import com.alibaba.polardbx.druid.sql.ast.SQLStatement;
import com.alibaba.polardbx.druid.sql.ast.statement.SQLShowCreateTableStatement;
import com.alibaba.polardbx.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import org.junit.Assert;
import java.util.List;
public class MySqlShowTest_createtable extends MysqlTest {
public void test_0() throws Exception {
String sql = "SHOW FULL CREATE TABLE T1";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLShowCreateTableStatement stmt = (SQLShowCreateTableStatement) statementList.get(0);
Assert.assertEquals(true, stmt.isFull());
assertEquals("SHOW FULL CREATE TABLE T1", stmt.toString());
}
}
|
3e0268be7ac775b1fb2cfe849c3981b3d64cbe7a | 3,093 | java | Java | src/main/java/test/api/segmenteffort/GetSegmentEffortTest.java | danshannon/javastrava-test | f9babdb9affe8dcf03f2731bdafce0dec5d94b7e | [
"Apache-2.0"
] | 1 | 2019-05-10T14:36:40.000Z | 2019-05-10T14:36:40.000Z | src/main/java/test/api/segmenteffort/GetSegmentEffortTest.java | danshannon/javastrava-test | f9babdb9affe8dcf03f2731bdafce0dec5d94b7e | [
"Apache-2.0"
] | 1 | 2015-03-02T00:49:11.000Z | 2015-03-22T11:45:23.000Z | src/main/java/test/api/segmenteffort/GetSegmentEffortTest.java | danshannon/javastrava-test | f9babdb9affe8dcf03f2731bdafce0dec5d94b7e | [
"Apache-2.0"
] | 8 | 2015-10-21T11:19:40.000Z | 2020-06-12T07:23:49.000Z | 25.561983 | 135 | 0.756224 | 994 | package test.api.segmenteffort;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import org.junit.Test;
import javastrava.api.API;
import javastrava.model.StravaSegmentEffort;
import javastrava.model.reference.StravaResourceState;
import javastrava.service.exception.UnauthorizedException;
import test.api.APIGetTest;
import test.api.callback.APIGetCallback;
import test.issues.strava.Issue78;
import test.service.standardtests.data.SegmentEffortDataUtils;
import test.utils.RateLimitedTestRunner;
/**
* <p>
* Specific config and tests for {@link API#getSegmentEffort(Long)}
* </p>
*
* @author Dan Shannon
*
*/
public class GetSegmentEffortTest extends APIGetTest<StravaSegmentEffort, Long> {
@Override
public void get_private() throws Exception {
RateLimitedTestRunner.run(() -> {
if (new Issue78().isIssue()) {
return;
}
super.get_private();
});
}
@Override
public void get_privateWithoutViewPrivate() throws Exception {
if (new Issue78().isIssue()) {
return;
}
super.get_privateWithoutViewPrivate();
}
@Override
protected APIGetCallback<StravaSegmentEffort, Long> getter() {
return ((api, id) -> api.getSegmentEffort(id));
}
@Override
protected Long invalidId() {
return SegmentEffortDataUtils.SEGMENT_EFFORT_INVALID_ID;
}
@Override
protected Long privateId() {
return SegmentEffortDataUtils.SEGMENT_EFFORT_PRIVATE_ID;
}
@Override
protected Long privateIdBelongsToOtherUser() {
return SegmentEffortDataUtils.SEGMENT_EFFORT_OTHER_USER_PRIVATE_ID;
}
/**
* Check that an effort on a private activity is not returned
*
* @throws Exception
* if the test fails in an unexpected way
*/
@SuppressWarnings("static-method")
@Test
public void testGetSegmentEffort_privateActivity() throws Exception {
RateLimitedTestRunner.run(() -> {
try {
api().getSegmentEffort(SegmentEffortDataUtils.SEGMENT_EFFORT_PRIVATE_ACTIVITY_ID);
} catch (final UnauthorizedException e) {
// expected
return;
}
fail("Returned segment effort for a private activity, without view_private"); //$NON-NLS-1$
});
}
/**
* Check that an effort on a private activity is returned with view_private scope
*
* @throws Exception
* if the test fails in an unexpected way
*/
@SuppressWarnings("static-method")
@Test
public void testGetSegmentEffort_privateActivityViewPrivate() throws Exception {
RateLimitedTestRunner.run(() -> {
final StravaSegmentEffort effort = apiWithViewPrivate().getSegmentEffort(SegmentEffortDataUtils.SEGMENT_EFFORT_PRIVATE_ACTIVITY_ID);
assertNotNull(effort);
assertEquals(StravaResourceState.DETAILED, effort.getResourceState());
});
}
@Override
protected void validate(final StravaSegmentEffort result) throws Exception {
SegmentEffortDataUtils.validateSegmentEffort(result);
}
@Override
protected Long validId() {
return SegmentEffortDataUtils.SEGMENT_EFFORT_VALID_ID;
}
@Override
protected Long validIdBelongsToOtherUser() {
return null;
}
}
|
3e02696894afa89061924af64936d031a1cb02bb | 895 | java | Java | gulimall-ware/src/main/java/com/nai/gulimall/ware/entity/PurchaseEntity.java | xny838754132/gulimall | 09bbc33e0aa8314a38c44506b00caaa9c9ef3d1d | [
"Apache-2.0"
] | 1 | 2022-01-22T15:40:18.000Z | 2022-01-22T15:40:18.000Z | gulimall-ware/src/main/java/com/nai/gulimall/ware/entity/PurchaseEntity.java | xny838754132/gulimall | 09bbc33e0aa8314a38c44506b00caaa9c9ef3d1d | [
"Apache-2.0"
] | null | null | null | gulimall-ware/src/main/java/com/nai/gulimall/ware/entity/PurchaseEntity.java | xny838754132/gulimall | 09bbc33e0aa8314a38c44506b00caaa9c9ef3d1d | [
"Apache-2.0"
] | null | null | null | 13.545455 | 53 | 0.646532 | 995 | package com.nai.gulimall.ware.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.math.BigDecimal;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 采购信息
*
* @author TheNai
* @email [email protected]
* @date 2021-02-06 22:58:53
*/
@Data
@TableName("wms_purchase")
public class PurchaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Long id;
/**
*
*/
private Long assigneeId;
/**
*
*/
private String assigneeName;
/**
*
*/
private String phone;
/**
*
*/
private Integer priority;
/**
*
*/
private Integer status;
/**
*
*/
private Long wareId;
/**
*
*/
private BigDecimal amount;
/**
*
*/
private Date createTime;
/**
*
*/
private Date updateTime;
}
|
3e0269a966f1e876282ccfe362d6c8a0046ec6f5 | 621 | java | Java | day19_dowhileloop/C2_Flag.java | yasinozmen/my_java_tutorial | f46e531b520059b7ec472fd51277390054a69991 | [
"MIT"
] | null | null | null | day19_dowhileloop/C2_Flag.java | yasinozmen/my_java_tutorial | f46e531b520059b7ec472fd51277390054a69991 | [
"MIT"
] | null | null | null | day19_dowhileloop/C2_Flag.java | yasinozmen/my_java_tutorial | f46e531b520059b7ec472fd51277390054a69991 | [
"MIT"
] | null | null | null | 18.818182 | 64 | 0.652174 | 996 | package day19_dowhileloop;
import java.util.Scanner;
public class C2_Flag {
public static void main(String[] args) {
// Kullanicidan bir cumle alin, while loop kullanarak
// Cumlede buyuk harf varmi, yok mu yazdirin
Scanner scan=new Scanner(System.in);
System.out.println("Lutfen bir cumle giriniz");
String cumle= scan.nextLine();
String flag="yok";
int index=0;
while(index<cumle.length()) {
if (cumle.charAt(index)>='A' && cumle.charAt(index)<='Z' ) {
flag="var";
}
index++;
}
System.out.println("verdiginiz cumlede buyuk harf " + flag);
scan.close();
}
}
|
3e0269da114f528e137d3dffc893a4079e7ba05f | 600 | java | Java | app/src/main/java/com/yuzeduan/Fragment/BaseFragment.java | yuzeduan/one | 61795853bc7a4642e25be7201d02f36e418ab828 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/yuzeduan/Fragment/BaseFragment.java | yuzeduan/one | 61795853bc7a4642e25be7201d02f36e418ab828 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/yuzeduan/Fragment/BaseFragment.java | yuzeduan/one | 61795853bc7a4642e25be7201d02f36e418ab828 | [
"Apache-2.0"
] | null | null | null | 26.086957 | 61 | 0.676667 | 997 | package com.yuzeduan.Fragment;
import android.support.v4.app.Fragment;
public abstract class BaseFragment extends Fragment {
protected boolean isVisible; // 用于判断Fragment是否可见
protected boolean isPrepared = false;
protected boolean isFirst = true;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(getUserVisibleHint()){
isVisible = true;
setView();
isFirst = false;
}
}
public abstract void setView();
public abstract void refreshView();
}
|
3e026ae887c7b1380c6955999eb0a5ba460b6821 | 2,713 | java | Java | openbaton-libs/catalogue/src/main/java/org/openbaton/catalogue/mano/common/faultmanagement/FaultManagementPolicy.java | shivaranjanikumar/gittest1 | 3b99681aeb4ebe0666e3425098fe42182a16a41c | [
"Apache-2.0"
] | null | null | null | openbaton-libs/catalogue/src/main/java/org/openbaton/catalogue/mano/common/faultmanagement/FaultManagementPolicy.java | shivaranjanikumar/gittest1 | 3b99681aeb4ebe0666e3425098fe42182a16a41c | [
"Apache-2.0"
] | null | null | null | openbaton-libs/catalogue/src/main/java/org/openbaton/catalogue/mano/common/faultmanagement/FaultManagementPolicy.java | shivaranjanikumar/gittest1 | 3b99681aeb4ebe0666e3425098fe42182a16a41c | [
"Apache-2.0"
] | null | null | null | 22.421488 | 75 | 0.672687 | 998 | /*
* Copyright (c) 2015 Fraunhofer FOKUS
* 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.openbaton.catalogue.mano.common.faultmanagement;
import org.openbaton.catalogue.mano.common.monitoring.PerceivedSeverity;
import org.openbaton.catalogue.util.IdGenerator;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import javax.persistence.Version;
/**
* Created by mob on 29.10.15.
*/
@Entity
public class FaultManagementPolicy implements Serializable {
@Id protected String id;
@Version protected int version = 0;
protected String name;
protected boolean isVNFAlarm;
protected int period;
protected PerceivedSeverity severity;
@OneToMany(
cascade = {CascadeType.ALL},
fetch = FetchType.EAGER
)
protected Set<Criteria> criteria;
@PrePersist
public void ensureId() {
id = IdGenerator.createUUID();
}
public void setName(String name) {
this.name = name;
}
public int getPeriod() {
return period;
}
public void setPeriod(int period) {
this.period = period;
}
public PerceivedSeverity getSeverity() {
return severity;
}
public void setSeverity(PerceivedSeverity severity) {
this.severity = severity;
}
public Set<Criteria> getCriteria() {
return criteria;
}
public void setCriteria(Set<Criteria> criteria) {
this.criteria = criteria;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public boolean isVNFAlarm() {
return isVNFAlarm;
}
public void setVNFAlarm(boolean VNFAlarm) {
isVNFAlarm = VNFAlarm;
}
@Override
public String toString() {
return "FaultManagementPolicy{"
+ "id='"
+ id
+ '\''
+ ", version="
+ version
+ ", name='"
+ name
+ '\''
+ ", isVNFAlarm="
+ isVNFAlarm
+ ", period="
+ period
+ ", severity="
+ severity
+ ", criteria="
+ criteria
+ '}';
}
}
|
3e026dda42b22a9d5ad306dad1f918eb2241e9e9 | 587 | java | Java | wx-sdk/src/main/java/cn/finder/wx/corp/request/FindAccessTokenRequest.java | cnfinder/wae | fd3f7332c825fbd2886d91fa4c2227cef64604a4 | [
"Apache-2.0"
] | 11 | 2018-06-05T09:05:26.000Z | 2020-12-14T06:33:01.000Z | wx-sdk/src/main/java/cn/finder/wx/corp/request/FindAccessTokenRequest.java | cnfinder/wae | fd3f7332c825fbd2886d91fa4c2227cef64604a4 | [
"Apache-2.0"
] | null | null | null | wx-sdk/src/main/java/cn/finder/wx/corp/request/FindAccessTokenRequest.java | cnfinder/wae | fd3f7332c825fbd2886d91fa4c2227cef64604a4 | [
"Apache-2.0"
] | 4 | 2019-06-13T18:21:28.000Z | 2022-03-28T13:46:26.000Z | 15.447368 | 83 | 0.737649 | 999 | package cn.finder.wx.corp.request;
import cn.finder.wx.corp.response.FindAccessTokenResponse;
import cn.finder.wx.request.WeixinRequest;
/***
*获取TOKEN
* @author whl
*
*/
public class FindAccessTokenRequest extends WeixinRequest<FindAccessTokenResponse>{
private String corpid;
private String corpsecret;
public String getCorpid() {
return corpid;
}
public void setCorpid(String corpid) {
this.corpid = corpid;
}
public String getCorpsecret() {
return corpsecret;
}
public void setCorpsecret(String corpsecret) {
this.corpsecret = corpsecret;
}
}
|
3e026e064b3b15a166da322fbc630879d8f2d58c | 11,215 | java | Java | awacs-component/awacs-fernflower-component/src/main/java/io/awacs/component/org/jetbrains/java/decompiler/util/SFormsFastMapDirect.java | netlomin/awacs | efb2beca9f02ec8a193438f4efd39f9eabe8d3df | [
"Apache-2.0"
] | 25 | 2016-10-13T15:29:17.000Z | 2016-11-22T06:52:05.000Z | awacs-component/awacs-fernflower-component/src/main/java/io/awacs/component/org/jetbrains/java/decompiler/util/SFormsFastMapDirect.java | netlomin/awacs | efb2beca9f02ec8a193438f4efd39f9eabe8d3df | [
"Apache-2.0"
] | 7 | 2017-02-07T04:26:34.000Z | 2017-03-22T16:31:23.000Z | awacs-component/awacs-fernflower-component/src/main/java/io/awacs/component/org/jetbrains/java/decompiler/util/SFormsFastMapDirect.java | netlomin/awacs | efb2beca9f02ec8a193438f4efd39f9eabe8d3df | [
"Apache-2.0"
] | 10 | 2017-11-07T13:58:05.000Z | 2019-09-04T11:56:30.000Z | 27.089372 | 150 | 0.597325 | 1,000 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.awacs.component.org.jetbrains.java.decompiler.util;
import io.awacs.component.org.jetbrains.java.decompiler.modules.decompiler.exps.VarExprent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
public class SFormsFastMapDirect {
private int size;
@SuppressWarnings("unchecked") private final FastSparseSetFactory.FastSparseSet<Integer>[][] elements = new FastSparseSetFactory.FastSparseSet[3][];
private final int[][] next = new int[3][];
public SFormsFastMapDirect() {
this(true);
}
private SFormsFastMapDirect(boolean initialize) {
if (initialize) {
for (int i = 2; i >= 0; i--) {
@SuppressWarnings("unchecked") FastSparseSetFactory.FastSparseSet<Integer>[] empty = FastSparseSetFactory.FastSparseSet.EMPTY_ARRAY;
elements[i] = empty;
next[i] = InterpreterUtil.EMPTY_INT_ARRAY;
}
}
}
public SFormsFastMapDirect(SFormsFastMapDirect map) {
for (int i = 2; i >= 0; i--) {
FastSparseSetFactory.FastSparseSet<Integer>[] arr = map.elements[i];
int[] arrnext = map.next[i];
int length = arr.length;
@SuppressWarnings("unchecked") FastSparseSetFactory.FastSparseSet<Integer>[] arrnew = new FastSparseSetFactory.FastSparseSet[length];
int[] arrnextnew = new int[length];
System.arraycopy(arr, 0, arrnew, 0, length);
System.arraycopy(arrnext, 0, arrnextnew, 0, length);
elements[i] = arrnew;
next[i] = arrnextnew;
size = map.size;
}
}
public SFormsFastMapDirect getCopy() {
SFormsFastMapDirect map = new SFormsFastMapDirect(false);
map.size = size;
FastSparseSetFactory.FastSparseSet[][] mapelements = map.elements;
int[][] mapnext = map.next;
for (int i = 2; i >= 0; i--) {
FastSparseSetFactory.FastSparseSet<Integer>[] arr = elements[i];
int length = arr.length;
if (length > 0) {
int[] arrnext = next[i];
@SuppressWarnings("unchecked") FastSparseSetFactory.FastSparseSet<Integer>[] arrnew = new FastSparseSetFactory.FastSparseSet[length];
int[] arrnextnew = new int[length];
System.arraycopy(arrnext, 0, arrnextnew, 0, length);
mapelements[i] = arrnew;
mapnext[i] = arrnextnew;
int pointer = 0;
do {
FastSparseSetFactory.FastSparseSet<Integer> set = arr[pointer];
if (set != null) {
arrnew[pointer] = set.getCopy();
}
pointer = arrnext[pointer];
}
while (pointer != 0);
}
else {
mapelements[i] = FastSparseSetFactory.FastSparseSet.EMPTY_ARRAY;
mapnext[i] = InterpreterUtil.EMPTY_INT_ARRAY;
}
}
return map;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void put(int key, FastSparseSetFactory.FastSparseSet<Integer> value) {
putInternal(key, value, false);
}
public void remove(int key) {
putInternal(key, null, true);
}
public void removeAllFields() {
FastSparseSetFactory.FastSparseSet<Integer>[] arr = elements[2];
int[] arrnext = next[2];
for (int i = arr.length - 1; i >= 0; i--) {
FastSparseSetFactory.FastSparseSet<Integer> val = arr[i];
if (val != null) {
arr[i] = null;
size--;
}
arrnext[i] = 0;
}
}
public void putInternal(final int key, final FastSparseSetFactory.FastSparseSet<Integer> value, boolean remove) {
int index = 0;
int ikey = key;
if (ikey < 0) {
index = 2;
ikey = -ikey;
}
else if (ikey >= VarExprent.STACK_BASE) {
index = 1;
ikey -= VarExprent.STACK_BASE;
}
FastSparseSetFactory.FastSparseSet<Integer>[] arr = elements[index];
if (ikey >= arr.length) {
if (remove) {
return;
}
else {
arr = ensureCapacity(index, ikey + 1, false);
}
}
FastSparseSetFactory.FastSparseSet<Integer> oldval = arr[ikey];
arr[ikey] = value;
int[] arrnext = next[index];
if (oldval == null && value != null) {
size++;
changeNext(arrnext, ikey, arrnext[ikey], ikey);
}
else if (oldval != null && value == null) {
size--;
changeNext(arrnext, ikey, ikey, arrnext[ikey]);
}
}
private static void changeNext(int[] arrnext, int key, int oldnext, int newnext) {
for (int i = key - 1; i >= 0; i--) {
if (arrnext[i] == oldnext) {
arrnext[i] = newnext;
}
else {
break;
}
}
}
public boolean containsKey(int key) {
return get(key) != null;
}
public FastSparseSetFactory.FastSparseSet<Integer> get(int key) {
int index = 0;
if (key < 0) {
index = 2;
key = -key;
}
else if (key >= VarExprent.STACK_BASE) {
index = 1;
key -= VarExprent.STACK_BASE;
}
FastSparseSetFactory.FastSparseSet<Integer>[] arr = elements[index];
if (key < arr.length) {
return arr[key];
}
return null;
}
public void complement(SFormsFastMapDirect map) {
for (int i = 2; i >= 0; i--) {
FastSparseSetFactory.FastSparseSet<Integer>[] lstOwn = elements[i];
if (lstOwn.length == 0) {
continue;
}
FastSparseSetFactory.FastSparseSet<Integer>[] lstExtern = map.elements[i];
int[] arrnext = next[i];
int pointer = 0;
do {
FastSparseSetFactory.FastSparseSet<Integer> first = lstOwn[pointer];
if (first != null) {
if (pointer >= lstExtern.length) {
break;
}
FastSparseSetFactory.FastSparseSet<Integer> second = lstExtern[pointer];
if (second != null) {
first.complement(second);
if (first.isEmpty()) {
lstOwn[pointer] = null;
size--;
changeNext(arrnext, pointer, pointer, arrnext[pointer]);
}
}
}
pointer = arrnext[pointer];
}
while (pointer != 0);
}
}
public void intersection(SFormsFastMapDirect map) {
for (int i = 2; i >= 0; i--) {
FastSparseSetFactory.FastSparseSet<Integer>[] lstOwn = elements[i];
if (lstOwn.length == 0) {
continue;
}
FastSparseSetFactory.FastSparseSet<Integer>[] lstExtern = map.elements[i];
int[] arrnext = next[i];
int pointer = 0;
do {
FastSparseSetFactory.FastSparseSet<Integer> first = lstOwn[pointer];
if (first != null) {
FastSparseSetFactory.FastSparseSet<Integer> second = null;
if (pointer < lstExtern.length) {
second = lstExtern[pointer];
}
if (second != null) {
first.intersection(second);
}
if (second == null || first.isEmpty()) {
lstOwn[pointer] = null;
size--;
changeNext(arrnext, pointer, pointer, arrnext[pointer]);
}
}
pointer = arrnext[pointer];
}
while (pointer != 0);
}
}
public void union(SFormsFastMapDirect map) {
for (int i = 2; i >= 0; i--) {
FastSparseSetFactory.FastSparseSet<Integer>[] lstExtern = map.elements[i];
if (lstExtern.length == 0) {
continue;
}
FastSparseSetFactory.FastSparseSet<Integer>[] lstOwn = elements[i];
int[] arrnext = next[i];
int[] arrnextExtern = map.next[i];
int pointer = 0;
do {
if (pointer >= lstOwn.length) {
lstOwn = ensureCapacity(i, lstExtern.length, true);
arrnext = next[i];
}
FastSparseSetFactory.FastSparseSet<Integer> second = lstExtern[pointer];
if (second != null) {
FastSparseSetFactory.FastSparseSet<Integer> first = lstOwn[pointer];
if (first == null) {
lstOwn[pointer] = second.getCopy();
size++;
changeNext(arrnext, pointer, arrnext[pointer], pointer);
}
else {
first.union(second);
}
}
pointer = arrnextExtern[pointer];
}
while (pointer != 0);
}
}
public String toString() {
StringBuilder buffer = new StringBuilder("{");
List<Entry<Integer, FastSparseSetFactory.FastSparseSet<Integer>>> lst = entryList();
if (lst != null) {
boolean first = true;
for (Entry<Integer, FastSparseSetFactory.FastSparseSet<Integer>> entry : lst) {
if (!first) {
buffer.append(", ");
}
else {
first = false;
}
Set<Integer> set = entry.getValue().toPlainSet();
buffer.append(entry.getKey()).append("={").append(set.toString()).append("}");
}
}
buffer.append("}");
return buffer.toString();
}
public List<Entry<Integer, FastSparseSetFactory.FastSparseSet<Integer>>> entryList() {
List<Entry<Integer, FastSparseSetFactory.FastSparseSet<Integer>>> list = new ArrayList<>();
for (int i = 2; i >= 0; i--) {
int ikey = 0;
for (final FastSparseSetFactory.FastSparseSet<Integer> ent : elements[i]) {
if (ent != null) {
final int key = i == 0 ? ikey : (i == 1 ? ikey + VarExprent.STACK_BASE : -ikey);
list.add(new Entry<Integer, FastSparseSetFactory.FastSparseSet<Integer>>() {
private final Integer var = key;
private final FastSparseSetFactory.FastSparseSet<Integer> val = ent;
public Integer getKey() {
return var;
}
public FastSparseSetFactory.FastSparseSet<Integer> getValue() {
return val;
}
public FastSparseSetFactory.FastSparseSet<Integer> setValue(FastSparseSetFactory.FastSparseSet<Integer> newvalue) {
return null;
}
});
}
ikey++;
}
}
return list;
}
private FastSparseSetFactory.FastSparseSet<Integer>[] ensureCapacity(int index, int size, boolean exact) {
FastSparseSetFactory.FastSparseSet<Integer>[] arr = elements[index];
int[] arrnext = next[index];
int minsize = size;
if (!exact) {
minsize = 2 * arr.length / 3 + 1;
if (size > minsize) {
minsize = size;
}
}
@SuppressWarnings("unchecked") FastSparseSetFactory.FastSparseSet<Integer>[] arrnew = new FastSparseSetFactory.FastSparseSet[minsize];
System.arraycopy(arr, 0, arrnew, 0, arr.length);
int[] arrnextnew = new int[minsize];
System.arraycopy(arrnext, 0, arrnextnew, 0, arrnext.length);
elements[index] = arrnew;
next[index] = arrnextnew;
return arrnew;
}
}
|
3e0270c899eb7afe094638244bd30e748b94b5cc | 2,069 | java | Java | components/event-stream/org.wso2.carbon.event.stream.admin/src/main/java/org/wso2/carbon/event/stream/admin/EventStreamInfoDto.java | ChamodDamitha/carbon-analytics-common | d339c4f2e5fe79a0eefbe0287e509e3e273e198e | [
"Apache-2.0"
] | null | null | null | components/event-stream/org.wso2.carbon.event.stream.admin/src/main/java/org/wso2/carbon/event/stream/admin/EventStreamInfoDto.java | ChamodDamitha/carbon-analytics-common | d339c4f2e5fe79a0eefbe0287e509e3e273e198e | [
"Apache-2.0"
] | null | null | null | components/event-stream/org.wso2.carbon.event.stream.admin/src/main/java/org/wso2/carbon/event/stream/admin/EventStreamInfoDto.java | ChamodDamitha/carbon-analytics-common | d339c4f2e5fe79a0eefbe0287e509e3e273e198e | [
"Apache-2.0"
] | null | null | null | 27.223684 | 82 | 0.700822 | 1,001 | /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.wso2.carbon.event.stream.admin;
/**
* This class contains properties of inputs and outputs
*/
public class EventStreamInfoDto {
private String streamName;
private String streamVersion;
private String streamDefinition;
private String streamDescription;
private boolean editable;
public EventStreamInfoDto(String streamName, String streamVersion) {
this.streamName = streamName;
this.streamVersion = streamVersion;
}
public EventStreamInfoDto() {
}
public String getStreamDescription() {
return streamDescription;
}
public void setStreamDescription(String streamDescription) {
this.streamDescription = streamDescription;
}
public String getStreamDefinition() {
return streamDefinition;
}
public void setStreamDefinition(String streamDefinition) {
this.streamDefinition = streamDefinition;
}
public String getStreamName() {
return streamName;
}
public void setStreamName(String streamName) {
this.streamName = streamName;
}
public String getStreamVersion() {
return streamVersion;
}
public void setStreamVersion(String streamVersion) {
this.streamVersion = streamVersion;
}
public void setEditable(boolean editable) {
this.editable = editable;
}
public boolean isEditable() {
return editable;
}
}
|
3e0270e794beab74e1efc4c4956ec2078b0058d0 | 54 | java | Java | src/main/java/org/ldap/Rest2LdapContext.java | lgangloff/ldap2rest | e88b40b001ce98cc4c8ce259ec3e23912ae1ff6a | [
"Apache-2.0"
] | null | null | null | src/main/java/org/ldap/Rest2LdapContext.java | lgangloff/ldap2rest | e88b40b001ce98cc4c8ce259ec3e23912ae1ff6a | [
"Apache-2.0"
] | null | null | null | src/main/java/org/ldap/Rest2LdapContext.java | lgangloff/ldap2rest | e88b40b001ce98cc4c8ce259ec3e23912ae1ff6a | [
"Apache-2.0"
] | null | null | null | 9 | 31 | 0.759259 | 1,002 | package org.ldap;
public class Rest2LdapContext {
}
|
3e0271714961638d4965eb3e57d8e30784675671 | 1,761 | java | Java | src/main/java/com/esri/PointWriterAvro.java | mraad/HBaseToolbox | 847302e3a63d1c2f87ee61e2b72437a91f16f22c | [
"Apache-2.0"
] | 4 | 2015-11-04T00:59:46.000Z | 2020-01-13T02:00:39.000Z | src/main/java/com/esri/PointWriterAvro.java | mraad/HBaseToolbox | 847302e3a63d1c2f87ee61e2b72437a91f16f22c | [
"Apache-2.0"
] | null | null | null | src/main/java/com/esri/PointWriterAvro.java | mraad/HBaseToolbox | 847302e3a63d1c2f87ee61e2b72437a91f16f22c | [
"Apache-2.0"
] | 3 | 2015-07-03T02:10:14.000Z | 2019-09-09T02:36:06.000Z | 29.847458 | 103 | 0.680295 | 1,003 | package com.esri;
import com.esri.arcgis.geometry.IGeometry;
import com.esri.arcgis.geometry.Point;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
*/
public class PointWriterAvro extends ByteArrayOutputStream implements ShapeWriterInterface
{
private AvroSpatialReference m_spatialReference;
private DataFileWriter<AvroPoint> m_dataFileWriter;
private final byte[] pointQual = Bytes.toBytes("point");
public PointWriterAvro(final int wkid)
{
final DatumWriter<AvroPoint> datumWriter = new SpecificDatumWriter<AvroPoint>(AvroPoint.class);
m_dataFileWriter = new DataFileWriter<AvroPoint>(datumWriter);
m_spatialReference = AvroSpatialReference.newBuilder().setWkid(wkid).build();
}
@Override
public void write(
final Put put,
final byte[] geomColFam,
final IGeometry geometry) throws IOException
{
final Point point = (Point) geometry;
m_dataFileWriter.create(AvroPoint.getClassSchema(), this);
final AvroCoord coord = AvroCoord.newBuilder().
setX(point.getX()).
setY(point.getY()).
build();
m_dataFileWriter.append(AvroPoint.newBuilder().
setSpatialReference(m_spatialReference).
setCoord(coord).
build());
m_dataFileWriter.close();
put.add(geomColFam, pointQual, this.toByteArray());
this.reset();
}
@Override
public void close()
{
}
}
|
3e0272295312a1cecedf02be77a46918856887ac | 598 | java | Java | org.aion.avm.core/test/org/aion/avm/core/testCall/Callee.java | jmdisher/AVM | e282ecee4bf204ad143d5295b1151ece5b3469c5 | [
"MIT"
] | 48 | 2018-12-05T17:18:50.000Z | 2022-03-08T15:25:07.000Z | org.aion.avm.core/test/org/aion/avm/core/testCall/Callee.java | jmdisher/AVM | e282ecee4bf204ad143d5295b1151ece5b3469c5 | [
"MIT"
] | 411 | 2018-12-04T21:29:50.000Z | 2020-08-13T17:25:48.000Z | org.aion.avm.core/test/org/aion/avm/core/testCall/Callee.java | jmdisher/AVM | e282ecee4bf204ad143d5295b1151ece5b3469c5 | [
"MIT"
] | 27 | 2018-12-05T17:06:58.000Z | 2021-11-11T14:56:02.000Z | 24.916667 | 89 | 0.571906 | 1,004 | package org.aion.avm.core.testCall;
import avm.Blockchain;
public class Callee {
private static byte[] merge(byte[] a, byte[] b) {
if (a == null || b == null) {
throw new IllegalArgumentException("The byte array to merge can't be null!");
}
byte[] ret = new byte[a.length + b.length];
System.arraycopy(a, 0, ret, 0, a.length);
System.arraycopy(b, 0, ret, a.length, b.length);
return ret;
}
public static byte[] main() {
byte[] data = Blockchain.getData();
return merge(data, "world".getBytes());
}
}
|
3e02727722da6a163315d09b967d347c2d0feb6b | 37,774 | java | Java | xerces/xerces-2_6_1/src/org/apache/xerces/dom/ParentNode.java | timtyler/texturegarden | 0c66902a819ab0dd7559d2f1fc643fad5367052f | [
"Unlicense"
] | 1 | 2022-02-19T21:02:06.000Z | 2022-02-19T21:02:06.000Z | xerces/xerces-2_6_1/src/org/apache/xerces/dom/ParentNode.java | timtyler/texturegarden | 0c66902a819ab0dd7559d2f1fc643fad5367052f | [
"Unlicense"
] | null | null | null | xerces/xerces-2_6_1/src/org/apache/xerces/dom/ParentNode.java | timtyler/texturegarden | 0c66902a819ab0dd7559d2f1fc643fad5367052f | [
"Unlicense"
] | null | null | null | 36.147368 | 134 | 0.600704 | 1,005 | /*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2002 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.dom;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* ParentNode inherits from ChildNode and adds the capability of having child
* nodes. Not every node in the DOM can have children, so only nodes that can
* should inherit from this class and pay the price for it.
* <P>
* ParentNode, just like NodeImpl, also implements NodeList, so it can
* return itself in response to the getChildNodes() query. This eliminiates
* the need for a separate ChildNodeList object. Note that this is an
* IMPLEMENTATION DETAIL; applications should _never_ assume that
* this identity exists. On the other hand, subclasses may need to override
* this, in case of conflicting names. This is the case for the classes
* HTMLSelectElementImpl and HTMLFormElementImpl of the HTML DOM.
* <P>
* While we have a direct reference to the first child, the last child is
* stored as the previous sibling of the first child. First child nodes are
* marked as being so, and getNextSibling hides this fact.
* <P>Note: Not all parent nodes actually need to also be a child. At some
* point we used to have ParentNode inheriting from NodeImpl and another class
* called ChildAndParentNode that inherited from ChildNode. But due to the lack
* of multiple inheritance a lot of code had to be duplicated which led to a
* maintenance nightmare. At the same time only a few nodes (Document,
* DocumentFragment, Entity, and Attribute) cannot be a child so the gain in
* memory wasn't really worth it. The only type for which this would be the
* case is Attribute, but we deal with there in another special way, so this is
* not applicable.
* <p>
* This class doesn't directly support mutation events, however, it notifies
* the document when mutations are performed so that the document class do so.
*
* <p><b>WARNING</b>: Some of the code here is partially duplicated in
* AttrImpl, be careful to keep these two classes in sync!
*
* @author Arnaud Le Hors, IBM
* @author Joe Kesselman, IBM
* @author Andy Clark, IBM
* @version $Id: ParentNode.java,v 1.40 2003/05/26 15:03:03 elena Exp $
*/
public abstract class ParentNode
extends ChildNode {
/** Serialization version. */
static final long serialVersionUID = 2815829867152120872L;
/** Owner document. */
protected CoreDocumentImpl ownerDocument;
/** First child. */
protected ChildNode firstChild = null;
// transients
/** NodeList cache */
protected transient NodeListCache fNodeListCache = null;
//
// Constructors
//
/**
* No public constructor; only subclasses of ParentNode should be
* instantiated, and those normally via a Document's factory methods
*/
protected ParentNode(CoreDocumentImpl ownerDocument) {
super(ownerDocument);
this.ownerDocument = ownerDocument;
}
/** Constructor for serialization. */
public ParentNode() {}
//
// NodeList methods
//
/**
* Returns a duplicate of a given node. You can consider this a
* generic "copy constructor" for nodes. The newly returned object should
* be completely independent of the source object's subtree, so changes
* in one after the clone has been made will not affect the other.
* <p>
* Example: Cloning a Text node will copy both the node and the text it
* contains.
* <p>
* Example: Cloning something that has children -- Element or Attr, for
* example -- will _not_ clone those children unless a "deep clone"
* has been requested. A shallow clone of an Attr node will yield an
* empty Attr of the same name.
* <p>
* NOTE: Clones will always be read/write, even if the node being cloned
* is read-only, to permit applications using only the DOM API to obtain
* editable copies of locked portions of the tree.
*/
public Node cloneNode(boolean deep) {
if (needsSyncChildren()) {
synchronizeChildren();
}
ParentNode newnode = (ParentNode) super.cloneNode(deep);
// set owner document
newnode.ownerDocument = ownerDocument;
// Need to break the association w/ original kids
newnode.firstChild = null;
// invalidate cache for children NodeList
newnode.fNodeListCache = null;
// Then, if deep, clone the kids too.
if (deep) {
for (ChildNode child = firstChild;
child != null;
child = child.nextSibling) {
newnode.appendChild(child.cloneNode(true));
}
}
return newnode;
} // cloneNode(boolean):Node
/**
* Find the Document that this Node belongs to (the document in
* whose context the Node was created). The Node may or may not
* currently be part of that Document's actual contents.
*/
public Document getOwnerDocument() {
return ownerDocument;
}
/**
* same as above but returns internal type and this one is not overridden
* by CoreDocumentImpl to return null
*/
CoreDocumentImpl ownerDocument() {
return ownerDocument;
}
/**
* NON-DOM
* set the ownerDocument of this node and its children
*/
void setOwnerDocument(CoreDocumentImpl doc) {
if (needsSyncChildren()) {
synchronizeChildren();
}
super.setOwnerDocument(doc);
ownerDocument = doc;
for (ChildNode child = firstChild;
child != null; child = child.nextSibling) {
child.setOwnerDocument(doc);
}
}
/**
* Test whether this node has any children. Convenience shorthand
* for (Node.getFirstChild()!=null)
*/
public boolean hasChildNodes() {
if (needsSyncChildren()) {
synchronizeChildren();
}
return firstChild != null;
}
/**
* Obtain a NodeList enumerating all children of this node. If there
* are none, an (initially) empty NodeList is returned.
* <p>
* NodeLists are "live"; as children are added/removed the NodeList
* will immediately reflect those changes. Also, the NodeList refers
* to the actual nodes, so changes to those nodes made via the DOM tree
* will be reflected in the NodeList and vice versa.
* <p>
* In this implementation, Nodes implement the NodeList interface and
* provide their own getChildNodes() support. Other DOMs may solve this
* differently.
*/
public NodeList getChildNodes() {
if (needsSyncChildren()) {
synchronizeChildren();
}
return this;
} // getChildNodes():NodeList
/** The first child of this Node, or null if none. */
public Node getFirstChild() {
if (needsSyncChildren()) {
synchronizeChildren();
}
return firstChild;
} // getFirstChild():Node
/** The last child of this Node, or null if none. */
public Node getLastChild() {
if (needsSyncChildren()) {
synchronizeChildren();
}
return lastChild();
} // getLastChild():Node
final ChildNode lastChild() {
// last child is stored as the previous sibling of first child
return firstChild != null ? firstChild.previousSibling : null;
}
final void lastChild(ChildNode node) {
// store lastChild as previous sibling of first child
if (firstChild != null) {
firstChild.previousSibling = node;
}
}
/**
* Move one or more node(s) to our list of children. Note that this
* implicitly removes them from their previous parent.
*
* @param newChild The Node to be moved to our subtree. As a
* convenience feature, inserting a DocumentNode will instead insert
* all its children.
*
* @param refChild Current child which newChild should be placed
* immediately before. If refChild is null, the insertion occurs
* after all existing Nodes, like appendChild().
*
* @return newChild, in its new state (relocated, or emptied in the case of
* DocumentNode.)
*
* @throws DOMException(HIERARCHY_REQUEST_ERR) if newChild is of a
* type that shouldn't be a child of this node, or if newChild is an
* ancestor of this node.
*
* @throws DOMException(WRONG_DOCUMENT_ERR) if newChild has a
* different owner document than we do.
*
* @throws DOMException(NOT_FOUND_ERR) if refChild is not a child of
* this node.
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if this node is
* read-only.
*/
public Node insertBefore(Node newChild, Node refChild)
throws DOMException {
// Tail-call; optimizer should be able to do good things with.
return internalInsertBefore(newChild, refChild, false);
} // insertBefore(Node,Node):Node
/** NON-DOM INTERNAL: Within DOM actions,we sometimes need to be able
* to control which mutation events are spawned. This version of the
* insertBefore operation allows us to do so. It is not intended
* for use by application programs.
*/
Node internalInsertBefore(Node newChild, Node refChild, boolean replace)
throws DOMException {
boolean errorChecking = ownerDocument.errorChecking;
if (newChild.getNodeType() == Node.DOCUMENT_FRAGMENT_NODE) {
// SLOW BUT SAFE: We could insert the whole subtree without
// juggling so many next/previous pointers. (Wipe out the
// parent's child-list, patch the parent pointers, set the
// ends of the list.) But we know some subclasses have special-
// case behavior they add to insertBefore(), so we don't risk it.
// This approch also takes fewer bytecodes.
// NOTE: If one of the children is not a legal child of this
// node, throw HIERARCHY_REQUEST_ERR before _any_ of the children
// have been transferred. (Alternative behaviors would be to
// reparent up to the first failure point or reparent all those
// which are acceptable to the target node, neither of which is
// as robust. PR-DOM-0818 isn't entirely clear on which it
// recommends?????
// No need to check kids for right-document; if they weren't,
// they wouldn't be kids of that DocFrag.
if (errorChecking) {
for (Node kid = newChild.getFirstChild(); // Prescan
kid != null; kid = kid.getNextSibling()) {
if (!ownerDocument.isKidOK(this, kid)) {
throw new DOMException(
DOMException.HIERARCHY_REQUEST_ERR,
DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "HIERARCHY_REQUEST_ERR", null));
}
}
}
while (newChild.hasChildNodes()) {
insertBefore(newChild.getFirstChild(), refChild);
}
return newChild;
}
if (newChild == refChild) {
// stupid case that must be handled as a no-op triggering events...
refChild = refChild.getNextSibling();
removeChild(newChild);
insertBefore(newChild, refChild);
return newChild;
}
if (needsSyncChildren()) {
synchronizeChildren();
}
if (errorChecking) {
if (isReadOnly()) {
throw new DOMException(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null));
}
if (newChild.getOwnerDocument() != ownerDocument) {
throw new DOMException(DOMException.WRONG_DOCUMENT_ERR,
DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "WRONG_DOCUMENT_ERR", null));
}
if (!ownerDocument.isKidOK(this, newChild)) {
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "HIERARCHY_REQUEST_ERR", null));
}
// refChild must be a child of this node (or null)
if (refChild != null && refChild.getParentNode() != this) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null));
}
// Prevent cycles in the tree
// newChild cannot be ancestor of this Node,
// and actually cannot be this
boolean treeSafe = true;
for (NodeImpl a = this; treeSafe && a != null; a = a.parentNode())
{
treeSafe = newChild != a;
}
if(!treeSafe) {
throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "HIERARCHY_REQUEST_ERR", null));
}
}
// notify document
ownerDocument.insertingNode(this, replace);
// Convert to internal type, to avoid repeated casting
ChildNode newInternal = (ChildNode)newChild;
Node oldparent = newInternal.parentNode();
if (oldparent != null) {
oldparent.removeChild(newInternal);
}
// Convert to internal type, to avoid repeated casting
ChildNode refInternal = (ChildNode)refChild;
// Attach up
newInternal.ownerNode = this;
newInternal.isOwned(true);
// Attach before and after
// Note: firstChild.previousSibling == lastChild!!
if (firstChild == null) {
// this our first and only child
firstChild = newInternal;
newInternal.isFirstChild(true);
newInternal.previousSibling = newInternal;
}
else {
if (refInternal == null) {
// this is an append
ChildNode lastChild = firstChild.previousSibling;
lastChild.nextSibling = newInternal;
newInternal.previousSibling = lastChild;
firstChild.previousSibling = newInternal;
}
else {
// this is an insert
if (refChild == firstChild) {
// at the head of the list
firstChild.isFirstChild(false);
newInternal.nextSibling = firstChild;
newInternal.previousSibling = firstChild.previousSibling;
firstChild.previousSibling = newInternal;
firstChild = newInternal;
newInternal.isFirstChild(true);
}
else {
// somewhere in the middle
ChildNode prev = refInternal.previousSibling;
newInternal.nextSibling = refInternal;
prev.nextSibling = newInternal;
refInternal.previousSibling = newInternal;
newInternal.previousSibling = prev;
}
}
}
changed();
// update cached length if we have any
if (fNodeListCache != null) {
if (fNodeListCache.fLength != -1) {
fNodeListCache.fLength++;
}
if (fNodeListCache.fChildIndex != -1) {
// if we happen to insert just before the cached node, update
// the cache to the new node to match the cached index
if (fNodeListCache.fChild == refInternal) {
fNodeListCache.fChild = newInternal;
} else {
// otherwise just invalidate the cache
fNodeListCache.fChildIndex = -1;
}
}
}
// notify document
ownerDocument.insertedNode(this, newInternal, replace);
checkNormalizationAfterInsert(newInternal);
return newChild;
} // internalInsertBefore(Node,Node,boolean):Node
/**
* Remove a child from this Node. The removed child's subtree
* remains intact so it may be re-inserted elsewhere.
*
* @return oldChild, in its new state (removed).
*
* @throws DOMException(NOT_FOUND_ERR) if oldChild is not a child of
* this node.
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if this node is
* read-only.
*/
public Node removeChild(Node oldChild)
throws DOMException {
// Tail-call, should be optimizable
return internalRemoveChild(oldChild, false);
} // removeChild(Node) :Node
/** NON-DOM INTERNAL: Within DOM actions,we sometimes need to be able
* to control which mutation events are spawned. This version of the
* removeChild operation allows us to do so. It is not intended
* for use by application programs.
*/
Node internalRemoveChild(Node oldChild, boolean replace)
throws DOMException {
CoreDocumentImpl ownerDocument = ownerDocument();
if (ownerDocument.errorChecking) {
if (isReadOnly()) {
throw new DOMException(
DOMException.NO_MODIFICATION_ALLOWED_ERR,
DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null));
}
if (oldChild != null && oldChild.getParentNode() != this) {
throw new DOMException(DOMException.NOT_FOUND_ERR,
DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null));
}
}
ChildNode oldInternal = (ChildNode) oldChild;
// notify document
ownerDocument.removingNode(this, oldInternal, replace);
// update cached length if we have any
if (fNodeListCache != null) {
if (fNodeListCache.fLength != -1) {
fNodeListCache.fLength--;
}
if (fNodeListCache.fChildIndex != -1) {
// if the removed node is the cached node
// move the cache to its (soon former) previous sibling
if (fNodeListCache.fChild == oldInternal) {
fNodeListCache.fChildIndex--;
fNodeListCache.fChild = oldInternal.previousSibling();
} else {
// otherwise just invalidate the cache
fNodeListCache.fChildIndex = -1;
}
}
}
// Patch linked list around oldChild
// Note: lastChild == firstChild.previousSibling
if (oldInternal == firstChild) {
// removing first child
oldInternal.isFirstChild(false);
firstChild = oldInternal.nextSibling;
if (firstChild != null) {
firstChild.isFirstChild(true);
firstChild.previousSibling = oldInternal.previousSibling;
}
} else {
ChildNode prev = oldInternal.previousSibling;
ChildNode next = oldInternal.nextSibling;
prev.nextSibling = next;
if (next == null) {
// removing last child
firstChild.previousSibling = prev;
} else {
// removing some other child in the middle
next.previousSibling = prev;
}
}
// Save previous sibling for normalization checking.
ChildNode oldPreviousSibling = oldInternal.previousSibling();
// Remove oldInternal's references to tree
oldInternal.ownerNode = ownerDocument;
oldInternal.isOwned(false);
oldInternal.nextSibling = null;
oldInternal.previousSibling = null;
changed();
// notify document
ownerDocument.removedNode(this, replace);
checkNormalizationAfterRemove(oldPreviousSibling);
return oldInternal;
} // internalRemoveChild(Node,boolean):Node
/**
* Make newChild occupy the location that oldChild used to
* have. Note that newChild will first be removed from its previous
* parent, if any. Equivalent to inserting newChild before oldChild,
* then removing oldChild.
*
* @return oldChild, in its new state (removed).
*
* @throws DOMException(HIERARCHY_REQUEST_ERR) if newChild is of a
* type that shouldn't be a child of this node, or if newChild is
* one of our ancestors.
*
* @throws DOMException(WRONG_DOCUMENT_ERR) if newChild has a
* different owner document than we do.
*
* @throws DOMException(NOT_FOUND_ERR) if oldChild is not a child of
* this node.
*
* @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if this node is
* read-only.
*/
public Node replaceChild(Node newChild, Node oldChild)
throws DOMException {
// If Mutation Events are being generated, this operation might
// throw aggregate events twice when modifying an Attr -- once
// on insertion and once on removal. DOM Level 2 does not specify
// this as either desirable or undesirable, but hints that
// aggregations should be issued only once per user request.
// notify document
ownerDocument.replacingNode(this);
internalInsertBefore(newChild, oldChild, true);
if (newChild != oldChild) {
internalRemoveChild(oldChild, true);
}
// notify document
ownerDocument.replacedNode(this);
return oldChild;
}
/*
* Get Node text content
* @since DOM Level 3
*/
public String getTextContent() throws DOMException {
Node child = getFirstChild();
if (child != null) {
Node next = child.getNextSibling();
if (next == null) {
return hasTextContent(child) ? ((NodeImpl) child).getTextContent() : "";
}
StringBuffer buf = new StringBuffer();
getTextContent(buf);
return buf.toString();
}
return "";
}
// internal method taking a StringBuffer in parameter
void getTextContent(StringBuffer buf) throws DOMException {
Node child = getFirstChild();
while (child != null) {
if (hasTextContent(child)) {
((NodeImpl) child).getTextContent(buf);
}
child = child.getNextSibling();
}
}
// internal method returning whether to take the given node's text content
final boolean hasTextContent(Node child) {
return child.getNodeType() != Node.COMMENT_NODE &&
child.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE &&
(child.getNodeType() != Node.TEXT_NODE ||
((TextImpl) child).isIgnorableWhitespace() == false);
}
/*
* Set Node text content
* @since DOM Level 3
*/
public void setTextContent(String textContent)
throws DOMException {
// get rid of any existing children
Node child;
while ((child = getFirstChild()) != null) {
removeChild(child);
}
// create a Text node to hold the given content
if (textContent != null && textContent.length() != 0){
appendChild(ownerDocument().createTextNode(textContent));
}
}
//
// NodeList methods
//
/**
* Count the immediate children of this node. Use to implement
* NodeList.getLength().
* @return int
*/
private int nodeListGetLength() {
if (fNodeListCache == null) {
// get rid of trivial cases
if (firstChild == null) {
return 0;
}
if (firstChild == lastChild()) {
return 1;
}
// otherwise request a cache object
fNodeListCache = ownerDocument.getNodeListCache(this);
}
if (fNodeListCache.fLength == -1) { // is the cached length invalid ?
int l;
ChildNode n;
// start from the cached node if we have one
if (fNodeListCache.fChildIndex != -1 &&
fNodeListCache.fChild != null) {
l = fNodeListCache.fChildIndex;
n = fNodeListCache.fChild;
} else {
n = firstChild;
l = 0;
}
while (n != null) {
l++;
n = n.nextSibling;
}
fNodeListCache.fLength = l;
}
return fNodeListCache.fLength;
} // nodeListGetLength():int
/**
* NodeList method: Count the immediate children of this node
* @return int
*/
public int getLength() {
return nodeListGetLength();
}
/**
* Return the Nth immediate child of this node, or null if the index is
* out of bounds. Use to implement NodeList.item().
* @param index int
*/
private Node nodeListItem(int index) {
if (fNodeListCache == null) {
// get rid of trivial case
if (firstChild == lastChild()) {
return index == 0 ? firstChild : null;
}
// otherwise request a cache object
fNodeListCache = ownerDocument.getNodeListCache(this);
}
int i = fNodeListCache.fChildIndex;
ChildNode n = fNodeListCache.fChild;
boolean firstAccess = true;
// short way
if (i != -1 && n != null) {
firstAccess = false;
if (i < index) {
while (i < index && n != null) {
i++;
n = n.nextSibling;
}
}
else if (i > index) {
while (i > index && n != null) {
i--;
n = n.previousSibling();
}
}
}
else {
// long way
n = firstChild;
for (i = 0; i < index && n != null; i++) {
n = n.nextSibling;
}
}
// release cache if reaching last child or first child
if (!firstAccess && (n == firstChild || n == lastChild())) {
fNodeListCache.fChildIndex = -1;
fNodeListCache.fChild = null;
ownerDocument.freeNodeListCache(fNodeListCache);
// we can keep using the cache until it is actually reused
// fNodeListCache will be nulled by the pool (document) if that
// happens.
// fNodeListCache = null;
}
else {
// otherwise update it
fNodeListCache.fChildIndex = i;
fNodeListCache.fChild = n;
}
return n;
} // nodeListItem(int):Node
/**
* NodeList method: Return the Nth immediate child of this node, or
* null if the index is out of bounds.
* @return org.w3c.dom.Node
* @param index int
*/
public Node item(int index) {
return nodeListItem(index);
} // item(int):Node
/**
* Create a NodeList to access children that is use by subclass elements
* that have methods named getLength() or item(int). ChildAndParentNode
* optimizes getChildNodes() by implementing NodeList itself. However if
* a subclass Element implements methods with the same name as the NodeList
* methods, they will override the actually methods in this class.
* <p>
* To use this method, the subclass should implement getChildNodes() and
* have it call this method. The resulting NodeList instance maybe
* shared and cached in a transient field, but the cached value must be
* cleared if the node is cloned.
*/
protected final NodeList getChildNodesUnoptimized() {
if (needsSyncChildren()) {
synchronizeChildren();
}
return new NodeList() {
/**
* @see NodeList.getLength()
*/
public int getLength() {
return nodeListGetLength();
} // getLength():int
/**
* @see NodeList.item(int)
*/
public Node item(int index) {
return nodeListItem(index);
} // item(int):Node
};
} // getChildNodesUnoptimized():NodeList
//
// DOM2: methods, getters, setters
//
/**
* Override default behavior to call normalize() on this Node's
* children. It is up to implementors or Node to override normalize()
* to take action.
*/
public void normalize() {
// No need to normalize if already normalized.
if (isNormalized()) {
return;
}
if (needsSyncChildren()) {
synchronizeChildren();
}
ChildNode kid;
for (kid = firstChild; kid != null; kid = kid.nextSibling) {
kid.normalize();
}
isNormalized(true);
}
/**
* DOM Level 3 WD- Experimental.
* Override inherited behavior from NodeImpl to support deep equal.
*/
public boolean isEqualNode(Node arg) {
if (!super.isEqualNode(arg)) {
return false;
}
// there are many ways to do this test, and there isn't any way
// better than another. Performance may vary greatly depending on
// the implementations involved. This one should work fine for us.
Node child1 = getFirstChild();
Node child2 = arg.getFirstChild();
while (child1 != null && child2 != null) {
if (!((NodeImpl) child1).isEqualNode(child2)) {
return false;
}
child1 = child1.getNextSibling();
child2 = child2.getNextSibling();
}
if (child1 != child2) {
return false;
}
return true;
}
//
// Public methods
//
/**
* Override default behavior so that if deep is true, children are also
* toggled.
* @see Node
* <P>
* Note: this will not change the state of an EntityReference or its
* children, which are always read-only.
*/
public void setReadOnly(boolean readOnly, boolean deep) {
super.setReadOnly(readOnly, deep);
if (deep) {
if (needsSyncChildren()) {
synchronizeChildren();
}
// Recursively set kids
for (ChildNode mykid = firstChild;
mykid != null;
mykid = mykid.nextSibling) {
if (mykid.getNodeType() != Node.ENTITY_REFERENCE_NODE) {
mykid.setReadOnly(readOnly,true);
}
}
}
} // setReadOnly(boolean,boolean)
//
// Protected methods
//
/**
* Override this method in subclass to hook in efficient
* internal data structure.
*/
protected void synchronizeChildren() {
// By default just change the flag to avoid calling this method again
needsSyncChildren(false);
}
/**
* Checks the normalized state of this node after inserting a child.
* If the inserted child causes this node to be unnormalized, then this
* node is flagged accordingly.
* The conditions for changing the normalized state are:
* <ul>
* <li>The inserted child is a text node and one of its adjacent siblings
* is also a text node.
* <li>The inserted child is is itself unnormalized.
* </ul>
*
* @param insertedChild the child node that was inserted into this node
*
* @throws NullPointerException if the inserted child is <code>null</code>
*/
void checkNormalizationAfterInsert(ChildNode insertedChild) {
// See if insertion caused this node to be unnormalized.
if (insertedChild.getNodeType() == Node.TEXT_NODE) {
ChildNode prev = insertedChild.previousSibling();
ChildNode next = insertedChild.nextSibling;
// If an adjacent sibling of the new child is a text node,
// flag this node as unnormalized.
if ((prev != null && prev.getNodeType() == Node.TEXT_NODE) ||
(next != null && next.getNodeType() == Node.TEXT_NODE)) {
isNormalized(false);
}
}
else {
// If the new child is not normalized,
// then this node is inherently not normalized.
if (!insertedChild.isNormalized()) {
isNormalized(false);
}
}
} // checkNormalizationAfterInsert(ChildNode)
/**
* Checks the normalized of this node after removing a child.
* If the removed child causes this node to be unnormalized, then this
* node is flagged accordingly.
* The conditions for changing the normalized state are:
* <ul>
* <li>The removed child had two adjacent siblings that were text nodes.
* </ul>
*
* @param previousSibling the previous sibling of the removed child, or
* <code>null</code>
*/
void checkNormalizationAfterRemove(ChildNode previousSibling) {
// See if removal caused this node to be unnormalized.
// If the adjacent siblings of the removed child were both text nodes,
// flag this node as unnormalized.
if (previousSibling != null &&
previousSibling.getNodeType() == Node.TEXT_NODE) {
ChildNode next = previousSibling.nextSibling;
if (next != null && next.getNodeType() == Node.TEXT_NODE) {
isNormalized(false);
}
}
} // checkNormalizationAfterRemove(Node)
//
// Serialization methods
//
/** Serialize object. */
private void writeObject(ObjectOutputStream out) throws IOException {
// synchronize chilren
if (needsSyncChildren()) {
synchronizeChildren();
}
// write object
out.defaultWriteObject();
} // writeObject(ObjectOutputStream)
/** Deserialize object. */
private void readObject(ObjectInputStream ois)
throws ClassNotFoundException, IOException {
// perform default deseralization
ois.defaultReadObject();
// hardset synchildren - so we don't try to sync - it does not make any
// sense to try to synchildren when we just deserialize object.
needsSyncChildren(false);
} // readObject(ObjectInputStream)
} // class ParentNode
|
Subsets and Splits