hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
aaccbffa9da3f12c03f89016c14b1b10ff603352 | 3,477 |
package com.prowidesoftware.swift;
import com.prowidesoftware.Generated;
/**
* Constants for qualifiers found in MTs starting with "D".
* <em>WARNING: These constants are automatically generated from SRU information
* they may change without entering the formal Prowide Deprecation Policy
* http://www.prowidesoftware.com/resources/deprecation-policy</em>
* @since 7.8.1
*
*
*/
@Generated
public interface SchemeConstantsD {
public final static String DERV = "DERV";
public final static String DUPL = "DUPL";
public final static String DIGI = "DIGI";
public final static String DKOT = "DKOT";
public final static String DKIN = "DKIN";
public final static String DBTR = "DBTR";
public final static String DAVO = "DAVO";
public final static String DAVF = "DAVF";
public final static String D = "D";
public final static String DPLO = "DPLO";
public final static String DAAC = "DAAC";
public final static String DRAW = "DRAW";
public final static String DIST = "DIST";
public final static String DENO = "DENO";
public final static String DBIR = "DBIR";
public final static String DOMI = "DOMI";
public final static String DDTE = "DDTE";
public final static String DFON = "DFON";
public final static String DEAL = "DEAL";
public final static String DEBT = "DEBT";
public final static String DBNM = "DBNM";
public final static String DECL = "DECL";
public final static String DEPO = "DEPO";
public final static String DEND = "DEND";
public final static String DBAM = "DBAM";
public final static String DEAG = "DEAG";
public final static String DSCA = "DSCA";
public final static String DEALTRAN = "DEALTRAN";
public final static String DACO = "DACO";
public final static String DENC = "DENC";
public final static String DIVR = "DIVR";
public final static String DVCP = "DVCP";
public final static String DERY = "DERY";
public final static String DROP = "DROP";
public final static String DEDI = "DEDI";
public final static String DSPL = "DSPL";
public final static String DEVI = "DEVI";
public final static String DEEM = "DEEM";
public final static String DSBT = "DSBT";
public final static String DSSE = "DSSE";
public final static String DEFP = "DEFP";
public final static String DSDA = "DSDA";
public final static String DSDE = "DSDE";
public final static String DEIT = "DEIT";
public final static String DSWN = "DSWN";
public final static String DSWO = "DSWO";
public final static String DSWS = "DSWS";
public final static String DFLT = "DFLT";
public final static String DISC = "DISC";
public final static String DISF = "DISF";
public final static String DSWA = "DSWA";
public final static String DIVI = "DIVI";
public final static String DITY = "DITY";
public final static String DLVR = "DLVR";
public final static String DUCA = "DUCA";
public final static String DTD = "DTD";
public final static String DDP = "DDP";
public final static String DDU = "DDU";
public final static String DAF = "DAF";
public final static String DEQ = "DEQ";
public final static String DES = "DES";
public final static String DISPAR = "DISPAR";
public final static String DELETE = "DELETE";
public final static String DIFF = "DIFF";
public final static String DGAR = "DGAR";
public final static String DOCR = "DOCR";
}
| 39.965517 | 80 | 0.684498 |
9c51f661b6440f506dfc7a98b9cf08c1c76998bc | 1,251 | package com.amazonaws.lab;
import java.util.Map;
import java.util.HashMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.amazonaws.services.lambda.runtime.Context;
public class HealthDataRouter {
static final Logger log = LogManager.getLogger(HealthDataRouter.class);
public Map<String, String> handleRequest(Map<String, String> map, Context context) {
// Parse InputFile to determine initial prefix path: i.e. '/processing/input/hl7/' or '/processing/input/fhir/'
String myS3key = map.get("InputFile");
log.debug("S3 Key: " + myS3key);
String[] keyPaths = myS3key.split("/");
String dataType = "";
log.debug("Array length: " + keyPaths.length);
if (keyPaths.length >= 3) {
if (keyPaths[2] != "") {
log.debug("Found: " + keyPaths[2]);
dataType = keyPaths[2];
}
}
Map<String, String> output = new HashMap<>();
output.put("S3Bucket", map.get("S3Bucket"));
output.put("FileName", map.get("FileName"));
output.put("InputFile", map.get("InputFile"));
output.put("DataType", dataType);
return output;
}
}
| 31.275 | 119 | 0.609912 |
01578cc54abd12657b928bba2bdca9fc191239c4 | 9,761 | package com.gentics.mesh.image.focalpoint;
import static com.gentics.mesh.core.rest.error.Errors.error;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import org.imgscalr.Scalr;
import org.imgscalr.Scalr.Mode;
import com.gentics.mesh.core.rest.node.field.image.FocalPoint;
import com.gentics.mesh.core.rest.node.field.image.Point;
import com.gentics.mesh.parameter.ImageManipulationParameters;
/**
* Implementation of the focal point modifier. This modifier will:
* <ul>
* <li>Resize the image so that it exceeds the targeted size in one dimension
* <li>Crop the image in a way so that the targeted size is reached
* <li>Or apply a zoom and crop to the image
* </ul>
*/
public class FocalPointModifier {
/**
* First resize the image and later crop the image to focus the focal point.
*
* @param img
* @param parameters
* @return resized and cropped image
*/
public BufferedImage apply(BufferedImage img, ImageManipulationParameters parameters) {
FocalPoint focalPoint = parameters.getFocalPoint();
if (focalPoint == null) {
return img;
}
if (parameters.getFocalPointDebug()) {
drawFocusPointAxis(img, focalPoint);
}
// Validate the focal point position
Point imageSize = new Point(img.getWidth(), img.getHeight());
Point absFocalPoint = parameters.getFocalPoint().convertToAbsolutePoint(imageSize);
if (!absFocalPoint.isWithinBoundsOf(imageSize)) {
throw error(BAD_REQUEST, "image_error_focalpoint_out_of_bounds", focalPoint.toString(), imageSize.toString());
}
Point targetSize = parameters.getSize();
Float zoomFactor = parameters.getFocalPointZoom();
BufferedImage zoomedImg = applyZoom(img, zoomFactor, focalPoint, targetSize);
// Apply the regular focal point logic if the zoom was not applied. Otherwise the image is already cropped and handled correctly.
if (zoomedImg == null) {
if (targetSize == null) {
throw error(BAD_REQUEST, "image_error_focalpoint_target_missing");
}
Point newSize = calculateResize(imageSize, targetSize);
// Resize the image to the largest dimension while keeping the aspect ratio
img = applyResize(img, newSize);
// No need for cropping. The image has already the target dimensions
if (imageSize.equals(targetSize)) {
return img;
}
boolean alignX = calculateAlignment(imageSize, targetSize);
Point cropStart = calculateCropStart(alignX, targetSize, newSize, focalPoint);
if (cropStart != null) {
img = applyCrop(img, cropStart, targetSize);
}
} else {
img = zoomedImg;
}
img.flush();
return img;
}
/**
* Apply the given zoom by cropping and resizing the image back to the original size. It is only supported to zoom in. Zooming out is not possible.
*
* @param img
* @param zoomFactor
* Positive zoom factor. Negative values will not result in any changes to the image
* @param focalPoint
* @param targetSize
* @return Zoomed image or null if zoom factor is invalid
*/
private BufferedImage applyZoom(BufferedImage img, Float zoomFactor, FocalPoint focalPoint, Point targetSize) {
if (zoomFactor == null || zoomFactor <= 1) {
return null;
}
int x = img.getWidth();
int y = img.getHeight();
// Use the original image size as target size if no specific target size has been specified.
if (targetSize == null) {
targetSize = new Point(x, y);
}
// We zoom by creating a sub image of the original image. The section size will be defined by the zoom factor and the target size.
int zw = Math.round(targetSize.getX() / zoomFactor);
int zh = Math.round(targetSize.getY() / zoomFactor);
// If the calculated sub image size is bigger than the original image, the zoom factor is not enough for target size.
if (zw > x || zh > y) {
throw error(BAD_REQUEST, "image_error_target_too_large_for_zoom");
}
Point zstart = calculateZoomStart(focalPoint, new Point(x, y), zw, zh);
// Now create the subimage
img = img.getSubimage(zstart.getX(), zstart.getY(), zw, zh);
// And resize it back to the target dimension and thus applying the zoom
img = applyResize(img, targetSize);
return img;
}
/**
* Calculate the zoom subimage start coordinates. The coordinates will take the focal point and the zoom area size into account.
*
* @param focalPoint
* @param imageSize
* @param zoomWidth
* @param zoomHeight
* @return
*/
protected Point calculateZoomStart(FocalPoint focalPoint, Point imageSize, int zoomWidth, int zoomHeight) {
int x = imageSize.getX();
int y = imageSize.getY();
Point absFocalPoint = focalPoint.convertToAbsolutePoint(imageSize);
// We need to determine the start point of our sub image in relation to the focal point
int zx = absFocalPoint.getX() - (zoomWidth / 2);
// Clamp the bounds so that the start point will not exceed the image bounds in relation to the sub image width
if (zx < 0) {
zx = 0;
} else if (zx > x - zoomWidth) {
zx = x - zoomWidth;
}
int zy = absFocalPoint.getY() - (zoomHeight / 2);
// Clamp the bounds so that the start point will not exceed the image bounds in relation to the sub image height
if (zy < 0) {
zy = 0;
} else if (zy > y - zoomHeight) {
zy = y - zoomHeight;
}
return new Point(zx, zy);
}
/**
* Resize the image.
*
* @param img
* @param size
* @return
*/
private BufferedImage applyResize(BufferedImage img, Point size) {
try {
return Scalr.resize(img, Mode.FIT_EXACT, size.getX(), size.getY());
} catch (IllegalArgumentException e) {
throw error(BAD_REQUEST, "image_error_resizing_failed", e);
}
}
/**
* Crop the image.
*
* @param img
* @param cropStart
* @param cropSize
* @return
*/
private BufferedImage applyCrop(BufferedImage img, Point cropStart, Point cropSize) {
try {
return Scalr.crop(img, cropStart.getX(), cropStart.getY(), cropSize.getX(), cropSize.getY());
} catch (IllegalArgumentException e) {
throw error(BAD_REQUEST, "image_error_cropping_failed", e);
}
}
/**
* Determine which dimension to resize.
*
* @param imageSize
* @param targetSize
* @return
*/
protected boolean calculateAlignment(Point imageSize, Point targetSize) {
double ratio = imageSize.getRatio();
// Determine which resize operation would yield the largest image. We will crop the rest of the image and thus align the image by that dimension.
int pixelByX = (int) (targetSize.getX() / ratio) * targetSize.getX();
int pixelByY = (int) (targetSize.getY() * ratio) * targetSize.getY();
return pixelByX > pixelByY;
}
/**
* Calculate the start point of the crop area. The point will take the given focal point and the image size into account.
*
* @param alignX
* @param targetSize
* @param imageSize
* @param focalPoint
* @return Calculated start point or null if cropping is not possible / not needed
*/
protected Point calculateCropStart(boolean alignX, Point targetSize, Point imageSize, FocalPoint focalPoint) {
// Cropping is actually not needed if the source already matches the target size
if (targetSize.equals(imageSize)) {
return null;
}
Point point = focalPoint.convertToAbsolutePoint(imageSize);
// Next we need to crop the image in order to achieve the final targeted size
// TODO next crop the other dimension using the focal point and choose the crop area closest to the middle of the needed focal point axis.
int startX = 0;
int startY = 0;
if (!alignX) {
int half = targetSize.getX() / 2;
startX = point.getX() - half;
// Clamp the start point to zero if the start-y value would be outside of the image.
if (startX < 0) {
startX = 0;
} else if (startX + targetSize.getX() > imageSize.getX()) {
startX = imageSize.getX() - targetSize.getX();
}
} else {
int half = targetSize.getY() / 2;
startY = point.getY() - half;
// Clamp the start point to zero if the start-y value would be outside of the image.
if (startY < 0) {
startY = 0;
} else if (startY + targetSize.getY() > imageSize.getY()) {
startY = imageSize.getY() - targetSize.getY();
}
}
return new Point(startX, startY);
}
/**
* Draw the focal point axis in the image.
*
* @param img
* @param focalPoint
*/
protected void drawFocusPointAxis(BufferedImage img, FocalPoint focalPoint) {
Point point = focalPoint.convertToAbsolutePoint(new Point(img.getWidth(), img.getHeight()));
float strokeWidth = 3f;
Graphics2D g = img.createGraphics();
g.setColor(Color.RED);
g.setStroke(new BasicStroke(strokeWidth));
// x-axis of focal point
g.drawLine(point.getX(), 0, point.getX(), img.getHeight());
// y-axis of focal point
g.drawLine(0, point.getY(), img.getWidth(), point.getY());
g.dispose();
}
/**
* Calculate the new size for the initial resize operation.
*
* @param imageSize
* @param targetSize
* @return
*/
protected Point calculateResize(Point imageSize, Point targetSize) {
Integer targetWidth = targetSize.getX();
Integer targetHeight = targetSize.getY();
// Determine which image dimension is nearest to the target dimension.
// The image should always be larger then the target size since the
// remaining additional area will be cropped
boolean alignX = calculateAlignment(imageSize, targetSize);
double aspectRatio = imageSize.getRatio();
int resizeX = targetWidth;
int resizeY = targetHeight;
if (alignX) {
double c = Math.floor((double) targetWidth / aspectRatio);
resizeY = (int) c;
} else {
double c = Math.floor((double) targetHeight * aspectRatio);
resizeX = (int) c;
}
return new Point(resizeX, resizeY);
}
}
| 32.108553 | 148 | 0.704334 |
f81ba785b884f6702531a72e89ea48d62905c5f6 | 1,652 | package org.apereo.cas.shell.commands.services;
import org.apereo.cas.authentication.principal.ShibbolethCompatiblePersistentIdGenerator;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.shell.standard.ShellCommandGroup;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;
/**
* This is {@link AnonymousUsernameAttributeProviderCommand}.
*
* @author Misagh Moayyed
* @since 6.0.0
*/
@ShellCommandGroup("Registered Services")
@ShellComponent
@Slf4j
public class AnonymousUsernameAttributeProviderCommand {
/**
* Generate username.
*
* @param username the username
* @param service the service
* @param salt the salt
* @return the string
*/
@ShellMethod(key = "generate-anonymous-user", value = "Generate an anonymous (persistent) username identifier")
public String generateUsername(
@ShellOption(value = { "username", "--username" },
help = "Authenticated username") final String username,
@ShellOption(value = { "service", "--service" },
help = "Service application URL for which CAS may generate the identifier") final String service,
@ShellOption(value = { "salt", "--salt" },
help = "Salt used to generate and encode the anonymous identifier") final String salt) {
val generator = new ShibbolethCompatiblePersistentIdGenerator(salt);
val id = generator.generate(username, service);
LOGGER.info("Generated identifier:\n[{}]", id);
return id;
}
}
| 37.545455 | 115 | 0.708838 |
9563c4ee25b18ad402e1245f2db24f8b0a331116 | 434 | package binarysearch;
public class RangeSum {
private final int[] prefixSum;
public RangeSum(int[] nums) {
prefixSum = new int[nums.length];
if (nums.length > 0) prefixSum[0] = nums[0];
for (int i = 1; i < nums.length; i++) prefixSum[i] = prefixSum[i - 1] + nums[i];
}
public int total(int i, int j) {
return prefixSum[j - 1] - (i > 0 ? prefixSum[i - 1] : 0);
}
}
| 27.125 | 89 | 0.541475 |
bb5a416668df58332b08d2aca76883fe1edb1a8b | 164 | package com.smoothie.dr_chicken.controller;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SampleApiController {
}
| 16.4 | 62 | 0.835366 |
0a595113b8ce11c2a141f77cb481f5ea270609b7 | 2,571 |
package mage.cards.a;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.common.BeginningOfUpkeepTriggeredAbility;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.SacrificeSourceUnlessPaysEffect;
import mage.abilities.effects.common.continuous.BoostAllEffect;
import mage.abilities.effects.common.continuous.BoostSourceEffect;
import mage.abilities.keyword.FlyingAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.Predicates;
import mage.filter.predicate.permanent.AttackingPredicate;
import mage.filter.predicate.permanent.TappedPredicate;
/**
* @author fireshoes
*/
public final class ArcadesSabboth extends CardImpl {
private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("untapped nonattacking creatures you control");
static {
filter.add(TargetController.YOU.getControllerPredicate());
filter.add(TappedPredicate.UNTAPPED);
filter.add(Predicates.not(AttackingPredicate.instance));
}
public ArcadesSabboth(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{G}{G}{W}{W}{U}{U}");
addSuperType(SuperType.LEGENDARY);
this.subtype.add(SubType.ELDER);
this.subtype.add(SubType.DRAGON);
this.power = new MageInt(7);
this.toughness = new MageInt(7);
// Flying
this.addAbility(FlyingAbility.getInstance());
// At the beginning of your upkeep, sacrifice Arcades Sabboth unless you pay {G}{W}{U}.
this.addAbility(new BeginningOfUpkeepTriggeredAbility(
new SacrificeSourceUnlessPaysEffect(new ManaCostsImpl("{G}{W}{U}")), TargetController.YOU, false));
// Each untapped creature you control gets +0/+2 as long as it's not attacking.
this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new BoostAllEffect(0, 2, Duration.WhileOnBattlefield, filter, false)));
// {W}: Arcades Sabboth gets +0/+1 until end of turn.
this.addAbility(new SimpleActivatedAbility(Zone.BATTLEFIELD, new BoostSourceEffect(0, 1, Duration.EndOfTurn), new ManaCostsImpl("{W}")));
}
private ArcadesSabboth(final ArcadesSabboth card) {
super(card);
}
@Override
public ArcadesSabboth copy() {
return new ArcadesSabboth(this);
}
}
| 38.954545 | 145 | 0.740179 |
071a79b6e2f80837fe10415f6f5676844a29dc06 | 4,417 | package com.qiwenge.android.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.liuguangqiang.android.mvp.BaseUi;
import com.liuguangqiang.android.mvp.Presenter;
import com.liuguangqiang.framework.utils.IntentUtils;
import com.liuguangqiang.framework.utils.ToastUtils;
import com.qiwenge.android.R;
import com.qiwenge.android.act.LegalActivity;
import com.qiwenge.android.async.AsyncCheckUpdate;
import com.qiwenge.android.base.BaseFragment;
import com.qiwenge.android.constant.Constants;
import com.qiwenge.android.listeners.OnPositiveClickListener;
import com.qiwenge.android.mvp.presenter.SettingsPresenter;
import com.qiwenge.android.mvp.ui.SettingUiCallback;
import com.qiwenge.android.mvp.ui.SettingsUi;
import com.qiwenge.android.ui.dialogs.MyDialog;
import com.qiwenge.android.utils.ImageLoaderUtils;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
public class SettingFragment extends BaseFragment implements SettingsUi {
@InjectView(R.id.set_tv_update)
TextView tvCheckUpdate;
@InjectView(R.id.tv_version_name)
TextView tvVersionName;
@InjectView(R.id.layout_set_user)
LinearLayout layoutUser;
@InjectView(R.id.iv_save_model)
ImageView ivSaveModel;
private MyDialog logoutDialog;
private boolean selectSaveModel = false;
SettingUiCallback mCallback;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_setting, container, false);
ButterKnife.inject(this, rootView);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initViews();
}
@Override
public Presenter setPresenter() {
return new SettingsPresenter(getActivity(), this);
}
@Override
public void setUiCallback(SettingUiCallback settingsUiCallback) {
mCallback = settingsUiCallback;
}
public void initViews() {
if (!ImageLoaderUtils.isOpen()) {
setCheckbox(ivSaveModel, true);
selectSaveModel = true;
}
if (Constants.DISABLE_UPDATE) {
tvCheckUpdate.setVisibility(View.GONE);
}
}
/**
* 切换流量模式
*/
@OnClick(R.id.iv_save_model)
public void switchSaveModel() {
if (selectSaveModel) {
setCheckbox(ivSaveModel, false);
ImageLoaderUtils.openLoader(getActivity());
} else {
setCheckbox(ivSaveModel, true);
ImageLoaderUtils.closeLoader(getActivity());
}
selectSaveModel = !selectSaveModel;
}
@OnClick(R.id.set_tv_rating)
public void skipToMarket() {
try {
IntentUtils.skipToMarket(getActivity());
} catch (Exception ex) {
ToastUtils.show(getActivity(), getString(R.string.error_not_find_market));
}
}
@OnClick(R.id.set_tv_legal)
public void skipToLegal() {
startActivity(LegalActivity.class);
}
@OnClick(R.id.set_tv_update)
public void chkVersionUpdate() {
new AsyncCheckUpdate(getActivity()).checkUpdate();
}
@OnClick(R.id.set_tv_logout)
public void showLogoutDialog() {
logoutDialog = new MyDialog(getActivity(), R.string.set_logout_title);
logoutDialog.setMessage(R.string.set_logout_msg);
logoutDialog.setPositiveButton(R.string.str_sure, new OnPositiveClickListener() {
@Override
public void onClick() {
mCallback.logout();
}
});
logoutDialog.show();
}
private void setCheckbox(ImageView iv, boolean ischecked) {
if (ischecked) {
iv.setBackgroundResource(R.drawable.icon_switch_on);
} else {
iv.setBackgroundResource(R.drawable.icon_switch_off);
}
}
@Override
public void setVersionName(String versionName) {
tvVersionName.setText(versionName);
}
@Override
public void setLogoutVisibility(int visibility) {
layoutUser.setVisibility(visibility);
}
}
| 29.059211 | 89 | 0.690514 |
70c02f4708c10e364e974b83230ee6271f900df8 | 19,743 | package de.rwth.dbis.acis.bazaar.service;
import de.rwth.dbis.acis.bazaar.service.dal.DALFacade;
import de.rwth.dbis.acis.bazaar.service.dal.entities.*;
import de.rwth.dbis.acis.bazaar.service.dal.helpers.PageInfo;
import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult;
import de.rwth.dbis.acis.bazaar.service.exception.BazaarException;
import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode;
import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler;
import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation;
import de.rwth.dbis.acis.bazaar.service.internalization.Localization;
import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager;
import i5.las2peer.api.Context;
import i5.las2peer.api.logging.MonitoringEvent;
import i5.las2peer.api.security.Agent;
import i5.las2peer.logging.L2pLogger;
import io.swagger.annotations.*;
import jodd.vtor.Vtor;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.HttpURLConnection;
import java.util.*;
@Api(value = "comments", description = "Comments resource")
@SwaggerDefinition(
info = @Info(
title = "Requirements Bazaar",
version = "0.6",
description = "Requirements Bazaar project",
termsOfService = "http://requirements-bazaar.org",
contact = @Contact(
name = "Requirements Bazaar Dev Team",
url = "http://requirements-bazaar.org",
email = "[email protected]"
),
license = @License(
name = "Apache2",
url = "http://requirements-bazaar.org/license"
)
),
schemes = SwaggerDefinition.Scheme.HTTPS
)
@Path("/comments")
public class CommentsResource {
private BazaarService bazaarService;
private final L2pLogger logger = L2pLogger.getInstance(CommentsResource.class.getName());
public CommentsResource() throws Exception {
bazaarService = (BazaarService) Context.getCurrent().getService();
}
/**
* This method returns the list of comments for a specific requirement.
*
* @param requirementId id of the requirement
* @param page page number
* @param perPage number of projects by page
* @return Response with comments as a JSON array.
*/
public Response getCommentsForRequirement(int requirementId, int page, int perPage) {
DALFacade dalFacade = null;
try {
Agent agent = Context.getCurrent().getMainAgent();
String userId = agent.getIdentifier();
String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING));
if (registrarErrors != null) {
ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors);
}
PageInfo pageInfo = new PageInfo(page, perPage);
Vtor vtor = bazaarService.getValidators();
vtor.validate(pageInfo);
if (vtor.hasViolations()) ExceptionHandler.getInstance().handleViolations(vtor.getViolations());
dalFacade = bazaarService.getDBConnection();
//Todo use requirement's projectId for security context, not the one sent from client
Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId);
Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId);
Project project = dalFacade.getProjectById(requirement.getProjectId(), internalUserId);
if (dalFacade.isRequirementPublic(requirementId)) {
boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, String.valueOf(project.getId()), dalFacade);
if (!authorized) {
ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous"));
}
} else {
boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMMENT, String.valueOf(project.getId()), dalFacade);
if (!authorized) {
ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.read"));
}
}
PaginationResult<Comment> commentsResult = dalFacade.listCommentsByRequirementId(requirementId, pageInfo);
bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_43,
requirementId, Activity.DataType.REQUIREMENT, internalUserId);
Map<String, List<String>> parameter = new HashMap<>();
parameter.put("page", new ArrayList() {{
add(String.valueOf(page));
}});
parameter.put("per_page", new ArrayList() {{
add(String.valueOf(perPage));
}});
Response.ResponseBuilder responseBuilder = Response.ok();
responseBuilder = responseBuilder.entity(commentsResult.toJSON());
responseBuilder = bazaarService.paginationLinks(responseBuilder, commentsResult, "requirements/" + String.valueOf(requirementId) + "/comments", parameter);
responseBuilder = bazaarService.xHeaderFields(responseBuilder, commentsResult);
return responseBuilder.build();
} catch (BazaarException bex) {
if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) {
return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build();
} else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) {
return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build();
} else {
logger.warning(bex.getMessage());
Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get comments for requirement " + requirementId);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build();
}
} catch (Exception ex) {
BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage());
logger.warning(bex.getMessage());
Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get comments for requirement " + requirementId);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build();
} finally {
bazaarService.closeDBConnection(dalFacade);
}
}
/**
* This method allows to retrieve a certain comment.
*
* @param commentId id of the comment
* @return Response with comment as a JSON object.
*/
@GET
@Path("/{commentId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "This method allows to retrieve a certain comment")
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain comment", response = Comment.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems")
})
public Response getComment(@PathParam("commentId") int commentId) {
DALFacade dalFacade = null;
try {
Agent agent = Context.getCurrent().getMainAgent();
String userId = agent.getIdentifier();
String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING));
if (registrarErrors != null) {
ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors);
}
dalFacade = bazaarService.getDBConnection();
Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId);
Comment comment = dalFacade.getCommentById(commentId);
Requirement requirement = dalFacade.getRequirementById(comment.getRequirementId(), internalUserId);
bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_45,
commentId, Activity.DataType.COMMENT, internalUserId);
if (dalFacade.isProjectPublic(requirement.getProjectId())) {
boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, String.valueOf(requirement.getProjectId()), dalFacade);
if (!authorized) {
ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous"));
}
} else {
boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMMENT, String.valueOf(requirement.getProjectId()), dalFacade);
if (!authorized) {
ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.read"));
}
}
return Response.ok(comment.toJSON()).build();
} catch (BazaarException bex) {
if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) {
return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build();
} else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) {
return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build();
} else {
logger.warning(bex.getMessage());
Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get comment " + commentId);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build();
}
} catch (Exception ex) {
BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage());
logger.warning(bex.getMessage());
Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get comment " + commentId);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build();
} finally {
bazaarService.closeDBConnection(dalFacade);
}
}
/**
* This method allows to create a new comment.
*
* @param commentToCreate comment as JSON object
* @return Response with the created comment as JSON object.
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "This method allows to create a new comment.")
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the created comment", response = Comment.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems")
})
public Response createComment(@ApiParam(value = "Comment entity", required = true) Comment commentToCreate) {
DALFacade dalFacade = null;
try {
Agent agent = Context.getCurrent().getMainAgent();
String userId = agent.getIdentifier();
// TODO: check whether the current user may create a new requirement
// TODO: check whether all required parameters are entered
String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING));
if (registrarErrors != null) {
ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors);
}
dalFacade = bazaarService.getDBConnection();
Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId);
Requirement requirement = dalFacade.getRequirementById(commentToCreate.getRequirementId(), internalUserId);
boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_COMMENT, String.valueOf(requirement.getProjectId()), dalFacade);
if (!authorized) {
ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.create"));
}
commentToCreate.setCreator(dalFacade.getUserById(internalUserId));
Vtor vtor = bazaarService.getValidators();
vtor.useProfiles("create");
vtor.validate(commentToCreate);
if (vtor.hasViolations()) {
ExceptionHandler.getInstance().handleViolations(vtor.getViolations());
}
dalFacade.followRequirement(internalUserId, requirement.getId());
Comment createdComment = dalFacade.createComment(commentToCreate);
bazaarService.getNotificationDispatcher().dispatchNotification(createdComment.getCreationDate(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_46,
createdComment.getId(), Activity.DataType.COMMENT, internalUserId);
return Response.status(Response.Status.CREATED).entity(createdComment.toJSON()).build();
} catch (BazaarException bex) {
if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) {
return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build();
} else {
logger.warning(bex.getMessage());
Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Create comment");
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build();
}
} catch (Exception ex) {
BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage());
logger.warning(bex.getMessage());
Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Create comment");
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build();
} finally {
bazaarService.closeDBConnection(dalFacade);
}
}
/**
* This method deletes a specific comment.
*
* @param commentId id of the comment, which should be deleted
* @return Response with the deleted comment as a JSON object.
*/
@DELETE
@Path("/{commentId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "This method deletes a specific comment.")
@ApiResponses(value = {
@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the deleted comment", response = Comment.class),
@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"),
@ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems")
})
public Response deleteComment(@PathParam("commentId") int commentId) {
DALFacade dalFacade = null;
try {
// TODO: check if the user may delete this requirement.
Agent agent = Context.getCurrent().getMainAgent();
String userId = agent.getIdentifier();
String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING));
if (registrarErrors != null) {
ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors);
}
dalFacade = bazaarService.getDBConnection();
Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId);
Comment commentToDelete = dalFacade.getCommentById(commentId);
Requirement requirement = dalFacade.getRequirementById(commentToDelete.getRequirementId(), internalUserId);
boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_COMMENT, Arrays.asList(String.valueOf(commentId), String.valueOf(requirement.getProjectId())), dalFacade);
if (!authorized) {
ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.modify"));
}
Comment deletedComment = dalFacade.deleteCommentById(commentId);
bazaarService.getNotificationDispatcher().dispatchNotification(deletedComment.getCreationDate(), Activity.ActivityAction.DELETE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_48,
deletedComment.getId(), Activity.DataType.COMMENT, internalUserId);
return Response.ok(deletedComment.toJSON()).build();
} catch (BazaarException bex) {
if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) {
return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build();
} else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) {
return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build();
} else {
logger.warning(bex.getMessage());
Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete comment " + commentId);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build();
}
} catch (Exception ex) {
BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage());
logger.warning(bex.getMessage());
Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete comment " + commentId);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build();
} finally {
bazaarService.closeDBConnection(dalFacade);
}
}
}
| 62.280757 | 218 | 0.682571 |
cdd87c2d96ed687d71606342cf47a7271aa1a8ed | 913 | import javax.swing.JOptionPane;
class Main{
public static void main (String args[]){
double reais;
reais = Double.parseDouble(JOptionPane.showInputDialog(null,"Quantos R$ voce deseja Converter?","JanelaReais",JOptionPane.QUESTION_MESSAGE));
double Dolar = 4.81;
double Euro = 5.45;
double Peso = 0.25;
float ResultadoD = (float) (reais/Dolar);
float ResultadoE = (float) (reais/Euro);
float ResultadoP = (float) (reais/Peso);
JOptionPane.showMessageDialog(null,"Valor Convertido " +reais+ " R$ "+
"\n"+"Dolar " +Dolar + " - Valor convertido US$ : " +ResultadoD+ +
"\n"+"Euro " +Euro+ " - Valor convertido EUR : " +ResultadoE+ +
"\n"+"Peso " +Peso+ " - Valor convertido ARS : " +ResultadoP+ );
}
}
| 38.041667 | 142 | 0.533406 |
de527bc12fd84be174343e6a4d2750717ea26fe5 | 304 | package wiki_out;
import java.io.IOException;
public class A_test2005 {
static void fun() throws IOException {
}
public static void main(String args[]) {
try {
extracted();
} catch (Exception e) {
}
}
protected static void extracted() throws IOException {
/*[*/
fun();
/*]*/
}
} | 13.818182 | 55 | 0.638158 |
a259019ae0e31114f369eca3ae22cfdcfa9dbc86 | 988 | package com.github.wkennedy.dto;
import java.util.Date;
public class Order {
private Integer id;
private Date orderDate;
private Integer quantity;
private Customer customer;
private String productName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
}
| 19 | 52 | 0.625506 |
987338fa274ca36d1a7e7bfbcc5855e32a9d4601 | 2,524 | package fr.xephi.authme.command.executable.authme;
import fr.xephi.authme.command.ExecutableCommand;
import fr.xephi.authme.data.auth.PlayerAuth;
import fr.xephi.authme.data.auth.PlayerCache;
import fr.xephi.authme.datasource.DataSource;
import fr.xephi.authme.message.MessageKey;
import fr.xephi.authme.service.BukkitService;
import fr.xephi.authme.service.CommonService;
import fr.xephi.authme.service.ValidationService;
import org.bukkit.command.CommandSender;
import javax.inject.Inject;
import java.util.List;
/**
* Admin command for setting an email to an account.
*/
public class SetEmailCommand implements ExecutableCommand {
@Inject
private DataSource dataSource;
@Inject
private CommonService commonService;
@Inject
private PlayerCache playerCache;
@Inject
private BukkitService bukkitService;
@Inject
private ValidationService validationService;
@Override
public void executeCommand(final CommandSender sender, List<String> arguments) {
// Get the player name and email address
final String playerName = arguments.get(0);
final String playerEmail = arguments.get(1);
// Validate the email address
if (!validationService.validateEmail(playerEmail)) {
commonService.send(sender, MessageKey.INVALID_EMAIL);
return;
}
bukkitService.runTaskOptionallyAsync(new Runnable() {
@Override
public void run() {
// Validate the user
PlayerAuth auth = dataSource.getAuth(playerName);
if (auth == null) {
commonService.send(sender, MessageKey.UNKNOWN_USER);
return;
} else if (!validationService.isEmailFreeForRegistration(playerEmail, sender)) {
commonService.send(sender, MessageKey.EMAIL_ALREADY_USED_ERROR);
return;
}
// Set the email address
auth.setEmail(playerEmail);
if (!dataSource.updateEmail(auth)) {
commonService.send(sender, MessageKey.ERROR);
return;
}
// Update the player cache
if (playerCache.getAuth(playerName) != null) {
playerCache.updatePlayer(auth);
}
// Show a status message
commonService.send(sender, MessageKey.EMAIL_CHANGED_SUCCESS);
}
});
}
}
| 31.949367 | 96 | 0.629952 |
2c288bb686e864be3e777370cef2a84d7c27e158 | 10,317 | /*
*
* This file was generated by LLRP Code Generator
* see http://llrp-toolkit.cvs.sourceforge.net/llrp-toolkit/
* for more information
* Generated on: Sun Apr 08 14:14:11 EDT 2012;
*
*/
/*
* Copyright 2007 ETH Zurich
*
* 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.llrp.ltk.generated.parameters;
import maximsblog.blogspot.com.llrpexplorer.Logger;
import org.jdom2.Content;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.llrp.ltk.exceptions.InvalidLLRPMessageException;
import org.llrp.ltk.exceptions.MissingParameterException;
import org.llrp.ltk.generated.LLRPConstants;
import org.llrp.ltk.types.Bit;
import org.llrp.ltk.types.BitList;
import org.llrp.ltk.types.LLRPBitList;
import org.llrp.ltk.types.LLRPMessage;
import org.llrp.ltk.types.SignedShort;
import org.llrp.ltk.types.TLVParameter;
import org.llrp.ltk.types.TVParameter;
import org.llrp.ltk.types.UnsignedShort;
import java.util.LinkedList;
import java.util.List;
/**
* This parameter carries a single antenna's properties. The properties include the gain and the connectivity status of the antenna.The antenna gain is the composite gain and includes the loss of the associated cable from the Reader to the antenna. The gain is represented in dBi*100 to allow fractional dBi representation.
See also {@link <a href="http://www.epcglobalinc.org/standards/llrp/llrp_1_0_1-standard-20070813.pdf#page=73&view=fit">LLRP Specification Section 12.2.5</a>}
and {@link <a href="http://www.epcglobalinc.org/standards/llrp/llrp_1_0_1-standard-20070813.pdf#page=141&view=fit">LLRP Specification Section 16.2.6.5</a>}
*/
/**
* This parameter carries a single antenna's properties. The properties include the gain and the connectivity status of the antenna.The antenna gain is the composite gain and includes the loss of the associated cable from the Reader to the antenna. The gain is represented in dBi*100 to allow fractional dBi representation.
See also {@link <a href="http://www.epcglobalinc.org/standards/llrp/llrp_1_0_1-standard-20070813.pdf#page=73&view=fit">LLRP Specification Section 12.2.5</a>}
and {@link <a href="http://www.epcglobalinc.org/standards/llrp/llrp_1_0_1-standard-20070813.pdf#page=141&view=fit">LLRP Specification Section 16.2.6.5</a>}
.
*/
public class AntennaProperties extends TLVParameter {
public static final SignedShort TYPENUM = new SignedShort(221);
private static final Logger LOGGER = Logger.getLogger(AntennaProperties.class);
protected Bit antennaConnected;
protected BitList reserved0 = new BitList(7);
protected UnsignedShort antennaID;
protected SignedShort antennaGain;
/**
* empty constructor to create new parameter.
*/
public AntennaProperties() {
}
/**
* Constructor to create parameter from binary encoded parameter
* calls decodeBinary to decode parameter.
* @param list to be decoded
*/
public AntennaProperties(LLRPBitList list) {
decodeBinary(list);
}
/**
* Constructor to create parameter from xml encoded parameter
* calls decodeXML to decode parameter.
* @param element to be decoded
*/
public AntennaProperties(Element element)
throws InvalidLLRPMessageException {
decodeXML(element);
}
/**
* {@inheritDoc}
*/
public LLRPBitList encodeBinarySpecific() {
LLRPBitList resultBits = new LLRPBitList();
if (antennaConnected == null) {
LOGGER.warn(" antennaConnected not set");
throw new MissingParameterException(
" antennaConnected not set for Parameter of Type AntennaProperties");
}
resultBits.append(antennaConnected.encodeBinary());
resultBits.append(reserved0.encodeBinary());
if (antennaID == null) {
LOGGER.warn(" antennaID not set");
throw new MissingParameterException(
" antennaID not set for Parameter of Type AntennaProperties");
}
resultBits.append(antennaID.encodeBinary());
if (antennaGain == null) {
LOGGER.warn(" antennaGain not set");
throw new MissingParameterException(
" antennaGain not set for Parameter of Type AntennaProperties");
}
resultBits.append(antennaGain.encodeBinary());
return resultBits;
}
/**
* {@inheritDoc}
*/
public Content encodeXML(String name, Namespace ns) {
// element in namespace defined by parent element
Element element = new Element(name, ns);
// child element are always in default LLRP namespace
ns = Namespace.getNamespace("llrp", LLRPConstants.LLRPNAMESPACE);
if (antennaConnected == null) {
LOGGER.warn(" antennaConnected not set");
throw new MissingParameterException(" antennaConnected not set");
} else {
element.addContent(antennaConnected.encodeXML("AntennaConnected", ns));
}
//element.addContent(reserved0.encodeXML("reserved",ns));
if (antennaID == null) {
LOGGER.warn(" antennaID not set");
throw new MissingParameterException(" antennaID not set");
} else {
element.addContent(antennaID.encodeXML("AntennaID", ns));
}
if (antennaGain == null) {
LOGGER.warn(" antennaGain not set");
throw new MissingParameterException(" antennaGain not set");
} else {
element.addContent(antennaGain.encodeXML("AntennaGain", ns));
}
//parameters
return element;
}
/**
* {@inheritDoc}
*/
protected void decodeBinarySpecific(LLRPBitList binary) {
int position = 0;
int tempByteLength;
int tempLength = 0;
int count;
SignedShort type;
int fieldCount;
Custom custom;
antennaConnected = new Bit(binary.subList(position, Bit.length()));
position += Bit.length();
position += reserved0.length();
antennaID = new UnsignedShort(binary.subList(position,
UnsignedShort.length()));
position += UnsignedShort.length();
antennaGain = new SignedShort(binary.subList(position,
SignedShort.length()));
position += SignedShort.length();
}
/**
* {@inheritDoc}
*/
public void decodeXML(Element element) throws InvalidLLRPMessageException {
List<Element> tempList = null;
boolean atLeastOnce = false;
Custom custom;
Element temp = null;
// child element are always in default LLRP namespace
Namespace ns = Namespace.getNamespace(LLRPConstants.LLRPNAMESPACE);
temp = element.getChild("AntennaConnected", ns);
if (temp != null) {
antennaConnected = new Bit(temp);
}
element.removeChild("AntennaConnected", ns);
temp = element.getChild("AntennaID", ns);
if (temp != null) {
antennaID = new UnsignedShort(temp);
}
element.removeChild("AntennaID", ns);
temp = element.getChild("AntennaGain", ns);
if (temp != null) {
antennaGain = new SignedShort(temp);
}
element.removeChild("AntennaGain", ns);
if (element.getChildren().size() > 0) {
String message = "AntennaProperties has unknown element " +
((Element) element.getChildren().get(0)).getName();
throw new InvalidLLRPMessageException(message);
}
}
//setters
/**
* set antennaConnected of type Bit .
* @param antennaConnected to be set
*/
public void setAntennaConnected(final Bit antennaConnected) {
this.antennaConnected = antennaConnected;
}
/**
* set antennaID of type UnsignedShort .
* @param antennaID to be set
*/
public void setAntennaID(final UnsignedShort antennaID) {
this.antennaID = antennaID;
}
/**
* set antennaGain of type SignedShort .
* @param antennaGain to be set
*/
public void setAntennaGain(final SignedShort antennaGain) {
this.antennaGain = antennaGain;
}
// end setter
//getters
/**
* get antennaConnected of type Bit.
* @return type Bit to be set
*/
public Bit getAntennaConnected() {
return this.antennaConnected;
}
/**
* get antennaID of type UnsignedShort.
* @return type UnsignedShort to be set
*/
public UnsignedShort getAntennaID() {
return this.antennaID;
}
/**
* get antennaGain of type SignedShort.
* @return type SignedShort to be set
*/
public SignedShort getAntennaGain() {
return this.antennaGain;
}
// end getters
//add methods
// end add
/**
* For TLV Parameter length can not be determined at compile time. This method therefore always returns 0.
* @return Integer always zero
*/
public static Integer length() {
return 0;
}
/**
* {@inheritDoc}
*/
public SignedShort getTypeNum() {
return TYPENUM;
}
/**
* {@inheritDoc}
*/
public String getName() {
return "AntennaProperties";
}
/**
* return string representation. All field values but no parameters are included
* @return String
*/
public String toString() {
String result = "AntennaProperties: ";
result += ", antennaConnected: ";
result += antennaConnected;
result += ", antennaID: ";
result += antennaID;
result += ", antennaGain: ";
result += antennaGain;
result = result.replaceFirst(", ", "");
return result;
}
}
| 30.981982 | 323 | 0.649801 |
dce554bec17987af381a2ddb89008e179df18dd7 | 5,449 | /*
* Copyright 2020 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
package com.google.cloud.healthcare.fdamystudies.filter;
import static com.google.cloud.healthcare.fdamystudies.common.CommonConstants.USER_ID_HEADER;
import static com.google.cloud.healthcare.fdamystudies.common.JsonUtils.getObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.cloud.healthcare.fdamystudies.common.ErrorCode;
import com.google.cloud.healthcare.fdamystudies.model.UserRegAdminEntity;
import com.google.cloud.healthcare.fdamystudies.repository.UserRegAdminRepository;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.annotation.PostConstruct;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.server.PathContainer;
import org.springframework.stereotype.Component;
import org.springframework.web.util.pattern.PathPattern;
import org.springframework.web.util.pattern.PathPatternParser;
@Component
@Order(3)
@ConditionalOnProperty(
value = "commonservice.activeuser.filter.enabled",
havingValue = "true",
matchIfMissing = false)
public class ActiveUserFilter implements Filter {
private XLogger logger = XLoggerFactory.getXLogger(ActiveUserFilter.class.getName());
public static final String TOKEN = "token";
public static final String ACTIVE = "active";
private Map<String, String[]> uriTemplateAndMethods = new HashMap<>();
@Autowired ServletContext context;
@Autowired private UserRegAdminRepository userRegAdminRepository;
@PostConstruct
public void init() {
uriTemplateAndMethods.put(
String.format("%s/locations", context.getContextPath()),
new String[] {HttpMethod.POST.name(), HttpMethod.GET.name()});
uriTemplateAndMethods.put(
String.format("%s/locations/{locationId}", context.getContextPath()),
new String[] {HttpMethod.PUT.name(), HttpMethod.GET.name()});
}
protected Map<String, String[]> getUriTemplateAndHttpMethodsMap() {
return uriTemplateAndMethods;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
logger.entry(
String.format("begin doFilter() for %s", ((HttpServletRequest) request).getRequestURI()));
HttpServletRequest req = (HttpServletRequest) request;
if (validatePathAndHttpMethod(req)) {
logger.info(String.format("check user status for %s", req.getRequestURI()));
String userId = req.getHeader(USER_ID_HEADER);
ErrorCode ec = null;
if (StringUtils.isEmpty(userId)) {
logger.error(String.format("userId is empty errorCode=%s", ErrorCode.USER_ID_REQUIRED));
ec = ErrorCode.USER_ID_REQUIRED;
} else {
Optional<UserRegAdminEntity> optUserRegAdminUser = userRegAdminRepository.findById(userId);
ec = !optUserRegAdminUser.isPresent() ? ErrorCode.USER_NOT_EXISTS : null;
if (optUserRegAdminUser.isPresent()) {
UserRegAdminEntity adminUser = optUserRegAdminUser.get();
ec = !adminUser.isActive() ? ErrorCode.USER_NOT_ACTIVE : null;
}
}
if (ec != null) {
logger.error(String.format("User status check failed with error code=%s", ec));
setErrorResponse(response, ec);
} else {
chain.doFilter(request, response);
}
} else {
logger.info(String.format("skip ActiveUserFilter for %s", req.getRequestURI()));
chain.doFilter(request, response);
}
}
private boolean validatePathAndHttpMethod(HttpServletRequest req) {
String method = req.getMethod().toUpperCase();
for (Map.Entry<String, String[]> entry : getUriTemplateAndHttpMethodsMap().entrySet()) {
if (ArrayUtils.contains(entry.getValue(), method)
&& checkPathMatches(entry.getKey(), req.getRequestURI())) {
return true;
}
}
return false;
}
private static boolean checkPathMatches(String uriTemplate, String path) {
PathPatternParser parser = new PathPatternParser();
parser.setMatchOptionalTrailingSeparator(true);
PathPattern p = parser.parse(uriTemplate);
return p.matches(PathContainer.parsePath(path));
}
private void setErrorResponse(ServletResponse response, ErrorCode ec) throws IOException {
HttpServletResponse res = (HttpServletResponse) response;
res.setStatus(ec.getStatus());
res.setContentType(MediaType.APPLICATION_JSON_VALUE);
JsonNode reponse = getObjectMapper().convertValue(ec, JsonNode.class);
res.getOutputStream().write(reponse.toString().getBytes());
}
}
| 38.373239 | 99 | 0.750963 |
c7261d9a89804829e249713fd88a17348c6539ba | 1,403 | package com.alorma.github.emoji;
import com.alorma.github.sdk.core.datasource.CacheDataSource;
import com.alorma.github.sdk.core.datasource.CloudDataSource;
import com.alorma.github.sdk.core.datasource.SdkItem;
import com.alorma.github.sdk.core.repository.GenericRepository;
import com.alorma.github.sdk.core.usecase.GenericUseCase;
import java.util.List;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class EmojisPresenter {
public EmojisPresenter() {
}
public Observable<List<Emoji>> getEmojis() {
CacheDataSource<Void, List<Emoji>> cache = new EmojisCacheDataSource();
CloudDataSource<Void, List<Emoji>> api = new EmojisApiDataSource(null);
GenericRepository<Void, List<Emoji>> repository = new GenericRepository<>(cache, api);
GenericUseCase<Void, List<Emoji>> useCase = new GenericUseCase<>(repository);
return useCase.execute(new SdkItem<>(null))
.map(SdkItem::getK)
.filter(emojis -> emojis.size() > 0)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
public Observable<List<Emoji>> getEmojis(String filter) {
Observable<List<Emoji>> emojis = getEmojis();
if (filter != null) {
return emojis.flatMap(Observable::from).filter(emoji -> emoji.getKey().contains(filter.toLowerCase())).toList();
}
return emojis;
}
}
| 35.075 | 118 | 0.735567 |
414df582da181942452bd7d6bf253b533c2794ab | 158 | /**
* This package contains classes that handle IO operations including reading and writing BioPAX from files and streams..
*/
package org.biopax.paxtools.io; | 39.5 | 119 | 0.791139 |
cf5d05002196fa3df3459d2b39043ad5a2103fea | 1,075 |
package com.muleinaction;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.mule.api.MuleMessage;
import org.mule.module.client.MuleClient;
import org.mule.tck.junit4.FunctionalTestCase;
public class CompressTestCase extends FunctionalTestCase
{
private static final String PAYLOAD = "The quick fox jumped over the lazy dog";
@Override
protected String getConfigResources()
{
return "compress.xml";
}
@Test
public void testCompress() throws Exception
{
MuleClient muleClient = new MuleClient(muleContext);
muleClient.dispatch("vm://compress.in", PAYLOAD, null);
MuleMessage result = muleClient.request("jms://uncompressedDataQueue", 10000);
assertThat(result, is(notNullValue()));
assertThat(result.getPayload(), is(notNullValue()));
assertThat((String) result.getPayload(), is(equalTo(PAYLOAD)));
}
}
| 27.564103 | 86 | 0.728372 |
e9944c1f89992ec6a93a19968ceeb4ab3f1c6039 | 4,554 | package psidev.psi.mi.jami.utils.comparator.experiment;
import psidev.psi.mi.jami.model.VariableParameterValue;
import java.util.Comparator;
/**
* Simple Comparator for VariableParameterValue
*
* It will first compare the value (case insensitive) and then the order.
* It ignores the variableParameter
*
* @author Marine Dumousseau ([email protected])
* @version $Id$
* @since <pre>22/05/13</pre>
*/
public class VariableParameterValueComparator implements Comparator<VariableParameterValue>{
private static VariableParameterValueComparator variableParameterValueComparator;
/**
* It will first compare the value (case insensitive) and then the order.
* It ignores the variableParameter
*
* @param variableParameterValue1 a {@link psidev.psi.mi.jami.model.VariableParameterValue} object.
* @param variableParameterValue2 a {@link psidev.psi.mi.jami.model.VariableParameterValue} object.
* @return a int.
*/
public int compare(VariableParameterValue variableParameterValue1, VariableParameterValue variableParameterValue2) {
int EQUAL = 0;
int BEFORE = -1;
int AFTER = 1;
if (variableParameterValue1 == variableParameterValue2){
return 0;
}
else if (variableParameterValue1 == null){
return AFTER;
}
else if (variableParameterValue2 == null){
return BEFORE;
}
else {
if(variableParameterValue1.getVariableParameter()!=null&&variableParameterValue2.getVariableParameter()!=null) {
String desc1 = variableParameterValue1.getVariableParameter().getDescription();
String desc2 = variableParameterValue2.getVariableParameter().getDescription();
if (desc1 != null && desc2 != null){
int compDesc;
compDesc = desc1.toLowerCase().trim().compareTo(desc2.toLowerCase().trim());
if (compDesc != 0) {
return compDesc;
}
}
}
// first compares values
String value1 = variableParameterValue1.getValue();
String value2 = variableParameterValue2.getValue();
int comp;
comp = value1.toLowerCase().trim().compareTo(value2.toLowerCase().trim());
if (comp != 0){
return comp;
}
Integer order1 = variableParameterValue1.getOrder();
Integer order2 = variableParameterValue2.getOrder();
if (order1 == null && order2 == null){
return EQUAL;
}
else if (order1 == null){
return AFTER;
}
else if (order2 == null){
return BEFORE;
}
else if (order1 < order2){
return BEFORE;
}
else if (order1 > order2){
return AFTER;
}
else {
return EQUAL;
}
}
}
/**
* Use VariableParameterValueComparator to know if two variableParameterValues are equals.
*
* @param parameterValue1 a {@link psidev.psi.mi.jami.model.VariableParameterValue} object.
* @param parameterValue2 a {@link psidev.psi.mi.jami.model.VariableParameterValue} object.
* @return true if the two variableParameterValues are equal
*/
public static boolean areEquals(VariableParameterValue parameterValue1, VariableParameterValue parameterValue2){
if (variableParameterValueComparator == null){
variableParameterValueComparator = new VariableParameterValueComparator();
}
return variableParameterValueComparator.compare(parameterValue1, parameterValue2) == 0;
}
/**
* <p>hashCode</p>
*
* @param value a {@link psidev.psi.mi.jami.model.VariableParameterValue} object.
* @return the hashcode consistent with the equals method for this comparator
*/
public static int hashCode(VariableParameterValue value){
if (variableParameterValueComparator == null){
variableParameterValueComparator = new VariableParameterValueComparator();
}
if (value == null){
return 0;
}
int hashcode = 31;
hashcode = 31*hashcode + (value.getValue() != null ? value.getValue().trim().toLowerCase().hashCode() : 0);
hashcode = 31*hashcode + (value.getOrder() != null ? value.getOrder() : 0);
return hashcode;
}
}
| 34.240602 | 124 | 0.614625 |
4aa5a1404974851de59c944f181769910f774e80 | 2,754 | package com.dev.cmielke.gui.dialogs.components;
import static com.dev.cmielke.gui.util.DialogConstants.ACTION_CMD_CODE_MI_COPY;
import static com.dev.cmielke.gui.util.DialogConstants.ACTION_CMD_CODE_MI_CUT;
import static com.dev.cmielke.gui.util.DialogConstants.ACTION_CMD_CODE_MI_PASTE;
import static com.dev.cmielke.gui.util.DialogConstants.RB_PARAM_NAME_MENU_ITEM_COPY;
import static com.dev.cmielke.gui.util.DialogConstants.RB_PARAM_NAME_MENU_ITEM_CUT;
import static com.dev.cmielke.gui.util.DialogConstants.RB_PARAM_NAME_MENU_ITEM_PASTE;
import java.awt.Component;
import java.awt.event.ActionListener;
import java.util.ResourceBundle;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
@SuppressWarnings("serial")
public class CopyPastePopupMenu extends JPopupMenu
{
protected static ResourceBundle rBundle = ResourceBundle.getBundle("pdf2epub");
private JMenuItem copyItem, pasteItem, cutItem;
public CopyPastePopupMenu(ActionListener listener)
{
initMenu(listener);
}
public void addMenuItemAt(int index, JMenuItem item)
{
add(item, index);
}
public void addMenuItem(JMenuItem item)
{
add(item);
}
public void removeCopyOption()
{
remove(copyItem);
}
public void removePasteOption()
{
remove(pasteItem);
}
public void removeCutOption()
{
remove(cutItem);
}
public void enableCopyOption(boolean b)
{
copyItem.setEnabled(b);
}
public void enablePasteOption(boolean b)
{
pasteItem.setEnabled(b);
}
public void enableCutOption(boolean b)
{
cutItem.setEnabled(b);
}
public void addSeparator()
{
addSeparatorAt(-1);
}
public void appendMenu(JMenu menu)
{
Component[] components = menu.getComponents();
if(components.length > 0)
{
addSeparator();
for(Component comp : components)
{
add(comp);
}
}
}
public void addSeparatorAt(int index)
{
JSeparator separator = new JSeparator(JSeparator.HORIZONTAL);
if(index > 0)
{
add(separator, index);
}
else
{
add(separator);
}
}
private void initMenu(ActionListener listener)
{
copyItem = new JMenuItem(rBundle.getString(RB_PARAM_NAME_MENU_ITEM_COPY));
copyItem.setActionCommand(Integer.toString(ACTION_CMD_CODE_MI_COPY));
copyItem.addActionListener(listener);
add(copyItem);
pasteItem = new JMenuItem(rBundle.getString(RB_PARAM_NAME_MENU_ITEM_PASTE));
pasteItem.setActionCommand(Integer.toString(ACTION_CMD_CODE_MI_PASTE));
pasteItem.addActionListener(listener);
add(pasteItem);
cutItem = new JMenuItem(rBundle.getString(RB_PARAM_NAME_MENU_ITEM_CUT));
cutItem.setActionCommand(Integer.toString(ACTION_CMD_CODE_MI_CUT));
cutItem.addActionListener(listener);
add(cutItem);
}
}
| 22.760331 | 85 | 0.766158 |
17e91effc78fb20ccacd688bd4ad119fc63e89c6 | 1,379 | package com.gradle.exportapi;
import io.netty.buffer.ByteBuf;
import io.reactivex.netty.protocol.http.client.HttpClient;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by grodion on 5/21/17.
*/
public class HttpClientFactory {
private static String defaultToHttps(final String server) {
return server.startsWith("http") ? server : "https://" + server;
}
public static HttpClient<ByteBuf, ByteBuf> create(String server, final String portStr) {
int port = 0;
try {
URL url = new URL(defaultToHttps(server));
if (portStr == null) {
port = url.getDefaultPort();
} else if (Integer.parseInt(portStr) > 0){
port = Integer.parseInt(portStr);
}
final HttpClient<ByteBuf, ByteBuf> httpClient = HttpClient.newClient(new InetSocketAddress(
url.getHost(), port));
if(url.getProtocol().equals("https")) {
return httpClient.unsafeSecure();
} else if (url.getProtocol().equals("http")) {
return httpClient;
} else {
throw new RuntimeException("Unsuported protocol");
}
}
catch(MalformedURLException e){
throw new RuntimeException(e);
}
}
}
| 31.340909 | 103 | 0.594634 |
36130d3b52a7ae019baa3a43c232aafef9ecd9eb | 2,009 | package com.ecorp.gorillamail.services.external;
import com.ecorp.bannerad.service.Confirmation;
import com.ecorp.bannerad.service.Customer;
import com.ecorp.bannerad.service.Dimension;
import com.ecorp.bannerad.service.OrderService;
import com.ecorp.bannerad.service.OrderService_Service;
import com.ecorp.bannerad.service.PlacingOrder;
import com.ecorp.gorillamail.services.external.exceptions.AdRequestException;
import java.util.List;
import java.util.Random;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Alternative;
import javax.xml.ws.WebServiceRef;
@ApplicationScoped
@Alternative
public class AdService implements AdServiceIF {
private Customer gorillamailCustomer;
private Random random;
@WebServiceRef(wsdlLocation = "WEB-INF/wsdl/im-lamport_8080/banner_ad-1.0-SNAPSHOT/OrderService.wsdl")
private OrderService_Service orderServiceRef;
private OrderService orderService;
@PostConstruct
public void postConstruct() {
orderService = orderServiceRef.getOrderServicePort();
gorillamailCustomer = new Customer();
gorillamailCustomer.setEmail("[email protected]");
random = new Random();
}
@Override
public String requestBannerUrl() throws AdRequestException {
final Dimension dimension = new Dimension();
dimension.setWidth(468);
dimension.setHeight(60);
final PlacingOrder order = new PlacingOrder();
order.setDimension(dimension);
try {
final Confirmation confirmation = orderService.orderBannerPlacement(gorillamailCustomer, order);
final List<String> banners = confirmation.getUrls();
final int bannerIndex = random.nextInt(banners.size());
return banners.get(bannerIndex);
} catch (Exception exception) {
throw new AdRequestException(exception);
}
}
}
| 35.245614 | 108 | 0.721254 |
563ade5c294dd582a8a8762c2820db333370d9e7 | 20,910 | /*******************************************************************************
* Copyright 2015 EMBL - European Bioinformatics Institute
*
* 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.mousephenotype.cda.indexers;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.mousephenotype.cda.constants.ParameterConstants;
import org.mousephenotype.cda.db.repositories.OntologyTermRepository;
import org.mousephenotype.cda.enumerations.SexType;
import org.mousephenotype.cda.indexers.exceptions.IndexerException;
import org.mousephenotype.cda.indexers.utils.IndexerMap;
import org.mousephenotype.cda.owl.OntologyParser;
import org.mousephenotype.cda.owl.OntologyParserFactory;
import org.mousephenotype.cda.owl.OntologyTermDTO;
import org.mousephenotype.cda.solr.service.StatisticalResultService;
import org.mousephenotype.cda.solr.service.dto.BasicBean;
import org.mousephenotype.cda.solr.service.dto.GenotypePhenotypeDTO;
import org.mousephenotype.cda.solr.service.dto.ImpressBaseDTO;
import org.mousephenotype.cda.solr.service.dto.ParameterDTO;
import org.mousephenotype.cda.utilities.RunStatus;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.Banner;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import javax.inject.Inject;
import javax.sql.DataSource;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
/**
* Populate the Genotype-Phenotype core
*/
@EnableAutoConfiguration
public class GenotypePhenotypeIndexer extends AbstractIndexer {
private final Logger logger = LoggerFactory.getLogger(GenotypePhenotypeIndexer.class);
private final int MAX_MISSING_LIFE_STAGE_ERRORS_TO_LOG = 100;
private final Set<String> SKIP_PROCEDURES = new HashSet<>(Arrays.asList( // Do not process parameters from these procecures
"IMPC_ELZ", "IMPC_EOL", "IMPC_EMO", "IMPC_MAA", "IMPC_EMA"
));
private SolrClient genotypePhenotypeCore;
private int missingLifeStageCount = 0;
private Map<Long, ImpressBaseDTO> pipelineMap = new HashMap<>();
private Map<Long, ImpressBaseDTO> procedureMap = new HashMap<>();
private Map<Long, ParameterDTO> parameterMap = new HashMap<>();
private OntologyParser mpParser;
private OntologyParser mpMaParser;
private OntologyParser maParser;
private OntologyParserFactory ontologyParserFactory;
protected GenotypePhenotypeIndexer() {
}
@Inject
public GenotypePhenotypeIndexer(
@NotNull DataSource komp2DataSource,
@NotNull OntologyTermRepository ontologyTermRepository,
@NotNull SolrClient genotypePhenotypeCore) {
super(komp2DataSource, ontologyTermRepository);
this.genotypePhenotypeCore = genotypePhenotypeCore;
}
@Override
public RunStatus validateBuild() throws IndexerException {
return super.validateBuild(genotypePhenotypeCore);
}
@Override
public RunStatus run() throws IndexerException {
int count = 0;
RunStatus runStatus = new RunStatus();
long start = System.currentTimeMillis();
try (Connection connection = komp2DataSource.getConnection()) {
ontologyParserFactory = new OntologyParserFactory(komp2DataSource, owlpath);
mpParser = ontologyParserFactory.getMpParser();
maParser = ontologyParserFactory.getMaParser();
mpMaParser = ontologyParserFactory.getMpMaParser();
pipelineMap = IndexerMap.getImpressPipelines(connection);
procedureMap = IndexerMap.getImpressProcedures(connection);
parameterMap = IndexerMap.getImpressParameters(connection);
count = populateGenotypePhenotypeSolrCore(connection, runStatus);
} catch (SQLException | IOException | SolrServerException | OWLOntologyCreationException | OWLOntologyStorageException ex) {
ex.printStackTrace();
throw new IndexerException(ex);
}
logger.info(" Added {} total beans in {}", count, commonUtils.msToHms(System.currentTimeMillis() - start));
return runStatus;
}
// Returns document count.
public int populateGenotypePhenotypeSolrCore(Connection connection, RunStatus runStatus) throws SQLException, IOException, SolrServerException {
int count = 0;
genotypePhenotypeCore.deleteByQuery("*:*");
// conditions of WHERE clauses
/*
- the first for normal lines
- the 2nd for viability and fertility
- the last s.p_value IS NULL is to pick up MPATH in the mp_acc column
*/
String query = "SELECT s.id AS id, CASE WHEN sur.statistical_method IS NOT NULL THEN sur.statistical_method WHEN scr.statistical_method IS NOT NULL THEN scr.statistical_method ELSE 'Unknown' END AS statistical_method, " +
" sur.genotype_percentage_change, o.name AS phenotyping_center, s.external_id, s.parameter_id AS parameter_id, s.procedure_id AS procedure_id, s.pipeline_id AS pipeline_id, s.gf_acc AS marker_accession_id, " +
" gf.symbol AS marker_symbol, s.allele_acc AS allele_accession_id, al.name AS allele_name, al.symbol AS allele_symbol, s.strain_acc AS strain_accession_id, st.name AS strain_name, " +
" s.sex AS sex, s.zygosity AS zygosity, p.name AS project_name, p.fullname AS project_fullname, s.mp_acc AS ontology_term_id, ot.name AS ontology_term_name, " +
" CASE WHEN s.p_value IS NOT NULL THEN s.p_value WHEN s.sex='female' THEN sur.gender_female_ko_pvalue WHEN s.sex='male' THEN sur.gender_male_ko_pvalue END AS p_value, " +
" s.effect_size AS effect_size, " +
" s.colony_id, db.name AS resource_fullname, db.short_name AS resource_name " +
"FROM phenotype_call_summary s " +
" LEFT OUTER JOIN stat_result_phenotype_call_summary srpcs ON srpcs.phenotype_call_summary_id = s.id " +
" LEFT OUTER JOIN stats_unidimensional_results sur ON sur.id = srpcs.unidimensional_result_id " +
" LEFT OUTER JOIN stats_categorical_results scr ON scr.id = srpcs.categorical_result_id " +
" LEFT OUTER JOIN stats_rrplus_results srr ON srr.id = srpcs.rrplus_result_id " +
" INNER JOIN organisation o ON s.organisation_id = o.id " +
" INNER JOIN project p ON s.project_id = p.id " +
" INNER JOIN ontology_term ot ON ot.acc = s.mp_acc " +
" INNER JOIN genomic_feature gf ON s.gf_acc = gf.acc " +
" LEFT OUTER JOIN strain st ON s.strain_acc = st.acc " +
" LEFT OUTER JOIN allele al ON s.allele_acc = al.acc " +
" INNER JOIN external_db db ON s.external_db_id = db.id " +
"WHERE (0.0001 >= s.p_value " +
" OR (s.p_value IS NULL AND s.sex='male' AND sur.gender_male_ko_pvalue <= 0.0001) " +
" OR (s.p_value IS NULL AND s.sex='female' AND sur.gender_female_ko_pvalue <= 0.0001)) " +
"OR (s.parameter_id IN (SELECT id FROM phenotype_parameter WHERE stable_id like 'IMPC_VIA%' OR stable_id LIKE 'IMPC_FER%')) " +
"OR s.p_value IS NULL ";
try (PreparedStatement p = connection.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) {
p.setFetchSize(Integer.MIN_VALUE);
ResultSet r = p.executeQuery();
Map<String, Integer> skippedNotWarned = new HashMap<>();
while (r.next()) {
GenotypePhenotypeDTO doc = new GenotypePhenotypeDTO();
doc.setId(r.getString("id"));
doc.setSex(r.getString("sex"));
doc.setZygosity(r.getString("zygosity"));
doc.setPhenotypingCenter(r.getString("phenotyping_center"));
doc.setProjectName(r.getString("project_name"));
doc.setProjectFullname(r.getString("project_fullname"));
String percentageChangeDb = r.getString("genotype_percentage_change");
if (!r.wasNull()) {
// Default female, override if male
Double percentageChange = StatisticalResultService.getFemalePercentageChange(percentageChangeDb);
if (doc.getSex().equals(SexType.male.getName())) {
percentageChange = StatisticalResultService.getMalePercentageChange(percentageChangeDb);
}
if (percentageChange != null) {
doc.setPercentageChange(percentageChange.toString() + "%");
}
}
doc.setStatisticalMethod(r.getString("statistical_method"));
// Only set the p_value and effect size if they are not null in the phenotype call summary table
Double d = r.getDouble("p_value");
if (!r.wasNull()) {
doc.setP_value(r.getDouble("p_value"));
}
d = r.getDouble("effect_size");
if (!r.wasNull()) {
doc.setEffectSize(r.getDouble("effect_size"));
}
doc.setMarkerAccessionId(r.getString("marker_accession_id"));
doc.setMarkerSymbol(r.getString("marker_symbol"));
String colonyId = r.getString("colony_id");
doc.setColonyId(colonyId);
doc.setAlleleAccessionId(r.getString("allele_accession_id"));
doc.setAlleleName(r.getString("allele_name"));
doc.setAlleleSymbol(r.getString("allele_symbol"));
doc.setStrainAccessionId(r.getString("strain_accession_id"));
doc.setStrainName(r.getString("strain_name"));
// Procedure prefix is the first two strings of the parameter after splitting on underscore
// i.e. IMPC_BWT_001_001 => IMPC_BWT
String procedurePrefix = StringUtils.join(Arrays.asList(parameterMap.get(r.getLong("parameter_id")).getStableId().split("_")).subList(0, 2), "_");
if (ParameterConstants.source3iProcedurePrefixes.contains(procedurePrefix)) {
doc.setResourceName("3i");
doc.setResourceFullname("Infection, Immunity and Immunophenotyping consortium");
} else {
doc.setResourceFullname(r.getString("resource_fullname"));
doc.setResourceName(r.getString("resource_name"));
}
doc.setExternalId(r.getString("external_id"));
String pipelineStableId = pipelineMap.get(r.getLong("pipeline_id")).getStableId();
doc.setPipelineStableKey("" + pipelineMap.get(r.getLong("pipeline_id")).getStableKey());
doc.setPipelineName(pipelineMap.get(r.getLong("pipeline_id")).getName());
doc.setPipelineStableId(pipelineStableId);
String procedureStableId = procedureMap.get(r.getLong("procedure_id")).getStableId();
doc.setProcedureStableKey("" + procedureMap.get(r.getLong("procedure_id")).getStableKey());
doc.setProcedureName(procedureMap.get(r.getLong("procedure_id")).getName());
doc.setProcedureStableId(procedureStableId);
if (SKIP_PROCEDURES.contains(procedurePrefix)) {
// Do not store phenotype associations for these parameters
// if somehow they make it into the database
continue;
}
doc.setParameterStableKey("" + parameterMap.get(r.getLong("parameter_id")).getStableKey());
doc.setParameterName(parameterMap.get(r.getLong("parameter_id")).getName());
doc.setParameterStableId(parameterMap.get(r.getLong("parameter_id")).getStableId());
BasicBean stage = getDevelopmentalStage(pipelineStableId, procedureStableId, colonyId);
if (stage != null) {
doc.setLifeStageAcc(stage.getId());
doc.setLifeStageName(stage.getName());
}
// MP association
if (r.getString("ontology_term_id").startsWith("MP:")) {
// some hard-coded stuff
doc.setOntologyDbId(5L);
if (doc.getP_value() != null) {
doc.setAssertionType("automatic");
doc.setAssertionTypeId("ECO:0000203");
} else {
doc.setAssertionType("manual");
doc.setAssertionTypeId("ECO:0000218");
}
String mpId = r.getString("ontology_term_id");
String mpName = r.getString("ontology_term_name");
doc.setMpTermId(mpId);
doc.setMpTermName(mpName);
// mp-ma mappings, only add to adult (POSTPARTUM_STAGE) (MmusDv:0000092) as mapping if to MA
if (doc.getLifeStageAcc() == null) {
if (missingLifeStageCount < MAX_MISSING_LIFE_STAGE_ERRORS_TO_LOG) {
logger.warn("life stage is NULL for " +
"mpTermId " + mpId +
", mpTermName " + mpName +
", external_id " + doc.getExternalId() +
", resourceName " + doc.getResourceName() +
", pipelineStableId " + doc.getPipelineStableId() +
", procedureStableId " + doc.getProcedureStableId() +
", parameterStableId " + doc.getParameterStableId() +
". Skipping...");
};
missingLifeStageCount++;
continue;
}
if (doc.getLifeStageAcc().equalsIgnoreCase(POSTPARTUM_STAGE)) {
getMaTermsForMp(doc, mpId, true);
// Also check mappings up the tree, as a leaf term might not have a mapping, but the parents might.
Set<String> anatomyIdsForAncestors = new HashSet<>();
for (String mpAncestorId : mpParser.getOntologyTerm(mpId).getIntermediateIds()) {
getMaTermsForMp(doc, mpAncestorId, false);
}
}
OntologyTermDTO mpDto = mpParser.getOntologyTerm(mpId);
if (mpDto == null) {
logger.warn(" Skipping missing mp term '" + mpId + "'");
continue;
}
if (mpDto.getTopLevelIds() == null || mpDto.getTopLevelIds().size() == 0 ){
// if the mpId itself is a top level, add itself as a top level
List<String> ids = new ArrayList<>(); ids.add(mpId);
List<String> names = new ArrayList<>(); names.add(doc.getMpTermName());
doc.setTopLevelMpTermId(ids);
doc.setTopLevelMpTermName(names);
}
else {
doc.setTopLevelMpTermId(mpDto.getTopLevelIds());
doc.setTopLevelMpTermName(mpDto.getTopLevelNames());
}
doc.setIntermediateMpTermId(mpDto.getIntermediateIds());
doc.setIntermediateMpTermName(mpDto.getIntermediateNames());
}
// MPATH association
else if (r.getString("ontology_term_id").startsWith("MPATH:")) {
// some hard-coded stuff
doc.setOntologyDbId(24L);
doc.setAssertionType("manual");
doc.setAssertionTypeId("ECO:0000218");
doc.setMpathTermId(r.getString("ontology_term_id"));
doc.setMpathTermName(r.getString("ontology_term_name"));
}
// EMAP association
else if (r.getString("ontology_term_id").startsWith("EMAP:")) {
// some hard-coded stuff
doc.setOntologyDbId(14L);
doc.setAssertionType("manual");
doc.setAssertionTypeId("ECO:0000218");
doc.setMpathTermId(r.getString("ontology_term_id"));
doc.setMpathTermName(r.getString("ontology_term_name"));
} else {
runStatus.addError(" Found unknown ontology term: " + r.getString("ontology_term_id"));
}
expectedDocumentCount++;
genotypePhenotypeCore.addBean(doc, 30000);
count++;
}
if (skippedNotWarned.size() > 0) {
logger.info("Skipped phenotypes for derived parametersId ");
for (String key : skippedNotWarned.keySet()) {
System.out.println(" " + key + " : " + skippedNotWarned.get(key));
}
}
// Final commit to save the rest of the docs
genotypePhenotypeCore.commit();
} catch (Exception e) {
runStatus.addError(" Big error " + e.getMessage());
e.printStackTrace();
}
if (missingLifeStageCount > 0) {
logger.warn("missingLifeStageCount = " + missingLifeStageCount);
}
return count;
}
/**
*
* @param dto
* @param mpId
* @param direct direct term or ancestors
*/
protected void getMaTermsForMp(GenotypePhenotypeDTO dto, String mpId, Boolean direct) {
// get MA ids referenced from MP
Set<String> maTerms = mpMaParser.getReferencedClasses(mpId, ontologyParserFactory.VIA_PROPERTIES, "MA");
for (String maId : maTerms) {
// get info about these MA terms. In the mp-ma file the MA classes have no details but the id. For example the labels or synonyms are not there.
OntologyTermDTO ma = maParser.getOntologyTerm(maId);
if (ma != null) {
if (direct) {
dto.addAnatomyTermId(ma.getAccessionId());
dto.addAnatomyTermName(ma.getName());
} else {
dto.addIntermediateAnatomyTermId(ma.getAccessionId());
dto.addIntermediateAnatomyTermName(ma.getName());
}
if (ma.getTopLevelIds() != null) {
dto.addTopLevelAnatomyTermId(ma.getTopLevelIds());
dto.addTopLevelAnatomyTermName(ma.getTopLevelNames());
}
dto.addIntermediateAnatomyTermId(ma.getIntermediateIds());
dto.addIntermediateAnatomyTermName(ma.getIntermediateNames());
} else {
//System.out.println("Term not found in MA : " + maId+ " for mpid:"+mpId);
}
}
}
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(GenotypePhenotypeIndexer.class)
.web(WebApplicationType.NONE)
.bannerMode(Banner.Mode.OFF)
.logStartupInfo(false)
.run(args);
context.close();
}
}
| 48.179724 | 229 | 0.597944 |
532894615098f77370d10d569fb23bbb35be27f2 | 2,358 | /*
* JPPF.
* Copyright (C) 2005-2019 JPPF Team.
* http://www.jppf.org
*
* 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.jppf.ui.picklist;
import java.util.*;
/**
* Event sent by a {@link PickList} when the list of picked items changes.
* @param <T> The type of the items in the pick list.
* @author Laurent Cohen
*/
public class PickListEvent<T> extends EventObject {
/**
* The items that were added to the selection.
*/
private final List<T> addedItems;
/**
* The items that were removed from the selection.
*/
private final List<T> removedItems;
/**
* Initialize this event with the specified source {@link PickList} and picked items.
* @param pickList the {@link PickList} from which this event originates.
* @param addedItems the items that were added to the selection.
* @param removedItems the items that were removed from the selection.
*/
public PickListEvent(final PickList<T> pickList, final List<T> addedItems, final List<T> removedItems) {
super(pickList);
this.addedItems = (addedItems != null) ? addedItems : Collections.<T>emptyList();
this.removedItems = (removedItems != null) ? removedItems : Collections.<T>emptyList();
}
/**
* Get the pick list component source of this event.
* @return a {@link PickList} object.
*/
@SuppressWarnings("unchecked")
public PickList<T> getPickList() {
return (PickList<T>) getSource();
}
/**
* Get the items that were added to the selection.
* @return a list of items which may be empty but never {@code null}.
*/
public List<T> getAddedItems() {
return addedItems;
}
/**
* Get the items that were removed from the selection.
* @return a list of items which may be empty but never {@code null}.
*/
public List<T> getRemovedItems() {
return removedItems;
}
}
| 31.44 | 106 | 0.691688 |
73828622e975cfa3ea5b5731e15cfb00e80b735e | 1,380 | package com.alibaba.nacos.security.nacos;
import com.alibaba.nacos.security.nacos.users.NacosUserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
/**
* auth provider.
*
* @author wfnuser
*/
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private NacosUserDetailsServiceImpl userDetailsService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = (String) authentication.getPrincipal();
String password = (String) authentication.getCredentials();
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (!password.equals(userDetails.getPassword())) {
return new UsernamePasswordAuthenticationToken(username, null, null);
}
return null;
}
@Override
public boolean supports(Class<?> aClass) {
return aClass.equals(UsernamePasswordAuthenticationToken.class);
}
}
| 32.857143 | 99 | 0.828986 |
0e80779851a510323e11deee21b01f74d471e466 | 1,620 | /*
* Copyright (C) 2010-2019, Danilo Pianini and contributors listed in the main project's alchemist/build.gradle file.
*
* This file is part of Alchemist, and is distributed under the terms of the
* GNU General Public License, with a linking exception,
* as described in the file LICENSE in the Alchemist distribution's top directory.
*/
package it.unibo.alchemist.boundary.projectview.utils;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.InputStream;
import org.kaikikm.threadresloader.ResourceLoader;
import de.codecentric.centerdevice.javafxsvg.SvgImageLoaderFactory;
import javafx.scene.image.Image;
/**
* A class with static methods that install a SVG loader and return a SVG image.
*
*/
public final class SVGImageUtils {
private SVGImageUtils() {
}
/**
* Install the SVG loader.
*/
public static void installSvgLoader() {
SvgImageLoaderFactory.install();
}
/**
* Returns the Image of a SVG image.
*
* @param path
* The SVG image position
* @param width
* The percent width of image
* @param height
* The percent height of image
* @return The image
*/
public static Image getSvgImage(final String path, final double width, final double height) {
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
final InputStream imageStream = ResourceLoader.getResourceAsStream(path);
return new Image(imageStream, screenSize.getWidth() * width / 100, screenSize.getHeight() * height / 100, true, true);
}
}
| 30.566038 | 126 | 0.690741 |
2f5b7f287ad780267f45153a614c6009f5672654 | 7,656 | package com.oskopek.transport.persistence;
import com.oskopek.transport.model.domain.Domain;
import com.oskopek.transport.model.domain.PddlLabel;
import com.oskopek.transport.model.domain.action.*;
import com.oskopek.transport.model.plan.Plan;
import com.oskopek.transport.model.plan.SequentialPlan;
import com.oskopek.transport.model.problem.*;
import com.oskopek.transport.model.problem.Package;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* Reader and writer for {@link SequentialPlan} to and from the VAL format (supports only Transport domain plans).
* Uses regexps for parsing.
*/
public class SequentialPlanIO implements DataIO<Plan> {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final Problem problem;
private final Domain domain;
/**
* Default constructor.
*
* @param domain the associated domain
* @param problem the associated problem
*/
public SequentialPlanIO(Domain domain, Problem problem) {
this.domain = domain;
this.problem = problem;
}
/**
* Util method for serializing an action to a VAL-format plan line. Does not handle time or capacities.
*
* @param action the action to serialize
* @return a string builder containing the serialized action (without a closing parenthesis)
*/
static StringBuilder serializeActionSimple(Action action) {
StringBuilder str = new StringBuilder();
String whoName = action.getWho().getName();
str.append('(').append(action.getName()).append(' ').append(whoName).append(' ')
.append(action.getWhere().getName());
if (Drive.class.isInstance(action)) {
str.append(' ').append(action.getWhat().getName());
} else if (PickUp.class.isInstance(action)) {
str.append(' ').append(action.getWhat().getName());
} else if (Drop.class.isInstance(action)) {
str.append(' ').append(action.getWhat().getName());
} else if (Refuel.class.isInstance(action)) {
str.append(""); // intentionally empty
} else {
throw new IllegalArgumentException("Not recognized action: " + action);
}
return str;
}
/**
* Util method for serializing an action to a VAL-like format plan line. Does not handle time or capacities.
* Is only <strong>informative</strong>.
*
* @param action the action to serialize
* @return a string containing the approximately serialized action
*/
public static String toApproximateValFormat(Action action) {
return serializeActionSimple(action).append(')').toString();
}
/**
* Util method for parsing an action from a VAL-format plan line. Does not handle time.
*
* @param domain the domain to parse to
* @param problem the problem to parse to
* @param line the line to parse
* @return the parsed action
* @throws IllegalArgumentException if an error during parsing occurs
* @throws IllegalStateException if a refuel action occurs in a fuel-less domain
*/
static Action parsePlanAction(Domain domain, Problem problem, String line) {
Pattern actionPattern = Pattern.compile("\\((([-a-zA-Z0-9]+ )+([-a-zA-Z0-9]+))\\)");
Matcher matcher = actionPattern.matcher(line);
String inside;
if (matcher.find()) {
inside = matcher.group(1);
} else {
throw new IllegalArgumentException("Couldn't parse line: " + line);
}
String[] groups = inside.split(" ");
String actionName = groups[0];
Vehicle vehicle = problem.getVehicle(groups[1]);
Location where = problem.getRoadGraph().getLocation(groups[2]);
switch (actionName) {
case "drop": {
Package what = problem.getPackage(groups[3]);
return domain.buildDrop(vehicle, where, what);
}
case "pick-up": {
Package what = problem.getPackage(groups[3]);
return domain.buildPickUp(vehicle, where, what);
}
case "refuel": {
if (!domain.getPddlLabels().contains(PddlLabel.Fuel)) {
throw new IllegalStateException("Cannot have a refuel action in a domain without fuel.");
}
return domain.buildRefuel(vehicle, where);
}
case "drive": {
Location to = problem.getRoadGraph().getLocation(groups[3]);
return domain.buildDrive(vehicle, where, to, problem.getRoadGraph());
}
default:
throw new IllegalArgumentException("Unknown action name: " + actionName);
}
}
/**
* Internal capacity-aware action serialization.
*
* @param action the action to serialize
* @param curCapacity the current capacity of the current (who) vehicle
* @return the serialized VAL-format plan action line
*/
private static String serializeAction(Action action, int curCapacity) {
StringBuilder str = serializeActionSimple(action);
if (PickUp.class.isInstance(action)) {
str.append(' ').append("capacity-").append(curCapacity - 1).append(' ').append("capacity-")
.append(curCapacity);
} else if (Drop.class.isInstance(action)) {
str.append(' ').append("capacity-").append(curCapacity).append(' ').append("capacity-")
.append(curCapacity + 1);
}
str.append(')');
return str.toString();
}
@Override
public synchronized String serialize(Plan plan) {
if (plan == null) {
return null;
}
Map<String, Integer> capacityMap = new HashMap<>();
StringBuilder builder = new StringBuilder();
for (Action action : plan.getActions()) {
Vehicle vehicle = (Vehicle) action.getWho();
int capacity = capacityMap.computeIfAbsent(vehicle.getName(), v -> vehicle.getCurCapacity().getCost());
builder.append(serializeAction(action, capacity)).append('\n');
if (action instanceof PickUp) {
capacity--;
if (capacity < 0) {
logger.warn("Cur capacity cannot be less than zero capacity.");
}
} else if (action instanceof Drop) {
capacity++;
if (capacity > vehicle.getMaxCapacity().getCost()) {
logger.warn("Cur capacity cannot be bigger than max capacity.");
}
}
capacityMap.put(vehicle.getName(), capacity);
}
ActionCost totalCost = plan.getActions().stream().map(Action::getCost).reduce(ActionCost.ZERO,
ActionCost::add);
if (totalCost != null) {
builder.append("; cost = ").append(totalCost.getCost()).append(" (general cost)");
}
return builder.toString();
}
@Override
public SequentialPlan parse(String contents) {
List<Action> actions = Arrays.stream(contents.split("\n")).map(s -> {
int index = s.indexOf(';');
return index >= 0 ? s.substring(0, index) : s;
}).filter(s -> !s.isEmpty()).map(s -> SequentialPlanIO.parsePlanAction(domain, problem, s)).collect(
Collectors.toList());
return new SequentialPlan(actions);
}
}
| 40.08377 | 115 | 0.613114 |
d6729f6991fe6264a7b2c1e9660d129e92a4b32d | 143 | package com.solar.event;
public class EventPlayerLiving extends Event {
public EventPlayerLiving(Type type) {
super(type);
}
}
| 14.3 | 46 | 0.699301 |
7df2879d50e231ebbcf540098231bb2aea844a3f | 559 | package fr.info.game.graphics.texture;
public class TextureSprite {
private TextureAtlas parentAtlas;
public final String name;
public final int x;
public final int y;
public final int width;
public final int height;
public TextureSprite(String name, int x, int y, int width, int height) {
this.name = name;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public TextureAtlas getParentAtlas() {
return parentAtlas;
}
public void setParentAtlas(TextureAtlas parentAtlas) {
this.parentAtlas = parentAtlas;
}
}
| 19.964286 | 73 | 0.726297 |
15b98cb0a64d86af290ae3242ca816590fb70923 | 557 | package com.rest.RESTfulExample.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PingPong {
@GetMapping("/host")
public ResponseEntity<?> getHost(HttpServletRequest request) {
return ResponseEntity.ok(request.getHeader("host"));
}
@GetMapping("/ping")
public ResponseEntity<?> ping() {
return ResponseEntity.ok("pong");
}
}
| 25.318182 | 64 | 0.773788 |
e68f48b6d22b941ed458284318c92caf1a37455a | 3,596 | package com.holonplatform.example.app.views;
import static com.holonplatform.example.app.model.Product.CATEGORY;
import static com.holonplatform.example.app.model.Product.DESCRIPTION;
import static com.holonplatform.example.app.model.Product.ID;
import static com.holonplatform.example.app.model.Product.PRODUCT;
import static com.holonplatform.example.app.model.Product.SKU;
import static com.holonplatform.example.app.model.Product.TARGET;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.holonplatform.core.Validator;
import com.holonplatform.core.datastore.Datastore;
import com.holonplatform.core.datastore.DefaultWriteOption;
import com.holonplatform.core.exceptions.DataAccessException;
import com.holonplatform.vaadin.components.Components;
import com.holonplatform.vaadin.components.PropertyInputForm;
import com.holonplatform.vaadin.navigator.ViewNavigator;
import com.holonplatform.vaadin.navigator.annotations.OnShow;
import com.holonplatform.vaadin.navigator.annotations.ViewParameter;
import com.holonplatform.vaadin.navigator.annotations.VolatileView;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.ui.Button;
import com.vaadin.ui.Notification;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.ValoTheme;
@VolatileView
@SpringView(name = "manage")
public class Manage extends VerticalLayout implements com.vaadin.navigator.View {
private static final long serialVersionUID = 1L;
@ViewParameter
private Long id;
@Autowired
private Datastore datastore;
private PropertyInputForm form;
private Button clearButton;
@PostConstruct
public void init() {
Components.configure(this)
// set margins and size full to view content
.margin().fullSize()
.addAndExpandFull(
// add a form using Product property set
form = Components.input.form().fullSize().properties(PRODUCT)
// set id as read-only
.readOnly(ID)
// set SKU as required
.required(SKU)
// set "DFT" as CATEGORY default value
.defaultValue(CATEGORY, p -> "DFT")
// add a validator to check DESCRIPTION with minimum 3 characters
.withValidator(DESCRIPTION, Validator.min(3))
// build the form
.build())
.add(Components.hl().margin().spacing()
// SAVE action
.add(Components.button().caption("Save").styleName(ValoTheme.BUTTON_PRIMARY)
.onClick(e -> save()).build())
// CLEAR action
.add(clearButton = Components.button().caption("Clear")
// clear the form
.onClick(e -> form.clear()).build())
.build());
}
@OnShow
public void load() {
// if id parameter is not null, we are in edit mode
if (id != null) {
// load the product data
form.setValue(datastore.query().target(TARGET).filter(ID.eq(id)).findOne(PRODUCT)
// throw an exception if a product with given id was not found
.orElseThrow(() -> new DataAccessException("Data not found: " + id)));
}
// enable the Clear button if not in edit mode
clearButton.setVisible(id == null);
}
@Transactional
private void save() {
// check valid and get PropertyBox value
form.getValueIfValid().ifPresent(value -> {
// save and notify
datastore.save(TARGET, value, DefaultWriteOption.BRING_BACK_GENERATED_IDS);
// notify the saved id
Notification.show("Saved [" + ((id != null) ? id : value.getValue(ID)) + "]");
// go back home
ViewNavigator.require().navigateToDefault();
});
}
}
| 33.924528 | 84 | 0.734983 |
658ff1edf03a01dc9a0ff7cf9b383bf368e54269 | 695 | package me.j360.dubbo.base.exception;
/**
* Package: me.j360.dubbo.base.exception
* User: min_xu
* Date: 16/8/23 下午2:01
* 说明:
*/
public class RepositoryException extends RuntimeException{
private static final long serialVersionUID = -6438755184394143413L;
protected int exceptionCode = -1;
public int getExceptionCode() {
return this.exceptionCode;
}
public RepositoryException(int exceptionCode,String message) {
super(message);
this.exceptionCode = exceptionCode;
}
public RepositoryException(int exceptionCode,String message, Throwable cause) {
super(message, cause);
this.exceptionCode = exceptionCode;
}
}
| 23.166667 | 83 | 0.696403 |
cb408fa98f99c525872be1aa07f2477179a4b9ab | 3,779 | /*
* 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 edu.hku.sdb.parse;
import java.util.ArrayList;
import java.util.List;
import edu.hku.sdb.catalog.DBMeta;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Joiner;
public class SelectionList implements ParseNode {
private static final Logger LOG = LoggerFactory
.getLogger(SelectionList.class);
protected List<SelectionItem> itemList;
protected SelectionItem rowID;
protected SelectionItem auxiliaryR;
protected SelectionItem auxiliaryS;
public SelectionList() {
itemList = new ArrayList<SelectionItem>();
}
public SelectionItem getRowID() {
return rowID;
}
public void setRowID(SelectionItem rowID) {
this.rowID = rowID;
}
public SelectionItem getAuxiliaryR() {
return auxiliaryR;
}
public void setAuxiliaryR(SelectionItem auxiliaryR) {
this.auxiliaryR = auxiliaryR;
}
public SelectionItem getAuxiliaryS() {
return auxiliaryS;
}
public void setAuxiliaryS(SelectionItem auxiliaryS) {
this.auxiliaryS = auxiliaryS;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SelectionList))
return false;
SelectionList listObj = (SelectionList) obj;
boolean equal = itemList.equals(listObj.itemList);
if (!equal) {
LOG.debug("Two selection lists are not equal!");
}
return equal;
}
/**
* @return the itemList
*/
public List<SelectionItem> getItemList() {
return itemList;
}
/**
* @param itemList the itemList to set
*/
public void setItemList(List<SelectionItem> itemList) {
this.itemList = itemList;
}
/**
* @see edu.hku.sdb.parse.ParseNode#analyze(edu.hku.sdb.catalog.DBMeta)
*/
@Override
public void analyze(DBMeta dbMeta, ParseNode... fieldSources)
throws SemanticException {
for (SelectionItem item : itemList)
item.analyze(dbMeta, fieldSources);
}
/*
* (non-Javadoc)
*
* @see edu.hku.sdb.parse.ParseNode#toSql()
*/
@Override
public String toSql() {
List<String> items = new ArrayList<String>();
for (SelectionItem item : itemList) {
items.add(item.toSql());
}
if(rowID != null)
items.add(rowID.toSql());
if(auxiliaryR != null)
items.add(auxiliaryR.toSql());
if(auxiliaryS != null)
items.add(auxiliaryS.toSql());
return Joiner.on(", ").join(items);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(SelectionItem item : itemList) {
sb.append("Selection Item: " + item + "\n");
}
return sb.toString();
}
/*
* (non-Javadoc)
*
* @see edu.hku.sdb.parse.ParseNode#involveSdbCol()
*/
@Override
public boolean involveEncrytedCol() {
for (SelectionItem item : itemList) {
if (item.involveEncrytedCol())
return true;
}
return false;
}
@Override
public EncryptionScheme getEncrytionScheme() {
return null;
}
}
| 22.76506 | 75 | 0.67928 |
96ef99ae862671553493bf02442f5a575d6662e1 | 440 | package com.example.mywiki.domain;
import lombok.Data;
import java.io.Serializable;
/**
* 用户
* @TableName user
*/
@Data
public class User implements Serializable {
/**
* 用户id
*/
private Long id;
/**
* 登录名
*/
private String loginName;
/**
* 昵称
*/
private String name;
/**
* 密码
*/
private String password;
private static final long serialVersionUID = 1L;
} | 12.941176 | 52 | 0.565909 |
919fce86cb086e8fe0ef9ad4ca974f88e6d2a610 | 318 | package org.nutz.cloud.config.spi;
import java.util.EventListener;
import java.util.List;
public interface ConfigureEventHandler extends EventListener {
void trigger(List<KeyEvent> events);
class KeyEvent {
public String name;
public String value;
public String action;
}
}
| 19.875 | 62 | 0.698113 |
e141462a9ae2d0934302ec292977b8d1fee6d99a | 5,418 | /*
* Copyright (c) 1998, 2010, 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.
*/
/*
* This test runs in othervm mode as it tests ClassLoader.findSystemClass
* and getSystemResource methods.
*/
/* @test
@bug 4147599 4478150
@summary In 1.2beta4-I ClassLoader loaded classes can not link
against application classes.
@run main/othervm Loader
*/
/*
* We are trying to test that certain methods of ClassLoader look at the same
* paths as they did in 1.1. To run this test on 1.1, you will have to pass
* "-1.1" as option on the command line.
*
* The required files are:
*
* - Loader.java (a 1.1 style class loader)
* - Loadee.java (source for a class that refers to Loader)
* - Loadee.classfile (to test findSystemClass)
* - Loadee.resource (to test getSystemResource)
* - java/lang/Object.class (to test getSystemResources)
*
* The extension ".classfile" is so the class file is not seen by any loader
* other than Loader. If you need to make any changes you will have to
* compile Loadee.java and rename Loadee.class to Loadee.classfile.
*/
import java.io.File;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashSet;
/**
* A 1.1-style ClassLoader. The only class it can really load is "Loadee".
* For other classes it might be asked to load, it relies on loaders set up by
* the launcher.
*/
public class Loader extends ClassLoader {
public Class loadClass(String name, boolean resolve)
throws ClassNotFoundException {
Class c = null;
try {
c = findSystemClass(name);
} catch (ClassNotFoundException cnfe) {
}
if (c == null) {
if (!name.equals("Loadee"))
throw new Error("java.lang.ClassLoader.findSystemClass() " +
"did not find class " + name);
byte[] b = locateBytes();
c = defineClass(name, b, 0, b.length);
}
if (resolve) {
resolveClass(c);
}
return c;
}
private byte[] locateBytes() {
try {
File f = new File(System.getProperty("test.src", "."),
"Loadee.classfile");
long l = f.length();
byte[] b = new byte[(int)l];
DataInputStream in =
new DataInputStream(new FileInputStream(f));
in.readFully(b);
return b;
} catch (IOException ioe) {
ioe.printStackTrace();
throw new Error("Test failed due to IOException!");
}
}
private static final int FIND = 0x1;
private static final int RESOURCE = 0x2;
private static final int RESOURCES = 0x4;
public static void main(String[] args) throws Exception {
int tests = FIND | RESOURCE | RESOURCES;
if (args.length == 1 && args[0].equals("-1.1")) {
tests &= ~RESOURCES; /* Do not run getResources test. */
}
if ((tests & FIND) == FIND) {
report("findSystemClass()");
ClassLoader l = new Loader();
Class c = l.loadClass("Loadee");
Object o = c.newInstance();
}
if ((tests & RESOURCE) == RESOURCE) {
report("getSystemResource()");
URL u = getSystemResource("Loadee.resource");
if (u == null)
throw new Exception
("java.lang.ClassLoader.getSystemResource() test failed!");
}
if ((tests & RESOURCES) == RESOURCES) {
report("getSystemResources()");
java.util.Enumeration e =
getSystemResources("java/lang/Object.class");
HashSet hs = new HashSet();
while (e.hasMoreElements()) {
URL u = (URL)e.nextElement();
if (u == null)
break;
System.out.println("url: " + u);
hs.add(u);
}
if (hs.size() != 2) {
throw
new Exception("java.lang.ClassLoader.getSystemResources()"+
" did not find all resources");
}
}
}
private static void report(String s) {
System.out.println("Testing java.lang.ClassLoader." + s + " ...");
}
}
| 34.954839 | 79 | 0.587855 |
077af80fd4d8a085b5e7e149e7930daa744e6b42 | 252 | package pkgbinternal;
public class InternalBSuperClass {
protected String doIt() {
return "from pkgbinternal.InternalBSuperClass";
}
protected String doItNotOverwritten() {
return "doItNotOverwritten";
}
}
| 21 | 56 | 0.65873 |
40da764334c7708a79d46da329aa03cd149c3f79 | 22,064 | /*
* Copyright 2014 Shape Security, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.shapesecurity.functional.data;
import com.shapesecurity.functional.Effect;
import com.shapesecurity.functional.F;
import com.shapesecurity.functional.F2;
import com.shapesecurity.functional.Pair;
import com.shapesecurity.functional.Unit;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
/**
* An immutable hash trie tree implementation.
*
* @param <K> Key type
* @param <V> Value type
*/
@CheckReturnValue
public abstract class HashTable<K, V> implements Iterable<Pair<K, V>> {
private final static Hasher<Object> EQUALITY_HASHER = new Hasher<Object>() {
@Override
public int hash(@Nonnull Object data) {
return data.hashCode();
}
@Override
public boolean eq(@Nonnull Object o, @Nonnull Object b) {
return o.equals(b);
}
};
public final static Hasher<Object> IDENTITY_HASHER = new Hasher<Object>() {
@Override
public int hash(@Nonnull Object data) {
return System.identityHashCode(data);
}
@Override
public boolean eq(@Nonnull Object o, @Nonnull Object b) {
return o == b;
}
};
@Nonnull
public final Hasher<K> hasher;
public final int length;
protected HashTable(@Nonnull Hasher<K> hasher, int length) {
super();
this.hasher = hasher;
this.length = length;
}
@SuppressWarnings("unchecked")
@Nonnull
public static <K> Hasher<K> equalityHasher() {
return (Hasher<K>) EQUALITY_HASHER;
}
@SuppressWarnings("unchecked")
@Nonnull
@Deprecated
public static <K> Hasher<K> defaultHasher() {
return HashTable.equalityHasher();
}
@SuppressWarnings("unchecked")
@Nonnull
public static <K> Hasher<K> identityHasher() {
return (Hasher<K>) IDENTITY_HASHER;
}
@Nonnull
public static <K, V> HashTable<K, V> empty(@Nonnull Hasher<K> hasher) {
return new Empty<>(hasher);
}
@Nonnull
public static <K, V> HashTable<K, V> emptyUsingEquality() {
return empty(HashTable.equalityHasher());
}
@Nonnull
public static <K, V> HashTable<K, V> emptyUsingIdentity() {
return empty(HashTable.identityHasher());
}
@Nonnull
@Deprecated
public static <K, V> HashTable<K, V> empty() {
return HashTable.emptyUsingEquality();
}
@Nonnull
@Deprecated
public static <K, V> HashTable<K, V> emptyP() {
return HashTable.emptyUsingIdentity();
}
@Nonnull
public final HashTable<K, V> put(@Nonnull K key, @Nonnull V value) {
return this.put(key, value, this.hasher.hash(key));
}
@Nonnull
public final HashTable<K, V> remove(@Nonnull K key) {
return this.remove(key, this.hasher.hash(key)).orJust(this);
}
@Nonnull
protected abstract HashTable<K, V> put(@Nonnull K key, @Nonnull V value, int hash);
@Nonnull
protected abstract Maybe<HashTable<K, V>> remove(@Nonnull K key, int hash);
@Nonnull
public final Maybe<V> get(@Nonnull K key) {
return this.get(key, this.hasher.hash(key));
}
@Nonnull
protected abstract Maybe<V> get(@Nonnull K key, int hash);
@SuppressWarnings("unchecked")
@Nonnull
public final HashTable<K, V> merge(@Nonnull HashTable<K, V> tree) {
return this.merge(tree, (a, b) -> b);
}
@Nonnull
public abstract HashTable<K, V> merge(@Nonnull HashTable<K, V> tree, @Nonnull F2<V, V, V> merger);
@Nonnull
public abstract <A> A foldLeft(@Nonnull F2<A, Pair<K, V>, A> f, @Nonnull A init);
@Nonnull
public abstract <A> A foldRight(@Nonnull F2<Pair<K, V>, A, A> f, @Nonnull A init);
@Nonnull
public ImmutableList<Pair<K, V>> entries() {
//noinspection unchecked
Pair<K, V>[] pairs = ((Pair<K, V>[]) new Pair[this.length]);
int[] i = new int[1];
this.forEach(x -> pairs[i[0]++] = x);
return ImmutableList.from(pairs);
}
public final void foreach(@Nonnull Effect<Pair<K, V>> e) {
this.forEach(e::e);
}
public abstract void forEach(@Nonnull Consumer<? super Pair<K, V>> e);
@Nonnull
public abstract Maybe<Pair<K, V>> find(@Nonnull F<Pair<K, V>, Boolean> f);
@Nonnull
public abstract <R> Maybe<R> findMap(@Nonnull F<Pair<K, V>, Maybe<R>> f);
public abstract <B> HashTable<K, B> map(@Nonnull F<V, B> f);
public boolean containsKey(@Nonnull K key) {
return this.containsKey(key, this.hasher.hash(key));
}
public abstract boolean containsKey(@Nonnull K key, int hash);
public boolean containsValue(@Nonnull V value) {
return this.find(p -> p.right == value).isJust();
}
@Nonnull
public ImmutableSet<K> keys() {
return new ImmutableSet<>(this.map(F.constant(Unit.unit)));
}
/**
* An empty hash table.
*
* @param <K> Key type
* @param <V> Value type
*/
private final static class Empty<K, V> extends HashTable<K, V> {
protected Empty(@Nonnull Hasher<K> hasher) {
super(hasher, 0);
}
@Nonnull
@Override
protected HashTable<K, V> put(@Nonnull K key, @Nonnull V value, int hash) {
return new Leaf<>(this.hasher, ImmutableList.of(new Pair<>(key, value)), hash, 1);
}
@Nonnull
@Override
protected Maybe<HashTable<K, V>> remove(@Nonnull K key, int hash) {
return Maybe.empty();
}
@Nonnull
@Override
protected Maybe<V> get(@Nonnull K key, int hash) {
return Maybe.empty();
}
@Nonnull
@Override
public HashTable<K, V> merge(@Nonnull HashTable<K, V> tree, @Nonnull F2<V, V, V> merger) {
return tree;
}
@Nonnull
@Override
public <A> A foldLeft(@Nonnull F2<A, Pair<K, V>, A> f, @Nonnull A init) {
return init;
}
@Nonnull
@Override
public <A> A foldRight(@Nonnull F2<Pair<K, V>, A, A> f, @Nonnull A init) {
return init;
}
@Override
public Iterator<Pair<K, V>> iterator() {
return new Iterator<Pair<K, V>>() {
@Override
public boolean hasNext() {
return false;
}
@Override
public Pair<K, V> next() {
throw new NoSuchElementException();
}
};
}
@Override
public void forEach(@Nonnull Consumer<? super Pair<K, V>> e) {
}
@Nonnull
@Override
public Maybe<Pair<K, V>> find(@Nonnull F<Pair<K, V>, Boolean> f) {
return Maybe.empty();
}
@Nonnull
@Override
public <R> Maybe<R> findMap(@Nonnull F<Pair<K, V>, Maybe<R>> f) {
return Maybe.empty();
}
@Override
public <B> HashTable<K, B> map(@Nonnull F<V, B> f) {
return empty(this.hasher);
}
@Override
public boolean containsKey(@Nonnull K key, int hash) {
return false;
}
}
/**
* A leaf node that contains a list of pairs where all the keys have exactly the same hash
* code.
*
* @param <K> Key type
* @param <V> Value type
*/
private final static class Leaf<K, V> extends HashTable<K, V> {
@Nonnull
private final ImmutableList<Pair<K, V>> dataList;
public int baseHash;
protected Leaf(@Nonnull Hasher<K> hasher, @Nonnull ImmutableList<Pair<K, V>> dataList, int baseHash, int length) {
super(hasher, length);
this.dataList = dataList;
this.baseHash = baseHash;
}
@Nonnull
@Override
protected HashTable<K, V> put(@Nonnull final K key, @Nonnull final V value, final int hash) {
if (hash == this.baseHash) {
Pair<Boolean, ImmutableList<Pair<K, V>>> result = this.dataList.mapAccumL((found, kvPair) -> {
if (found) {
return new Pair<>(true, kvPair);
}
if (Leaf.this.hasher.eq(kvPair.left, key)) {
return new Pair<>(true, new Pair<>(key, value));
}
return new Pair<>(false, kvPair);
}, false);
if (result.left) {
return new Leaf<>(this.hasher, result.right, hash, this.length);
}
return new Leaf<>(this.hasher, this.dataList.cons(new Pair<>(key, value)), hash, this.length + 1);
}
return this.toFork().put(key, value, hash);
}
@Nonnull
@Override
protected Maybe<HashTable<K, V>> remove(@Nonnull final K key, int hash) {
if (this.baseHash != hash) {
return Maybe.empty();
}
Pair<Boolean, ImmutableList<Pair<K, V>>> result = this.dataList.foldRight((i, p) -> {
if (p.left) {
return new Pair<>(true, p.right.cons(i));
}
if (Leaf.this.hasher.eq(i.left, key)) {
return new Pair<>(true, p.right);
}
return new Pair<>(false, p.right.cons(i));
}, new Pair<>(false, ImmutableList.empty()));
if (result.left) {
if (this.length == 1) {
return Maybe.of(empty(this.hasher));
}
return Maybe.of(new Leaf<>(this.hasher, result.right, this.baseHash, this.length - 1));
}
return Maybe.empty();
}
@SuppressWarnings("unchecked")
private Fork<K, V> toFork() {
int subHash = this.baseHash & 31;
HashTable<K, V>[] children = new HashTable[32];
children[subHash] = new Leaf<>(this.hasher, this.dataList, this.baseHash >>> 5, this.length);
return new Fork<>(this.hasher, children, this.length);
}
@Nonnull
@Override
protected Maybe<V> get(@Nonnull final K key, final int hash) {
if (this.baseHash != hash) {
return Maybe.empty();
}
Maybe<Pair<K, V>> pairMaybe = this.dataList.find(kvPair -> Leaf.this.hasher.eq(kvPair.left, key));
return pairMaybe.map(p -> p.right);
}
@SuppressWarnings("unchecked")
@Nonnull
@Override
public HashTable<K, V> merge(@Nonnull HashTable<K, V> tree, @Nonnull final F2<V, V, V> merger) {
if (tree instanceof Empty) {
return this;
} else if (tree instanceof Leaf) {
final Leaf<K, V> leaf = (Leaf<K, V>) tree;
if (leaf.baseHash == this.baseHash) {
final Pair<K, V>[] pairs = this.dataList.toArray(new Pair[this.dataList.length]);
ImmutableList<Pair<K, V>> right = leaf.dataList.foldLeft(
(@Nonnull ImmutableList<Pair<K, V>> result, @Nonnull Pair<K, V> kvPair) -> {
for (int i = 0; i < pairs.length; i++) {
if (Leaf.this.hasher.eq(pairs[i].left, kvPair.left)) {
pairs[i] = new Pair<>(pairs[i].left, merger.apply(pairs[i].right, kvPair.right));
return result;
}
}
return result.cons(kvPair);
}, ImmutableList.empty());
ImmutableList<Pair<K, V>> newList = ImmutableList.from(pairs).append(right);
return new Leaf<>(this.hasher, newList, this.baseHash, newList.length);
}
}
return this.toFork().merge(tree, merger);
}
@Nonnull
public <A> A foldLeft(@Nonnull F2<A, Pair<K, V>, A> f, @Nonnull A init) {
return this.dataList.foldLeft(f, init);
}
@Nonnull
@Override
public <A> A foldRight(@Nonnull F2<Pair<K, V>, A, A> f, @Nonnull A init) {
return this.dataList.foldRight(f, init);
}
@Override
public Iterator<Pair<K, V>> iterator() {
return dataList.iterator();
}
@Override
public void forEach(@Nonnull Consumer<? super Pair<K, V>> e) {
this.dataList.forEach(e);
}
@Nonnull
@Override
public Maybe<Pair<K, V>> find(@Nonnull F<Pair<K, V>, Boolean> f) {
return this.dataList.find(f);
}
@Nonnull
@Override
public <R> Maybe<R> findMap(@Nonnull F<Pair<K, V>, Maybe<R>> f) {
return this.dataList.findMap(f);
}
@Override
public <B> Leaf<K, B> map(@Nonnull F<V, B> f) {
return new Leaf<>(this.hasher, this.dataList.map(pair -> pair.mapRight(f)), this.baseHash, this.length);
}
@Override
public boolean containsKey(@Nonnull K key, int hash) {
return hash == this.baseHash
&& this.dataList.exists(kvPair -> Leaf.this.hasher.eq(kvPair.left, key));
}
}
private final static class Fork<K, V> extends HashTable<K, V> {
@Nonnull
private final HashTable<K, V>[] children;
private Fork(@Nonnull Hasher<K> hasher, @Nonnull HashTable<K, V>[] children, int length) {
super(hasher, length);
this.children = children;
}
@Nonnull
@Override
protected HashTable<K, V> put(@Nonnull K key, @Nonnull V value, int hash) {
int subHash = hash & 31;
HashTable<K, V>[] cloned = Fork.this.children.clone();
if (cloned[subHash] == null) {
cloned[subHash] = new Leaf<>(Fork.this.hasher, ImmutableList.empty(), hash >>> 5, 0);
}
//noinspection UnnecessaryLocalVariable
int oldLength = cloned[subHash].length;
cloned[subHash] = cloned[subHash].put(key, value, hash >>> 5);
return new Fork<>(this.hasher, cloned, this.length - oldLength + cloned[subHash].length);
}
@Nonnull
@Override
protected Maybe<HashTable<K, V>> remove(@Nonnull K key, int hash) {
final int subHash = hash & 31;
if (this.children[subHash] == null) {
return Maybe.empty();
}
Maybe<HashTable<K, V>> removed = this.children[subHash].remove(key, hash >>> 5);
return removed.map(newChild -> {
HashTable<K, V>[] cloned = Fork.this.children.clone();
cloned[subHash] = newChild;
return new Fork<>(Fork.this.hasher, cloned, Fork.this.length - 1);
});
}
@Nonnull
@Override
protected Maybe<V> get(@Nonnull K key, int hash) {
int subHash = hash & 31;
if (this.children[subHash] == null) {
return Maybe.empty();
}
return this.children[subHash].get(key, hash >>> 5);
}
@Nonnull
@Override
public Fork<K, V> merge(@Nonnull HashTable<K, V> tree, @Nonnull F2<V, V, V> merger) {
if (tree instanceof Empty) {
return this;
} else if (tree instanceof Leaf) {
Leaf<K, V> leaf = (Leaf<K, V>) tree;
return this.mergeFork(leaf.toFork(), merger);
}
return this.mergeFork(((Fork<K, V>) tree), merger);
}
@Nonnull
private Fork<K, V> mergeFork(@Nonnull Fork<K, V> tree, @Nonnull F2<V, V, V> merger) {
// Mutable array.
HashTable<K, V>[] cloned = Fork.this.children.clone();
int count = 0;
for (int i = 0; i < cloned.length; i++) {
if (cloned[i] == null) {
cloned[i] = tree.children[i];
} else if (tree.children[i] != null) {
cloned[i] = cloned[i].merge(tree.children[i], merger);
}
if (cloned[i] != null) {
count += cloned[i].length;
}
}
return new Fork<>(this.hasher, cloned, count);
}
@Nonnull
@Override
public <A> A foldLeft(@Nonnull F2<A, Pair<K, V>, A> f, @Nonnull A init) {
for (@Nullable HashTable<K, V> child : this.children) {
if (child != null) {
init = child.foldLeft(f, init);
}
}
return init;
}
@Nonnull
@Override
public <A> A foldRight(@Nonnull F2<Pair<K, V>, A, A> f, @Nonnull A init) {
for (int i = this.children.length - 1; i >= 0; i--) {
if (this.children[i] == null) {
continue;
}
init = this.children[i].foldRight(f, init);
}
return init;
}
public Iterator<Pair<K, V>> iterator() {
return new Iterator<Pair<K, V>>() {
@SuppressWarnings("unchecked")
private final HashTable<K, V>[] stack = new HashTable[Fork.this.length];
private Iterator<Pair<K, V>> currentIterator = null;
int i = 0;
{
this.stack[this.i++] = Fork.this;
}
private void updateState() {
if (currentIterator != null && currentIterator.hasNext()) {
return;
} else {
currentIterator = null;
}
while (this.i > 0) {
this.i--;
HashTable<K, V> curr = this.stack[this.i];
if (curr instanceof Fork) {
Fork<K, V> fork = (Fork<K, V>) curr;
for (HashTable<K, V> child : fork.children) {
if (child != null && child.length > 0) {
this.stack[this.i] = child;
this.i++;
}
}
} else if (curr instanceof Leaf) {
currentIterator = ((Leaf<K, V>) curr).dataList.iterator();
if (currentIterator.hasNext()) {
return;
} else {
currentIterator = null;
}
}
}
}
@Override
public boolean hasNext() {
updateState();
return currentIterator != null;
}
@Override
public Pair<K, V> next() {
updateState();
if (currentIterator == null) {
throw new NoSuchElementException();
}
return currentIterator.next();
}
};
}
@Override
public void forEach(@Nonnull Consumer<? super Pair<K, V>> e) {
for (@Nullable HashTable<K, V> child : this.children) {
if (child != null) {
child.forEach(e);
}
}
}
@Nonnull
@Override
public Maybe<Pair<K, V>> find(@Nonnull F<Pair<K, V>, Boolean> f) {
HashTable<K, V>[] children = this.children;
for (HashTable<K, V> child : children) {
if (child != null) {
Maybe<Pair<K, V>> p = child.find(f);
if (p.isJust()) {
return p;
}
}
}
return Maybe.empty();
}
@Nonnull
@Override
public <R> Maybe<R> findMap(@Nonnull F<Pair<K, V>, Maybe<R>> f) {
HashTable<K, V>[] children = this.children;
for (HashTable<K, V> child : children) {
if (child != null) {
Maybe<R> p = child.findMap(f);
if (p.isJust()) {
return p;
}
}
}
return Maybe.empty();
}
@SuppressWarnings("unchecked")
@Override
public <B> Fork<K, B> map(@Nonnull F<V, B> f) {
HashTable<K, B>[] clone = new HashTable[this.children.length];
for (int i = 0; i < clone.length; i++) {
if (this.children[i] != null) {
clone[i] = this.children[i].map(f);
}
}
return new Fork<>(this.hasher, clone, this.length);
}
@Override
public boolean containsKey(@Nonnull K key, int hash) {
int subHash = hash & 31;
return this.children[subHash] != null && this.children[subHash].containsKey(key, hash >>> 5);
}
}
}
| 33.685496 | 122 | 0.505801 |
8e103f1c7a732785dec9099b179d63c19916fecb | 12,355 | package com.smartbear.readyapi4j.cucumber;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
import com.smartbear.readyapi4j.assertions.Assertions;
import com.smartbear.readyapi4j.assertions.DefaultResponseSLAAssertionBuilder;
import com.smartbear.readyapi4j.assertions.ValidHttpStatusCodesAssertionBuilder;
import com.smartbear.readyapi4j.client.model.Assertion;
import com.smartbear.readyapi4j.client.model.Authentication;
import com.smartbear.readyapi4j.client.model.RestParameter;
import com.smartbear.readyapi4j.client.model.RestTestRequestStep;
import com.smartbear.readyapi4j.cucumber.hiptest.ActionWord;
import com.smartbear.readyapi4j.support.ContentUtils;
import com.smartbear.readyapi4j.teststeps.TestStepTypes;
import com.smartbear.readyapi4j.teststeps.restrequest.ParameterBuilder;
import cucumber.runtime.java.guice.ScenarioScoped;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Generic StepDefs for REST API Testing
*/
@ScenarioScoped
public class RestStepDefs {
private final static Logger LOG = LoggerFactory.getLogger(RestStepDefs.class);
private final CucumberRecipeBuilder builder;
private String endpoint = "";
private String method = "GET";
private String path = "";
private String requestBody;
private String token;
private String mediaType;
private List<RestParameter> parameters = Lists.newArrayList();
private Map<String, String> bodyValues = Maps.newHashMap();
private List<Assertion> assertions = Lists.newArrayList();
private RestTestRequestStep testStep;
@Inject
public RestStepDefs(CucumberRecipeBuilder recipeBuilder) {
this.builder = recipeBuilder;
}
@Given("^the oAuth2 token (.*)$")
@ActionWord( "the oAuth2 token \"oauth-token\"")
public void theOauth2Token(String token) {
this.token = CucumberUtils.stripQuotes(token);
}
@Given("^the API running at (.*)$")
@ActionWord( "the API running at \"api-endpoint\"")
public void theAPIRunningAt(String endpoint) {
this.endpoint = CucumberUtils.stripQuotes(endpoint);
}
@When("^a (.*) request to ([^ ]*) is made$")
@ActionWord( "a \"method\" request to \"path\" is made")
public void aRequestToPathIsMade(String method, String path) {
this.method = CucumberUtils.stripQuotes(method);
this.path = CucumberUtils.stripQuotes(path);
}
@When("^a (.*) request is made$")
@ActionWord( "a \"method\" request is made")
public void aRequestIsMade(String method) {
this.method = CucumberUtils.stripQuotes(method);
}
@Given("^the request body is$")
@ActionWord( value = "the request body is", addFreetext = true)
public void theRequestBodyIs(String requestBody) {
this.requestBody = requestBody;
}
@Then("^a status code of (.*) is returned$")
@ActionWord( "a status code of \"status-code\" is returned")
public void aStatusCodeIsReturned(String statusCode) {
aResponseIsReturnedWithin(statusCode, "0");
}
@Then("^a (.*) response is returned$")
@ActionWord( "a \"status-code\" response is returned")
public void aResponseIsReturned(String statusCode) {
aResponseIsReturnedWithin(statusCode, "0");
}
@Then("^a (.*) response is returned within (.*)ms$")
@ActionWord( "a \"status-code\" response is returned withing \"milliseconds\"ms" )
public void aResponseIsReturnedWithin(String statusCode, String timeoutString) {
int timeout = Integer.parseInt(CucumberUtils.stripQuotes(timeoutString));
if (timeout > 0) {
assertions.add(DefaultResponseSLAAssertionBuilder.create().maxResponseTime(String.valueOf(timeout)));
}
addAssertion(ValidHttpStatusCodesAssertionBuilder.create().validStatusCodes(
Arrays.asList(CucumberUtils.stripQuotes(statusCode))));
pushRestRequest();
}
@Then("^the response body contains$")
@ActionWord( value = "the response body contains", addFreetext = true)
public void theResponseBodyContains(String responseBody) {
addAssertion(Assertions.contains(responseBody).build());
}
@Then("^the response body matches$")
@ActionWord( value = "the response body matches", addFreetext = true)
public void theResponseBodyMatches(String responseBodyRegEx) {
addAssertion(Assertions.matches(responseBodyRegEx).build());
}
@Given("^the (.*) parameter is (.*)$")
@ActionWord( "the \"name\" parameter is \"value\"")
public void theParameterIs(String name, String value) {
name = CucumberUtils.stripQuotes(name);
value = CucumberUtils.stripQuotes(value);
ParameterBuilder parameterBuilder = (endpoint + path).contains("{" + name + "}") ?
ParameterBuilder.path(name, value) :
ParameterBuilder.query(name, value);
parameters.add(parameterBuilder.build());
}
@Given("^the (.*) header is (.*)$")
@ActionWord( "the \"name\" header is \"value\"")
public void theHeaderIs(String name, String value) {
parameters.add(ParameterBuilder.header(CucumberUtils.stripQuotes(name), CucumberUtils.stripQuotes(value)).build());
}
@Given("^the type is (.*)$")
@ActionWord("the type is \"request-content-type\"")
public void theTypeIs(String type) {
this.mediaType = CucumberUtils.stripQuotes(type);
}
@Given("^the request expects (.*)")
@ActionWord( "the request expects \"expected-content-type\"")
public void theRequestExpects(String format) {
theHeaderIs("Accept", ContentUtils.expandContentType(CucumberUtils.stripQuotes(format)));
}
@Then("^the response type is (.*)$")
@ActionWord( "the response type is \"expected-content-type\"")
public void theResponseTypeIs(String format) {
addAssertion(Assertions.contentType(CucumberUtils.stripQuotes(format)).build());
}
@Then("^the response contains a (.*) header$")
@ActionWord( "the response contains a \"header-name\" header")
public void theResponseContainsHeader(String header) {
addAssertion(Assertions.headerExists(CucumberUtils.stripQuotes(header)).build());
}
@Then("^the path (.*) equals (.*)$")
@ActionWord( value = "the path \"json-path\" equals \"expected-value\"" )
public void thePathEquals(String path, String content) {
addAssertion(Assertions.json(CucumberUtils.stripQuotes(path), CucumberUtils.stripQuotes(content)).build());
}
@Then("^the path (.*) equals")
@ActionWord( value = "the path \"json-path\" equals", addFreetext = true )
public void thePathEqualsContent(String path, String content) {
thePathMatches( path, content );
}
@Then("^the path (.*) matches (.*)$")
@ActionWord( value = "the path \"json-path\" matches \"regex-expression\"")
public void thePathMatches(String path, String content) {
addAssertion(Assertions.jsonRegEx(CucumberUtils.stripQuotes(path), CucumberUtils.stripQuotes(content)).build());
}
@Then("^the path (.*) matches$")
@ActionWord( value = "the path \"json-path\" matches", addFreetext = true)
public void thePathMatchesContent(String path, String content) {
thePathMatches( path, content );
}
@Then("^the path (.*) finds (.*) items?$")
@ActionWord( value = "the path \"json-path\" finds \"number-of-items\"")
public void thePathFinds(String path, String count) {
addAssertion(Assertions.jsonCount(CucumberUtils.stripQuotes(path), CucumberUtils.stripQuotes(count)).build());
}
@Then("^the path (.*) exists$")
@ActionWord( value = "the path \"json-path\" exists")
public void thePathExists(String path) {
addAssertion(Assertions.jsonExists(CucumberUtils.stripQuotes(path)).build());
}
@Then("^the xpath (.*) matches (.*)$")
@ActionWord( value = "the xpath \"xpath\" equals \"expected-value\"" )
public void theXPathMatches(String path, String content) {
addAssertion(Assertions.xPathContains(CucumberUtils.stripQuotes(path), CucumberUtils.stripQuotes(content)).build());
}
@Then("^the xpath (.*) matches$")
@ActionWord( value = "the xpath \"xpath\" equals", addFreetext = true )
public void theXPathMatchesContent(String path, String content) {
theXPathMatches( path, content );
}
@Then("^the response (.*) header is (.*)$")
@ActionWord( value = "the response \"response-header\" header is \"expected-value\"" )
public void theResponseHeaderIs(String header, String value) {
addAssertion(Assertions.headerValue(CucumberUtils.stripQuotes(header), CucumberUtils.stripQuotes(value)).build());
}
@Then("^the response (.*) header matches (.*)$")
@ActionWord( value = "the response \"response-header\" header matches \"regex-expression\"" )
public void theResponseHeaderMatches(String header, String regex) {
addAssertion(Assertions.headerMatches(CucumberUtils.stripQuotes(header), CucumberUtils.stripQuotes(regex)).build());
}
@Then("^the response body contains (.*)$")
@ActionWord( value = "the response body contains \"value\"" )
public void theResponseBodyContains2(String content) {
theResponseBodyContains(CucumberUtils.stripQuotes(content));
}
public RestTestRequestStep pushRestRequest() {
testStep = new RestTestRequestStep();
testStep.setURI(endpoint + path);
testStep.setMethod(method);
testStep.setType(TestStepTypes.REST_REQUEST.getName());
testStep.setAssertions(Lists.newArrayList());
testStep.setParameters(Lists.newArrayList());
if (requestBody != null) {
testStep.setRequestBody(requestBody);
testStep.setMediaType(mediaType == null ? "application/json" : mediaType);
}
if (token != null) {
Authentication authentication = new Authentication();
authentication.setAccessToken(token);
authentication.setType("OAuth 2.0");
testStep.setAuthentication(authentication);
}
if (!bodyValues.isEmpty()) {
testStep.setMediaType("application/json");
testStep.setRequestBody(ContentUtils.serializeContent(bodyValues, "application/json"));
}
if (!assertions.isEmpty()) {
testStep.getAssertions().addAll(assertions);
}
if (!parameters.isEmpty()) {
testStep.getParameters().addAll(parameters);
}
builder.addTestStep(testStep);
return testStep;
}
public void addBodyValue(String name, String value) {
bodyValues.put(name, value);
}
public void addParameter(RestParameter parameter) {
parameters.add(parameter);
}
public void addAssertion(Assertion assertion) {
if (testStep == null) {
assertions.add(assertion);
} else {
testStep.getAssertions().add(assertion);
}
}
public Map<String, String> getBodyValues() {
return bodyValues;
}
public List<Assertion> getAssertions() {
return assertions;
}
public List<RestParameter> getParameters() {
return parameters;
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getMediaType() {
return mediaType;
}
public void setMediaType(String mediaType) {
this.mediaType = mediaType;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getRequestBody() {
return requestBody;
}
public void setRequestBody(String requestBody) {
this.requestBody = requestBody;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
| 35.401146 | 124 | 0.672036 |
75fe02766529a58da7159cb4bbb9161fb6c8c87f | 918 | package ui;
import java.util.HashMap;
import java.util.Map;
/**
* Store static variables of the current simulation.
* The information stored are the current user, the current date,
* the current selected station and selected card
*/
public class UiDataStore {
private Map<String, UiData> data = new HashMap<>();
static final String CURRENT_USER = "currentUser";
static final String CURRENT_FILTER_DATE = "currentFilterDate";
static final String CURRENT_STATION = "currentStation";
static final String CURRENT_CARD = "currentCard";
public void set(String name, UiData uiData) {
if (uiData == null) {
data.put(name, new UiData<>(null));
} else {
data.put(name, uiData);
}
}
public UiData get(String name) {
UiData uiData = data.get(name);
if (uiData == null) {
return new UiData<>(null);
}
return uiData;
}
}
| 24.810811 | 66 | 0.653595 |
347c33196323717232783586b650df272edac08f | 3,340 | package com.company.cruisesample.gis.utils;
import com.vividsolutions.jts.geom.*;
import com.vividsolutions.jts.geom.util.AffineTransformation;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import org.apache.commons.lang3.StringUtils;
/**
* Created by aleksey on 10/03/2017.
*/
public class GeometryUtils {
//WGS84 datum
public static final int SRID_4326 = 4326;
public static Double getLatitude(Coordinate c) {
return c != null ? c.getOrdinate(Coordinate.Y) : null;
}
public static Double getLongitude(Coordinate c) {
return c != null ? c.getOrdinate(Coordinate.X) : null;
}
public static Double getAltitude(Coordinate c) {
return c != null ? c.getOrdinate(Coordinate.Z) : null;
}
public static Polygon wktStringToPolygon(String s) {
Geometry g = wktStringToGeometry(s);
if (g == null) {
return null;
}
if (!(g instanceof Polygon)) {
throw new RuntimeException("Polygon data expected, found " + g.getGeometryType());
}
return (Polygon) g;
}
public static LineString wktStringToLineString(String s) {
Geometry g = wktStringToGeometry(s);
if (g == null) {
return null;
}
if (!(g instanceof LineString)) {
throw new RuntimeException("LineString data expected, found " + g.getGeometryType());
}
return (LineString) g;
}
public static Point wktStringToPoint(String s) {
Geometry g = wktStringToGeometry(s);
if (g == null) {
return null;
}
if (!(g instanceof Point)) {
throw new RuntimeException("Point data expected, found " + g.getGeometryType());
}
return (Point) g;
}
public static MultiPolygon wktStringToMultiPolygon(String s) {
Geometry g = wktStringToGeometry(s);
if (g == null) {
return null;
}
if (g instanceof MultiPolygon) {
return (MultiPolygon) g;
} else if (g instanceof Polygon) {
Polygon p = (Polygon) g;
return new MultiPolygon(new Polygon[]{p}, getGeometryFactory());
} else {
throw new RuntimeException("Polygon or MultiPolygon data expected, found " + g.getGeometryType());
}
}
public static Geometry wktStringToGeometry(String s) {
if (StringUtils.isBlank(s)) {
return null;
}
WKTReader reader = new WKTReader();
Geometry g;
try {
g = reader.read(s);
} catch (ParseException e) {
throw new RuntimeException("Cannot parse Geometry data from WKT format", e);
}
if (g == null) {
return null;
}
return g;
}
public static Geometry convertTo3857SRID(Geometry geometry) {
//affine tranbsformation that switches X and Y coordinates
AffineTransformation transformation = new AffineTransformation(0, 1, 0, 1, 0, 0);
Geometry transformed = transformation.transform(geometry);
transformed.setSRID(3857);
return transformed;
}
public static GeometryFactory getGeometryFactory() {
return new GeometryFactory(new PrecisionModel(), SRID_4326);
}
}
| 29.043478 | 110 | 0.608683 |
2b98d85a1d4631a3ae8e19b6f16f6f36fa1044fa | 921 | package p005cm.aptoide.p006pt.editorial;
import p005cm.aptoide.p006pt.app.DownloadModel.Action;
import p026rx.p027b.C0132p;
/* renamed from: cm.aptoide.pt.editorial.Z */
/* compiled from: lambda */
public final /* synthetic */ class C3134Z implements C0132p {
/* renamed from: a */
private final /* synthetic */ EditorialPresenter f6492a;
/* renamed from: b */
private final /* synthetic */ EditorialDownloadEvent f6493b;
/* renamed from: c */
private final /* synthetic */ Action f6494c;
public /* synthetic */ C3134Z(EditorialPresenter editorialPresenter, EditorialDownloadEvent editorialDownloadEvent, Action action) {
this.f6492a = editorialPresenter;
this.f6493b = editorialDownloadEvent;
this.f6494c = action;
}
public final Object call(Object obj) {
return this.f6492a.mo13896a(this.f6493b, this.f6494c, (EditorialViewModel) obj);
}
}
| 31.758621 | 136 | 0.704669 |
066efd40470336f08926c6778f964518b979f054 | 1,376 | package com.rest.eskaysoftAPI.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "manfacturer")
public class Manfacturer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long manfacturerId;
private String manfacturerName;
public Manfacturer() {
super();
}
public Manfacturer(Long manfacturerId, String manfacturerName) {
super();
this.manfacturerId = manfacturerId;
this.manfacturerName = manfacturerName;
}
public Manfacturer(String manfacturerName) {
super();
this.manfacturerName = manfacturerName;
}
/**
* @return the manfacturerId
*/
public Long getManfacturerId() {
return manfacturerId;
}
/**
* @param manfacturerId
* the manfacturerId to set
*/
public void setManfacturerId(Long manfacturerId) {
this.manfacturerId = manfacturerId;
}
/**
* @return the manfacturerName
*/
public String getManfacturerName() {
return manfacturerName;
}
/**
* @param manfacturerName
* the manfacturerName to set
*/
public void setManfacturerName(String manfacturerName) {
this.manfacturerName = manfacturerName;
}
}
| 20.235294 | 65 | 0.739826 |
2fefe9a877b2ba7aa686a4631780ffe979f9c228 | 847 | package org.nutz.dao.impl.jdbc;
import java.io.File;
import java.sql.Clob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.nutz.dao.util.blob.SimpleClob;
import org.nutz.filepool.FilePool;
import org.nutz.lang.Files;
public class ClobValueAdaptor extends AbstractFileValueAdaptor {
public ClobValueAdaptor(FilePool pool) {
super(pool);
suffix = ".clob";
}
public Object get(ResultSet rs, String colName) throws SQLException {
File f = this.createTempFile();
Files.write(f, rs.getClob(colName).getAsciiStream());
return new SimpleClob(f);
}
public void set(PreparedStatement stat, Object obj, int i) throws SQLException {
if (null == obj) {
stat.setNull(i, Types.CLOB);
} else {
Clob clob = (Clob) obj;
stat.setClob(i, clob);
}
}
}
| 22.891892 | 81 | 0.731995 |
7c3fc539ef6005b2466a626e8b40737059c17044 | 3,544 | /*
* Copyright 2005-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
*
* 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.openwms.tms.impl.removal;
import org.ameba.annotation.Measured;
import org.ameba.annotation.TxService;
import org.openwms.common.transport.api.ValidationGroups;
import org.openwms.common.transport.api.commands.TUCommand;
import org.openwms.core.SpringProfiles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.transaction.event.TransactionalEventListener;
import org.springframework.util.Assert;
import javax.validation.Validator;
import static org.ameba.system.ValidationUtil.validate;
/**
* A TransportUnitRemovalListener is an AMQP listener that listens on commands when a
* TransportUnit is going to be deleted.
*
* @author Heiko Scherrer
*/
@Profile(SpringProfiles.ASYNCHRONOUS_PROFILE)
@TxService
class TransportUnitRemovalListener {
private static final Logger LOGGER = LoggerFactory.getLogger(TransportUnitRemovalListener.class);
private final TransportUnitRemovalHandler handler;
private final Validator validator;
private final AmqpTemplate amqpTemplate;
private final String exchangeName;
TransportUnitRemovalListener(TransportUnitRemovalHandler handler, Validator validator, AmqpTemplate amqpTemplate, @Value("${owms.commands.common.tu.exchange-name}") String exchangeName) {
this.handler = handler;
this.validator = validator;
this.amqpTemplate = amqpTemplate;
this.exchangeName = exchangeName;
}
@TransactionalEventListener(fallbackExecution = true)
public void onEvent(TUCommand command) {
switch (command.getType()) {
case REMOVE:
validate(validator, command, ValidationGroups.TransportUnit.Remove.class);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Sending command to finally REMOVE the TransportUnit with pKey [{}]", command.getTransportUnit().getpKey());
}
amqpTemplate.convertAndSend(exchangeName, "common.tu.command.in.remove", command);
break;
default:
}
}
@Measured
@RabbitListener(queues = "${owms.commands.common.tu.queue-name}")
public void handle(@Payload TUCommand command) {
Assert.notNull(command, "Command is null");
try {
switch(command.getType()) {
case REMOVING:
handler.preRemove(command);
break;
default:
}
} catch (Exception e) {
throw new AmqpRejectAndDontRequeueException(e.getMessage(), e);
}
}
} | 39.377778 | 191 | 0.721501 |
a1d4bc50c7ebbe09413732f546ecb5b9a0fc9322 | 568 | package io.pivotal.workshop.directory.annotation;
import io.pivotal.workshop.directory.utils.DirectoryWebClientUtilsConfiguration;
import org.springframework.context.annotation.Import;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Import(DirectoryWebClientUtilsConfiguration.class)
public @interface EnableDirectoryWebClientUtils {
Algorithm algorithm() default Algorithm.BCRYPT;
}
| 31.555556 | 80 | 0.850352 |
861c4f7a07c6f8245e50ffde6ad4e992d4aa6fb0 | 1,838 | package com.k8s.xmetrics.vo.hardware;
import com.k8s.xmetrics.vo.AbstractAgentVO;
import java.util.Collection;
/**
* @author apastoriza
*/
public class NetworkInfoVO extends AbstractAgentVO {
private String hostname;
private String domainName;
private String ipV4DefaultGateway;
private String ipV6DefaultGateway;
private Collection<NetworkInterfaceVO> networkInterfaces;
public String getHostname() {
return this.hostname;
}
public void setHostname(final String hostname) {
this.hostname = hostname;
}
public String getDomainName() {
return this.domainName;
}
public void setDomainName(final String domainName) {
this.domainName = domainName;
}
public String getIpV4DefaultGateway() {
return this.ipV4DefaultGateway;
}
public void setIpV4DefaultGateway(final String ipV4DefaultGateway) {
this.ipV4DefaultGateway = ipV4DefaultGateway;
}
public String getIpV6DefaultGateway() {
return this.ipV6DefaultGateway;
}
public void setIpV6DefaultGateway(final String ipV6DefaultGateway) {
this.ipV6DefaultGateway = ipV6DefaultGateway;
}
public Collection<NetworkInterfaceVO> getNetworkInterfaces() {
return this.networkInterfaces;
}
public void setNetworkInterfaces(final Collection<NetworkInterfaceVO> networkInterfaces) {
this.networkInterfaces = networkInterfaces;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("NetworkInfoVO{");
sb.append("hostname='").append(this.hostname).append('\'');
sb.append(", domainName='").append(this.domainName).append('\'');
sb.append(", ipV4DefaultGateway='").append(this.ipV4DefaultGateway).append('\'');
sb.append(", ipV6DefaultGateway='").append(this.ipV6DefaultGateway).append('\'');
sb.append(", networkInterfaces=").append(this.networkInterfaces);
sb.append('}');
return sb.toString();
}
}
| 26.637681 | 91 | 0.763874 |
81474f9c1fd49f09cbb87e96617c77e79362eb53 | 1,344 | package com.ruoyi.web.service.impl;
import static org.junit.Assert.*;
import com.ruoyi.RuoYiApplication;
import com.ruoyi.common.json.JSON;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.service.IZzTestService;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Created by jingchun.zhang on 2019/5/8.
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {RuoYiApplication.class})
public class ZzTestServiceImplTest {
Object ret = null;
@Autowired
IZzTestService testService;
@Autowired
ISysUserService userService;
@After
public void tearDown() throws Exception {
System.out.println(JSON.marshal(ret));
}
@Test
public void selectZzTestById() throws Exception {
ret =testService.selectZzTestById(1L);
}
@Test
public void selectZzTestList() throws Exception {
ret = userService.selectUserById(1L);
}
@Test
public void insertZzTest() throws Exception {
}
@Test
public void updateZzTest() throws Exception {
}
@Test
public void deleteZzTestByIds() throws Exception {
}
} | 23.578947 | 62 | 0.72619 |
90b1666e000c407a01559d293f560c08930aa7d0 | 394 | package com.jd.blockchain.peer;
import com.jd.blockchain.consensus.service.NodeServer;
import com.jd.blockchain.crypto.hash.HashDigest;
import com.jd.blockchain.tools.initializer.LedgerBindingConfig;
import java.util.List;
public interface LedgerBindingConfigAware {
void setConfig(LedgerBindingConfig config);
NodeServer setConfig(LedgerBindingConfig config, HashDigest ledgerHash);
}
| 26.266667 | 73 | 0.835025 |
b4e30340c9442bceb9f2d41b11313652c4b05cf0 | 203 | package com.graylogging.graylogging.log;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
public class KfMarker {
public static final Marker REQUEST = MarkerFactory.getMarker("REQUEST");
}
| 22.555556 | 76 | 0.788177 |
1837ab9fcf45947394af53d3e1130059bf719895 | 907 | package fr.wcs.wildemo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import fr.wcs.wildemo.repository.AccountRepository;
@Service
public class AuthService implements UserDetailsService {
@Autowired
private AccountRepository repo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return this.repo.findOneByUsername(username);
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
} | 32.392857 | 90 | 0.84785 |
26e95d6b36e263673a0b40790a14459bbf580338 | 5,261 | /*
* Copyright 2021 Nordnet Bank AB
* 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.
*/
import com.fasterxml.jackson.databind.JsonNode;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Arrays;
public class SimpleFeedClient {
private final Socket socket;
private String sessionKey;
private final BufferedReader in;
private final BufferedWriter out;
private final String SERVICE = "NEXTAPI";
SimpleFeedClient(JsonNode loginResponse) throws IOException {
sessionKey = loginResponse.get("session_key").asText();
String hostName = loginResponse.get("public_feed").get("hostname").asText();
int port = Integer.parseInt(loginResponse.get("public_feed").get("port").asText());
// Open an encrypted TCP connection
SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
socket = ssf.createSocket(hostName, port);
// Configure connection
socket.setSoTimeout(10000000);
socket.setKeepAlive(true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
}
public Socket getSocket() {
return socket;
}
public void closeSocket() throws IOException {
socket.close();
}
public void login() {
String loginRequest = """
{ "cmd": "login", "args": { "session_key": "%s", "service":"%s"}}\n
""".formatted(sessionKey, SERVICE);
// Always validate your JSON
Util.assertValidateJSONString(loginRequest);
try {
out.write(loginRequest);
out.flush();
} catch(IOException e) {
System.err.println("Could not write to API");
}
}
public void logout() {
// Log out of NNAPI
try {
in.close();
out.close();
closeSocket();
} catch (IOException e) {
System.err.println("Could not close feedclient connection");
}
}
public void subscribePublicFeed(String feedSubscription) throws Exception {
Util.assertValidateJSONString(feedSubscription);
out.write(feedSubscription);
out.flush();
System.out.println(">> Response from Price Feed");
String responsePriceFeed = in.readLine();
Util.prettyPrintJSON(responsePriceFeed);
}
public void printCertificateDetails() {
// Output details about certificates and session
SSLSession session = ((SSLSocket) getSocket()).getSession();
Certificate[] certificates = null;
try {
certificates = session.getPeerCertificates();
} catch (SSLPeerUnverifiedException e) {
// empty
}
SimpleFeedClient.printCertificateDetails(certificates);
SimpleFeedClient.printSessionDetails(session);
}
public static void printSessionDetails(SSLSession session) {
System.out.println(">> NAPI's certificate");
System.out.println("Peer host: " + session.getPeerHost());
System.out.println("Cipher: " + session.getCipherSuite());
System.out.println("Protocol: " + session.getProtocol());
System.out.println("ID: " + new BigInteger(session.getId()));
System.out.println("Session created: " + session.getCreationTime());
System.out.println("Session accessed: " + session.getLastAccessedTime());
}
public static void printCertificateDetails(Certificate[] certificates) {
Arrays.stream(certificates)
.map(c -> (X509Certificate)c)
.map(X509Certificate::getSubjectDN)
.forEach(System.out::println);
}
}
| 37.848921 | 107 | 0.681429 |
0c020bbcb048fb7c54b807ecc6d2a06dd064d522 | 2,235 | package nyla.solutions.commas.file;
import java.io.File;
import nyla.solutions.core.exception.RequiredException;
import nyla.solutions.core.exception.SystemException;
import nyla.solutions.core.io.IO;
import nyla.solutions.core.io.SynchronizedIO;
import nyla.solutions.core.util.Config;
import nyla.solutions.core.util.Debugger;
import nyla.solutions.core.util.Text;
/**
* This class includes the text content of a related file into the given file.
* The related file is read.
* The input text indicated by the replacementRE in the given execute method is replaced at runtime.
* @author Gregory Green
*
*/
public class ReplaceIncludeRelatedFileCommand implements FileCommand<Void>
{
/**
* Implement the file processing
* @param
*/
public Void execute(File file)
{
if(this.replacementRE == null)
throw new RequiredException("this. in ReplaceWithFormattedFileCommand");
//read RACI HTML
try
{
String includeFileContent = IO.readFile(file.getAbsolutePath()+includeFileSufix);
//applied formatting
String fileText = IO.readFile(file);
//replace text in processMapHTMLFile with formatted output
SynchronizedIO.getInstance().writeFile(file.getAbsolutePath(),Text.replaceForRegExprWith(fileText,
this.replacementRE,includeFileContent));
return null;
}
catch (Exception e)
{
throw new SystemException(Debugger.stackTrace(e));
}
}//---------------------------------------------
/**
* @return the replacementRE
*/
public String getReplacementRE()
{
return replacementRE;
}
/**
* @param replacementRE the replacementRE to set
*/
public void setReplacementRE(String replacementRE)
{
this.replacementRE = replacementRE;
}
/**
* @return the includeFileSufix
*/
public String getIncludeFileSufix()
{
return includeFileSufix;
}
/**
* @param includeFileSufix the includeFileSufix to set
*/
public void setIncludeFileSufix(String includeFileSufix)
{
this.includeFileSufix = includeFileSufix;
}
private String replacementRE = null;
private String includeFileSufix = Config.getProperty(this.getClass(),"includeFileSufix");
}
| 25.397727 | 102 | 0.697987 |
085d40ea45f770d752c78e50e5c1c11aed448134 | 2,651 | /**
* Copyright Indra Soluciones Tecnologías de la Información, S.L.U.
* 2013-2019 SPAIN
*
* 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.minsait.onesait.platform.business.services.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.minsait.onesait.platform.multitenant.MultitenancyContextHolder;
import com.minsait.onesait.platform.multitenant.Tenant2SchemaMapper;
import com.minsait.onesait.platform.multitenant.config.services.MultitenancyService;
import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
public class MultitenancyInterceptor extends HandlerInterceptorAdapter {
@Autowired
private MultitenancyService multitenancyService;
@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler)
throws Exception {
final String vertical = request.getHeader(Tenant2SchemaMapper.VERTICAL_HTTP_HEADER);
if (!StringUtils.isEmpty(vertical)) {
multitenancyService.getVerticalSchema(vertical).ifPresent(v -> {
final String tenant = request.getHeader(Tenant2SchemaMapper.TENANT_HTTP_HEADER);
MultitenancyContextHolder.setTenantName(tenant);
MultitenancyContextHolder.setVerticalSchema(v);
});
}
return true;
}
@Override
public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response,
final Object handler, final Exception ex) throws Exception {
MultitenancyContextHolder.clear();
}
public static void addMultitenantHeaders(HttpHeaders headers) {
try {
headers.add(Tenant2SchemaMapper.VERTICAL_HTTP_HEADER, MultitenancyContextHolder.getVerticalSchema());
headers.add(Tenant2SchemaMapper.TENANT_HTTP_HEADER, MultitenancyContextHolder.getTenantName());
} catch (final Exception e) {
log.error("No tenant or vertical set");
}
}
}
| 38.42029 | 117 | 0.804602 |
0714aed2ad69d6c7603c4f8b3e234282d159cb7d | 953 | package com.developer.base.utils.android.lists;
import androidx.annotation.Nullable;
import java.util.Map;
import java.util.Map.Entry;
public class BaseEntry<K, V> implements Map.Entry<K, V> {
private final K mKey;
private V mValue;
public BaseEntry(K Key, V Value) {
this.mKey = Key;
this.mValue = Value;
}
@Override
public K getKey() {
return this.mKey;
}
@Override
public V getValue() {
return this.mValue;
}
@Override
public V setValue(V value) {
V old = this.mValue;
this.mValue = value;
return old;
}
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj)
return true;
if (!(obj instanceof Map.Entry<?, ?>))
return false;
Entry<?, ?> e = (Entry<?, ?>) obj;
return this.getKey().equals(e.getKey()) && this.getValue().equals(e.getValue());
}
} | 20.717391 | 88 | 0.56978 |
2f511fa764362e958bfd7522bfaf174d68b66892 | 878 | package com.sebsonic2o.spring.basics.springin5steps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.sebsonic2o.spring.basics.springin5steps.xml.XmlPersonDAO;
public class SpringIn5StepsXmlContextApplication {
private static Logger LOGGER =
LoggerFactory.getLogger(SpringIn5StepsXmlContextApplication.class);
public static void main(String[] args) {
// Get bean from application context
try(ClassPathXmlApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml")) {
LOGGER.info("Loaded beans - {}", (Object)applicationContext.getBeanDefinitionNames());
XmlPersonDAO personDAO = applicationContext.getBean(XmlPersonDAO.class);
LOGGER.info("{} connection-{}", personDAO, personDAO.getXmlJdbcConnection());
}
}
}
| 33.769231 | 89 | 0.8041 |
36c07739d2ac4397f4a020e370990520c9f6f41b | 1,202 | /*
*
* Copyright 2017-2018 [email protected](xiaoyu)
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, see <http://www.gnu.org/licenses/>.
*
*/
package com.happylifeplat.transaction.core.netty;
import com.happylifeplat.transaction.common.netty.bean.HeartBeat;
import com.happylifeplat.transaction.core.config.TxConfig;
public interface NettyClientService {
/**
* 启动netty客户端
*/
void start(TxConfig txConfig);
/**
* 停止服务
*/
void stop();
void doConnect();
/**
* 重启
*/
void restart();
/**
* 检查状态
*
* @return TRUE 正常
*/
boolean checkState();
}
| 23.568627 | 82 | 0.685524 |
4a429b4c8c29aa0224d11e3b69cf99c88150ad60 | 6,624 | package org.artifactory.api.governance;
import org.apache.commons.lang.StringUtils;
import org.artifactory.api.maven.MavenArtifactInfo;
import org.artifactory.api.module.ModuleInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
/**
* @author Dan Feldman
* @author Chen Keinan
*/
public class ExtComponentCoordinates implements Serializable {
private static final Logger log = LoggerFactory.getLogger(ExtComponentCoordinates.class);
//Packages that are separated by '/' and have a version that consists of 4 numbers are converted to links by browsers
private static final String MAIL_COMPATIBLE_DELIMITER = ":";
//Namespace prefixes
public enum PackageType {
MAVEN("org.apache.maven"), NUGET("org.nuget"), UNSPECIFIED("");
private final String stringValue;
PackageType(final String s) {
stringValue = s;
}
public String toString() {
return stringValue;
}
}
private PackageType packageType;
private String coordinates;
private String groupId;
private String name;
private String nameSpace;
private String version;
private String externalId;
private String mailCompatibleCoordinates; // :(
public ExtComponentCoordinates() {
}
/**
* To be used only when coordinates are not used to directly resolve components (i.e.
*/
public ExtComponentCoordinates(String coordinates) {
name = "";
version = "";
packageType = PackageType.UNSPECIFIED;
this.coordinates = coordinates;
}
/**
* No groupId (i.e. NuGet)
*/
public ExtComponentCoordinates(String packageName, String packageVersion, PackageType packageType) {
this.name = StringUtils.isNotBlank(packageName) ? packageName : "";
this.version = StringUtils.isNotBlank(packageVersion) ? packageVersion : "";
this.packageType = packageType;
this.coordinates = assembleCoordinates(packageType, null, packageName, packageVersion);
}
/**
* Maven
*/
public ExtComponentCoordinates(MavenArtifactInfo artifactInfo) {
this.name = StringUtils.isNotBlank(artifactInfo.getArtifactId()) ? artifactInfo.getArtifactId() : "";
this.version = StringUtils.isNotBlank(artifactInfo.getVersion()) ? artifactInfo.getVersion() : "";
this.groupId = StringUtils.isNotBlank(artifactInfo.getGroupId()) ? artifactInfo.getGroupId() : "";
this.packageType = PackageType.MAVEN;
this.coordinates = assembleCoordinates(packageType, groupId, name, version);
}
public ExtComponentCoordinates(ModuleInfo moduleInfo, PackageType packageType) {
this.groupId = StringUtils.isNotBlank(moduleInfo.getOrganization()) ? moduleInfo.getOrganization() : "";
this.name = StringUtils.isNotBlank(moduleInfo.getModule()) ? moduleInfo.getModule() : "";
StringBuilder version = new StringBuilder(StringUtils.isNotBlank(moduleInfo.getBaseRevision())
? moduleInfo.getBaseRevision() : "");
version.append(StringUtils.isNotBlank(moduleInfo.getFolderIntegrationRevision())
? "-" + moduleInfo.getFolderIntegrationRevision() : "");
this.version = version.toString();
this.packageType = packageType;
this.coordinates = assembleCoordinates(packageType, groupId, name, this.version);
}
private String assembleCoordinates(PackageType packageType, String groupId, String name, String version) {
String delimiter = getDelimiterByPackageType(packageType);
StringBuilder coordinates = new StringBuilder();
StringBuilder mailCoordinates = new StringBuilder();
if (StringUtils.isNotBlank(groupId)) {
coordinates.append(groupId).append(delimiter);
mailCoordinates.append(groupId).append(MAIL_COMPATIBLE_DELIMITER);
}
if (StringUtils.isNotBlank(name)) {
coordinates.append(name);
mailCoordinates.append(name);
}
if (StringUtils.isNotBlank(version)) {
coordinates.append(delimiter).append(version);
mailCoordinates.append(MAIL_COMPATIBLE_DELIMITER).append(version);
}
log.debug("Creating Black Duck component coordinates for {} package: {}, version: {}, with Code Center " +
"Namespace: {}. Coordinates are: {}",
StringUtils.isBlank(groupId) ? "" : "groupId: " + groupId,
name, version, packageType, coordinates);
this.mailCompatibleCoordinates = mailCoordinates.toString();
return coordinates.toString();
}
public String getNamespace() {
return this.nameSpace;
}
public String getCoordinates() {
return coordinates;
}
public String getMailCompatibleCoordinates() {
return mailCompatibleCoordinates;
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
/**
* @return externalId if set, coordinates if not
*/
public String getExternalId() {
return StringUtils.isNotBlank(externalId) ? externalId : coordinates;
}
public void setExternalId(String externalId) {
this.externalId = externalId;
}
public boolean isValid() {
return StringUtils.isNotBlank(name) && StringUtils.isNotBlank(version) && StringUtils.isNotBlank(coordinates)
&& packageType != null;
}
private String getDelimiterByPackageType(PackageType packageType) {
if (PackageType.MAVEN.equals(packageType)) {
return ":";
} else if (PackageType.NUGET.equals(packageType)) {
return "/";
}
return "";
}
public PackageType getPackageType() {
return packageType;
}
public void setPackageType(PackageType packageType) {
this.packageType = packageType;
}
public void setCoordinates(String coordinates) {
this.coordinates = coordinates;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public void setName(String name) {
this.name = name;
}
public void setVersion(String version) {
this.version = version;
}
public void setMailCompatibleCoordinates(String mailCompatibleCoordinates) {
this.mailCompatibleCoordinates = mailCompatibleCoordinates;
}
public void setNameSpace(String nameSpace) {
this.nameSpace = nameSpace;
}
}
| 33.454545 | 121 | 0.665157 |
5a6f28dc96e5b65e8ddfc5223fa51e0522b39559 | 579 | /*
* 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 model;
import PROV.DM.Agent;
import javax.persistence.Column;
import javax.persistence.Table;
/**
*
* @author tassio
*/
@javax.persistence.Entity
@Table(name = "Agent")
public class AgentP extends Agent {
@Column
private int idUser;
public int getIdUser() {
return idUser;
}
public void setIdUser(int idUser) {
this.idUser = idUser;
}
}
| 18.09375 | 79 | 0.680484 |
e9ef89f59e3fccf49356f2aad34f452e79acbb9f | 695 | package app.xlui.algo.LeetCode.p024;
public class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode node = head.next;
head.next = swapPairs(node.next);
node.next=head;
return node;
}
public static void main(String[] args) {
Solution solution = new Solution();
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
out(solution.swapPairs(head));
}
private static void out(ListNode root ) {
while (root != null) {
System.out.print(root.val + " ");
root = root.next;
}
}
}
| 23.166667 | 44 | 0.630216 |
f87d68436109822288aa1baf838a717a164ecb30 | 1,413 | //
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.server.session;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* ProxiableSessionAttributeObjectInvocationHandler
*/
public class FooInvocationHandler implements InvocationHandler, Serializable
{
private static final long serialVersionUID = -4009478822490178554L;
private Foo foo;
public FooInvocationHandler(Foo f)
{
foo = f;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
return method.invoke(foo, args);
}
}
| 31.4 | 85 | 0.606511 |
4867425ccbb87670626804fd9e619b7c82f4f410 | 7,168 | /*******************************************************************************
* Copyright 2021 Danny Kunz
*
* 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.omnaest.utils.counter.internal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.DoubleConsumer;
import java.util.function.DoubleSupplier;
import java.util.function.LongConsumer;
import java.util.function.LongSupplier;
import java.util.function.Supplier;
import org.omnaest.utils.counter.Counter;
import org.omnaest.utils.counter.DurationProgressCounter;
import org.omnaest.utils.counter.ImmutableProgressCounter;
import org.omnaest.utils.counter.ProgressCounter;
/**
* Special counter implementation that also tracks the progress
*
* @author omnaest
*/
public class DefaultProgressCounter extends AbstractImmutableProgressCounter implements ProgressCounter
{
private Counter counter;
private AtomicReference<Supplier<Long>> maximumProvider = new AtomicReference<Supplier<Long>>(() -> Long.MAX_VALUE);
private List<DoubleSupplier> synchronizePullProgressSuppliers = new ArrayList<>();
private List<Runnable> synchronizePushOperation = new ArrayList<>();
public DefaultProgressCounter(Counter counter)
{
super(counter);
this.counter = counter;
}
@Override
public ProgressCounter withMaximum(long maximum)
{
this.maximumProvider.set(() -> maximum);
return this;
}
@Override
public ProgressCounter withMaximumProvider(Supplier<Long> maximumProvider)
{
this.maximumProvider.set(maximumProvider);
return this;
}
@Override
public ProgressCounter setProgress(double progress)
{
this.counter.accept(Math.round(progress * this.getMaximum()));
return this;
}
@Override
public void accept(double value)
{
this.setProgress(value);
}
@Override
public ProgressCounter synchronizeProgressContinouslyFrom(ProgressCounter progressCounter)
{
return this.synchronizeProgressContinouslyFrom(progressCounter, 1.0);
}
@Override
public ProgressCounter synchronizeProgressContinouslyFrom(ProgressCounter progressCounter, double weight)
{
this.synchronizePullProgressSuppliers.add(() -> weight * Optional.ofNullable(progressCounter)
.map(ProgressCounter::getProgress)
.orElse(0.0));
return this;
}
@Override
public ProgressCounter doWithProgress(DoubleConsumer progressConsumer)
{
super.doWithProgress(progressConsumer);
return this;
}
@Override
public ProgressCounter synchronizeProgressContinouslyFromAndRegisterTo(ProgressCounter progressCounter, double weight)
{
progressCounter.synchronizeProgressContinouslyTo((progress) -> this.synchronize());
return this.synchronizeProgressContinouslyFrom(progressCounter, weight);
}
@Override
public ProgressCounter synchronizeProgressContinouslyTo(ProgressCounter progressCounter)
{
return this.synchronizeProgressContinouslyTo((DoubleConsumer) progressCounter);
}
@Override
public ProgressCounter synchronizeProgressContinouslyTo(DoubleConsumer progressCounter)
{
this.synchronizePushOperation.add(() -> Optional.ofNullable(progressCounter)
.ifPresent(counter -> counter.accept(this.getProgress())));
return this;
}
@Override
public ProgressCounter synchronizeProgressContinouslyToByRegistrationTo(ProgressCounter progressCounter)
{
progressCounter.synchronizeProgressContinouslyFrom(this);
return this;
}
@Override
public ProgressCounter synchronize()
{
this.counter.synchronize();
this.runSynchronizePullOperations();
this.runSynchronizePushOperations();
return this;
}
@Override
public ProgressCounter synchronizeCountContinouslyFrom(Counter counter)
{
this.counter.synchronizeCountContinouslyFrom(counter);
return this;
}
public static ProgressCounter of(Counter counter)
{
return new DefaultProgressCounter(counter);
}
@Override
public ProgressCounter synchronizeFrom(Counter sourceCounter)
{
this.counter.synchronizeFrom(sourceCounter);
return this;
}
@Override
public ProgressCounter incrementBy(int delta)
{
this.counter.incrementBy(delta);
this.runSynchronizePushOperations();
return this;
}
@Override
public ProgressCounter increment()
{
this.counter.increment();
this.runSynchronizePushOperations();
return this;
}
private void runSynchronizePushOperations()
{
this.synchronizePushOperation.forEach(Runnable::run);
}
@Override
public ProgressCounter asProgressCounter()
{
return this;
}
@Override
public DurationProgressCounter asDurationProgressCounter()
{
return DurationProgressCounter.of(this);
}
@Override
public void accept(long value)
{
this.counter.accept(value);
this.runSynchronizePullOperations();
}
@Override
protected LongSupplier getMaximumProvider()
{
return () -> this.maximumProvider.get()
.get();
}
@Override
protected void runSynchronizePullOperations()
{
if (!this.synchronizePullProgressSuppliers.isEmpty())
{
this.setProgress(this.synchronizePullProgressSuppliers.stream()
.mapToDouble(DoubleSupplier::getAsDouble)
.sum());
}
}
@Override
public ImmutableProgressCounter asImmutableProgressCounter()
{
return this;
}
@Override
public ProgressCounter ifModulo(int modulo, LongConsumer counterConsumer)
{
super.ifModulo(modulo, counterConsumer);
return this;
}
@Override
public ProgressCounter ifModulo(int modulo, ProgressConsumer progressConsumer)
{
super.ifModulo(modulo, progressConsumer);
return this;
}
}
| 30.502128 | 137 | 0.651088 |
0c3cc184b924c4d44477e9743835d8e795e1ea56 | 947 | package com.tianjunwei.provider.web;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ComputeController {
private final Logger logger = Logger.getLogger(getClass());
@RequestMapping(value = "/add" ,method = RequestMethod.GET)
public Integer add(@RequestParam Integer a, @RequestParam Integer b) {
Integer r = a + b;
return r;
}
@RequestMapping(value = "/info" ,method = RequestMethod.GET)
public String info(){
return "success";
}
} | 31.566667 | 74 | 0.758184 |
046ce7d9e3a2160f952baa0860d789d516f212fd | 5,928 | package eu.xenit.contentcloud.blacksmith.messaging.rabbit;
import com.fasterxml.jackson.databind.JsonNode;
import com.rabbitmq.client.Channel;
import eu.xenit.contentcloud.blacksmith.model.ArtifactBuildFailed;
import eu.xenit.contentcloud.blacksmith.model.ArtifactBuildSuccess;
import eu.xenit.contentcloud.blacksmith.model.BuildRequestId;
import eu.xenit.contentcloud.blacksmith.model.RequestDetails;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.test.TestRabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.boot.autoconfigure.amqp.RabbitTemplateConfigurer;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.messaging.Message;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willReturn;
import static org.mockito.Mockito.mock;
@SpringBootTest(properties = "blacksmith.rabbitmq.enabled=true")
class ApplicationEventToRabbitmqBridgeTest {
@Configuration
@Import({RabbitmqConfiguration.class, RabbitAutoConfiguration.class})
public static class Config {
final List<Message<JsonNode>> success = new ArrayList<>();
final List<Message<JsonNode>> failed = new ArrayList<>();
@RabbitListener(queues = "build.success")
public void listenBuildSuccess(Message<JsonNode> msg) {
success.add(msg);
}
@RabbitListener(queues = "build.failed")
public void listenBuildFailed(Message<JsonNode> msg) {
failed.add(msg);
}
@Bean
public TestRabbitTemplate template(RabbitTemplateConfigurer configurer, ConnectionFactory connectionFactory) {
var template = new TestRabbitTemplate(connectionFactory);
configurer.configure(template, connectionFactory);
return template;
}
@Bean
public ConnectionFactory connectionFactory() {
ConnectionFactory factory = mock(ConnectionFactory.class);
Connection connection = mock(Connection.class);
Channel channel = mock(Channel.class);
willReturn(connection).given(factory).createConnection();
willReturn(channel).given(connection).createChannel(anyBoolean());
given(channel.isOpen()).willReturn(true);
return factory;
}
}
@Autowired
private ApplicationEventToRabbitmqBridge bridge;
@Autowired
private Config config;
@Test
void forward_buildSuccess() {
assertThat(bridge).isNotNull();
var buildRequestId = BuildRequestId.randomId();
var successEvent = new ArtifactBuildSuccess(
buildRequestId,
"rg.fr-par.scw.cloud/content-cloud-apps/holmes.dcm-api",
"docker-image",
new RequestDetails(
URI.create("https://api.content-cloud.eu/orgs/holmes/projects/dcm/changesets/a470d440-3519-4802-8576-650237c9151f"),
"api",
"docker-image"),
Map.of("deployment", "c754baf7-0db9-44ac-ad1d-da4633e44a68",
"artifact", "f5cae000-29a5-497b-b78c-806c9157918e")
);
bridge.forwardBuildSuccess(successEvent);
assertThat(config.success).singleElement()
.satisfies(msg -> assertThat(msg.getHeaders().get("contentType")).isEqualTo("application/json"))
.extracting(Message::getPayload)
.satisfies(json -> {
assertThat(json.get("id").asText()).isEqualTo(buildRequestId.toString());
assertThat(json.get("artifact").asText())
.isEqualTo("rg.fr-par.scw.cloud/content-cloud-apps/holmes.dcm-api");
assertThat(json.get("success").asBoolean()).isEqualTo(true);
assertThat(json.get("type").asText()).isEqualTo("docker-image");
});
}
@Test
void forward_buildFailed() {
assertThat(bridge).isNotNull();
var buildRequestId = BuildRequestId.randomId();
var buildFailed = new ArtifactBuildFailed(
buildRequestId,
new RequestDetails(
URI.create("https://api.content-cloud.eu/orgs/holmes/projects/dcm/changesets/a470d440-3519-4802-8576-650237c9151f"),
"api",
"docker-image"),
"I stumbled",
new String[]{ "because I'm clumsy"},
Map.of("deployment", "c754baf7-0db9-44ac-ad1d-da4633e44a68",
"artifact", "f5cae000-29a5-497b-b78c-806c9157918e")
);
bridge.forwardBuildFailed(buildFailed);
assertThat(config.failed).singleElement()
.satisfies(msg -> assertThat(msg.getHeaders().get("contentType")).isEqualTo("application/json"))
.extracting(Message::getPayload)
.satisfies(json -> {
assertThat(json.get("id").asText()).isEqualTo(buildRequestId.toString());
assertThat(json.get("success").asBoolean()).isEqualTo(false);
assertThat(json.get("reason").asText()).isEqualTo("I stumbled");
});
}
} | 42.342857 | 140 | 0.662112 |
2dcccd586c5eb4d3d3dfb3414ca7b8fc265c66e7 | 2,701 | package org.xpdojo.bank;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.xpdojo.bank.exceptions.IllegalDepositAmount;
import org.xpdojo.bank.exceptions.IllegalWithdrawAmount;
import static org.assertj.core.api.Assertions.assertThat;
public class AccountTest {
@Test
public void newAccountShouldHaveZeroBalance() {
Account account = new Account();
assertThat(account.balance()).isEqualTo(0);
}
@Test
public void depositAmountsToIncreaseExistingBalance() throws IllegalDepositAmount{
Account account = new Account();
account.deposit(10);
account.deposit(30);
assertThat(account.balance()).isEqualTo(40);
}
@Test
public void depositFractionalAmountsToIncreaseExistingBalance() throws IllegalDepositAmount {
Account account = new Account();
account.deposit(10.5d);
assertThat(account.balance()).isEqualTo(10.5d);
}
@Test
public void depositNegativeAmountsIsRefused(){
Exception exception = Assertions.assertThrows(IllegalDepositAmount.class, () -> {
Account account = new Account();
account.deposit(-10);
});
assertThat(exception.getMessage()).isEqualTo("Cannot deposit negative amount! Use withdrawal for that!");
}
@Test
public void depositFractionalNegativeAmountsIsRefused(){
Exception exception = Assertions.assertThrows(IllegalDepositAmount.class, () -> {
Account account = new Account();
account.deposit(-10.5d);
});
assertThat(exception.getMessage()).isEqualTo("Cannot deposit negative amount! Use withdrawal for that!");
}
@Test
public void refuseWithdrawlIfBalanceIsInsufficient(){
Exception exception = Assertions.assertThrows(IllegalWithdrawAmount.class, () -> {
Account account = new Account();
account.withdraw(10);
});
assertThat(exception.getMessage()).isEqualTo("Cannot withdraw any money! Insufficient balance!");
}
@Test
public void withdrawAmount() throws IllegalDepositAmount, IllegalWithdrawAmount {
Account account = new Account();
account.deposit(10);
account.withdraw(4);
assertThat(account.balance()).isEqualTo(6);
}
@Test
public void transferMoneyBetweenAccounts() throws IllegalDepositAmount, IllegalWithdrawAmount {
Account account1 = new Account();
Account account2 = new Account();
account1.deposit(10);
account1.transfer(2, account2);
assertThat(account1.balance()).isEqualTo(8);
assertThat(account2.balance()).isEqualTo(2);
}
}
| 33.7625 | 113 | 0.677157 |
eb90473234917a255985f54c3013f99e9b34651e | 1,232 | package replicatedWindow.jitter;
import replicatedWindow.AReplicatedWindowsComposerAndLauncher;
import replicatedWindow.AliceReplicatedWindows;
import replicatedWindow.CommunicatorBasedComposerAndLauncher;
import im.IMComposerAndLauncher;
import im.delay.p2p.CathyP2PIM;
import trace.im.IMTracerSetter;
import util.session.Communicator;
import util.trace.Tracer;
public class AliceJitteryReplicatedWindows extends AliceReplicatedWindows{
public static final int DELAY_TO_CATHY = 1000;
public static final int DELAY_VARIATION = 2000;
public static void main (String[] args) {
String[] launcherArgs = {SESSION_SERVER_HOST, SESSION_NAME, USER_NAME, APPLICATION_NAME, Communicator.DIRECT};
// Tracer.showInfo(true);
// IMTracerSetter.traceIM();
CommunicatorBasedComposerAndLauncher aCommunicatorBasedComposerAndLauncher =
new AReplicatedWindowsComposerAndLauncher();
aCommunicatorBasedComposerAndLauncher.composeAndLaunch(launcherArgs);
delayToCathy(aCommunicatorBasedComposerAndLauncher.getCommunicator());
}
public static void delayToCathy(Communicator aCommunicator) {
aCommunicator.setMinimumDelayToPeer(CathyP2PIM.USER_NAME, DELAY_TO_CATHY);
aCommunicator.setDelayVariation(DELAY_VARIATION);
}
}
| 38.5 | 114 | 0.840909 |
fd0bb640605a0cdbb7e888e25c7d197e24ebe20b | 549 | package com.bowyer.app.parsesendclient;
/**
* Created by Bowyer on 2015/08/02.
*/
public class ParsePushDto {
public Object data;
public String[] channels;
public String push_time;
public ParsePushDto setParsePushModel(Object model) {
this.data = model;
return this;
}
public ParsePushDto setChannels(String[] channels) {
this.channels = channels;
return this;
}
public ParsePushDto setPushTime(String pushTime) {
this.push_time = pushTime;
return this;
}
}
| 20.333333 | 57 | 0.64663 |
5ee59523fe6bcd32766ff09f302f4ff93fef1f98 | 2,057 | package org.apache.tomcat.dbcp.dbcp.ext;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory;
public class EncryptDatasourceFactory extends BasicDataSourceFactory {
// common key for encryption and decryption
private static final String ENC_KEY = "EncryptDatasourceFactory";
public EncryptDatasourceFactory() {
}
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception {
if (obj instanceof Reference) {
setUsername((Reference) obj);
setPassword((Reference) obj);
}
return super.getObjectInstance(obj, name, nameCtx, environment);
}
private void setUsername(Reference ref) throws Exception {
findDecryptAndReplace("username", ref);
}
private void setPassword(Reference ref) throws Exception {
findDecryptAndReplace("password", ref);
}
private void findDecryptAndReplace(String refType, Reference ref) throws Exception {
int idx = find(refType, ref);
String decrypted = decrypt(idx, ref);
replace(idx, refType, decrypted, ref);
}
private void replace(int idx, String refType, String newValue, Reference ref) throws Exception {
ref.remove(idx);
ref.add(idx, new StringRefAddr(refType, newValue));
}
private String decrypt(int idx, Reference ref) throws Exception {
CipherEncrypter c = new CipherEncrypter(ENC_KEY, "AES");
return c.decrypt(c.statickey(), ref.get(idx).getContent().toString());
}
private int find(String addrType, Reference ref) throws Exception {
Enumeration enu = ref.getAll();
for (int i = 0; enu.hasMoreElements(); i++) {
RefAddr addr = (RefAddr) enu.nextElement();
if (addr.getType().compareTo(addrType) == 0)
return i;
}
throw new Exception("The \"" + addrType + "\" name/value pair was not found" + " in the Reference object. The reference Object is" + " "
+ ref.toString());
}
}
| 30.25 | 139 | 0.742343 |
764940df53b761beebb6e4742c80079ed5913b5f | 2,113 | package com.nepxion.discovery.platform.server.tool;
/**
* <p>Title: Nepxion Discovery</p>
* <p>Description: Nepxion Discovery</p>
* <p>Copyright: Copyright (c) 2017-2050</p>
* <p>Company: Nepxion</p>
*
* @author Ning Zhang
* @version 1.0
*/
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
public class DateTool {
private static final DateFormat DATA_SEQUENCE_FORMAT = new SimpleDateFormat("yyyyMMdd");
private static final DateFormat TIME_SEQUENCE_FORMAT = new SimpleDateFormat("yyyyMMddhhmmssSSS");
private static final List<DateFormat> DATE_FORMAT_LIST = Arrays.asList(
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"),
new SimpleDateFormat("yyyy-MM-dd hh:mm"),
new SimpleDateFormat("yyyy-MM-dd"),
new SimpleDateFormat("yyyy-MM"),
new SimpleDateFormat("yyyy/MM/dd hh:mm:ss"),
new SimpleDateFormat("yyyy/MM/dd hh:mm"),
new SimpleDateFormat("yyyy/MM/dd"),
new SimpleDateFormat("yyyy/MM"),
new SimpleDateFormat("yyyy.MM.dd hh:mm:ss"),
new SimpleDateFormat("yyyy.MM.dd hh:mm"),
new SimpleDateFormat("yyyy.MM.dd"),
new SimpleDateFormat("yyyy.MM")
);
public static Date parse(String value) {
if (StringUtils.isEmpty(value)) {
return null;
}
Date result = null;
for (DateFormat dateFormat : DATE_FORMAT_LIST) {
try {
result = dateFormat.parse(value);
} catch (ParseException ignored) {
}
}
if (result == null) {
throw new IllegalArgumentException(String.format("Invalid date value [%s]", value));
}
return result;
}
public static String getDataSequence() {
return DATA_SEQUENCE_FORMAT.format(new Date());
}
public static String getTimeSequence() {
return TIME_SEQUENCE_FORMAT.format(new Date());
}
} | 31.073529 | 101 | 0.632276 |
5b0ed45445a6148a61df22047cfb1556166ab80e | 1,196 | package twijava.oauth;
import twijava.encode.ParamEncoder;
import java.util.TreeMap;
public class OAuthHeaderFactory {
public static String makeOAuthHeader(String signature,TreeMap<String,String> oAuthParam,
String cks,String ats) throws Exception{
String compoKey = ParamEncoder.encode(cks)+"&"+ ParamEncoder.encode(ats);
String oauthSignature = OAuthBasicCodeFactory.makeBasicCode(signature,compoKey);
String encodedSignature = ParamEncoder.encode(oauthSignature);
//esape data strings
String authHeaderTemp="OAuth oauth_consumer_key=\"%s\", oauth_nonce=\"%s\", oauth_signature=\"%s\", " +
"oauth_signature_method=\"%s\", oauth_timestamp=\"%s\", oauth_token=\"%s\", oauth_version=\"%s\"";
return String.format(authHeaderTemp,
oAuthParam.get("oauth_consumer_key"),
oAuthParam.get("oauth_nonce"),
encodedSignature,
oAuthParam.get("oauth_signature_method"),
oAuthParam.get("oauth_timestamp"),
oAuthParam.get("oauth_token"),
oAuthParam.get("oauth_version"));
}
}
| 36.242424 | 114 | 0.635452 |
0d79bd2e43f872ea3cfa111627f9b213e334c30f | 5,375 | package org.bkpathak.ds.linklist;
/**
* Created by bijay on 1/24/16.
* Basic Least Recently Used Cache Implementation
*
*/
public class LRUCache {
// A QNode implemented using doubly LinkedList
class QNode {
QNode prev, next;
int pageNumber;
QNode(int pageNumber) {
this.pageNumber = pageNumber;
this.prev = null;
this.next = null;
}
}
// A Hash pointing to the QNode
class Hash {
int capacity; // Capacity of Hash
QNode[] array; // An array of QNode
Hash(int capacity) {
this.capacity = capacity;
// Array of pointers to refer to QNode
this.array = new QNode[capacity];
//Initialize it to NULL
for (int i = 0; i < this.capacity; i++) {
this.array[i] = null;
}
}
}
// A Cache implementation of QNode
int count; // Number of filled frames in Cache
int totalFrame; // Total number of frame available
QNode front, rear;
Hash hash;
// Create Queue to hold at most totalFrame
LRUCache(int totalFrame) {
this.count = 0;
this.front = this.rear = null;
this.totalFrame = totalFrame;
this.hash = new Hash(totalFrame);
}
// Check if the frames are full or not.
boolean areFramesFull(){
return this.count == this.totalFrame;
}
// Check if Cache is empty
boolean isCacheEmpty(){
return this.rear == null;
}
// Delete frame from Cache(Queueu)
// We'll always remove from the rear of the cache list
void deleteFrame(){
if (!isCacheEmpty()){
// If this is only node in cache , then change front
if (this.front == this.rear){
this.front = null;
}
//Move the rear to previous
this.rear = rear.prev;
// Set the rear next to null
this.rear.next = null;
// Decrease the count of frames in cache
this.count --;
}
}
// Add page to Cache and Hash.
// We'll add the page at the front of the cache list
// And put the page in the hash with pageNumber as Key
void addFrame(int pageNumber){
// If cache is full, remove the element from the rear of the cache list
if (areFramesFull()){
deleteFrame();
}
// Create the new node with given page number
QNode new_node = new QNode(pageNumber);
// Add the node to the front of the queue
new_node.next = this.front;
// If cache is empty, change both front and rear to point to the new_node
if (isCacheEmpty()){
this.front = this.rear = new_node;
}
else{
// Change the front to point to the new_node
this.front.prev = new_node;
this.front = new_node;
}
// Add page entry to the Hash
this.hash.array[pageNumber] = new_node;
// Increase the count of frames
this.count ++;
}
// If page is not in cache; bring the page and add to the front of the cache.
// If already present in cache; move the page to the front of the cache
void referencePage(int pageNumber){
QNode requestPage = this.hash.array[pageNumber];
// If page is not in cache
if (requestPage == null){
this.addFrame(pageNumber);
}
else{
// Page is already in cache; move it to the front of the cache.
// First remove the page from it's current location
requestPage.prev.next = requestPage.next;
// Check if requestPage is the rear node in the cache list
if (requestPage == this.rear){
this.rear = requestPage.prev;
this.rear.next = null;
}
// Put the requestPage at the front of the cache list
requestPage.next = this.front;
requestPage.prev = null;
// Change the previous of current front to point to the requestPage
this.front.prev = requestPage;
// Change the front to point to the requestPage;
this.front = requestPage;
}
}
void displayCache(){
// Display the current pages in Cache
QNode temp = this.front;
while(temp != null){
System.out.print(temp.pageNumber + " ");
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args){
// Create the LRU Cache of size 10
LRUCache cache = new LRUCache(10);
// Page referenced are numbered from 0 to 9.
// The order of reference is
// 3 -> 6 -> 8 -> 3 -> 1 -> 2 -> 6
System.out.println("Page reference order: 3 -> 6 -> 8 -> 3 -> 1 -> 2 -> 6");
cache.referencePage(3);
cache.referencePage(6);
cache.referencePage(8);
System.out.print("Current pages in Cache: ");
cache.displayCache();
System.out.println("Page 3 is reference again.");
cache.referencePage(3);
cache.displayCache();
cache.referencePage(1);
cache.referencePage(2);
cache.referencePage(6);
System.out.print("Current pages in Cache: ");
cache.displayCache();
}
}
| 29.696133 | 84 | 0.559442 |
5491e8914d7cd631594a822004def5bc8fc6d93b | 300 | package me.shanepelletier.sequenceomatic;
import java.io.File;
import java.io.IOException;
public class SequenceFileReader implements IterableCollection {
@Override
public CustomIterator createIterator(File file) throws IOException {
return new SequenceFileIterator(file);
}
}
| 23.076923 | 72 | 0.776667 |
fc6ee8918bcf82ebfdbb872cc95dad41a57dd073 | 22,268 | package org.checkerframework.framework.util.typeinference.solver;
import org.checkerframework.framework.type.AnnotatedTypeFactory;
import org.checkerframework.framework.type.AnnotatedTypeMirror;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable;
import org.checkerframework.framework.util.typeinference.TypeArgInferenceUtil;
import org.checkerframework.framework.util.typeinference.solver.InferredValue.InferredTarget;
import org.checkerframework.framework.util.typeinference.solver.InferredValue.InferredType;
import org.checkerframework.framework.util.typeinference.solver.TargetConstraints.Equalities;
import org.checkerframework.javacutil.ErrorReporter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeVariable;
/**
* EqualitiesSolver infers type arguments for targets using the equality constraints in ConstraintMap. When
* a type is inferred, it rewrites the remaining equality/supertype constraints
*/
public class EqualitiesSolver {
private boolean dirty = false;
/**
* For each target,
* if there is one or more equality constraints involving concrete types that lets us infer a
* primary annotation in all qualifier hierarchies then infer a concrete type argument.
* else if there is one or more equality constraints involving other targets that lets us
* infer a primary annotation in all qualifier hierarchies then infer that type argument
* is the other type argument
*
* if we have inferred either a concrete type or another target as type argument
* rewrite all of the constraints for the current target to instead use the inferred type/target
*
*
* We do this iteratively until NO new inferred type argument is found
*
*
* @param targets The list of type parameters for which we are inferring type arguments
* @param constraintMap The set of constraints over the set of targets
* @return A Map( {@code target -> inferred type or target })
*/
public InferenceResult solveEqualities(Set<TypeVariable> targets, ConstraintMap constraintMap, AnnotatedTypeFactory typeFactory) {
final InferenceResult solution = new InferenceResult();
do {
dirty = false;
for (TypeVariable target : targets) {
if (solution.containsKey(target)) {
continue;
}
Equalities equalities = constraintMap.getConstraints(target).equalities;
InferredValue inferred = mergeConstraints(target, equalities, solution, constraintMap, typeFactory);
if (inferred != null) {
if (inferred instanceof InferredType) {
rewriteWithInferredType(target, ((InferredType) inferred).type, constraintMap);
} else {
rewriteWithInferredTarget(target, ((InferredTarget) inferred).target, constraintMap, typeFactory);
}
solution.put(target, inferred);
}
}
} while (dirty);
solution.resolveChainedTargets();
return solution;
}
/**
* Let Ti be a target type parameter.
* When we reach this method we have inferred an argument, Ai, for Ti
*
* However, there still may be constraints of the form Ti = Tj, Ti <: Tj, Tj <: Ti in the constraint map. In this
* case we need to replace Ti with the type. That is, they become Ai = Tj, Ai <: Tj, and Tj <: Ai
*
* To do this, we find the TargetConstraints for Tj and add these constraints to the appropriate map
* in TargetConstraints. We can then clear the constraints for the current target since we have inferred a type.
*
* @param target The target for which we have inferred a concrete type argument
* @param type the type inferred
*/
private void rewriteWithInferredType(final TypeVariable target, final AnnotatedTypeMirror type, final ConstraintMap constraints) {
final TargetConstraints targetRecord = constraints.getConstraints(target);
final Map<TypeVariable, Set<AnnotationMirror>> equivalentTargets = targetRecord.equalities.targets;
//each target that was equivalent to this one needs to be equivalent in the same hierarchies as the inferred type
for (final Entry<TypeVariable, Set<AnnotationMirror>> eqEntry : equivalentTargets.entrySet()) {
constraints.addTypeEqualities(eqEntry.getKey(), type, eqEntry.getValue());
}
for (TypeVariable otherTarget : constraints.getTargets()) {
if (otherTarget != target) {
final TargetConstraints record = constraints.getConstraints(otherTarget);
//each target that was equivalent to this one needs to be equivalent in the same hierarchies as the inferred type
final Set<AnnotationMirror> hierarchies = record.equalities.targets.get(target);
if (hierarchies != null) {
record.equalities.targets.remove(target);
constraints.addTypeEqualities(otherTarget, type, hierarchies);
}
//otherTypes may have AnnotatedTypeVariables of type target, run substitution on these with type
Map<AnnotatedTypeMirror, Set<AnnotationMirror>> toIterate = new LinkedHashMap<>(record.equalities.types);
record.equalities.types.clear();
for (AnnotatedTypeMirror otherType : toIterate.keySet()) {
final AnnotatedTypeMirror copy = TypeArgInferenceUtil.substitute(target, type, otherType);
final Set<AnnotationMirror> otherHierarchies = toIterate.get(otherType);
record.equalities.types.put(copy, otherHierarchies);
}
}
}
for (TypeVariable otherTarget : constraints.getTargets()) {
if (otherTarget != target) {
final TargetConstraints record = constraints.getConstraints(otherTarget);
//each target that was equivalent to this one needs to be equivalent in the same hierarchies as the inferred type
final Set<AnnotationMirror> hierarchies = record.supertypes.targets.get(target);
if (hierarchies != null) {
record.supertypes.targets.remove(target);
constraints.addTypeEqualities(otherTarget, type, hierarchies);
}
//otherTypes may have AnnotatedTypeVariables of type target, run substitution on these with type
Map<AnnotatedTypeMirror, Set<AnnotationMirror>> toIterate = new LinkedHashMap<>(record.supertypes.types);
record.supertypes.types.clear();
for (AnnotatedTypeMirror otherType : toIterate.keySet()) {
final AnnotatedTypeMirror copy = TypeArgInferenceUtil.substitute(target, type, otherType);
final Set<AnnotationMirror> otherHierarchies = toIterate.get(otherType);
record.supertypes.types.put(copy, otherHierarchies);
}
}
}
targetRecord.equalities.clear();
targetRecord.supertypes.clear();
}
/**
* Let Ti be a target type parameter.
* When we reach this method we have inferred that Ti has the exact same argument as another target Tj
*
* Therefore, we want to stop solving for Ti and instead wait till we solve for Tj and use that result.
*
* Let ATM be any annotated type mirror and Tk be a target type parameter where k != i and k != j
* Even though we've inferred Ti = Tj, there still may be constraints of the form Ti = ATM or Ti <: Tk
* These constraints are still useful for inferring a argument for Ti/Tj. So, we replace Ti in these
* constraints with Tj and place those constraints in the TargetConstraints object for Tj.
*
* We then clear the constraints for Ti.
*
* @param target The target for which we know another target is exactly equal to this target
* @param inferredTarget the other target inferred to be equal
*/
private void rewriteWithInferredTarget(final TypeVariable target, final TypeVariable inferredTarget, final ConstraintMap constraints,
final AnnotatedTypeFactory typeFactory) {
final TargetConstraints targetRecord = constraints.getConstraints(target);
final Map<AnnotatedTypeMirror, Set<AnnotationMirror>> equivalentTypes = targetRecord.equalities.types;
final Map<AnnotatedTypeMirror, Set<AnnotationMirror>> supertypes = targetRecord.supertypes.types;
//each type that was equivalent to this one needs to be equivalent in the same hierarchies to the inferred target
for (final Entry<AnnotatedTypeMirror, Set<AnnotationMirror>> eqEntry : equivalentTypes.entrySet()) {
constraints.addTypeEqualities(inferredTarget, eqEntry.getKey(), eqEntry.getValue());
}
for (final Entry<AnnotatedTypeMirror, Set<AnnotationMirror>> superEntry : supertypes.entrySet()) {
constraints.addTypeSupertype(inferredTarget, superEntry.getKey(), superEntry.getValue());
}
for (TypeVariable otherTarget : constraints.getTargets()) {
if (otherTarget != target && otherTarget != inferredTarget) {
final TargetConstraints record = constraints.getConstraints(otherTarget);
//each target that was equivalent to this one needs to be equivalent in the same hierarchies as the inferred target
final Set<AnnotationMirror> hierarchies = record.equalities.targets.get(target);
if (hierarchies != null) {
record.equalities.targets.remove(target);
constraints.addTargetEquality(otherTarget, inferredTarget, hierarchies);
}
//otherTypes may have AnnotatedTypeVariables of type target, run substitution on these with type
Map<AnnotatedTypeMirror, Set<AnnotationMirror>> toIterate = new LinkedHashMap<>(record.equalities.types);
record.equalities.types.clear();
for (AnnotatedTypeMirror otherType : toIterate.keySet()) {
final AnnotatedTypeMirror copy = TypeArgInferenceUtil.substitute(target, createAnnotatedTypeVar(target, typeFactory), otherType);
final Set<AnnotationMirror> otherHierarchies = toIterate.get(otherType);
record.equalities.types.put(copy, otherHierarchies);
}
}
}
for (TypeVariable otherTarget : constraints.getTargets()) {
if (otherTarget != target && otherTarget != inferredTarget) {
final TargetConstraints record = constraints.getConstraints(otherTarget);
final Set<AnnotationMirror> hierarchies = record.supertypes.targets.get(target);
if (hierarchies != null) {
record.supertypes.targets.remove(target);
constraints.addTargetSupertype(otherTarget, inferredTarget, hierarchies);
}
//otherTypes may have AnnotatedTypeVariables of type target, run substitution on these with type
Map<AnnotatedTypeMirror, Set<AnnotationMirror>> toIterate = new LinkedHashMap<>(record.supertypes.types);
record.supertypes.types.clear();
for (AnnotatedTypeMirror otherType : toIterate.keySet()) {
final AnnotatedTypeMirror copy = TypeArgInferenceUtil.substitute(target, createAnnotatedTypeVar(target, typeFactory), otherType);
final Set<AnnotationMirror> otherHierarchies = toIterate.get(otherType);
record.supertypes.types.put(copy, otherHierarchies);
}
}
}
targetRecord.equalities.clear();
targetRecord.supertypes.clear();
}
/**
* Creates a declaration AnnotatedTypeVariable for TypeVariable.
*/
private AnnotatedTypeVariable createAnnotatedTypeVar(final TypeVariable typeVariable, final AnnotatedTypeFactory typeFactory) {
return (AnnotatedTypeVariable) typeFactory.getAnnotatedType(typeVariable.asElement());
}
/**
*
* @param typesToHierarchies A mapping of (types -> hierarchies) that indicate that the argument being inferred
* is equal to the types in each of the hierarchies
* @param primaries A map (hierarchy -> annotation in hierarchy) where the annotation in hierarchy is equal to
* the primary annotation on the argument being inferred
* @param tops The set of top annotations in the qualifier hierarchy
* @return A concrete type argument or null if there was not enough information to infer one
*/
private InferredType mergeTypesAndPrimaries(
Map<AnnotatedTypeMirror, Set<AnnotationMirror>> typesToHierarchies,
Map<AnnotationMirror, AnnotationMirror> primaries,
final Set<? extends AnnotationMirror> tops) {
final Set<AnnotationMirror> missingAnnos = new HashSet<>(tops);
Iterator<Entry<AnnotatedTypeMirror, Set<AnnotationMirror>>> entryIterator = typesToHierarchies.entrySet().iterator();
if (!entryIterator.hasNext()) {
ErrorReporter.errorAbort("Merging a list of empty types!");
}
final Entry<AnnotatedTypeMirror, Set<AnnotationMirror>> head = entryIterator.next();
AnnotatedTypeMirror mergedType = head.getKey();
missingAnnos.removeAll(head.getValue());
//1. if there are multiple equality constraints in a ConstraintMap then the types better have
//the same underlying type or Javac will complain and we won't be here. When building ConstraintMaps
//constraints involving AnnotatedTypeMirrors that are exactly equal are combined so there must be some
//difference between two types being merged here.
//2. Otherwise, we might have the same underlying type but conflicting annotations, then we take
//the first set of annotations and show an error for the argument/return type that caused the second
//differing constraint
//3. Finally, we expect the following types to be involved in equality constraints:
//AnnotatedDeclaredTypes, AnnotatedTypeVariables, and AnnotatedArrayTypes
while (entryIterator.hasNext() && !missingAnnos.isEmpty()) {
final Entry<AnnotatedTypeMirror, Set<AnnotationMirror>> current = entryIterator.next();
final AnnotatedTypeMirror currentType = current.getKey();
final Set<AnnotationMirror> currentHierarchies = current.getValue();
Set<AnnotationMirror> found = new HashSet<>();
for (AnnotationMirror top : missingAnnos) {
if (currentHierarchies.contains(top)) {
final AnnotationMirror newAnno = currentType.getAnnotationInHierarchy(top);
if (newAnno != null) {
mergedType.replaceAnnotation(newAnno);
found.add(top);
} else if (mergedType.getKind() == TypeKind.TYPEVAR
&& currentType.getUnderlyingType().equals(mergedType.getUnderlyingType())) {
//the options here are we are merging with the same typevar, in which case
//we can just remove the annotation from the missing list
found.add(top);
} else {
//otherwise the other type is missing an annotation
ErrorReporter.errorAbort("Missing annotation.\n"
+ "\nmergedType=" + mergedType
+ "\ncurrentType=" + currentType);
}
}
}
missingAnnos.removeAll(found);
}
//add all the annotations from the primaries
final HashSet<AnnotationMirror> foundHierarchies = new HashSet<>();
for (final AnnotationMirror top : missingAnnos) {
final AnnotationMirror anno = primaries.get(top);
if (anno != null) {
foundHierarchies.add(top);
mergedType.replaceAnnotation(anno);
}
}
typesToHierarchies.clear();
if (missingAnnos.isEmpty()) {
return new InferredType(mergedType);
}
//TODO: we probably can do more with this information than just putting it back into the
//TODO: ConstraintMap (which is what's happening here)
final Set<AnnotationMirror> hierarchies = new HashSet<>(tops);
hierarchies.removeAll(missingAnnos);
typesToHierarchies.put(mergedType, hierarchies);
return null;
}
public InferredValue mergeConstraints(final TypeVariable target, final Equalities equalities,
final InferenceResult solution, ConstraintMap constraintMap,
AnnotatedTypeFactory typeFactory) {
final Set<? extends AnnotationMirror> tops = typeFactory.getQualifierHierarchy().getTopAnnotations();
InferredValue inferred = null;
if (!equalities.types.isEmpty()) {
inferred = mergeTypesAndPrimaries(equalities.types, equalities.primaries, tops);
}
if (inferred != null) {
return inferred;
} //else
//We did not have enough information to infer an annotation in all hierarchies for one concrete type.
//However, we have a "partial solution", one in which we know the type in some but not all qualifier hierarchies
//Update our set of constraints with this information
dirty |= updateTargetsWithPartiallyInferredType(equalities, constraintMap, typeFactory);
inferred = findEqualTarget(equalities, tops);
return inferred;
}
//If we determined that this target T1 is equal to a type ATM in hierarchies @A,@B,@C
//for each of those hierarchies, if a target is equal to T1 in that hierarchy it is also equal to ATM
// e.g.
// if : T1 == @A @B @C ATM in only the A,B hierarchies
// and T1 == T2 only in @A hierarchy
//
// then T2 == @A @B @C only in the @A hierarchy
//
public boolean updateTargetsWithPartiallyInferredType( final Equalities equalities, ConstraintMap constraintMap,
AnnotatedTypeFactory typeFactory) {
boolean updated = false;
if (!equalities.types.isEmpty()) {
if (equalities.types.size() != 1) {
ErrorReporter.errorAbort("Equalities should have at most 1 constraint.");
}
Entry<AnnotatedTypeMirror, Set<AnnotationMirror>> remainingTypeEquality;
remainingTypeEquality = equalities.types.entrySet().iterator().next();
final AnnotatedTypeMirror remainingType = remainingTypeEquality.getKey();
final Set<AnnotationMirror> remainingHierarchies = remainingTypeEquality.getValue();
//update targets
for (Map.Entry<TypeVariable, Set<AnnotationMirror>> targetToHierarchies : equalities.targets.entrySet()) {
final TypeVariable equalTarget = targetToHierarchies.getKey();
final Set<AnnotationMirror> hierarchies = targetToHierarchies.getValue();
final Set<AnnotationMirror> equalTypeHierarchies = new HashSet<>(remainingHierarchies);
equalTypeHierarchies.retainAll(hierarchies);
final Map<AnnotatedTypeMirror, Set<AnnotationMirror>> otherTargetsEqualTypes =
constraintMap.getConstraints(equalTarget).equalities.types;
Set<AnnotationMirror> equalHierarchies = otherTargetsEqualTypes.get(remainingType);
if (equalHierarchies == null) {
equalHierarchies = new HashSet<>(equalTypeHierarchies);
otherTargetsEqualTypes.put(remainingType, equalHierarchies);
updated = true;
} else {
final int size = equalHierarchies.size();
equalHierarchies.addAll(equalTypeHierarchies);
updated = size == equalHierarchies.size();
}
}
}
return updated;
}
/**
* Attempt to find a target which is equal to this target.
* @return a target equal to this target in all hierarchies, or null
*/
public InferredTarget findEqualTarget(final Equalities equalities, Set<? extends AnnotationMirror> tops) {
for (Map.Entry<TypeVariable, Set<AnnotationMirror>> targetToHierarchies : equalities.targets.entrySet()) {
final TypeVariable equalTarget = targetToHierarchies.getKey();
final Set<AnnotationMirror> hierarchies = targetToHierarchies.getValue();
//Now see if target is equal to equalTarget in all hierarchies
boolean targetIsEqualInAllHierarchies = hierarchies.size() == tops.size();
if (targetIsEqualInAllHierarchies) {
return new InferredTarget(equalTarget, new HashSet<AnnotationMirror>());
} else {
//annos in primaries that are not covered by the target's list of equal hierarchies
final Set<AnnotationMirror> requiredPrimaries = new HashSet<AnnotationMirror>(equalities.primaries.keySet());
requiredPrimaries.removeAll(hierarchies);
boolean typeWithPrimariesIsEqual = (requiredPrimaries.size() + hierarchies.size()) == tops.size();
if (typeWithPrimariesIsEqual) {
return new InferredTarget(equalTarget, requiredPrimaries);
}
}
}
return null;
}
}
| 51.546296 | 149 | 0.654302 |
06cd02cc7850c4d0db7072c3378043ab271ade26 | 2,745 | package com.redhat.service.smartevents.executor;
import java.net.URI;
import java.util.UUID;
import java.util.concurrent.CompletionStage;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.eclipse.microprofile.reactive.messaging.Incoming;
import org.eclipse.microprofile.reactive.messaging.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.redhat.service.smartevents.infra.exceptions.definitions.user.CloudEventDeserializationException;
import com.redhat.service.smartevents.infra.models.processors.ProcessorType;
import com.redhat.service.smartevents.infra.utils.CloudEventUtils;
import io.cloudevents.CloudEvent;
import io.cloudevents.core.builder.CloudEventBuilder;
import io.cloudevents.jackson.JsonCloudEventData;
@ApplicationScoped
public class ExecutorService {
/**
* Channel used for receiving events.
*/
public static final String EVENTS_IN_CHANNEL = "events-in";
public static final String CLOUD_EVENT_SOURCE = "RHOSE";
private static final Logger LOG = LoggerFactory.getLogger(ExecutorService.class);
@Inject
Executor executor;
@Inject
ObjectMapper mapper;
@Incoming(EVENTS_IN_CHANNEL)
public CompletionStage<Void> processEvent(final Message<String> message) {
try {
String eventPayload = message.getPayload();
CloudEvent cloudEvent = executor.getProcessor().getType() == ProcessorType.SOURCE
? wrapToCloudEvent(eventPayload)
: CloudEventUtils.decode(eventPayload);
executor.onEvent(cloudEvent);
} catch (Exception e) {
LOG.error("Processor with id '{}' on bridge '{}' failed to handle Event. The message is acked anyway.",
executor.getProcessor().getId(), executor.getProcessor().getBridgeId(), e);
}
return message.ack();
}
private CloudEvent wrapToCloudEvent(String event) {
try {
return CloudEventBuilder.v1()
.withId(UUID.randomUUID().toString())
.withSource(URI.create(CLOUD_EVENT_SOURCE))
.withType(String.format("%sSource", executor.getProcessor().getDefinition().getRequestedSource().getType()))
.withData(JsonCloudEventData.wrap(mapper.readTree(event)))
.build();
} catch (JsonProcessingException e2) {
LOG.error("JsonProcessingException when generating CloudEvent for '{}'", event, e2);
throw new CloudEventDeserializationException("Failed to generate event map");
}
}
}
| 38.125 | 128 | 0.703097 |
e50d9eac475b603c78ddebf44c0c943023f3ca5a | 860 | /**
* Exercise 19
*/
package com.ciaoshen.thinkinjava.chapter11;
import java.util.*;
public class Exercise19 {
public static void main(String[] args) {
// fill HashSet
HashSet<String> hashSet = new HashSet<String>();
hashSet.add("one");
hashSet.add("two");
hashSet.add("three");
hashSet.add("four");
hashSet.add("five");
// print HashSet
System.out.println(hashSet);
// transit to list
List<String> list = new ArrayList<String>();
list.addAll(hashSet);
// sort list
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
// insert into LinkedHashSet
Set<String> linkedHashSet = new LinkedHashSet<String>();
linkedHashSet.addAll(list);
// print LinkedHashSet
System.out.println(linkedHashSet);
}
}
| 28.666667 | 64 | 0.602326 |
b1b9fe0f57fde7f6b23246e3ae2b0a8dad83e687 | 2,875 | /*******************************************************************************
* Copyright 2021 spancer
*
* 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.hermes.util;
/**
* @author spancer.ray
*/
public class Classes {
/**
* The package separator character '.'
*/
private static final char PACKAGE_SEPARATOR = '.';
private Classes() {
}
/**
* Return the default ClassLoader to use: typically the thread context ClassLoader, if available;
* the ClassLoader that loaded the ClassUtils class will be used as fallback.
* <p/>
* <p>
* Call this method if you intend to use the thread context ClassLoader in a scenario where you
* absolutely need a non-null ClassLoader reference: for example, for class path resource loading
* (but not necessarily for <code>Class.forName</code>, which accepts a <code>null</code>
* ClassLoader reference as well).
*
* @return the default ClassLoader (never <code>null</code>)
* @see java.lang.Thread#getContextClassLoader()
*/
public static ClassLoader getDefaultClassLoader() {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
} catch (Throwable ex) {
// Cannot access thread context ClassLoader - falling back to system class loader...
}
if (cl == null) {
// No thread context class loader -> use class loader of this class.
cl = Classes.class.getClassLoader();
}
return cl;
}
/**
* Determine the name of the package of the given class: e.g. "java.lang" for the
* <code>java.lang.String</code> class.
*
* @param clazz the class
* @return the package name, or the empty String if the class is defined in the default package
*/
public static String getPackageName(Class clazz) {
String className = clazz.getName();
int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);
return (lastDotIndex != -1 ? className.substring(0, lastDotIndex) : "");
}
public static String getPackageNameNoDomain(Class clazz) {
String fullPackage = getPackageName(clazz);
if (fullPackage.startsWith("org.") || fullPackage.startsWith("com.")
|| fullPackage.startsWith("net.")) {
return fullPackage.substring(4);
}
return fullPackage;
}
}
| 35.060976 | 99 | 0.65287 |
56f02497fd32fd9fe27353d05f01f315b3011390 | 7,188 | package com.whensunet.core.init;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import com.whensunet.core.init.module.ImageManagerInitModule;
import com.whensunet.core.init.module.PreferenceInitModule;
import com.whensunset.annotation.singleton.Singleton;
import com.whensunset.logutil.debuglog.DebugLogger;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/**
* Created by whensunset on 2018/10/3.
*/
@Singleton
public class InitManager {
private static final String TAG = "INIT_MANAGER";
private static final long MAX_DELAY_ACTIVITY_DISPLAY = 5000L;
private static final long MIN_COST_FOR_REPORT = 10; // 10ms以内不记录
private static final String METHOD_ON_APPLICATION_ATTACH_BASE_CONTEXT =
"onApplicationAttachBaseContext";
private static final String METHOD_ON_APPLICATION_CREATE = "onApplicationCreate";
private static final String METHOD_ON_ACTIVITY_CREATE = "onMainActivityCreate";
private static final String METHOD_ON_ACTIVITY_RESUME = "onMainActivityResume";
private static final String METHOD_ON_ACTIVITY_DESTROY = "onMainActivityDestroy";
private static final String METHOD_ON_BACKGROUND = "onCurrentActivityBackground";
private static final String METHOD_ON_FOREGROUND = "onCurrentActivityForeground";
private static final String METHOD_ON_ACTIVITY_LOAD_FINISHED_OR_AFTER_CREATE_10S =
"onMainActivityLoadFinished";
private final Set<InitModule> mTasks = new LinkedHashSet<>();
private final Map<String, Map<String, Long>> mCosts = new HashMap<>();
long MAX_DELAY_ACTIVITY_LOADED = 10000L;
private boolean mCostReported;
private boolean mActivityLoadFinished;
public InitManager() {
// Preference是全局使用的, 要先初始化
mTasks.add(new PreferenceInitModule());
mTasks.add(new ImageManagerInitModule());
Iterator<InitModule> iterator = mTasks.iterator();
while (iterator.hasNext()) {
if (iterator.next() == null) {
iterator.remove();
}
}
}
public void onApplicationAttachBaseContext(Context base) {
for (InitModule task : mTasks) {
long start = SystemClock.elapsedRealtime();
try {
task.onApplicationAttachBaseContext(base);
} catch (Throwable ignored) {
DebugLogger.e(TAG, "error", ignored);
}
long end = SystemClock.elapsedRealtime();
logCost(task, METHOD_ON_APPLICATION_ATTACH_BASE_CONTEXT, end - start);
}
}
public void onApplicationCreate(Application application) {
for (InitModule task : mTasks) {
long start = SystemClock.elapsedRealtime();
try {
task.onApplicationCreate(application);
} catch (Throwable ignored) {
DebugLogger.e(TAG, "error", ignored);
}
long end = SystemClock.elapsedRealtime();
logCost(task, METHOD_ON_APPLICATION_CREATE, end - start);
}
}
public void onMainActivityCreate(Activity activity, Bundle savedInstanceState) {
mCostReported = false;
mActivityLoadFinished = false;
for (InitModule task : mTasks) {
long start = SystemClock.elapsedRealtime();
try {
task.onMainActivityCreate(activity, savedInstanceState);
} catch (Throwable ignored) {
DebugLogger.e(TAG, "error", ignored);
}
long end = SystemClock.elapsedRealtime();
logCost(task, METHOD_ON_ACTIVITY_CREATE, end - start);
}
final Handler handler = new Handler();
// 兜底ActivityLoadFinishEvent
handler.postDelayed(new Runnable() {
@Override
public void run() {
// EventBus.getDefault().post(new ActivityLoadFinishEvent());
}
}, MAX_DELAY_ACTIVITY_LOADED);
}
public void onMainActivityResume(Activity activity) {
for (InitModule task : mTasks) {
long start = SystemClock.elapsedRealtime();
try {
task.onMainActivityResume(activity);
} catch (Throwable ignored) {
DebugLogger.e(TAG, "error", ignored);
}
long end = SystemClock.elapsedRealtime();
logCost(task, METHOD_ON_ACTIVITY_RESUME, end - start);
}
}
public void onMainActivityDestroy(Activity activity) {
for (InitModule task : mTasks) {
long start = SystemClock.elapsedRealtime();
try {
task.onMainActivityDestroy(activity);
} catch (Throwable ignored) {
DebugLogger.e(TAG, "error", ignored);
}
long end = SystemClock.elapsedRealtime();
logCost(task, METHOD_ON_ACTIVITY_DESTROY, end - start);
}
}
// todo 需要用 类似 eventbus 来在主 Activity 真正加载完成的时候例如 首页的数据都显示出来了 通知这个方法进行调用,可能是 rxbus
public void onMainActivityLoadFinished() {
if (mActivityLoadFinished) {
return;
}
mActivityLoadFinished = true;
for (InitModule task : mTasks) {
long start = SystemClock.elapsedRealtime();
try {
task.onMainActivityLoadFinished();
} catch (Throwable ignored) {
DebugLogger.e(TAG, "error", ignored);
}
long end = SystemClock.elapsedRealtime();
logCost(task, METHOD_ON_ACTIVITY_LOAD_FINISHED_OR_AFTER_CREATE_10S, end - start);
}
// 使用主 Activity 加载数据完毕来当做结束计时的时间点
reportCost();
}
// todo 需要用 类似 eventbus 来在当前 Activity stop 的时候 通知这个方法进行调用,可能是 rxbus
public void onCurrentActivityBackground() {
for (InitModule task : mTasks) {
long start = SystemClock.elapsedRealtime();
try {
task.onCurrentActivityBackground();
} catch (Throwable ignored) {
DebugLogger.e(TAG, "error", ignored);
}
long end = SystemClock.elapsedRealtime();
logCost(task, METHOD_ON_BACKGROUND, end - start);
}
}
// todo 需要用 类似 eventbus 来在当前 Activity start的时候 通知这个方法进行调用,可能是 rxbus
public void onCurrentActivityForeground() {
for (InitModule task : mTasks) {
long start = SystemClock.elapsedRealtime();
try {
task.onCurrentActivityForeground();
} catch (Throwable ignored) {
DebugLogger.e(TAG, "error", ignored);
}
long end = SystemClock.elapsedRealtime();
logCost(task, METHOD_ON_FOREGROUND, end - start);
}
}
private void logCost(InitModule task, String method, long cost) {
if (mCostReported) {
return;
}
if (cost < MIN_COST_FOR_REPORT) {
return;
}
Map<String, Long> map = mCosts.get(method);
if (map == null) {
map = new HashMap<>();
mCosts.put(method, map);
}
map.put(task.getClass().getSimpleName(), cost);
}
private void reportCost() {
if (mCostReported) {
return;
}
for (Map.Entry<String, Map<String, Long>> entry : mCosts.entrySet()) {
String method = entry.getKey();
Map<String, Long> map = entry.getValue();
long cost = 0;
for (Map.Entry<String, Long> longEntry : map.entrySet()) {
cost += longEntry.getValue();
}
reportMethodCost(method, cost, map);
}
mCosts.clear();
mCostReported = true;
}
private void reportMethodCost(String method, long cost, Map<String, Long> map) {
// todo 一个上报点
}
}
| 32.524887 | 87 | 0.683083 |
758b4f9a14d620ef51f69a65075b96a60e848842 | 2,134 | /*
* 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.aliyuncs.sofa.transform.v20190815;
import com.aliyuncs.sofa.model.v20190815.UpdateLinkeBahamutPaasupdateappsResponse;
import com.aliyuncs.transform.UnmarshallerContext;
public class UpdateLinkeBahamutPaasupdateappsResponseUnmarshaller {
public static UpdateLinkeBahamutPaasupdateappsResponse unmarshall(UpdateLinkeBahamutPaasupdateappsResponse updateLinkeBahamutPaasupdateappsResponse, UnmarshallerContext _ctx) {
updateLinkeBahamutPaasupdateappsResponse.setRequestId(_ctx.stringValue("UpdateLinkeBahamutPaasupdateappsResponse.RequestId"));
updateLinkeBahamutPaasupdateappsResponse.setResultCode(_ctx.stringValue("UpdateLinkeBahamutPaasupdateappsResponse.ResultCode"));
updateLinkeBahamutPaasupdateappsResponse.setResultMessage(_ctx.stringValue("UpdateLinkeBahamutPaasupdateappsResponse.ResultMessage"));
updateLinkeBahamutPaasupdateappsResponse.setErrorMessage(_ctx.stringValue("UpdateLinkeBahamutPaasupdateappsResponse.ErrorMessage"));
updateLinkeBahamutPaasupdateappsResponse.setErrorMsgParamsMap(_ctx.stringValue("UpdateLinkeBahamutPaasupdateappsResponse.ErrorMsgParamsMap"));
updateLinkeBahamutPaasupdateappsResponse.setMessage(_ctx.stringValue("UpdateLinkeBahamutPaasupdateappsResponse.Message"));
updateLinkeBahamutPaasupdateappsResponse.setResponseStatusCode(_ctx.longValue("UpdateLinkeBahamutPaasupdateappsResponse.ResponseStatusCode"));
updateLinkeBahamutPaasupdateappsResponse.setSuccess(_ctx.booleanValue("UpdateLinkeBahamutPaasupdateappsResponse.Success"));
return updateLinkeBahamutPaasupdateappsResponse;
}
} | 59.277778 | 177 | 0.85239 |
2c45942de2efe643b27e8d8c3361b32d7a367057 | 4,440 | /*
* The MIT License
*
* Copyright 2019 Clayn <[email protected]>.
*
* 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 net.bplaced.clayn.jshed.io;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import net.bplaced.clayn.jshed.JShed;
import net.bplaced.clayn.jshed.util.ProgressingTask;
/**
*
* @author Clayn <[email protected]>
*/
public final class IOTools
{
private IOTools()
{
}
public static ProgressingTask copyAsync(InputStream src, OutputStream dest,
long amount)
{
long max = amount;
AtomicLong current = new AtomicLong(0);
AtomicBoolean done = new AtomicBoolean(false);
ProgressingTask progress = new ProgressingTask()
{
@Override
public double getProgress()
{
return max > 0 ? (current.get() * 1.0) / (max * 1.0) : -1;
}
public boolean isDone()
{
return done.get();
}
};
Runnable task = new Runnable()
{
@Override
public void run()
{
try
{
byte[] buffer = new byte[256];
int read;
while ((read = src.read(buffer)) != -1)
{
dest.write(buffer, 0, read);
current.addAndGet(read);
if (progress.getOnProgressChanged() != null)
{
progress.getOnProgressChanged().accept(
progress.getProgress());
}
}
dest.flush();
done.set(true);
} catch (IOException ex)
{
throw new RuntimeException(ex);
}
}
};
JShed.getExecutorService().execute(task);
return progress;
}
public static void copy(InputStream src, OutputStream dest) throws IOException
{
Objects.requireNonNull(src);
Objects.requireNonNull(dest);
byte[] buffer = new byte[256];
int read;
while ((read = src.read(buffer)) != -1)
{
dest.write(buffer, 0, read);
}
dest.flush();
}
public static void copy(DataSource src, DataSink dest) throws IOException
{
try (InputStream in = src.getSource(); OutputStream out = dest.getSink())
{
copy(in, out);
}
}
public static IOObject toIOObject(File f)
{
Objects.requireNonNull(f);
return toIOObject(f.toPath());
}
public static IOObject toIOObject(Path p)
{
Objects.requireNonNull(p);
return new IOObject()
{
@Override
public InputStream getSource() throws IOException
{
return Files.newInputStream(p);
}
@Override
public OutputStream getSink() throws IOException
{
return Files.newOutputStream(p);
}
};
}
}
| 30.204082 | 82 | 0.570045 |
905028b2ad1d7977c9a576cc5ee988632ce05e9b | 10,105 | package com.github.meteorcraft.mixin;
import com.github.meteorcraft.MeteorWorlds;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.Flutterer;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.MovementType;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.effect.StatusEffects;
import net.minecraft.fluid.Fluid;
import net.minecraft.fluid.FluidState;
import net.minecraft.sound.SoundEvent;
import net.minecraft.tag.FluidTags;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.Objects;
@Mixin(LivingEntity.class)
public abstract class LivingEntityMixin extends Entity {
public LivingEntityMixin(EntityType<?> entityType, World world) {
super(entityType, world);
}
@Shadow
public abstract boolean canMoveVoluntarily();
@Shadow
public abstract boolean hasStatusEffect(StatusEffect effect);
@Shadow
protected abstract boolean shouldSwimInFluids();
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
@Shadow
public abstract boolean canWalkOnFluid(Fluid fluid);
@Shadow
protected abstract float getBaseMovementSpeedMultiplier();
@Shadow
public abstract float getMovementSpeed();
@Shadow
public abstract boolean isClimbing();
@Shadow
public abstract Vec3d method_26317(double d, boolean bl, Vec3d vec3d);
@Shadow
public abstract boolean isFallFlying();
@Shadow
protected abstract SoundEvent getFallSound(int distance);
@Shadow
public abstract Vec3d method_26318(Vec3d vec3d, float f);
@Shadow
@Nullable
public abstract StatusEffectInstance getStatusEffect(StatusEffect effect);
@Shadow
public abstract boolean hasNoDrag();
@Shadow
public abstract void updateLimbs(LivingEntity entity, boolean flutter);
@Shadow public abstract boolean removeStatusEffect(StatusEffect type);
@Inject(method = "tick", at = @At("RETURN"))
public void tick(CallbackInfo ci) {
if (getScoreboardTags().contains("slowfalling")) {
if (isOnGround()) {
removeStatusEffect(StatusEffects.SLOW_FALLING);
removeScoreboardTag("slowfalling");
}
}
}
/**
* @author WinCho
* @reason Jump higher on the moon.
*/
@Overwrite
public float getJumpVelocity() {
return 0.42F * this.getJumpVelocityMultiplier() + (MeteorWorlds.isMoon(world) ? 0.3f : 0);
}
/**
* @author WinCho
* @reason It falls more slowly from the moon.
*/
@Overwrite
public void travel(Vec3d movementInput) {
if (this.canMoveVoluntarily() || this.isLogicalSideForUpdatingMovement()) {
double d = 0.08D;
boolean bl = this.getVelocity().y <= 0.0D;
if (bl && this.hasStatusEffect(StatusEffects.SLOW_FALLING)) {
d = 0.01D;
this.fallDistance = 0.0F;
}
if (bl && MeteorWorlds.isMoon(world)) {
d = 0.03;
this.fallDistance = 0.0F;
}
FluidState fluidState = this.world.getFluidState(this.getBlockPos());
float j;
double e;
if (this.isTouchingWater() && this.shouldSwimInFluids() && !this.canWalkOnFluid(fluidState.getFluid())) {
e = this.getY();
j = this.isSprinting() ? 0.9F : this.getBaseMovementSpeedMultiplier();
float g = 0.02F;
float h = (float) EnchantmentHelper.getDepthStrider((LivingEntity) (Entity) this);
if (h > 3.0F) {
h = 3.0F;
}
if (!this.onGround) {
h *= 0.5F;
}
if (h > 0.0F) {
j += (0.54600006F - j) * h / 3.0F;
g += (this.getMovementSpeed() - g) * h / 3.0F;
}
if (this.hasStatusEffect(StatusEffects.DOLPHINS_GRACE)) {
j = 0.96F;
}
this.updateVelocity(g, movementInput);
this.move(MovementType.SELF, this.getVelocity());
Vec3d vec3d = this.getVelocity();
if (this.horizontalCollision && this.isClimbing()) {
vec3d = new Vec3d(vec3d.x, 0.2D, vec3d.z);
}
this.setVelocity(vec3d.multiply(j, 0.800000011920929D, j));
Vec3d vec3d2 = this.method_26317(d, bl, this.getVelocity());
this.setVelocity(vec3d2);
if (this.horizontalCollision && this.doesNotCollide(vec3d2.x, vec3d2.y + 0.6000000238418579D - this.getY() + e, vec3d2.z)) {
this.setVelocity(vec3d2.x, 0.30000001192092896D, vec3d2.z);
}
} else if (this.isInLava() && this.shouldSwimInFluids() && !this.canWalkOnFluid(fluidState.getFluid())) {
e = this.getY();
this.updateVelocity(0.02F, movementInput);
this.move(MovementType.SELF, this.getVelocity());
Vec3d vec3d4;
if (this.getFluidHeight(FluidTags.LAVA) <= this.getSwimHeight()) {
this.setVelocity(this.getVelocity().multiply(0.5D, 0.800000011920929D, 0.5D));
vec3d4 = this.method_26317(d, bl, this.getVelocity());
this.setVelocity(vec3d4);
} else {
this.setVelocity(this.getVelocity().multiply(0.5D));
}
if (!this.hasNoGravity()) {
this.setVelocity(this.getVelocity().add(0.0D, -d / 4.0D, 0.0D));
}
vec3d4 = this.getVelocity();
if (this.horizontalCollision && this.doesNotCollide(vec3d4.x, vec3d4.y + 0.6000000238418579D - this.getY() + e, vec3d4.z)) {
this.setVelocity(vec3d4.x, 0.30000001192092896D, vec3d4.z);
}
} else if (this.isFallFlying()) {
Vec3d vec3d5 = this.getVelocity();
if (vec3d5.y > -0.5D) {
this.fallDistance = 1.0F;
}
Vec3d vec3d6 = this.getRotationVector();
j = this.getPitch() * 0.017453292F;
double k = Math.sqrt(vec3d6.x * vec3d6.x + vec3d6.z * vec3d6.z);
double l = vec3d5.horizontalLength();
double m = vec3d6.length();
float n = MathHelper.cos(j);
n = (float) ((double) n * (double) n * Math.min(1.0D, m / 0.4D));
vec3d5 = this.getVelocity().add(0.0D, d * (-1.0D + (double) n * 0.75D), 0.0D);
double q;
if (vec3d5.y < 0.0D && k > 0.0D) {
q = vec3d5.y * -0.1D * (double) n;
vec3d5 = vec3d5.add(vec3d6.x * q / k, q, vec3d6.z * q / k);
}
if (j < 0.0F && k > 0.0D) {
q = l * (double) (-MathHelper.sin(j)) * 0.04D;
vec3d5 = vec3d5.add(-vec3d6.x * q / k, q * 3.2D, -vec3d6.z * q / k);
}
if (k > 0.0D) {
vec3d5 = vec3d5.add((vec3d6.x / k * l - vec3d5.x) * 0.1D, 0.0D, (vec3d6.z / k * l - vec3d5.z) * 0.1D);
}
this.setVelocity(vec3d5.multiply(0.9900000095367432D, 0.9800000190734863D, 0.9900000095367432D));
this.move(MovementType.SELF, this.getVelocity());
if (this.horizontalCollision && !this.world.isClient) {
q = this.getVelocity().horizontalLength();
double r = l - q;
float s = (float) (r * 10.0D - 3.0D);
if (s > 0.0F) {
this.playSound(this.getFallSound((int) s), 1.0F, 1.0F);
this.damage(DamageSource.FLY_INTO_WALL, s);
}
}
if (this.onGround && !this.world.isClient) {
this.setFlag(7, false);
}
} else {
BlockPos blockPos = this.getVelocityAffectingPos();
float t = this.world.getBlockState(blockPos).getBlock().getSlipperiness();
j = this.onGround ? t * 0.91F : 0.91F;
Vec3d vec3d7 = this.method_26318(movementInput, t);
double v = vec3d7.y;
if (this.hasStatusEffect(StatusEffects.LEVITATION)) {
v += (0.05D * (double) (Objects.requireNonNull(this.getStatusEffect(StatusEffects.LEVITATION)).getAmplifier() + 1) - vec3d7.y) * 0.2D;
this.fallDistance = 0.0F;
} else //noinspection deprecation
if (this.world.isClient && !this.world.isChunkLoaded(blockPos)) {
if (this.getY() > (double) this.world.getBottomY()) {
v = -0.1D;
} else {
v = 0.0D;
}
} else if (!this.hasNoGravity()) {
v -= d;
}
if (this.hasNoDrag()) {
this.setVelocity(vec3d7.x, v, vec3d7.z);
} else {
this.setVelocity(vec3d7.x * (double) j, v * 0.9800000190734863D, vec3d7.z * (double) j);
}
}
}
this.updateLimbs((LivingEntity) (Entity) this, this instanceof Flutterer);
}
}
| 39.627451 | 154 | 0.556655 |
80106c33b45b1e52a05d1157653debb6fe10bcee | 306 | public class BubbleSort{
public void bubbleSort(int[] array){
int length = array.length;
int temp = 0;
for(int i=0; i<length; i++){
for(int j=1; j<(length-i); j++){
if(array[j-1] > array[j]){
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}
}
} | 17 | 37 | 0.519608 |
8f5711cd12f8353db9adb8c5be3436038d5b921b | 23,439 | /**
* This file is referred and derived from project apache/tinkerpop
*
* https://github.com/apache/tinkerpop/blob/master/gremlin-server/src/test/java/org/apache/tinkerpop/gremlin/driver/remote/GraphBinaryRemoteGraphComputerProvider.java
*
* which has the following license:
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.alibaba.maxgraph.function.test;
import org.apache.commons.configuration.Configuration;
import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategies;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.finalization.ProfileStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.optimization.FilterRankingStrategy;
import org.apache.tinkerpop.gremlin.structure.Graph;
//@Graph.OptIn("com.alibaba.maxgraph.function.test.gremlin.OtherGraphTestSuite")
@Graph.OptIn("com.alibaba.maxgraph.function.test.gremlin.GremlinStandardTestSuite")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest",
method = "g_V_repeatXoutXknowsXX_untilXrepeatXoutXcreatedXX_emitXhasXname_lopXXX_path_byXnameX",
reason = "Not support nest loop")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest",
method = "g_V_repeatXout_repeatXoutX_timesX1XX_timesX1X_limitX1X_path_by_name",
reason = "Not support nest loop")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest",
method = "g_V_repeatXbothX_untilXname_eq_marko_or_loops_gt_1X_groupCount_byXnameX",
reason = "Not support lambda")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest",
method = "g_VX1X_repeatXgroupCountXmX_byXloopsX_outX_timesX3X_capXmX",
reason = "Not support group count side effect")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest",
method = "g_VX1X_repeatXrepeatXunionXout_uses_out_traversesXX_whereXloops_isX0X_timesX1X_timeX2X_name",
reason = "Not support nest loop")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest",
method = "g_V_untilXconstantXtrueXX_repeatXrepeatXout_createdXX_untilXhasXname_rippleXXXemit_lang",
reason = "Not support nest loop")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest",
method = "g_VX6X_repeatXa_bothXcreatedX_simplePathX_emitXrepeatXb_bothXknowsXX_untilXloopsXbX_asXb_whereXloopsXaX_asXbX_hasXname_vadasXX_dedup_name",
reason = "Not support nest loop")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest",
method = "g_VX3X_repeatXbothX_createdXX_untilXloops_is_40XXemit_repeatXin_knowsXX_emit_loopsXisX1Xdedup_values",
reason = "Not support nest loop")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest",
method = "g_V_repeatXgroupCountXmX_byXnameX_outX_timesX2X_capXmX",
reason = "Not support group count side effect")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest",
method = "g_V_repeatXrepeatXout_createdXX_untilXhasXname_rippleXXXemit_lang",
reason = "Not support nest loop")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest",
method = "g_V_emit_repeatXa_outXknows_filterXloops_isX0XX_lang",
reason = "Not support filter loops")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest",
method = "g_V_repeatXoutX_timesX2X_repeatXinX_timesX2X_name",
reason = "Not support repeat brother")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.UnionTest",
method = "g_VX1_2X_localXunionXoutE_count__inE_count__outE_weight_sumXX",
reason = "Not support local operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.UnionTest",
method = "g_VX1_2X_localXunionXcountXX",
reason = "Not support local operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.CyclicPathTest",
method = "g_VX1X_asXaX_outXcreatedX_asXbX_inXcreatedX_asXcX_cyclicPath_fromXaX_toXbX_path",
reason = "Not support path from to")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.DedupTest",
method = "g_V_out_in_valuesXnameX_fold_dedupXlocalX_unfold",
reason = "Not support dedup local")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.DedupTest",
method = "g_V_out_asXxX_in_asXyX_selectXx_yX_byXnameX_fold_dedupXlocal_x_yX_unfold",
reason = "Not support dedup local")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.DedupTest",
method = "g_V_both_name_order_byXa_bX_dedup_value",
reason = "Not support lambda")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.DedupTest",
method = "g_V_asXaX_both_asXbX_dedupXa_bX_byXlabelX_selectXa_bX",
reason = "Not support dedup(a, b).by(...).by(...)")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.DedupTest",
method = "g_V_asXaX_outXcreatedX_asXbX_inXcreatedX_asXcX_dedupXa_bX_path",
reason = "Not support dedup(a, b).by(...).by(...)")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest",
method = "g_V_outXcreatedX_hasXname__mapXlengthX_isXgtX3XXX_name",
reason = "lambda")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest",
method = "g_V_hasXname_containingXarkXX",
reason = "not support TextP")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest",
method = "g_V_hasXname_startingWithXmarXX",
reason = "not support TextP")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest",
method = "g_V_hasXname_endingWithXasXX",
reason = "not support TextP")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest",
method = "g_V_hasXname_not_containingXarkXX",
reason = "not support TextP")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest",
method = "g_V_hasXname_not_startingWithXmarXX",
reason = "not support TextP")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest",
method = "g_V_hasXname_not_endingWithXasXX",
reason = "not support TextP")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest",
method = "g_V_hasXperson_name_containingXoX_andXltXmXXX",
reason = "not support TextP")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest",
method = "g_V_hasXname_gtXmX_andXcontainingXoXXX",
reason = "not support TextP")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest",
method = "g_VX1X_out_hasXid_lt_3X",
reason = "not support compare vertex id")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.RangeTest",
method = "g_V_localXoutE_limitX1X_inVX_limitX3X",
reason = "not support local operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.RangeTest",
method = "g_V_asXaX_in_asXaX_in_asXaX_selectXmixed_aX_byXunfold_valuesXnameX_foldX_limitXlocal_1X",
reason = "not support local operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.RangeTest",
method = "g_V_asXaX_in_asXaX_in_asXaX_selectXmixed_aX_byXunfold_valuesXnameX_foldX_limitXlocal_2X",
reason = "not support local operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.RangeTest",
method = "g_V_asXaX_out_asXaX_out_asXaX_selectXmixed_aX_byXunfold_valuesXnameX_foldX_rangeXlocal_1_2X",
reason = "not support local operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.RangeTest",
method = "g_V_asXaX_out_asXaX_out_asXaX_selectXmixed_aX_byXunfold_valuesXnameX_foldX_rangeXlocal_1_3X",
reason = "not support local operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.RangeTest",
method = "g_V_asXaX_out_asXaX_out_asXaX_selectXmixed_aX_byXunfold_valuesXnameX_foldX_rangeXlocal_4_5X",
reason = "not support local operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.SimplePathTest",
method = "g_V_asXaX_out_asXbX_out_asXcX_simplePath_byXlabelX_fromXbX_toXcX_path_byXnameX",
reason = "not support from to")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTest",
method = "g_V_hasXageX_asXaX_out_in_hasXageX_asXbX_selectXa_bX_whereXb_hasXname_markoXX",
reason = "Not support match")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTest",
method = "g_V_hasXageX_asXaX_out_in_hasXageX_asXbX_selectXa_bX_whereXa_outXknowsX_bX",
reason = "Not support match")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTest",
method = "g_V_asXaX_outXcreatedX_whereXasXaX_name_isXjoshXX_inXcreatedX_name",
reason = "Not support match")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTest",
method = "g_VX1X_asXaX_outXcreatedX_inXcreatedX_asXbX_whereXasXbX_outXcreatedX_hasXname_rippleXX_valuesXage_nameX",
reason = "Not support match")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTest",
method = "g_V_asXaX_out_asXbX_whereXandXasXaX_outXknowsX_asXbX__orXasXbX_outXcreatedX_hasXname_rippleX__asXbX_inXknowsX_count_isXnotXeqX0XXXXX_selectXa_bX",
reason = "Not support match")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTest",
method = "g_withSideEffectXa_josh_peterX_VX1X_outXcreatedX_inXcreatedX_name_whereXwithinXaXX",
reason = "Not support match")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTest",
method = "g_withSideEffectXa_g_VX2XX_VX1X_out_whereXneqXaXX",
reason = "Not support side effect")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTest",
method = "g_VX1X_out_aggregateXxX_out_whereXnotXwithinXaXXX",
reason = "Not support aggregate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTest",
method = "g_VX1X_repeatXbothEXcreatedX_whereXwithoutXeXX_aggregateXeX_otherVX_emit_path",
reason = "Not support aggregate")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTest",
method = "g_V_whereXnotXoutXcreatedXXX_name",
reason = "Not support nest not in where")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTest",
method = "g_V_asXaX_outEXcreatedX_asXbX_inV_asXcX_whereXa_gtXbX_orXeqXbXXX_byXageX_byXweightX_byXweightX_selectXa_cX_byXnameX",
reason = "Not support nest not in where")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTest",
method = "g_V_whereXoutXcreatedX_and_outXknowsX_or_inXknowsXX_valuesXnameX",
reason = "Not support nest not in where")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTest",
method = "g_V_asXaX_out_asXbX_whereXin_count_isXeqX3XX_or_whereXoutXcreatedX_and_hasXlabel_personXXX_selectXa_bX",
reason = "Not support nest not in where")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTest",
method = "g_V_asXaX_outEXcreatedX_asXbX_inV_asXcX_inXcreatedX_asXdX_whereXa_ltXbX_orXgtXcXX_andXneqXdXXX_byXageX_byXweightX_byXinXcreatedX_valuesXageX_minX_selectXa_c_dX",
reason = "Not support nest not in where")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTest",
method = "g_V_asXaX_outXcreatedX_asXbX_whereXandXasXbX_in__notXasXaX_outXcreatedX_hasXname_rippleXXX_selectXa_bX",
reason = "Not support nest not in where")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.WhereTest",
method = "g_V_asXaX_outXcreatedX_asXbX_inXcreatedX_asXcX_bothXknowsX_bothXknowsX_asXdX_whereXc__notXeqXaX_orXeqXdXXXX_selectXa_b_c_dX",
reason = "Not support nest not in where")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.CountTest",
method = "g_V_repeatXoutX_timesX5X_asXaX_outXwrittenByX_asXbX_selectXa_bX_count",
reason = "Not support grateful graph")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.FoldTest",
method = "g_V_age_foldX0_plusX",
reason = "Not support BinaryOperator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.MaxTest",
method = "g_V_name_fold_maxXlocalX",
reason = "Not support max local")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.MaxTest",
method = "g_V_age_fold_maxXlocalX",
reason = "Not support max local")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.MaxTest",
method = "g_V_foo_fold_maxXlocalX",
reason = "Not support max local")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.MinTest",
method = "g_V_age_fold_minXlocalX",
reason = "Not support min local")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.MinTest",
method = "g_V_foo_fold_minXlocalX",
reason = "Not support min local")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.MinTest",
method = "g_V_name_fold_minXlocalX",
reason = "Not support min local")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.MinTest",
method = "g_V_foo_injectX9999999999X_min",
reason = "Not support inject operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SumTest",
method = "g_V_age_fold_sumXlocalX",
reason = "Not support sum local")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SumTest",
method = "g_V_foo_fold_sumXlocalX",
reason = "Not support sum local")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.OrderTest",
method = "g_V_asXvX_mapXbothE_weight_foldX_sumXlocalX_asXsX_selectXv_sX_order_byXselectXsX_descX",
reason = "Not support map/local/lambda operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.OrderTest",
method = "g_V_mapXbothE_weight_foldX_order_byXsumXlocalX_descX",
reason = "Not support map/local/lambda operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.OrderTest",
method = "g_VX1X_hasXlabel_personX_mapXmapXint_ageXX_orderXlocalX_byXvalues_descX_byXkeys_ascX",
reason = "Not support map/local/lambda operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.OrderTest",
method = "g_V_name_order_byXa1_b1X_byXb2_a2X",
reason = "Not support map/local/lambda operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.OrderTest",
method = "g_V_hasLabelXpersonX_order_byXvalueXageX_descX_name",
reason = "Not support map/local/lambda operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.OrderTest",
method = "g_V_order_byXname_a1_b1X_byXname_b2_a2X_name",
reason = "Not support map/local/lambda operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.OrderTest",
method = "g_V_properties_order_byXkey_descX_key",
reason = "Not support remove id property from graph")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.PathTest",
method = "g_V_asXaX_out_asXbX_out_asXcX_path_fromXbX_toXcX_byXnameX",
reason = "Not support path from to")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest",
method = "g_V_asXaX_out_aggregateXxX_asXbX_selectXa_bX_byXnameX",
reason = "Not support aggregate operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest",
method = "g_V_outXcreatedX_unionXasXprojectX_inXcreatedX_hasXname_markoX_selectXprojectX__asXprojectX_inXcreatedX_inXknowsX_hasXname_markoX_selectXprojectXX_groupCount_byXnameX",
reason = "Not support match")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest",
method = "g_V_hasLabelXpersonX_asXpX_mapXbothE_label_groupCountX_asXrX_selectXp_rX",
reason = "Not support map")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest",
method = "g_V_chooseXoutE_count_isX0X__asXaX__asXbXX_chooseXselectXaX__selectXaX__selectXbXX",
reason = "Not support choose")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest",
method = "g_VX1X_asXaX_repeatXout_asXaXX_timesX2X_selectXlast_aX",
reason = "Not support choose")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest",
method = "g_V_asXaX_groupXmX_by_byXbothE_countX_barrier_selectXmX_selectXselectXaXX",
reason = "Not support group side effect")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest",
method = "g_V_asXaX_groupXmX_by_byXbothE_countX_barrier_selectXmX_selectXselectXaXX_byXmathX_plus_XX",
reason = "Not support group side effect")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest",
method = "g_V_asXaX_outXknowsX_asXbX_localXselectXa_bX_byXnameXX",
reason = "Not support local operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest",
method = "g_V_untilXout_outX_repeatXin_asXaXX_selectXaX_byXtailXlocalX_nameX",
reason = "Not support tail operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest",
method = "g_V_asXa_bX_out_asXcX_path_selectXkeysX",
reason = "Not support path keys value set not match list")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest",
method = "g_VX1X_groupXaX_byXconstantXaXX_byXnameX_selectXaX_selectXaX",
reason = "Not support tail operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest",
method = "g_VX1X_asXaX_repeatXout_asXaXX_timesX2X_selectXfirst_aX",
reason = "Not support tail operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest",
method = "g_V_asXaX_outXknowsX_asXaX_selectXall_constantXaXX",
reason = "Not support select traversal")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.VertexTest",
method = "g_VX1_2_3_4X_name",
reason = "Not support drop vertex in the case")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.VertexTest",
method = "g_V_hasLabelXpersonX_V_hasLabelXsoftwareX_name",
reason = "Not support multiple source")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.ValueMapTest",
method = "g_VX1X_valueMapXname_locationX_byXunfoldX_by",
reason = "Not support value map by operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.ValueMapTest",
method = "g_V_valueMapXname_ageX_withXtokens_labelsX_byXunfoldX",
reason = "Not support value map by operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.PropertiesTest",
method = "g_V_hasXageX_properties_hasXid_nameIdX_value",
reason = "Not support value map by operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.PropertiesTest",
method = "g_V_hasXageX_properties_hasXid_nameIdAsStringX_value",
reason = "Not support value map by operator")
@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.PropertiesTest",
method = "g_injectXg_VX1X_propertiesXnameX_nextX_value",
reason = "Not support inject operator")
public class RemoteTestGraph extends DummyGraph {
public static final String GRAPH_NAME = "test.graph.name";
private RemoteGremlinConnection remoteGremlinConnection;
public RemoteTestGraph(final Configuration configuration) {
try {
String gremlinEndpoint = configuration.getString(GRAPH_NAME);
remoteGremlinConnection = new RemoteGremlinConnection(gremlinEndpoint);
} catch (Exception e) {
throw new RuntimeException("initiate remote test graph fail " + e);
}
}
public static RemoteTestGraph open(final Configuration configuration) {
return new RemoteTestGraph(configuration);
}
@Override
public void close() throws Exception {
remoteGremlinConnection.close();
}
@Override
public Configuration configuration() {
return null;
}
@Override
public GraphTraversalSource traversal() {
GraphTraversalSource graphTraversalSource = new GraphTraversalSource(
this,
TraversalStrategies.GlobalCache.getStrategies(this.getClass())).withRemote(remoteGremlinConnection);
TraversalStrategies strategies = graphTraversalSource.getStrategies();
strategies.removeStrategies(
ProfileStrategy.class,
FilterRankingStrategy.class);
return graphTraversalSource;
}
}
| 63.177898 | 186 | 0.763172 |
ae5c7b2cbd87ea9f99982df0b5d03f12c72fbaa3 | 1,312 | package tests;
import neat.ConnectionGene;
import neat.Genome;
import neat.NodeGene;
import java.util.ArrayList;
/**
* Created by lukas on 28.3.2018.
*/
public class GenomeTest {
public static void main(String[] args) {
Genome g = new Genome();
//System.out.println("Hidden nodes: " + g.countHiddenNodes(g.getConnections()));
System.out.println("Before add node mutation:");
for (ConnectionGene con: g.getConnections()) {
System.out.println("Connection " + con.getInnovation() + ": input node = " + con.getInNode() + "; output node = " + con.getOutNode() + "; weight = " + con.getWeight() + "; expressed = " + con.getExpressed());
}
ArrayList<NodeGene> nodes = g.getNodes();
for (int i = 0; i < nodes.size(); i++) {
NodeGene node = nodes.get(i);
if (node.getType() == NodeGene.Type.INPUT) {
System.out.println("This is an input node.");
} else if (node.getType() == NodeGene.Type.HIDDEN) {
System.out.println("This is a hidden node.");
} else if (node.getType() == NodeGene.Type.OUTPUT) {
System.out.println("This is an output node.");
}
}
System.out.println("There are " + nodes.size() + " nodes");
}
}
| 35.459459 | 220 | 0.572409 |
5e77b14f7b69f4fc9123dfb5607aced1231500d9 | 5,010 | package com.oregonscientific.meep.database.table;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class TablePermission {
public static final String S_TABLE_NAME = "permission";
public static final String S_ID = "id";
public static final String S_APP_NAME = "appName";
public static final String S_CAN_ACCESS = "canAccess";
public static final String S_TIME_LIMIT = "timeLimit";
public static final String S_TIME_USED = "timeUsed";
public static final String S_LAST_OPEN = "lastOpen";
public static final String S_TIME_STAMP = "timeStamp";
private int mId;
private String mAppName;
private int mCanAccess;
private int mTimeLimit;
private int mTimeUsed;
private long mLastOpen;
private long mTimeStamp;
public int getId() {
return mId;
}
public void setId(int id) {
this.mId = id;
}
public String getAppName() {
return mAppName;
}
public void setAppName(String appName) {
this.mAppName = appName;
}
public int getCanAccess() {
return mCanAccess;
}
public void setCanAccess(int canAccess) {
this.mCanAccess = canAccess;
}
public int getTimeLimit() {
return mTimeLimit;
}
public void setTimeLimit(int timeLimit) {
this.mTimeLimit = timeLimit;
}
public int getTimeUsed() {
return mTimeUsed;
}
public void setTimeUsed(int timeUsed) {
this.mTimeUsed = timeUsed;
}
public long getLastOpen() {
return mLastOpen;
}
public void setLastOpen(long lastOpen) {
this.mLastOpen = lastOpen;
}
public static String getCreateSql()
{
StringBuilder sb = new StringBuilder();
sb.append("CREATE TABLE IF NOT EXISTS "); sb.append(S_TABLE_NAME); sb.append(" (");
sb.append(S_ID); sb.append( " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, ");
sb.append(S_APP_NAME); sb.append(" VARCHAR(50) NOT NULL, ");
sb.append(S_CAN_ACCESS); sb.append(" INTEGER NOT NULL, ");
sb.append(S_TIME_LIMIT); sb.append(" INTEGER NOT NULL, ");
sb.append(S_TIME_USED); sb.append(" INTEGER NOT NULL, ");
sb.append(S_LAST_OPEN); sb.append(" UNSIGNED BIG INT NOT NULL,");
sb.append(S_TIME_STAMP); sb.append(" VARCHAR(50)");
sb.append(" )");
return sb.toString();
}
public String getInsertSql()
{
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO "); sb.append(S_TABLE_NAME); sb.append( " (" );
sb.append( S_APP_NAME ); sb.append(",");
sb.append( S_CAN_ACCESS ); sb.append(",");
sb.append( S_TIME_LIMIT ); sb.append(",");
sb.append( S_TIME_USED ); sb.append(",");
sb.append( S_LAST_OPEN );
sb.append(") VALUES ("); sb.append("'");
sb.append( getAppName() ); sb.append("','");
sb.append( getCanAccess() ); sb.append("','");
sb.append( getTimeLimit() ); sb.append("','");
sb.append( getTimeUsed() ); sb.append("','");
sb.append( getLastOpen() ); sb.append("'");
sb.append( ")");
return sb.toString();
}
public String getUpdateSql()
{
StringBuilder sb = new StringBuilder();
sb.append("UPDATE "); sb.append(S_TABLE_NAME);
sb.append( " SET " );
sb.append( S_APP_NAME ); sb.append(" = '"); sb.append( getAppName() ); sb.append("',");
sb.append( S_CAN_ACCESS ); sb.append(" = '"); sb.append( getCanAccess() ); sb.append("',");
sb.append( S_TIME_LIMIT ); sb.append(" = '"); sb.append( getTimeLimit() ); sb.append("',");
sb.append( S_TIME_USED ); sb.append(" = '"); sb.append( getTimeUsed() ); sb.append("',");
sb.append( S_LAST_OPEN ); sb.append(" = '"); sb.append( getLastOpen() ); sb.append("'");
sb.append(" WHERE ");
sb.append( S_ID ); sb.append(" = "); sb.append( getId() );
return sb.toString();
}
public String getUpdateTimeUsedSql()
{
StringBuilder sb = new StringBuilder();
sb.append("UPDATE "); sb.append(S_TABLE_NAME);
sb.append( " SET " );
sb.append( S_TIME_USED ); sb.append(" = '"); sb.append( getTimeUsed() ); sb.append("',");
sb.append( S_LAST_OPEN ); sb.append(" = '"); sb.append( getLastOpen() ); sb.append("'");
sb.append(" WHERE ");
sb.append( S_ID ); sb.append(" = "); sb.append( getId() );
return sb.toString();
}
public static String getSelectSql()
{
StringBuilder sb = new StringBuilder();
sb.append("SELECT * FROM "); sb.append(S_TABLE_NAME);
return sb.toString();
}
public static String getDropTableSql()
{
StringBuilder sb = new StringBuilder();
sb.append("DROP TABLE "); sb.append(S_TABLE_NAME);
return sb.toString();
}
public static String addColumnTimeStamp()
{
StringBuilder sb = new StringBuilder();
sb.append("ALTER TABLE "); sb.append(S_TABLE_NAME);
sb.append(" ADD COLUMN "); sb.append(S_TIME_STAMP);
sb.append(" VARCHAR(50)");
return sb.toString();
}
public static boolean isTimeStampColumnExisted(SQLiteDatabase db){
String sql = "SELECT " + S_TIME_STAMP + " FROM " + S_TABLE_NAME;
try{
db.rawQuery(sql, null);
return true;
}catch(Exception ex){
return false;
}
}
public static String getTimeStampSql(){
String sql = "SELECT " + S_TIME_STAMP + " FROM " + S_TABLE_NAME;
return sql;
}
} | 29.127907 | 93 | 0.669261 |
20605739f64dd91f2d02592b49c5c656b2938834 | 7,314 | /*
* Copyright 2015-present wequick.net
*
* 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 net.wequick.small.webkit;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.ViewGroup;
import net.wequick.small.Small;
import java.util.ArrayList;
/**
* Created by galen on 15/3/27.
*/
public final class WebViewPool {
private static final int POOL_SIZE = 8;
private static final int POOL_GROWTH = 2;
private static WebViewPool o;
public static WebViewPool getInstance() {
if (o == null) {
synchronized (WebViewPool.class) {
if (o == null) {
o = new WebViewPool();
}
}
}
return o;
}
private static ArrayList<WebViewSpec> mWebViewSpecs;
public static Context getContext(String url) {
if (mWebViewSpecs == null) {
return null;
}
for (WebViewSpec spec : mWebViewSpecs) {
if (spec.getUrl().equals(url)) {
return spec.getActivity();
}
}
return null;
}
public static Activity getContext(android.webkit.WebView wv) {
if (mWebViewSpecs == null) {
return null;
}
for (WebViewSpec spec : mWebViewSpecs) {
if (spec.webView.equals(wv)) {
return spec.getActivity();
}
}
return null;
}
public void bindActivity(Activity activity, String url) {
if (mWebViewSpecs == null) {
return;
}
for (WebViewSpec spec : mWebViewSpecs) {
if (spec.getUrl().equals(url)) {
spec.setActivity(activity);
}
}
}
public WebView get(String url) {
if (mWebViewSpecs == null) {
return alloc(url);
}
for (WebViewSpec spec : mWebViewSpecs) {
if (spec.getUrl().equals(url)) {
return spec.getWebView();
}
}
return null;
}
public WebView create(String url) {
WebView webView = get(url);
if (webView == null) {
webView = alloc(url);
}
return webView;
}
public WebView alloc(String url) {
if (url == null) {
return null;
}
if (mWebViewSpecs == null) {
mWebViewSpecs = new ArrayList<WebViewSpec>(POOL_GROWTH);
WebView webView = createWebView(url);
mWebViewSpecs.add(new WebViewSpec(url, webView));
return webView;
} else if (mWebViewSpecs.size() < POOL_SIZE) {
WebView webView = get(url);
if (webView != null)
return webView;
// 压入栈顶
webView = createWebView(url);
mWebViewSpecs.add(new WebViewSpec(url, webView));
return webView;
} else {
WebView webView = get(url);
if (webView != null)
return webView;
// 替换栈尾,并移到栈顶
WebViewSpec spec = mWebViewSpecs.get(0);
spec.loadUrl(url);
mWebViewSpecs.add(spec);
mWebViewSpecs.remove(0);
}
return null;
}
public void free(String url) {
if (mWebViewSpecs == null) return;
int index = -1;
WebViewSpec spec = null;
for (int i=0; i<mWebViewSpecs.size(); i++) {
WebViewSpec aSpec = mWebViewSpecs.get(i);
if (aSpec.getUrl().equals(url)) {
index = i;
spec = aSpec;
break;
}
}
if (index != -1) {
if (mWebViewSpecs.size() < POOL_SIZE) {
spec.release();
mWebViewSpecs.remove(index);
if (mWebViewSpecs.size() == 0) {
mWebViewSpecs = null;
}
} else {
int size = spec.urls.size();
if (size == 1) {
spec.release();
mWebViewSpecs.remove(index);
if (mWebViewSpecs.size() == 0) {
mWebViewSpecs = null;
}
} else {
spec.loadPrevUrl();
}
}
}
}
public WebView createWebView(String url) {
WebView wv = new WebView(Small.getContext());
Log.d("Web", "loadUrl: " + url);
wv.loadUrl(url);
return wv;
}
private final class WebViewSpec {
private ArrayList<String> urls;
private ArrayList<Activity> activities;
private WebView webView;
public WebViewSpec(String url, WebView webView) {
this.webView = webView;
this.loadUrl(url);
}
public void loadUrl(String url) {
if (this.urls != null) {
this.webView.loadData("", "text/html", "utf-8"); // Blank
}
this.webView.loadUrl(url);
this.setUrl(url);
}
public void loadPrevUrl() {
int size = this.urls.size();
int lastIndex = size - 1;
this.urls.remove(lastIndex);
ViewGroup parent = (ViewGroup) this.webView.getParent();
parent.removeView(this.webView);
this.activities.remove(lastIndex);
Activity activity = this.activities.get(lastIndex - 1);
activity.setContentView(this.webView);
this.webView.loadUrl(this.getUrl());
}
public Activity getActivity() {
if (activities == null)
return null;
return activities.get(activities.size() - 1);
}
public void setActivity(Activity activity) {
if (activities == null) {
activities = new ArrayList<Activity>(POOL_GROWTH);
}
activities.add(activity);
}
public String getUrl() {
if (urls == null)
return null;
return urls.get(urls.size() - 1);
}
public void setUrl(String url) {
if (urls == null) {
urls = new ArrayList<String>(POOL_GROWTH);
}
urls.add(url);
}
public WebView getWebView() {
Activity activity = this.getActivity();
if (activity != null) {
ViewGroup parent = (ViewGroup) this.webView.getParent();
if (parent != null) {
parent.removeView(this.webView);
}
}
return this.webView;
}
public void release() {
this.urls = null;
this.activities = null;
this.webView = null;
}
}
}
| 29.02381 | 76 | 0.513399 |
c6df4f726ed186a4b8069f3c1a90968926add735 | 780 | package org.openecomp.sdc.be.model.tosca.constraints;
import org.junit.Test;
import org.openecomp.sdc.be.model.tosca.ToscaType;
public class ConstraintUtilTest {
@Test
public void testCheckStringType() throws Exception {
ToscaType propertyType = ToscaType.STRING;
// default test
ConstraintUtil.checkStringType(propertyType);
}
@Test
public void testCheckComparableType() throws Exception {
ToscaType propertyType = ToscaType.INTEGER;
// default test
ConstraintUtil.checkComparableType(propertyType);
}
@Test
public void testConvertToComparable() throws Exception {
ToscaType propertyType = ToscaType.BOOLEAN;
String value = "";
Comparable result;
// default test
result = ConstraintUtil.convertToComparable(propertyType, value);
}
} | 20.526316 | 67 | 0.766667 |
4f430a11a4ad9f4d4fec52b7abcdd1fb7c301eb5 | 864 | package edu.umass.cs.gigapaxos.interfaces;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* @author arun
*
* @param <V>
*/
public interface RequestFuture<V> {
/**
* @return Refer {@link Future#isDone()}.
*/
public boolean isDone();
/**
* @return Refer {@link Future#get()}.
*
* @throws InterruptedException
* @throws ExecutionException
*/
public V get() throws InterruptedException, ExecutionException;
/**
* @param timeout
* @param unit
* @return Refer {@link Future#get(long, TimeUnit)}.
* @throws InterruptedException
* @throws ExecutionException
* @throws TimeoutException
*/
public V get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException;
}
| 21.6 | 71 | 0.71875 |
fce65dded5aece46fe3d45994e750659be350c8d | 963 | package net.gliby.voicechat.common.networking.packets;
import io.netty.buffer.ByteBuf;
import net.gliby.voicechat.VoiceChat;
import net.gliby.voicechat.common.networking.MinecraftPacket;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
public class MinecraftServerVoiceEndPacket extends MinecraftPacket implements IMessageHandler<MinecraftServerVoiceEndPacket, IMessage> {
@Override
public void fromBytes(ByteBuf buf) {
}
@Override
public IMessage onMessage(MinecraftServerVoiceEndPacket packet, MessageContext ctx) {
VoiceChat.getServerInstance().getVoiceServer().handleVoiceData(ctx.getServerHandler().player, null, (byte) 0, ctx.getServerHandler().player.getEntityId(), true);
return null;
}
@Override
public void toBytes(ByteBuf buf) {
}
}
| 37.038462 | 169 | 0.790239 |
213aa046ac8535b1c414d7a954b728808afa2477 | 751 | package org.dsa.iot.commons;
/**
* Provides an easy way to set variables from an inner class to an
* outer class.
*
* @author Samuel Grenier
*/
public class Container<T> {
private T value;
/**
* Initializes the {@link Container} with no value.
*/
public Container() {
this(null);
}
/**
* Initializes the {@link Container} with a value.
*
* @param value Value to initialize.
*/
public Container(T value) {
this.value = value;
}
/**
* @param value Value to set.
*/
public void setValue(T value) {
this.value = value;
}
/**
* @return Value of the {@link Container}.
*/
public T getValue() {
return value;
}
}
| 17.465116 | 66 | 0.545939 |
2bdf29e7e7e17d9d7527fcd0716110f5e115edf7 | 3,758 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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 org.spongepowered.mod.mixin.core.fml.common;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Strings.emptyToNull;
import com.google.common.collect.ImmutableList;
import net.minecraftforge.fml.common.ModContainer;
import net.minecraftforge.fml.common.ModMetadata;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.asm.mixin.Implements;
import org.spongepowered.asm.mixin.Interface;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.mod.plugin.DependencyHandler;
import org.spongepowered.plugin.meta.PluginDependency;
import java.io.File;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* Make FML mod containers our mod containers.
*/
@Mixin(ModContainer.class)
@Implements(@Interface(iface = PluginContainer.class, prefix = "plugin$"))
public interface MixinModContainer extends ModContainer {
default String getId() {
return checkNotNull(emptyToNull(getModId()), "modid");
}
default Optional<String> plugin$getVersion() {
String version = emptyToNull(getVersion());
if (version != null && (version.equalsIgnoreCase("unknown") || version.equalsIgnoreCase("dev"))) {
version = null;
}
return Optional.ofNullable(version);
}
default Optional<String> getDescription() {
ModMetadata meta = getMetadata();
return meta != null ? Optional.ofNullable(emptyToNull(meta.description)) : Optional.empty();
}
default Optional<String> getUrl() {
ModMetadata meta = getMetadata();
return meta != null ? Optional.ofNullable(emptyToNull(meta.url)) : Optional.empty();
}
default List<String> getAuthors() {
ModMetadata meta = getMetadata();
return meta != null ? ImmutableList.copyOf(meta.authorList) : ImmutableList.of();
}
default Set<PluginDependency> plugin$getDependencies() {
return DependencyHandler.collectDependencies(this);
}
default Optional<PluginDependency> getDependency(String id) {
return Optional.ofNullable(DependencyHandler.findDependency(this, id));
}
default Optional<Path> plugin$getSource() {
File source = getSource();
if (source != null) {
return Optional.of(source.toPath());
}
return Optional.empty();
}
default Optional<?> getInstance() {
return Optional.ofNullable(getMod());
}
}
| 36.843137 | 106 | 0.722991 |
890d5a54a1046a6c0520cf4aca715414e0acd617 | 2,445 | package org.ranji.lemon.model.liquid.authority;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.ranji.lemon.common.core.util.JsonUtil;
/**
* 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.
* Copyright [2017] [RanJi] [[email protected]]
*
* Authority模块中的User用户类
* @author RanJi
* @date 2013-10-1
* @since JDK1.7
* @version 1.0
*/
public class User implements Serializable {
private static final long serialVersionUID = -7866077717886165234L;
private int id;
private String userName; //用户名
private String userPass; //密码
private String phone; //电话
private String email; //邮箱
private String createTime; //创建时间
private List<Role> roleList = new ArrayList<Role>(); //页面显示字段(解决前台缓存列表页直接获取用户角色信息)
public List<Role> getRoleList() {
return roleList;
}
public void setRoleList(List<Role> roleList) {
this.roleList = roleList;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
return JsonUtil.objectToJson(this);
}
}
| 23.285714 | 101 | 0.726789 |
07d47c0a93d0c192e607283015480da14bea9569 | 406 | package sde_questions.arrays.kadanes;
import Algorithms.slidingWindow.minNumberFromSubArray;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
public class MaximumSubArrayTest {
@Test
public void maxNum() {
int[] a = new int[]{-2, 1, -3, 4, -1, 2, 1,-5,4};
int maxOfMins = MaximumSubArray.maxNum(a);
System.out.println(maxOfMins);
}
} | 23.882353 | 57 | 0.67734 |
865727096e21a8d0619d0a33da5d2642bc4e9a31 | 2,412 | /**
* Copyright 2017-2021 O2 Czech Republic, a.s.
*
* 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 cz.o2.proxima.storage.internal;
import com.google.common.collect.Streams;
import cz.o2.proxima.annotations.Internal;
import cz.o2.proxima.repository.DataOperator;
import cz.o2.proxima.repository.Repository;
import java.io.Serializable;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.stream.Collectors;
/** Loader for various implementations of {@link AbstractDataAccessorFactory}. */
@Internal
public class DataAccessorLoader<
OP extends DataOperator,
A extends AbstractDataAccessor,
T extends AbstractDataAccessorFactory<OP, A>>
implements Serializable {
public static <
OP extends DataOperator,
A extends AbstractDataAccessor,
T extends AbstractDataAccessorFactory<OP, A>>
DataAccessorLoader<OP, A, T> of(Repository repo, Class<T> cls) {
return new DataAccessorLoader<>(repo, cls);
}
private final List<T> loaded;
private DataAccessorLoader(Repository repo, Class<T> cls) {
this.loaded = Streams.stream(ServiceLoader.load(cls)).collect(Collectors.toList());
this.loaded.forEach(f -> f.setup(repo));
}
/**
* Find {@link AbstractDataAccessorFactory} that best handles given URI.
*
* @param uri the storage URI to search for
* @return optional {@link AbstractDataAccessorFactory}.
*/
public Optional<T> findForUri(URI uri) {
List<T> acceptConditionally = new ArrayList<>();
for (T f : loaded) {
switch (f.accepts(uri)) {
case ACCEPT:
return Optional.of(f);
case ACCEPT_IF_NEEDED:
acceptConditionally.add(f);
break;
default:
break;
}
}
return acceptConditionally.stream().findAny();
}
}
| 31.736842 | 87 | 0.704809 |
15d002c651120268925ad16f94047b2c2d19f27a | 247 | public abstract class BackupFocused {
protected abstract boolean isComplete();
protected abstract boolean crackPlea(Methodology prevalentMethod);
protected abstract void tallySection(Paper postscript, Methodology continuingMechanisms);
}
| 27.444444 | 91 | 0.825911 |
8ada850249192a5394751c6022ea0fd6cee3b5ef | 13,591 | package com.tle.webtests.test.drm;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import com.dytech.devlib.PropBagEx;
import com.tle.webtests.framework.TestInstitution;
import com.tle.webtests.pageobject.searching.PowerSearchPage;
import com.tle.webtests.pageobject.searching.SearchPage;
import com.tle.webtests.pageobject.viewitem.ItemId;
import com.tle.webtests.pageobject.viewitem.SummaryPage;
import com.tle.webtests.pageobject.wizard.ContributePage;
import com.tle.webtests.pageobject.wizard.DRMAccessWizardPage;
import com.tle.webtests.pageobject.wizard.DRMUsageWizardPage;
import com.tle.webtests.pageobject.wizard.WizardPageTab;
import com.tle.webtests.pageobject.wizard.WizardUrlPage;
import com.tle.webtests.pageobject.wizard.controls.AbstractWizardControlsTest;
import java.util.Calendar;
import java.util.Date;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.Test;
@TestInstitution("fiveo")
public class WizardDRMTest extends AbstractWizardControlsTest {
private static final String AUTOTEST_USERID = "adfcaf58-241b-4eca-9740-6a26d1c3dd58";
private static final String TERM_MSG = "These are the DRM terms";
private static final String ITEM_ALL_NAME = "All Options";
private static final String ITEM_CUSTOM_NAME = "Custom Options";
private static final String ITEM_NO_NAME = "No Options";
private static final String ITEM_CONTROL_NAME = "Control Test";
private static final String COLLECTION_ALL_NAME = "DRM All Contributor Options";
private static final String COLLECTION_CUSTOM_NAME = "DRM Custom Contributor Options";
private static final String COLLECTION_NO_NAME = "DRM No Contributor Options";
@Override
protected void prepareBrowserSession() {
logon();
}
@Test
public void contributeAll() throws Exception {
ContributePage contributePage = new ContributePage(context).load();
WizardPageTab wizardPage = contributePage.openWizard(COLLECTION_ALL_NAME);
wizardPage.editbox(1, context.getFullName(ITEM_ALL_NAME));
wizardPage.next();
DRMUsageWizardPage rightsPage = new DRMUsageWizardPage(context, wizardPage);
rightsPage.setWho("everyone");
rightsPage.addOther("Jolse", "[email protected]");
rightsPage.setWhat("adapt");
wizardPage.next();
DRMAccessWizardPage accessPage = new DRMAccessWizardPage(context, wizardPage);
accessPage.selectUserId(AUTOTEST_USERID);
accessPage.selectNetwork("localhost");
accessPage.setLicenseCount(10);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2020);
cal.set(Calendar.DAY_OF_MONTH, 8);
cal.set(Calendar.MONTH, Calendar.APRIL);
accessPage.setDateRange(new Date(0), cal.getTime());
accessPage.setEducationSector(true);
accessPage.setRequireAttribution(true);
accessPage.setAcceptanceTerms(TERM_MSG);
SummaryPage viewing = wizardPage.save().publish();
ItemId itemId = viewing.getItemId();
soap.login("AutoTest", "automated");
PropBagEx itemXml = new PropBagEx(soap.getItem(itemId.getUuid(), itemId.getVersion(), null));
checkOdrl(itemXml);
wizardPage = new WizardUrlPage(context, itemId).edit();
wizardPage.next();
wizardPage.next();
wizardPage.saveNoConfirm();
itemXml = new PropBagEx(soap.getItem(itemId.getUuid(), itemId.getVersion(), null));
checkOdrl(itemXml);
}
@Test
public void contributeAllNone() throws Exception {
ContributePage contributePage = new ContributePage(context).load();
WizardPageTab wizardPage = contributePage.openWizard(COLLECTION_ALL_NAME);
wizardPage.editbox(1, context.getFullName(""));
wizardPage.next();
DRMUsageWizardPage rightsPage = new DRMUsageWizardPage(context, wizardPage);
rightsPage.setWho("myself");
rightsPage.setWhat("basic");
wizardPage.next();
SummaryPage viewing = wizardPage.save().publish();
ItemId itemId = viewing.getItemId();
soap.login("AutoTest", "automated");
PropBagEx itemXml = new PropBagEx(soap.getItem(itemId.getUuid(), itemId.getVersion(), null));
checkOdrlCustom(itemXml, true);
wizardPage = new WizardUrlPage(context, itemId).edit();
wizardPage.next();
wizardPage.next();
wizardPage.saveNoConfirm();
itemXml = new PropBagEx(soap.getItem(itemId.getUuid(), itemId.getVersion(), null));
checkOdrlCustom(itemXml, true);
}
@Test
public void contributeAllEnableDisableTest() throws Exception {
// DTEC tests 14596, 14597, 14897
ContributePage contributePage = new ContributePage(context).load();
WizardPageTab wizardPage = contributePage.openWizard(COLLECTION_ALL_NAME);
String fullitemname = context.getFullName(ITEM_CONTROL_NAME);
wizardPage.editbox(1, fullitemname);
wizardPage.next();
DRMUsageWizardPage rightsPage = new DRMUsageWizardPage(context, wizardPage);
rightsPage.setWho("myself");
rightsPage.setWhat("basic");
wizardPage.next();
DRMAccessWizardPage accessPage = new DRMAccessWizardPage(context, wizardPage);
// Enable disable Licence acceptance control
assertFalse(accessPage.isLicenseCountEnabled());
accessPage.enableLicenseCount(true);
assertTrue(accessPage.isLicenseCountEnabled());
accessPage.enableLicenseCount(false);
assertFalse(accessPage.isLicenseCountEnabled());
// Enable disable DRM date range control
assertFalse(accessPage.isDateRangeEnabled());
accessPage.enableDateRange(true);
assertTrue(accessPage.isDateRangeEnabled());
accessPage.enableDateRange(false);
assertFalse(accessPage.isDateRangeEnabled());
// Require agreement and attempt save without agreement filled
assertFalse(accessPage.isRequireTermsAcceptanceEnabled());
accessPage.enableRequireTermsAcceptance(true);
assertTrue(accessPage.isRequireTermsAcceptanceEnabled());
accessPage = wizardPage.save().finishInvalid(accessPage);
// Check for error and enter
accessPage.hasError("Please enter a value in this field");
accessPage.setAcceptanceTerms(TERM_MSG);
// Fill out correctly and save and get ItemID
ItemId itemId = wizardPage.save().publish().getItemId();
// Search page
SearchPage searchPage = new SearchPage(context).load();
// Choose power search
PowerSearchPage powerSearchPage = searchPage.setWithinPowerSearch("DRM Party search");
// Fill out criteria
WebElement control = powerSearchPage.getControl(1);
control.clear();
control.sendKeys("Auto Test");
// Get results
searchPage = powerSearchPage.search();
searchPage.exactQuery(fullitemname);
Assert.assertEquals(searchPage.results().getResult(1).getTitle(), fullitemname);
// Check item xml
soap.login("AutoTest", "automated");
PropBagEx itemXml = new PropBagEx(soap.getItem(itemId.getUuid(), itemId.getVersion(), null));
assertEquals(itemXml, "/item/rights/offer/party/context/name", "Auto Test [AutoTest]");
soap.logout();
}
@Test
public void contributeCustom() throws Exception {
ContributePage contributePage = new ContributePage(context).load();
WizardPageTab wizardPage = contributePage.openWizard(COLLECTION_CUSTOM_NAME);
wizardPage.editbox(1, context.getFullName(ITEM_CUSTOM_NAME));
wizardPage.next();
DRMUsageWizardPage rightsPage = new DRMUsageWizardPage(context, wizardPage);
rightsPage.setWho("myself");
rightsPage.setWhat("custom");
rightsPage.setCustomUse(true, "print", "play");
rightsPage.setCustomUse(false, "display", "execute");
rightsPage.setCustomReuse(true, "modify", "excerpt");
rightsPage.setCustomReuse(false, "annotate", "aggregate");
SummaryPage viewing = wizardPage.save().publish();
ItemId itemId = viewing.getItemId();
soap.login("AutoTest", "automated");
PropBagEx itemXml = new PropBagEx(soap.getItem(itemId.getUuid(), itemId.getVersion(), null));
checkOdrlCustom(itemXml, false);
wizardPage = new WizardUrlPage(context, itemId).edit();
wizardPage.next();
rightsPage.setWhat("basic");
wizardPage.saveNoConfirm();
itemXml = new PropBagEx(soap.getItem(itemId.getUuid(), itemId.getVersion(), null));
checkOdrlCustom(itemXml, true);
}
private void checkOdrlCustom(PropBagEx itemXml, boolean basic) {
PropBagEx rightsXml = itemXml.getSubtree("item/rights/offer");
assertUser(
rightsXml.getSubtree("party[0]"),
"Auto Test [AutoTest]",
"[email protected]",
AUTOTEST_USERID,
true);
PropBagEx permissionXml = rightsXml.getSubtree("permission");
if (!basic) {
assertPermissions(permissionXml, "print", "play", "modify", "excerpt");
assertNonPermissions(permissionXml, "display", "execute", "annotate", "aggregate");
} else {
assertPermissions(permissionXml, "display", "execute", "print", "play");
assertNonPermissions(permissionXml, "modify", "excerpt", "annotate", "aggregate");
}
assertFalse(permissionXml.nodeExists("requirement/accept"));
assertNoConstraints(permissionXml);
}
@Test
public void contributeNone() throws Exception {
ContributePage contributePage = new ContributePage(context).load();
WizardPageTab wizardPage = contributePage.openWizard(COLLECTION_NO_NAME);
wizardPage.editbox(1, context.getFullName(ITEM_NO_NAME));
wizardPage.next();
DRMUsageWizardPage rightsPage = new DRMUsageWizardPage(context, wizardPage);
rightsPage.setWho("others");
rightsPage.addOther("Jolse", "[email protected]");
SummaryPage viewing = wizardPage.save().publish();
ItemId itemId = viewing.getItemId();
soap.login("AutoTest", "automated");
PropBagEx itemXml = new PropBagEx(soap.getItem(itemId.getUuid(), itemId.getVersion(), null));
checkOdrlNone(itemXml);
wizardPage = new WizardUrlPage(context, itemId).edit();
wizardPage.next();
wizardPage.saveNoConfirm();
itemXml = new PropBagEx(soap.getItem(itemId.getUuid(), itemId.getVersion(), null));
checkOdrlNone(itemXml);
}
private void checkOdrlNone(PropBagEx itemXml) {
PropBagEx rightsXml = itemXml.getSubtree("item/rights/offer");
assertUser(
rightsXml.getSubtree("party[0]"), "Jolse", "[email protected]", null, false);
PropBagEx permissionXml = rightsXml.getSubtree("permission");
assertNonPermissions(
permissionXml,
"display",
"execute",
"play",
"print",
"modify",
"excerpt",
"annotate",
"aggregate");
assertFalse(permissionXml.nodeExists("requirement/accept"));
assertNoConstraints(permissionXml);
}
private void assertNoConstraints(PropBagEx permissionXml) {
PropBagEx constraintXml = permissionXml.getSubtree("container/constraint");
if (constraintXml != null) {
assertFalse(constraintXml.nodeExists("purpose"));
assertFalse(constraintXml.nodeExists("individual"));
assertFalse(constraintXml.nodeExists("count"));
assertFalse(constraintXml.nodeExists("network"));
assertFalse(constraintXml.nodeExists("datetime"));
}
}
private void checkOdrl(PropBagEx itemXml) {
PropBagEx rightsXml = itemXml.getSubtree("item/rights/offer");
assertUser(
rightsXml.getSubtree("party[0]"),
"Auto Test [AutoTest]",
"[email protected]",
AUTOTEST_USERID,
true);
assertUser(
rightsXml.getSubtree("party[1]"), "Jolse", "[email protected]", null, false);
PropBagEx permissionXml = rightsXml.getSubtree("permission");
assertPermissions(
permissionXml,
"display",
"execute",
"play",
"print",
"modify",
"excerpt",
"annotate",
"aggregate");
assertTrue(permissionXml.nodeExists("requirement/attribution"));
assertEquals(permissionXml, "requirement/accept/context/remark", TERM_MSG);
PropBagEx constraintXml = permissionXml.getSubtree("container/constraint");
assertEquals(constraintXml, "purpose/@type", "sectors:educational");
assertUser(constraintXml.getSubtree("individual"), null, null, AUTOTEST_USERID, false);
assertEquals(constraintXml, "count", "10");
assertNetwork(constraintXml.getSubtree("network"), "localhost", "127.0.0.1", "127.0.0.1");
assertEquals(constraintXml, "datetime/start", "1970-01-01T00:00:00");
assertEquals(constraintXml, "datetime/end", "2020-04-08T00:00:00");
}
private void assertNetwork(PropBagEx networkXml, String name, String min, String max) {
assertEquals(networkXml, "@name", name);
assertEquals(networkXml, "range/min", min);
assertEquals(networkXml, "range/max", max);
}
private void assertPermissions(PropBagEx permissionXml, String... permissions) {
for (String permission : permissions) {
assertTrue(permissionXml.nodeExists(permission), "Missing permission '" + permission + "':");
}
}
private void assertNonPermissions(PropBagEx permissionXml, String... permissions) {
for (String permission : permissions) {
assertFalse(
permissionXml.nodeExists(permission), "Shouldn't have permission '" + permission + "':");
}
}
private void assertUser(PropBagEx party, String name, String email, String uuid, boolean owner) {
PropBagEx context = party.getSubtree("context");
Assert.assertEquals(context.isNodeTrue("@owner"), owner);
if (name != null) {
assertEquals(context, "name", name);
}
if (email != null) {
assertEquals(context, "remark", email);
}
if (uuid != null) {
assertEquals(context, "uid", "tle:" + uuid);
}
}
}
| 41.31003 | 99 | 0.723126 |
89d6ee54208088383f2ba52692f5737805a2b7ee | 558 | package vip.gadfly.chakkispring.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import vip.gadfly.chakkispring.model.QuestionnaireQuestionOptionDO;
import vip.gadfly.chakkispring.vo.OptionVO;
import java.util.List;
/**
* @author Gadfly
*/
@Repository
public interface QuestionnaireQuestionOptionMapper extends BaseMapper<QuestionnaireQuestionOptionDO> {
List<OptionVO> selectOptionsByQuestionId(@Param("questionId") Integer questionId);
}
| 31 | 102 | 0.831541 |
84f6c5e951f96ff3f78bcd1fff92c7deaa31da58 | 5,054 | package com.yao2san.sim.gateway.api.service.impl;
import com.github.pagehelper.PageInfo;
import com.yao2san.sim.framework.web.service.impl.BaseServiceImpl;
import com.yao2san.sim.gateway.api.request.GrayRouteReq;
import com.yao2san.sim.gateway.api.request.RouteReq;
import com.yao2san.sim.gateway.api.response.GrayRouteRes;
import com.yao2san.sim.gateway.api.response.RouteRes;
import com.yao2san.sim.gateway.api.service.GrayRouteManagerService;
import com.yao2san.sim.gateway.api.service.RouteManagerService;
import com.yao2san.sim.gateway.config.Constant;
import com.yao2san.sim.gateway.route.gray.GrayRouteHelper;
import com.yao2san.sim.gateway.utils.ServiceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Set;
@Service
public class GrayRouteManagerServiceImpl extends BaseServiceImpl implements GrayRouteManagerService {
@Autowired
private RouteManagerService routeManagerService;
@Override
public GrayRouteRes detail(Long routeGrayId) {
return this.sqlSession.selectOne("grayRoute.detail", routeGrayId);
}
@Override
public PageInfo<RouteRes> list(GrayRouteReq grayRouteReq) {
return this.qryList("grayRoute.list", grayRouteReq);
}
@Override
@Transactional
public void add(GrayRouteReq grayRouteReq) {
grayRouteReq.setStatus("1200");
this.sqlSession.insert("grayRoute.add", grayRouteReq);
}
@Override
public void delete(Long routeGrayId) {
this.sqlSession.delete("grayRoute.delete", routeGrayId);
}
@Override
@Transactional
public void update(GrayRouteReq grayRouteReq) {
this.sqlSession.update("grayRoute.update", grayRouteReq);
}
@Override
@Transactional
public void online(Long routeGrayId) {
//update service instances metadata
GrayRouteRes grayRouteRes = this.detail(routeGrayId);
Set<String> serviceInstances = grayRouteRes.getServiceInstances();
if (serviceInstances != null) {
for (String serviceInstance : serviceInstances) {
ServiceUtil.upsertMetadata(
grayRouteRes.getServiceId(),
serviceInstance,
Constant.VERSION_KEY,
grayRouteRes.getGrayVersion());
ServiceUtil.upsertMetadata(
grayRouteRes.getServiceId(),
serviceInstance,
Constant.GRAY_STATUS_KEY,
"1");
}
}
//update status
GrayRouteReq req = new GrayRouteReq();
req.setRouteGrayId(routeGrayId);
req.setStatus("1000");
this.update(req);
GrayRouteHelper.refresh();
}
@Override
@Transactional
public void offline(Long routeGrayId) {
//update service instances metadata
GrayRouteRes grayRouteRes = this.detail(routeGrayId);
RouteRes routeRes = routeManagerService.detail(grayRouteRes.getRouteId());
Set<String> serviceInstances = grayRouteRes.getServiceInstances();
if (serviceInstances != null) {
for (String serviceInstance : serviceInstances) {
ServiceUtil.upsertMetadata(
grayRouteRes.getServiceId(),
serviceInstance,
Constant.GRAY_STATUS_KEY,
"-1");
}
}
//update status
GrayRouteReq req = new GrayRouteReq();
req.setRouteGrayId(routeGrayId);
req.setStatus("1300");
this.update(req);
GrayRouteHelper.refresh();
}
@Override
@Transactional
public void formal(Long routeGrayId) {
GrayRouteReq grayRoute = new GrayRouteReq();
grayRoute.setRouteGrayId(routeGrayId);
GrayRouteRes grayRouteRes = this.detail(routeGrayId);
//update service instance
Set<String> serviceInstances = grayRouteRes.getServiceInstances();
for (String serviceInstance : serviceInstances) {
ServiceUtil.upsertMetadata(
grayRouteRes.getServiceId(),
serviceInstance,
Constant.GRAY_STATUS_KEY,
"0");
ServiceUtil.upsertMetadata(
grayRouteRes.getServiceId(),
serviceInstance,
Constant.VERSION_KEY,
grayRouteRes.getMainVersion());
}
// update route.version to current gray version
/*RouteReq routeReq = new RouteReq();
routeReq.setRouteId(grayRouteRes.getRouteId());
routeReq.setVersion(grayRouteRes.getMainVersion());
routeManagerService.update(routeReq);*/
//update gray route to formal
grayRoute.setStatus("1400");
this.update(grayRoute);
//refresh gray routes
GrayRouteHelper.refresh();
}
}
| 35.097222 | 101 | 0.64444 |
d3f147a0f63fcd67c90273becebd6cfeb3e46699 | 326 | package JavaSE.day25.demo2;
/*
* String s = "abc";final char[] value
*/
public class Demo {
public static void main(String[] args) {
int[] arr = {1};
System.out.println(arr);
char[] ch = {'a', 'b'};
System.out.println(ch);
byte[] b = {};
System.out.println(b);
}
}
| 18.111111 | 44 | 0.509202 |
294352567c6601b18a1132398ba5232865561b85 | 172 | package DataStructures.Hashing;
public class MapObject {
int key, val;
public MapObject(int key, int val) {
this.key = key;
this.val = val;
}
} | 19.111111 | 40 | 0.604651 |
8d38e8d8cb34be95cb530df55a3ca5067dc3eee8 | 1,066 | package com.williamlian.showme.client.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
@JsonIgnoreProperties(ignoreUnknown = true)
public class GoogleImageSearchResult implements Serializable{
public String width;
public String height;
public String imageId;
@JsonProperty("tbWidth")
private String thumbnailWidth;
@JsonProperty("tbHeight")
private String thumbnailHeight;
public String url;
public String visibleUrl;
public String title;
@JsonProperty("titleNoFormatting")
public String plainTitle;
@JsonProperty("tbUrl")
public String thumbnailUrl;
public int getWidth() {
return Integer.parseInt(width);
}
public int getHeight() {
return Integer.parseInt(height);
}
public int getThumbnailWidth() {
return Integer.parseInt(thumbnailWidth);
}
public int getThumbnailHeight() {
return Integer.parseInt(thumbnailHeight);
}
}
| 20.901961 | 62 | 0.71576 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.