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
|
|---|---|---|---|---|---|
10d948a26ee16b82c57170c3e03868a09f583db8
| 4,345
|
/**
* JBoss, Home of Professional Open Source
* Copyright Red Hat, Inc., and individual contributors.
*
* 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.jboss.aerogear.unifiedpush.api.validation;
import org.jboss.aerogear.unifiedpush.api.VariantType;
import org.jboss.aerogear.unifiedpush.api.Installation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;
/**
* Validator that will validate if the device token matches to {@code VariantType} specific pattern.
* @see VariantType
*/
public class DeviceTokenValidator implements ConstraintValidator<DeviceTokenCheck, Installation> {
/**
* Pattern for iOS is pretty well defined as the library we use for sending assumes HEX.
* @see <a href="https://github.com/notnoop/java-apns/blob/20c10ebd22e15a55c0c1c12695c535d37435dcfd/src/main/java/com/notnoop/apns/internal/Utilities.java#L114">notnoop apns</a>
*/
private static final Pattern IOS_DEVICE_TOKEN = Pattern.compile("(?i)[a-f0-9 -]{64,}");
/**
* Pattern for android is harder to define that is why we kept it lenient it is at least 100 characters long and can
* consist of digits, alphas, - and _ all have one of these separators
*/
private static final Pattern ANDROID_DEVICE_TOKEN = Pattern.compile("(?i)[0-9a-z\\-_:]{100,}");
/**
* Pattern for windows is a uri that can be 1024 characters long
* @see <a href="http://blogs.windows.com/windows_phone/b/wpdev/archive/2013/10/22/recommended-practices-for-using-microsoft-push-notification-service-mpns.aspx?Redirected=true">Windows developer blog</a>
*/
private static final Pattern WINDOWS_DEVICE_TOKEN = Pattern.compile("https?://.{0,1024}");
/**
* The SimplePush token is an URI. While we strongly recommend https, it is in theory possible that users of the
* AeroGear SimplePush Server do not protect the "update" endpoint via SSL.
*/
private static final Pattern SIMPLE_PUSH_DEVICE_TOKEN = Pattern.compile("https?://.{0,2000}");
/**
* Pattern for Amazon is harder to define that is why we kept it lenient it is at least 100 characters long and can
* consist of digits, alphas, - , _ and . and all have one of these separators
*/
private static final Pattern ADM_DEVICE_TOKEN = Pattern.compile("(?i)[0-9a-z\\-_.]{100,}");
@Override
public void initialize(DeviceTokenCheck constraintAnnotation) {
}
@Override
public boolean isValid(Installation installation, ConstraintValidatorContext context) {
final String deviceToken = installation.getDeviceToken();
if (installation.getVariant() == null || installation.getVariant().getType() == null || deviceToken == null) {
return false;
}
final VariantType type = installation.getVariant().getType();
return isValidDeviceTokenForVariant(deviceToken, type);
}
/**
* Helper to run quick up-front validations.
*
* @param deviceToken the submitted device token
* @param type type of the variant
* @return true if the token is valid
*/
public static boolean isValidDeviceTokenForVariant(final String deviceToken, final VariantType type) {
switch (type) {
case IOS:
return IOS_DEVICE_TOKEN.matcher(deviceToken).matches();
case ANDROID:
return ANDROID_DEVICE_TOKEN.matcher(deviceToken).matches();
case WINDOWS_WNS:
return WINDOWS_DEVICE_TOKEN.matcher(deviceToken).matches();
case SIMPLE_PUSH:
return SIMPLE_PUSH_DEVICE_TOKEN.matcher(deviceToken).matches();
case ADM:
return ADM_DEVICE_TOKEN.matcher(deviceToken).matches();
}
return false;
}
}
| 44.336735
| 208
| 0.701726
|
ad65326395dd63cfe37534aeee8aa6ddabd9a0e6
| 5,082
|
package ncu.cc.digger.services;
import ncu.cc.commons.utils.StackTraceUtil;
import ncu.cc.commons.webdev.models.MenuEntry;
import ncu.cc.commons.webdev.utils.MenuBuilder;
import ncu.cc.digger.constants.RolesEnum;
import ncu.cc.digger.constants.ValueConstants;
import ncu.cc.digger.security.AppUserAuthentication;
import ncu.cc.digger.security.AppUserDetails;
import ncu.cc.digger.security.AuthenticationService;
import ncu.cc.digger.sessionbeans.MenuBarSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @author Mac Liu (linuzilla@gmail.com)
* @version 1.0
* @since 1.0
*/
@Service
public class MenuServiceImpl implements MenuService {
@Autowired
private AuthenticationService authenticationService;
@Value(ValueConstants.CONTEXT_PATH)
private String contextPath;
@Autowired
private MessageResourceService messageResourceService;
@Autowired
private MenuBuilder menuBuilder;
private List<MenuBarSession.Entry> recursiveBuildMenu(AppUserAuthentication principal, String rootKey, String parentUrl, List<MenuEntry> menuEntries) {
List<MenuBarSession.Entry> list = new ArrayList<>();
for (MenuEntry entry: menuEntries) {
String messageKey = rootKey + "." + entry.getName();
String urlpath = parentUrl + entry.getUrlpath();
boolean requireAuthorities = false;
boolean haveAuthority = false;
// FIXME
if (entry.getAuthorities() != null && entry.getAuthorities().length > 0) {
for (String authority : entry.getAuthorities()) {
if (authority != null && authority.length() > 0) {
requireAuthorities = true;
if (principal == null) {
break;
} else if (principal.hasRole(RolesEnum.toAuthority(authority))) {
haveAuthority = true;
break;
}
}
}
}
if (principal != null && entry.getNegativeAuthorities() != null && entry.getNegativeAuthorities().length > 0) {
for (String authority: entry.getNegativeAuthorities()) {
if (authority != null && authority.length() > 0) {
if (principal.hasRole(RolesEnum.toAuthority(authority))) {
requireAuthorities = true;
haveAuthority = false;
break;
}
}
}
}
if (!requireAuthorities || haveAuthority) {
MenuBarSession.Entry menuBarEntry = new MenuBarSession.Entry();
menuBarEntry.setMessageKey(messageKey);
menuBarEntry.setUrlpath(urlpath);
menuBarEntry.setOrder(entry.getOrder());
if (entry.getSubmenu() != null && entry.getSubmenu().size() > 0) {
List<MenuBarSession.Entry> entries = recursiveBuildMenu(principal, messageKey, parentUrl, entry.getSubmenu());
if (entries != null && entries.size() > 0) {
menuBarEntry.setSubentries(entries);
}
}
list.add(menuBarEntry);
}
}
Collections.sort(list, Comparator.comparingInt(MenuBarSession.Entry::getOrder));
return list;
}
@Override
public void fillLocalizationMessage(List<MenuBarSession.Entry> menu) {
for (MenuBarSession.Entry entry: menu) {
try {
entry.setMessage(messageResourceService.getMessage(entry.getMessageKey()));
} catch (Exception e) {
StackTraceUtil.print1(entry.getMessageKey() + " not apply");
entry.setMessage(entry.getMessageKey());
}
if (entry.getSubentries() != null) {
fillLocalizationMessage(entry.getSubentries());
}
}
}
@Override
public List<MenuBarSession.Entry> buildMenu() {
String parentUrl = contextPath != null && ! "/".equals(contextPath) ? contextPath : "";
Authentication authentication = authenticationService.getAuthentication();
if (authentication instanceof AppUserAuthentication) {
var appUserAuthentication = (AppUserAuthentication) authentication;
return recursiveBuildMenu(appUserAuthentication,
"menu", parentUrl, menuBuilder.getRootMenuEntry().getSubmenu());
} else {
return recursiveBuildMenu(null,
"menu", parentUrl, menuBuilder.getRootMenuEntry().getSubmenu());
}
}
}
| 39.092308
| 155
| 0.60547
|
a317a61be97967c023cbad804bb609930fde8d32
| 10,295
|
/*
* Copyright 2000-2018 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.flow.internal;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.LoggerFactory;
/**
* Utility class for Java Beans information access.
*
*
* @author Vaadin Ltd
* @since 1.0
*/
public final class BeanUtil implements Serializable {
// Prevent instantiation of util class
private BeanUtil() {
}
/**
* Returns the property descriptors of a class or an interface.
*
* For an interface, superinterfaces are also iterated as Introspector does
* not take them into account (Oracle Java bug 4275879), but in that case,
* both the setter and the getter for a property must be in the same
* interface and should not be overridden in subinterfaces for the discovery
* to work correctly.
* <p>
* NOTE : This utility method relies on introspection (and returns
* PropertyDescriptor) which is a part of java.beans package. The latter
* package could require bigger JDK in the future (with Java 9+). So it may
* be changed in the future.
* <p>
* For interfaces, the iteration is depth first and the properties of
* superinterfaces are returned before those of their subinterfaces.
*
* @param beanType
* the type whose properties to query
* @return a list of property descriptors of the given type
* @throws IntrospectionException
* if the introspection fails
*/
public static List<PropertyDescriptor> getBeanPropertyDescriptors(
final Class<?> beanType) throws IntrospectionException {
// Oracle bug 4275879: Introspector does not consider superinterfaces of
// an interface
if (beanType.isInterface()) {
List<PropertyDescriptor> propertyDescriptors = new ArrayList<>();
for (Class<?> cls : beanType.getInterfaces()) {
propertyDescriptors.addAll(getBeanPropertyDescriptors(cls));
}
BeanInfo info = Introspector.getBeanInfo(beanType);
propertyDescriptors.addAll(getPropertyDescriptors(info));
return propertyDescriptors;
} else {
BeanInfo info = Introspector.getBeanInfo(beanType);
return getPropertyDescriptors(info);
}
}
/**
* Returns the type of the property with the given name and declaring class.
* The property name may refer to a nested property, e.g.
* "property.subProperty" or "property.subProperty1.subProperty2". The
* property must have a public read method (or a chain of read methods in
* case of a nested property).
*
* @param beanType
* the type declaring the property
* @param propertyName
* the name of the property
* @return the property type
* @throws IntrospectionException
* if the introspection fails
*/
public static Class<?> getPropertyType(Class<?> beanType,
String propertyName) throws IntrospectionException {
PropertyDescriptor descriptor = getPropertyDescriptor(beanType,
propertyName);
if (descriptor != null) {
return descriptor.getPropertyType();
} else {
return null;
}
}
/**
* Returns the property descriptor for the property of the given name and
* declaring class. The property name may refer to a nested property, e.g.
* "property.subProperty" or "property.subProperty1.subProperty2". The
* property must have a public read method (or a chain of read methods in
* case of a nested property).
*
* @param beanType
* the type declaring the property
* @param propertyName
* the name of the property
* @return the corresponding descriptor
* @throws IntrospectionException
* if the introspection fails
*/
public static PropertyDescriptor getPropertyDescriptor(Class<?> beanType,
String propertyName) throws IntrospectionException {
if (propertyName.contains(".")) {
String[] parts = propertyName.split("\\.", 2);
// Get the type of the field in the bean class
Class<?> propertyBean = getPropertyType(beanType, parts[0]);
// Find the rest from the sub type
return getPropertyDescriptor(propertyBean, parts[1]);
} else {
List<PropertyDescriptor> descriptors = getBeanPropertyDescriptors(
beanType);
for (PropertyDescriptor descriptor : descriptors) {
final Method getMethod = descriptor.getReadMethod();
if (descriptor.getName().equals(propertyName)
&& getMethod != null
&& getMethod.getDeclaringClass() != Object.class) {
return descriptor;
}
}
return null;
}
}
/**
* Returns whether an implementation of JSR-303 version 1.0 or 1.1 is
* present on the classpath. If this method returns false, trying to create
* a {@code BeanValidator} instance will throw an
* {@code IllegalStateException}. If an implementation is not found, logs a
* level {@code FINE} message the first time it is run.
*
* @return {@code true} if bean validation is available, {@code false}
* otherwise.
*/
public static boolean checkBeanValidationAvailable() {
return LazyValidationAvailability.BEAN_VALIDATION_AVAILABLE;
}
// Workaround for Java6 bug JDK-6788525. Do nothing for JDK7+.
private static List<PropertyDescriptor> getPropertyDescriptors(
BeanInfo beanInfo) {
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
List<PropertyDescriptor> result = new ArrayList<>(descriptors.length);
for (PropertyDescriptor descriptor : descriptors) {
try {
result.add(fixPropertyDescriptor(descriptor));
} catch (SecurityException exception) {
LoggerFactory.getLogger(BeanUtil.class.getName()).info(null,
exception);
// handle next descriptor
} catch (IntrospectionException e) {
LoggerFactory.getLogger(BeanUtil.class.getName()).info(null,
e);
result.add(descriptor);
}
}
return result;
}
private static PropertyDescriptor fixPropertyDescriptor(
PropertyDescriptor descriptor) throws IntrospectionException {
Method readMethod = getMethodFromBridge(descriptor.getReadMethod());
if (readMethod != null) {
Method writeMethod = getMethodFromBridge(
descriptor.getWriteMethod(), readMethod.getReturnType());
if (writeMethod == null) {
writeMethod = descriptor.getWriteMethod();
}
return new PropertyDescriptor(descriptor.getName(), readMethod,
writeMethod);
} else {
return descriptor;
}
}
/**
* Return declared method for which {@code bridgeMethod} is generated. If
* {@code bridgeMethod} is not a bridge method then return null.
*/
private static Method getMethodFromBridge(Method bridgeMethod)
throws SecurityException {
if (bridgeMethod == null) {
return null;
}
return getMethodFromBridge(bridgeMethod,
bridgeMethod.getParameterTypes());
}
/**
* Return declared method for which {@code bridgeMethod} is generated using
* its {@code paramTypes}. If {@code bridgeMethod} is not a bridge method
* then return null.
*/
private static Method getMethodFromBridge(Method bridgeMethod,
Class<?>... paramTypes) throws SecurityException {
if (bridgeMethod == null || !bridgeMethod.isBridge()) {
return null;
}
try {
return bridgeMethod.getDeclaringClass()
.getMethod(bridgeMethod.getName(), paramTypes);
} catch (NoSuchMethodException e) {
return null;
}
}
private static class LazyValidationAvailability implements Serializable {
private static final boolean BEAN_VALIDATION_AVAILABLE = isAvailable();
private LazyValidationAvailability() {
}
private static boolean isAvailable() {
try {
Class<?> clazz = Class.forName("javax.validation.Validation");
Method method = clazz.getMethod("buildDefaultValidatorFactory");
method.invoke(null);
return true;
} catch (ClassNotFoundException | NoSuchMethodException
| InvocationTargetException e) {
LoggerFactory.getLogger("com.vaadin.validator.BeanValidator").info(
"A JSR-303 bean validation implementation not found on the classpath or could not be initialized. BeanValidator cannot be used.",
e);
return false;
} catch (IllegalAccessException | IllegalArgumentException e) {
throw new RuntimeException(
"Unable to invoke javax.validation.Validation.buildDefaultValidatorFactory()",
e);
}
}
}
}
| 39.903101
| 153
| 0.631083
|
8fcdf2c9bb6329aafda8ed3ee145ffbae172557b
| 7,727
|
package ristogo.ui.graphics;
import java.util.Optional;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import ristogo.common.entities.Reservation;
import ristogo.common.entities.Restaurant;
import ristogo.common.entities.User;
import ristogo.common.net.ResponseMessage;
import ristogo.net.Protocol;
import ristogo.ui.graphics.config.GUIConfig;
import ristogo.ui.graphics.controls.FormButton;
public final class RistogoGUI extends Application
{
private static User loggedUser;
private static Restaurant restaurant;
private static ModifyRestaurantForm restaurantForm;
@Override
public void start(Stage primaryStage)
{
LoginDialog login = new LoginDialog();
Optional<User> result = login.showAndWait();
result.ifPresentOrElse(
data -> { loggedUser = data; },
() -> { System.exit(0); }
);
HBox applicationInterface;
applicationInterface = loggedUser.isOwner() ? buildOwnerInterface() : buildCustomerInterface();
Scene scene = new Scene(new Group(applicationInterface));
scene.setFill(GUIConfig.getBgColor());
primaryStage.setTitle("RistoGo");
primaryStage.setResizable(true);
primaryStage.setScene(scene);
primaryStage.getIcons().add(new Image("/resources/logo.png"));
primaryStage.show();
}
@Override
public void stop()
{
Protocol.getInstance().performLogout();
System.exit(0);
}
private HBox buildCustomerInterface()
{
HBox applicationInterface = new HBox(10);
GridPane title = generateTitle();
Label reservationsTableTitle = new Label("List of Restaurant: you can find restaurants searching by city");
reservationsTableTitle.setFont(GUIConfig.getFormTitleFont());
reservationsTableTitle.setTextFill(GUIConfig.getFgColor());
reservationsTableTitle.setStyle(GUIConfig.getCSSFormTitleStyle());
TableViewReservation reservationsTable = new TableViewReservation();
reservationsTable.refreshReservations();
BookForm bookForm = new BookForm(reservationsTable::refreshReservations);
TextField findCityField = new TextField();
findCityField.setPromptText("insert a name of a city");
findCityField.setMinSize(200, 30);
findCityField.setMaxSize(200, 30);
Button find = new Button("Find");
find.setFont(GUIConfig.getButtonFont());
find.setTextFill(GUIConfig.getInvertedFgColor());
find.setStyle(GUIConfig.getInvertedCSSButtonBgColor());
HBox findBox = new HBox(10);
findBox.getChildren().addAll(findCityField, find);
TableViewRestaurant restaurantsTable = new TableViewRestaurant();
restaurantsTable.refreshRestaurants();
Label descriptionLabel = new Label("Description: ");
descriptionLabel.setFont(GUIConfig.getBoldVeryTinyTextFont());
descriptionLabel.setTextFill(GUIConfig.getFgColor());
TextArea descriptionField = new TextArea();
descriptionField.setWrapText(true);
descriptionField.setEditable(false);
descriptionField.setMinSize(480, 100);
descriptionField.setMaxSize(480, 100);
HBox descriptionBox = new HBox(20);
descriptionBox.getChildren().addAll(descriptionLabel, descriptionField);
Label restaurantsTableTitle = new Label("My Reservation");
restaurantsTableTitle.setFont(GUIConfig.getFormTitleFont());
restaurantsTableTitle.setTextFill(GUIConfig.getFgColor());
restaurantsTableTitle.setStyle(GUIConfig.getCSSFormTitleStyle());
restaurantsTable.setOnMouseClicked((event) -> {
Restaurant restaurant = restaurantsTable.getSelectedEntity();
if (restaurant == null)
return;
bookForm.fill(restaurant);
descriptionField.setText(restaurant.getDescription());
});
reservationsTable.setOnMouseClicked((event) -> {
Reservation reservation = reservationsTable.getSelectedEntity();
if (reservation == null)
return;
bookForm.fill(reservation);
});
find.setOnAction((event) -> {
String city = findCityField.getText();
if (city == null)
return;
restaurantsTable.refreshRestaurants(city);
});
VBox leftPart = new VBox(10);
VBox rightPart = new VBox(10);
leftPart.getChildren().addAll(title, bookForm);
rightPart.getChildren().addAll(reservationsTableTitle,findBox, restaurantsTable, descriptionBox, restaurantsTableTitle, reservationsTable);
applicationInterface.getChildren().addAll(leftPart, rightPart);
leftPart.setStyle(GUIConfig.getCSSInterfacePartStyle());
rightPart.setStyle(GUIConfig.getCSSInterfacePartStyle());
leftPart.setPrefSize(400, 600);
rightPart.setPrefSize(600, 600);
applicationInterface.setPrefSize(1000, 600);
return applicationInterface;
}
private HBox buildOwnerInterface()
{
HBox applicationInterface = new HBox(10);
GridPane title = generateTitle();
restaurantForm = new ModifyRestaurantForm(this::getOwnRestaurant);
getOwnRestaurant();
Label reservationsTableTitle = new Label("List of Reservations at your restaurant");
reservationsTableTitle.setFont(GUIConfig.getFormTitleFont());
reservationsTableTitle.setTextFill(GUIConfig.getFgColor());
reservationsTableTitle.setStyle(GUIConfig.getCSSFormTitleStyle());
TableViewReservation reservationsTable = new TableViewReservation(restaurant);
reservationsTable.refreshReservations();
FormButton refreshButton = new FormButton("Refresh");
refreshButton.setOnAction((ActionEvent ev) -> {
reservationsTable.refreshReservations();
});
VBox leftPart = new VBox(10);
VBox rightPart = new VBox(10);
leftPart.getChildren().addAll(title, restaurantForm);
rightPart.getChildren().addAll(reservationsTableTitle, reservationsTable, refreshButton);
applicationInterface.getChildren().addAll(leftPart, rightPart);
leftPart.setStyle(GUIConfig.getCSSInterfacePartStyle());
rightPart.setStyle(GUIConfig.getCSSInterfacePartStyle());
leftPart.setPrefSize(400, 600);
rightPart.setPrefSize(600, 600);
applicationInterface.setPrefSize(1000, 600);
rightPart.setAlignment(Pos.CENTER);
return applicationInterface;
}
private GridPane generateTitle()
{
Label title = new Label("RistoGo");
title.setFont(GUIConfig.getTitleFont());
title.setTextFill(GUIConfig.getFgColor());
ImageView icon = new ImageView(getClass().getResource("/resources/logo.png").toString());
icon.setFitHeight(30);
icon.setFitWidth(30);
Label welcomeLabel = new Label("Welcome");
welcomeLabel.setFont(GUIConfig.getWelcomeFont());
welcomeLabel.setTextFill(GUIConfig.getFgColor());
Label usernameLabel = new Label(loggedUser.getUsername());
usernameLabel.setFont(GUIConfig.getUsernameFont());
usernameLabel.setTextFill(GUIConfig.getFgColor());
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(30);
grid.setPadding(new Insets(1, 1, 5, 1));
grid.add(title, 0, 0);
grid.add(icon, 1, 0);
grid.add(welcomeLabel, 0, 1);
grid.add(usernameLabel, 1, 1);
return grid;
}
public static void launch(String... args)
{
Application.launch(args);
}
private void getOwnRestaurant()
{
if (restaurantForm == null)
return;
ResponseMessage resMsg = Protocol.getInstance().getOwnRestaurant();
if (!resMsg.isSuccess()) {
new ErrorBox("Error", "An error has occured while fetching the informations about your restaurant.", resMsg.getErrorMsg()).showAndExit();
restaurant = null;
return;
}
restaurant = (Restaurant)resMsg.getEntity();
restaurantForm.setRestaurant(restaurant);
}
}
| 32.330544
| 141
| 0.770545
|
55d6c86c9f5ab20b0c938a0092836c2235a7cfbb
| 4,296
|
/*
* Copyright (c) 2014, DoubleDoorDevelopment
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the project nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.doubledoordev.pay2spawn.checkers;
import net.doubledoordev.pay2spawn.Pay2Spawn;
import net.doubledoordev.pay2spawn.hud.DonationsBasedHudEntry;
import net.doubledoordev.pay2spawn.util.Donation;
import net.doubledoordev.pay2spawn.util.Statistics;
import net.minecraft.client.Minecraft;
import net.minecraftforge.common.config.Configuration;
import java.util.HashSet;
/**
* Base class for all donation checkers
*
* @author Dries007
*/
public abstract class AbstractChecker
{
public double min_donation = 1;
protected HashSet<String> doneIDs = new HashSet<>();
protected HashSet<Donation> backlog = new HashSet<>();
protected AbstractChecker()
{
}
public abstract String getName();
public abstract void init();
public abstract boolean enabled();
public abstract void doConfig(Configuration configuration);
public abstract DonationsBasedHudEntry[] getDonationsBasedHudEntries();
public boolean addToTotal()
{
return true;
}
protected void doWait(int time)
{
try
{
synchronized (this)
{
this.wait(time * 1000);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
protected void process(Donation donation, boolean msg, AbstractChecker tracker)
{
if (Minecraft.getMinecraft().thePlayer == null || !Pay2Spawn.enable)
{
if (!backlog.contains(donation)) backlog.add(donation);
return;
}
if (!doneIDs.contains(donation.id))
{
doneIDs.add(donation.id);
if (donation.amount > 0 && tracker.addToTotal()) // Only do these things for real donation amounts.
{
Statistics.addToDonationAmount(donation.amount);
if (donation.amount < min_donation) return;
}
try
{
if (this.getDonationsBasedHudEntries() != null)
{
for (DonationsBasedHudEntry donationsBasedHudEntry : this.getDonationsBasedHudEntries())
{
if (donationsBasedHudEntry != null) donationsBasedHudEntry.add(donation);
else Pay2Spawn.getLogger().warn("DonationsBasedHudEntry was null" + this.getName());
}
}
Pay2Spawn.getRewardsDB().process(donation, msg);
}
catch (Exception e)
{
Pay2Spawn.getLogger().warn("Error processing a donation with " + this.getName());
e.printStackTrace();
}
}
}
}
| 34.645161
| 111
| 0.655028
|
c605ac7aa1abb9ba783dee756070466869b347ba
| 6,231
|
package com.mapzen.android.graphics;
import com.mapzen.android.core.MapzenManager;
import com.mapzen.android.graphics.model.BitmapMarkerManager;
import com.mapzen.android.graphics.model.BubbleWrapStyle;
import com.mapzen.android.graphics.model.MapStyle;
import com.mapzen.android.graphics.model.ThemedMapStyle;
import com.mapzen.tangram.MapController;
import com.mapzen.tangram.SceneError;
import com.mapzen.tangram.SceneUpdate;
import android.content.Context;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
/**
* Class responsible for initializing the map.
*/
public class MapInitializer {
private Context context;
private MapzenMapHttpHandler mapzenMapHttpHandler;
private PersistDataManagers persistDataManagers;
private SceneUpdateManager sceneUpdateManager;
private Locale locale = Locale.getDefault();
MapReadyInitializer mapReadyInitializer;
private BitmapMarkerManager bitmapMarkerManager;
private ImportYamlGenerator yamlGenerator;
MapController controller;
/**
* Creates a new instance.
*/
@Inject MapInitializer(Context context, MapzenMapHttpHandler mapzenMapHttpHandler,
PersistDataManagers persistDataManagers, SceneUpdateManager sceneUpdateManager,
BitmapMarkerManager bitmapMarkerManager, ImportYamlGenerator yamlGenerator) {
this.context = context;
this.mapzenMapHttpHandler = mapzenMapHttpHandler;
this.persistDataManagers = persistDataManagers;
this.sceneUpdateManager = sceneUpdateManager;
mapReadyInitializer = new MapReadyInitializer();
this.bitmapMarkerManager = bitmapMarkerManager;
this.yamlGenerator = yamlGenerator;
}
/**
* Initialize map for the current {@link MapView} and notify via {@link OnMapReadyCallback}.
*/
public void init(final MapView mapView, final OnMapReadyCallback callback) {
loadMap(mapView, null, new BubbleWrapStyle(), false, callback);
}
/**
* Initialize map for the current {@link MapView} and notify via {@link OnMapReadyCallback}.
*/
public void init(final MapView mapView, String mapId, final OnMapReadyCallback callback) {
loadMap(mapView, mapId, new BubbleWrapStyle(), false, callback);
}
/**
* Initialize map for current {@link MapView} and {@link MapStyle} before notifying via
* {@link OnMapReadyCallback}.
*/
public void init(final MapView mapView, MapStyle mapStyle, final OnMapReadyCallback callback) {
loadMap(mapView, null, mapStyle, true, callback);
}
/**
* Initialize map for current {@link MapView} and {@link MapStyle} before notifying via
* {@link OnMapReadyCallback}.
*/
public void init(final MapView mapView, String mapId, MapStyle mapStyle,
final OnMapReadyCallback callback) {
loadMap(mapView, mapId, mapStyle, true, callback);
}
/**
* Initialize map for current {@link MapView} and {@link MapStyle} before notifying via
* {@link OnMapReadyCallback}.
*
* Also sets {@link Locale} used to determine default language when rendering map labels.
*/
public void init(final MapView mapView, MapStyle mapStyle, Locale locale,
final OnMapReadyCallback callback) {
this.locale = locale;
loadMap(mapView, null, mapStyle, true, callback);
}
/**
* Initialize map for current {@link MapView} and {@link MapStyle} before notifying via
* {@link OnMapReadyCallback}.
*
* Also sets {@link Locale} used to determine default language when rendering map labels.
*/
public void init(final MapView mapView, String mapId, MapStyle mapStyle, Locale locale,
final OnMapReadyCallback callback) {
this.locale = locale;
loadMap(mapView, mapId, mapStyle, true, callback);
}
private void loadMap(final MapView mapView, String mapId, MapStyle mapStyle,
boolean styleExplicitlySet, final OnMapReadyCallback callback) {
MapStateManager mapStateManager = persistDataManagers.getMapStateManager(mapId);
if (mapStateManager.getPersistMapState() && !styleExplicitlySet) {
MapStyle restoredMapStyle = mapStateManager.getMapStyle();
mapStyle = restoredMapStyle;
}
mapStateManager.setMapStyle(mapStyle);
if (mapStyle instanceof ThemedMapStyle) {
ThemedMapStyle themedStyle = (ThemedMapStyle) mapStyle;
mapStateManager.setLabelLevel(themedStyle.getDefaultLabelLevel());
mapStateManager.setLod(themedStyle.getDefaultLod());
mapStateManager.setThemeColor(themedStyle.getDefaultColor());
}
loadMap(mapView, mapId, mapStyle, callback);
}
private void loadMap(final MapView mapView, final String mapId, MapStyle mapStyle,
final OnMapReadyCallback callback) {
final MapStateManager mapStateManager = persistDataManagers.getMapStateManager(mapId);
final String apiKey = MapzenManager.instance(context).getApiKey();
final List<SceneUpdate> sceneUpdates = sceneUpdateManager.getUpdatesFor(apiKey, locale,
mapStateManager.isTransitOverlayEnabled(), mapStateManager.isBikeOverlayEnabled(),
mapStateManager.isPathOverlayEnabled());
final MapDataManager mapDataManager = persistDataManagers.getMapDataManager(mapId);
controller = mapView.getTangramMapView().getMap(
new MapController.SceneLoadListener() {
@Override public void onSceneReady(int sceneId, SceneError sceneError) {
mapReadyInitializer.onMapReady(mapView, mapzenMapHttpHandler, callback, mapDataManager,
mapStateManager, sceneUpdateManager, locale, bitmapMarkerManager, yamlGenerator);
}
});
if (mapStyle instanceof ThemedMapStyle) {
ThemedMapStyle themedMapStyle = (ThemedMapStyle) mapStyle;
String yaml = yamlGenerator.getImportYaml(themedMapStyle, mapStateManager.getLabelLevel(),
mapStateManager.getLod(), mapStateManager.getThemeColor());
controller.loadSceneYamlAsync(yaml, themedMapStyle.getStyleRootPath(), sceneUpdates);
} else {
controller.loadSceneFileAsync(mapStyle.getSceneFile(), sceneUpdates);
}
}
/**
* Called my {@link MapView} when the view has been destroyed. Use this method to prevent scene
* updates and other future interaction with {@link MapController}.
*/
public void takeDown() {
controller.setSceneLoadListener(null);
}
}
| 38.462963
| 97
| 0.753972
|
8ee47fd7d91d5e496aa57535c8f220c00a72c698
| 7,915
|
/*
* Copyright 2015 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.comcast.cdn.traffic_control.traffic_router.core.http;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.net.URL;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.comcast.cdn.traffic_control.traffic_router.core.http.HTTPAccessRecord;
import com.comcast.cdn.traffic_control.traffic_router.logger.NoLogAppender;
@RunWith(JMock.class)
public class HTTPAccessRecordTest {
private static final Logger LOGGER = Logger.getLogger("com.comcast.cdn.traffic_control.traffic_router.core.access");
private static final NoLogAppender APPENDER = new NoLogAppender();
private final Mockery context = new JUnit4Mockery() {
{
setImposteriser(ClassImposteriser.INSTANCE);
}
};
private HTTPAccessRecord access;
private HttpServletRequest request;
@Before
public void setUp() throws Exception {
access = new HTTPAccessRecord();
request = context.mock(HttpServletRequest.class);
APPENDER.clear();
}
@Test
public void testLog302NoQueryString() throws Exception {
final Date date = new Date(0);
final String ip = "127.0.0.1";
final String requestURL = "http://foo.com/stuff";
final int responseCode = 302;
final URL responseURL = new URL("http://bar.com/stuff");
final String expected = String.format("HTTP [01/Jan/1970:00:00:00.000 +0000] %s %s %s %s", ip, requestURL,
String.valueOf(responseCode), responseURL);
access.setRequestDate(date);
access.setRequest(request);
access.setResponseCode(responseCode);
access.setResponseURL(responseURL);
context.checking(new Expectations() {
{
allowing(request).getRemoteAddr();
will(returnValue(ip));
allowing(request).getRequestURL();
will(returnValue(new StringBuffer(requestURL)));
allowing(request).getQueryString();
will(returnValue(null));
}
});
access.log();
final List<LoggingEvent> events = APPENDER.getEvents();
assertNotNull(events);
assertEquals(1, events.size());
final LoggingEvent event = events.get(0);
assertEquals(Level.INFO, event.getLevel());
assertEquals(expected, event.getMessage());
}
@Test
public void testLog302WithQueryString() throws Exception {
final Date date = new Date(0);
final String ip = "127.0.0.1";
final String requestURL = "http://foo.com/stuff";
final String queryString = "foo=bar&stuff=lots";
final int responseCode = 302;
final URL responseURL = new URL("http://bar.com/stuff");
final String expected = String.format("HTTP [01/Jan/1970:00:00:00.000 +0000] %s %s?%s %s %s", ip, requestURL,
queryString, String.valueOf(responseCode), responseURL);
access.setRequestDate(date);
access.setRequest(request);
access.setResponseCode(responseCode);
access.setResponseURL(responseURL);
context.checking(new Expectations() {
{
allowing(request).getRemoteAddr();
will(returnValue(ip));
allowing(request).getRequestURL();
will(returnValue(new StringBuffer(requestURL)));
allowing(request).getQueryString();
will(returnValue(queryString));
}
});
access.log();
final List<LoggingEvent> events = APPENDER.getEvents();
assertNotNull(events);
assertEquals(1, events.size());
final LoggingEvent event = events.get(0);
assertEquals(Level.INFO, event.getLevel());
assertEquals(expected, event.getMessage());
}
@Test
public void testLog503NoQueryString() throws Exception {
final Date date = new Date(0);
final String ip = "127.0.0.1";
final String requestURL = "http://foo.com/stuff";
final int responseCode = 503;
final URL responseURL = null;
final String expected = String.format("HTTP [01/Jan/1970:00:00:00.000 +0000] %s %s %s %s", ip, requestURL,
String.valueOf(responseCode), "-");
access.setRequestDate(date);
access.setRequest(request);
access.setResponseCode(responseCode);
access.setResponseURL(responseURL);
context.checking(new Expectations() {
{
allowing(request).getRemoteAddr();
will(returnValue(ip));
allowing(request).getRequestURL();
will(returnValue(new StringBuffer(requestURL)));
allowing(request).getQueryString();
will(returnValue(null));
}
});
access.log();
final List<LoggingEvent> events = APPENDER.getEvents();
assertNotNull(events);
assertEquals(1, events.size());
final LoggingEvent event = events.get(0);
assertEquals(Level.INFO, event.getLevel());
assertEquals(expected, event.getMessage());
}
@Test
public void testLogErrorNoQueryString() throws Exception {
final Date date = new Date(0);
final String ip = "127.0.0.1";
final String requestURL = "http://foo.com/stuff";
final int responseCode = -1;
final URL responseURL = null;
final String expected = String.format("HTTP [01/Jan/1970:00:00:00.000 +0000] %s %s %s %s", ip, requestURL, "-",
"-");
access.setRequestDate(date);
access.setRequest(request);
access.setResponseCode(responseCode);
access.setResponseURL(responseURL);
context.checking(new Expectations() {
{
allowing(request).getRemoteAddr();
will(returnValue(ip));
allowing(request).getRequestURL();
will(returnValue(new StringBuffer(requestURL)));
allowing(request).getQueryString();
will(returnValue(null));
}
});
access.log();
final List<LoggingEvent> events = APPENDER.getEvents();
assertNotNull(events);
assertEquals(1, events.size());
final LoggingEvent event = events.get(0);
assertEquals(Level.INFO, event.getLevel());
assertEquals(expected, event.getMessage());
}
@BeforeClass
public static void setUpBeforeClass() {
LOGGER.addAppender(APPENDER);
LOGGER.setLevel(Level.INFO);
LOGGER.setAdditivity(false);
}
@AfterClass
public static void tearDownAfterClass() {
LOGGER.removeAppender(APPENDER);
LOGGER.setLevel(null);
LOGGER.setAdditivity(true);
}
}
| 37.870813
| 120
| 0.638661
|
a7c7fe98e31129cc03c89eafd99c07892e318de8
| 1,345
|
package org.infinispan.persistence.dummy;
import org.infinispan.commons.io.ByteBufferFactoryImpl;
import org.infinispan.marshall.core.MarshalledEntryFactoryImpl;
import org.infinispan.persistence.BaseStoreTest;
import org.infinispan.persistence.CacheLoaderException;
import org.infinispan.persistence.DummyInitializationContext;
import org.infinispan.persistence.spi.AdvancedLoadWriteStore;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.Test;
@Test(groups = "unit", testName = "persistence.dummy.DummyInMemoryStoreTest")
public class DummyInMemoryStoreTest extends BaseStoreTest {
@Override
protected AdvancedLoadWriteStore createStore() throws CacheLoaderException {
DummyInMemoryStore cl = new DummyInMemoryStore();
final DummyInMemoryStoreConfigurationBuilder loader = TestCacheManagerFactory
.getDefaultCacheConfiguration(false)
.persistence()
.addStore(DummyInMemoryStoreConfigurationBuilder.class);
loader
.storeName(getClass().getName());
cl.init(new DummyInitializationContext(loader.create(), getCache(), getMarshaller(), new ByteBufferFactoryImpl(),
new MarshalledEntryFactoryImpl(getMarshaller())));
cl.start();
csc = loader.create();
return cl;
}
}
| 43.387097
| 119
| 0.75539
|
9cdaebba6fd0f44a85bf54ae1a252d7e92c572d2
| 951
|
package com.sicedesign.micro.controller.handler;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.sicedesign.micro.service.exception.NomeNacionalidadeJaCadastradoException;
import com.sicedesign.micro.service.exception.NomeProfissaoJaCadastradoException;
@ControllerAdvice
public class ControllerAdviceExceptionHandler {
@ExceptionHandler(NomeNacionalidadeJaCadastradoException.class)
public ResponseEntity<String> handleNomeNacionalidadeJaCadastradoException(NomeNacionalidadeJaCadastradoException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
@ExceptionHandler(NomeProfissaoJaCadastradoException.class)
public ResponseEntity<String> handleNomeProfissaoJaCadastradoException(NomeProfissaoJaCadastradoException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
| 41.347826
| 119
| 0.865405
|
4143d9d0d347199b25c0032eefd2045e209c430a
| 505
|
package maven.version.plugin.versioninfo;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
@Mojo(name = "clean")
public class VersionInfoCleanMojo extends AbstractMojo {
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
// TODO Auto-generated method stub
System.out.println("Cleaning .....");
}
}
| 28.055556
| 77
| 0.786139
|
8c910926953ecb1726ac3de6dfd6aa457bb89bf8
| 507
|
package com.mxgraph.server.biz.dao;
import com.mxgraph.server.biz.base.DrawBaseDao;
import com.mxgraph.server.biz.bean.DrawData;
import java.util.List;
/**
* @author coral
*/
// 自定义接口 不会创建接口的实例 必须加此注解
public interface DrawDataDao extends DrawBaseDao<DrawData,String> {
/**
* 采用Uid获取
* @param ownerId
* @return
*/
List<DrawData> findByOwnerId(String ownerId);
/**
* 采用用户名获取
* @param uuid
* @return
*/
List<DrawData> findByUuid(String uuid);
}
| 17.482759
| 67
| 0.650888
|
d30afe013f286b29c426bff8f7aea7159f805ca7
| 2,013
|
package com.infamous.zod.base.rest;
import com.infamous.framework.logging.ZodLogger;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.function.Consumer;
import java.util.function.Supplier;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@SuppressWarnings("SuspiciousInvocationHandlerImplementation")
public class DynamicEndPointHandler<T> implements InvocationHandler {
private final ZodLogger m_logger;
private final T m_target;
public DynamicEndPointHandler(ProxyEndpointContext<T> context) {
this.m_logger = context.getLogger();
this.m_target = context.getTarget();
Consumer<T> postInit = context.getPostInit();
if (postInit != null) {
postInit.accept(m_target);
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getAnnotation(RestEndPoint.class) != null) {
return executeWithTemplate(() -> {
try {
return (Response) method.invoke(m_target, args);
} catch (Exception e) {
throw new RuntimeException(e.getCause());
}
});
}
return method.invoke(m_target, args);
}
private Response executeWithTemplate(Supplier<Response> supplier) {
try {
return supplier.get();
} catch (Exception e) {
return unknownResponse(e);
}
}
private Response unknownResponse(Exception e) {
logUnexpectedException(e);
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
.entity(e.getMessage())
.build();
}
private void logUnexpectedException(Exception e) {
m_logger.error("Internal Exception: ", e);
}
}
| 31.952381
| 87
| 0.645802
|
d29e6903705246b374bc38d43f728dfdccc511a8
| 2,241
|
package js.tiny.container.unit;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionContext;
@SuppressWarnings(
{
"unchecked", "rawtypes", "deprecation"
})
public abstract class HttpSessionStub implements javax.servlet.http.HttpSession
{
@Override
public Object getAttribute(String arg0)
{
throw new UnsupportedOperationException();
}
@Override
public Enumeration getAttributeNames()
{
throw new UnsupportedOperationException();
}
@Override
public long getCreationTime()
{
throw new UnsupportedOperationException();
}
@Override
public String getId()
{
throw new UnsupportedOperationException();
}
@Override
public long getLastAccessedTime()
{
throw new UnsupportedOperationException();
}
@Override
public int getMaxInactiveInterval()
{
throw new UnsupportedOperationException();
}
@Override
public ServletContext getServletContext()
{
throw new UnsupportedOperationException();
}
@Override
public HttpSessionContext getSessionContext()
{
throw new UnsupportedOperationException();
}
@Override
public Object getValue(String arg0)
{
throw new UnsupportedOperationException();
}
@Override
public String[] getValueNames()
{
throw new UnsupportedOperationException();
}
@Override
public void invalidate()
{
throw new UnsupportedOperationException();
}
@Override
public boolean isNew()
{
throw new UnsupportedOperationException();
}
@Override
public void putValue(String arg0, Object arg1)
{
throw new UnsupportedOperationException();
}
@Override
public void removeAttribute(String arg0)
{
throw new UnsupportedOperationException();
}
@Override
public void removeValue(String arg0)
{
throw new UnsupportedOperationException();
}
@Override
public void setAttribute(String arg0, Object arg1)
{
throw new UnsupportedOperationException();
}
@Override
public void setMaxInactiveInterval(int arg0)
{
throw new UnsupportedOperationException();
}
}
| 18.368852
| 80
| 0.682285
|
ea60b122b42aa109d1c17e72176eeea29a929e66
| 1,961
|
/*
* Copyright 2019 Google, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.clouddriver.google.compute;
import com.google.api.services.compute.Compute;
import com.google.api.services.compute.model.Instance;
import com.google.api.services.compute.model.InstanceList;
import com.netflix.spectator.api.Registry;
import com.netflix.spinnaker.clouddriver.google.deploy.GoogleOperationPoller;
import com.netflix.spinnaker.clouddriver.google.security.GoogleNamedAccountCredentials;
public final class Instances {
private final Compute.Instances computeApi;
private final GoogleNamedAccountCredentials credentials;
private final GlobalGoogleComputeRequestFactory requestFactory;
Instances(
GoogleNamedAccountCredentials credentials,
GoogleOperationPoller operationPoller,
Registry registry) {
this.computeApi = credentials.getCompute().instances();
this.credentials = credentials;
this.requestFactory =
new GlobalGoogleComputeRequestFactory("instances", credentials, operationPoller, registry);
}
public PaginatedComputeRequest<Compute.Instances.List, Instance> list(String zone) {
return new PaginatedComputeRequestImpl<>(
pageToken ->
requestFactory.wrapRequest(
computeApi.list(credentials.getProject(), zone).setPageToken(pageToken), "list"),
InstanceList::getNextPageToken,
InstanceList::getItems);
}
}
| 38.45098
| 99
| 0.766446
|
216c05796ac434f9de8ffce5abe729417337c2c9
| 2,834
|
package algorithm.conversions;
public class DecimalToHexadecimal {
//Inisialisasi Input Decimal yang ingin di konversi
//Inputan Angka dapat diubah sesuai yang diinginkan
static int input = 1247;
//Inisialisasi variabel hasil bagi
//ini digunakan untuk menampung hasil setiap pembagian pada setiap perulangan
int hasil_bagi;
//Inisialisasi modulo untuk menampung sisa pembagian pada setiap perulangan
//Yang akan digunakan untuk pengkonverisna ke Hexadecimal
int [] modulo = new int[1000];
public void konversi() {
hasil_bagi = input;
int i = 0;
//Perulangan yang akan selesai jika hasil bagi sudah tidak dapat dibagi lagi dengan 16
//Ini tahap inti untuk mendapatkan nilai modulo (sisa dari hasil bagi)
//Untuk pengkonversian ke Hexadecimal
while (hasil_bagi >= 16) {
System.out.println("\t \t" + hasil_bagi);
System.out.print("Perulagan " +(i+1)+" -------------");
//Perintah menampung nilai modulo pada Array
modulo[i] = hasil_bagi % 16;
System.out.println(" " + modulo[i]);
//Perintah membagi Inputan/hasil bagi dengan angka 16
//Dan dibulatkan kebawah untuk mencegah pembulatan ke atas yg salah
hasil_bagi = (int) Math.floor(hasil_bagi / 16);
System.out.println("\t \t" + hasil_bagi);
i++;
}
//Perintah menampung nilai hasil bagi akhir pada Array
modulo[i] = hasil_bagi;
System.out.println("Sebelum Di Konversi : ");
//Perulangan dimulai dari belakang
//Karena pengkonversian dan penulisannya dimulai dari hasil bagi terakhir
//Dan modulonya pun dimulai dari perulangan terakhir hingga pertama
for (int j = i; j >= 0; j--) {
System.out.print(modulo[j] + " ");
}
//Perulangan dimulai dari belakang
//Karena pengkonversian dan penulisannya dimulai dari hasil bagi terakhir
//Pemanggilan method toHexadecimal
System.out.println("\nSesudah Di Konversi : ");
for (int j = i; j >= 0; j--) {
System.out.print(toHexadecimal(modulo[j]) + " ");
}
}
//Method mengkonversian dari hasil bagi dan modulo diatas
//Mengembalikan nilai String yang sesuai dengan rules Hexadecimal
public String toHexadecimal(int x){
String hexadecimal = " ";
String [] hexa = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
hexadecimal = hexa[x];
return hexadecimal;
}
public static void main(String[] args) {
System.out.println("\t **Fungsi Sederhana Konversi Desimal ke Heksadesimal** ");
DecimalToHexadecimal app = new DecimalToHexadecimal();
app.konversi();
}
}
| 35.873418
| 107
| 0.61609
|
3437ba26807fc1a43d2a297b6dca333b93ae1488
| 782
|
/**
*
*/
package com.yusys.biapp.input.template.utils.object;
import java.io.Serializable;
import java.util.ArrayList;
/**
* <pre>
* Title:实现序列化接口,可将导出对象序列化到文件
* Description:
* </pre>
* @author guojiangping
* @version 1.00.00
*
* <pre>
* 修改记录
* 修改后版本: 修改人: 修改日期: 修改内容:
* </pre>
*/
public class BOList extends ArrayList<Object> implements Serializable {
private static final long serialVersionUID = 1175845558331676390L;
private String className;
public BOList(Class<?> clazz) {
this.className = clazz.getName();
}
public BOList(String className){
this.className=className;
}
public BOList() {
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
| 16.638298
| 71
| 0.684143
|
b25411d11db8fd8192d004422aa9c2c7c22a6295
| 276
|
package com.sxdsf.async.imitate2.backpressure;
/**
* com.sxdsf.async.imitate2.backpressure.TelephonerOnCall
*
* @author SXDSF
* @date 2017/11/7 下午12:42
* @desc 当打电话的时候
*/
public interface TelephonerOnCall<T> {
void call(TelephonerEmitter<T> telephonerEmitter);
}
| 18.4
| 57
| 0.735507
|
285273e95a43ba3a96d81345dfb7d9c968c90d86
| 1,798
|
package week_3;
/**
Write a method called countUppercase that takes a String array argument.
You can assume that every element in the array is a one-letter String, for example
String[] test = { "a", "B", "c", "D", "e"};
This method will count the number of uppercase letters from the set A through Z in the array,
and return that number. So for the example array above, your method will return 2.
You will need to use some Java library methods. You may need some methods from
some or all of these library classes: String, Character, Integer.
COMMENT YOUR CODE. As well as the tests, the instructor will also read your comments
to verify that you understand and can describe the code you've written.
*/
public class Question_5_Count_Uppercase_Letters {
public static void main(String[] args) {
new Question_5_Count_Uppercase_Letters().countUppercaseLetters();
}
private void countUppercaseLetters() {
// You can call your new countUppercase() method with these example arrays.
String[] test1 = { "a", "b", "c" }; // no uppercase letters - your method should return 0
String[] test2 = { "a", "B", "c", "D", "e" }; // two uppercase letters - your method should return 2
String[] test3 = { "A", "B", "C", "D" }; // four uppercase letters - your method should return 4
String[] test4 = { "$", "B", "c", "6", "D", "\n", "E" }; // three uppercase letters - your method should return 3
// You don't need any user input in this program.
}
/*
TODO Create a public method called countUppercase.
This method should take a String array argument, and return an int.
This method should count the number of uppercase letters - in the range A through Z - and return that count.
*/
}
| 33.296296
| 122
| 0.67297
|
48b404eaa35d298253542dd6b3486eba6cd98384
| 2,266
|
package com.byk.pandora.atomwebview;
import android.net.Uri;
import android.support.annotation.CallSuper;
import android.text.TextUtils;
import com.tencent.smtt.export.external.interfaces.JsPromptResult;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
/**
* Created by Byk on 2018/1/24.
*
* @author Byk
*/
public class AtomWebChromeClient extends WebChromeClient {
private static final int MAX_PROGRESS = 100;
private AtomWebView mWebView;
public AtomWebChromeClient(AtomWebView webView) {
mWebView = webView;
}
public IProgress progress() {
return null;
}
@CallSuper
@Override
public void onProgressChanged(WebView webView, int progress) {
if (progress >= MAX_PROGRESS) {
setProgressVisible(false);
} else {
setProgressValue(progress);
setProgressVisible(true);
}
super.onProgressChanged(webView, progress);
}
@CallSuper
@Override
public boolean onJsPrompt(WebView view, String url, String msg, String defaultValue, JsPromptResult jsResult) {
Uri uri = Uri.parse(msg);
String scheme = uri.getScheme();
if (!TextUtils.isEmpty(scheme)) {
String confirm = "";
if (!AtomUtil.apply(mWebView.getContext(), uri, msg, scheme)) {
AtomResult result = new AtomResult();
result.setScheme(scheme);
result.setContent(msg);
result.setAction(uri.getAuthority());
result.setData(uri.getQuery());
result.setUri(uri);
confirm = mWebView.applyJsBridge(result);
}
jsResult.confirm(confirm);
return true;
}
return super.onJsPrompt(view, url, msg, defaultValue, jsResult);
}
private void setProgressValue(int value) {
if (progress() != null) {
progress().onProgress(value);
}
}
private void setProgressVisible(boolean visible) {
if (progress() != null) {
progress().onVisible(visible);
}
}
public interface IProgress {
void onProgress(int progress);
void onVisible(boolean visible);
}
}
| 26.97619
| 115
| 0.61474
|
2559099b3ff12c8d1ce9dd2e4bc94d6a89a90ce7
| 1,014
|
package com.sparrowwallet.drongo.protocol;
public class HashIndex {
private final Sha256Hash hash;
private final long index;
public HashIndex(Sha256Hash hash, long index) {
this.hash = hash;
this.index = index;
}
public Sha256Hash getHash() {
return hash;
}
public long getIndex() {
return index;
}
@Override
public String toString() {
return hash.toString() + ":" + index;
}
@Override
public boolean equals(Object o) {
if(this == o) {
return true;
}
if(o == null || getClass() != o.getClass()) {
return false;
}
HashIndex hashIndex = (HashIndex) o;
if(index != hashIndex.index) {
return false;
}
return hash.equals(hashIndex.hash);
}
@Override
public int hashCode() {
int result = hash.hashCode();
result = 31 * result + (int) (index ^ (index >>> 32));
return result;
}
}
| 20.693878
| 62
| 0.535503
|
8b4872de0e564e643fe0ba33a0ab8d2b34f629df
| 2,712
|
/**
*/
package iso20022;
import java.util.Map;
import org.eclipse.emf.common.util.DiagnosticChain;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Syntax</b></em>'.
* <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* a particular syntax for a MessageInstance
* <!-- end-model-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link iso20022.Syntax#getPossibleEncodings <em>Possible Encodings</em>}</li>
* <li>{@link iso20022.Syntax#getGeneratedFor <em>Generated For</em>}</li>
* </ul>
*
* @see iso20022.Iso20022Package#getSyntax()
* @model
* @generated
*/
public interface Syntax extends ModelEntity {
/**
* Returns the value of the '<em><b>Possible Encodings</b></em>' reference list.
* The list contents are of type {@link iso20022.Encoding}.
* It is bidirectional and its opposite is '{@link iso20022.Encoding#getSyntax <em>Syntax</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* the set of possible encodings for a given Syntax
* <!-- end-model-doc -->
* @return the value of the '<em>Possible Encodings</em>' reference list.
* @see iso20022.Iso20022Package#getSyntax_PossibleEncodings()
* @see iso20022.Encoding#getSyntax
* @model opposite="syntax" required="true" ordered="false"
* @generated
*/
EList<Encoding> getPossibleEncodings();
/**
* Returns the value of the '<em><b>Generated For</b></em>' reference list.
* The list contents are of type {@link iso20022.MessageSet}.
* It is bidirectional and its opposite is '{@link iso20022.MessageSet#getGeneratedSyntax <em>Generated Syntax</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* the scheme in which a syntax is encoded
* <!-- end-model-doc -->
* @return the value of the '<em>Generated For</em>' reference list.
* @see iso20022.Iso20022Package#getSyntax_GeneratedFor()
* @see iso20022.MessageSet#getGeneratedSyntax
* @model opposite="generatedSyntax" transient="true" changeable="false" volatile="true" derived="true" ordered="false"
* @generated
*/
EList<MessageSet> getGeneratedFor();
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* the syntax that is valid for a MessageSet, based on the Encoding used
* generatedFor-> asBag()=possibleEncodings.messageSet
* <!-- end-model-doc -->
* @model required="true" ordered="false" contextRequired="true" contextOrdered="false" diagnosticsRequired="true" diagnosticsOrdered="false"
* @generated
*/
boolean GeneratedForDerivation(Map context, DiagnosticChain diagnostics);
} // Syntax
| 34.329114
| 142
| 0.672935
|
741ab69e03f7f8e7bed25d5e0c5512a1619d98a1
| 1,574
|
package com.tugab.adspartners.domain.entities;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
@Data
@NoArgsConstructor
@Entity
@Table(name = "user")
public class User extends UserInfo implements UserDetails {
@Column(name = "password", nullable = false)
private String password;
@Column(name = "created_date", nullable = false)
private Date createdDate;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable( name = "user_role",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
public void addRole(Role role) {
this.roles.add(role);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roles;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public String getUsername() {
return super.getEmail();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
| 22.169014
| 68
| 0.668996
|
6fa6e22ace8932593940b2f0be1f7f8c4b7a17bb
| 627
|
package nl.gogognome.messagepropertiessynchronizer;
public class CommentLine implements Line{
private final String line;
public CommentLine(String line) {
this.line = line;
}
@Override
public String getOriginalLine() {
return line;
}
@Override
public Line addTodoMessage(String todoMessage) {
return this;
}
@Override
public boolean equals(Object object) {
return object instanceof CommentLine;
}
@Override
public int hashCode() {
return 83;
}
@Override
public String toString() {
return line;
}
}
| 16.945946
| 52
| 0.623604
|
ef9ccf173f6ec23263b8e0b28abb032e6859c14b
| 120
|
package com.vemec.api.constants;
public enum Estado {
CRITICO,
INTERMEDIO,
ESTABLE,
SANO,
DIFUNTO
}
| 13.333333
| 32
| 0.65
|
a33ff707b32d979377ea9f50dbed5230d38dbc36
| 19,186
|
/*
* (c) Copyright 2016 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.palantir.docker.compose.execution;
import static com.palantir.docker.compose.execution.DockerComposeExecArgument.arguments;
import static com.palantir.docker.compose.execution.DockerComposeExecOption.options;
import static org.apache.commons.io.IOUtils.toInputStream;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.Is.is;
import static org.mockito.Matchers.anyVararg;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.palantir.docker.compose.connection.Container;
import com.palantir.docker.compose.connection.ContainerName;
import com.palantir.docker.compose.connection.DockerMachine;
import com.palantir.docker.compose.connection.DockerPort;
import com.palantir.docker.compose.connection.ImmutableContainerName;
import com.palantir.docker.compose.connection.Ports;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class DockerComposeShould {
@Rule
public ExpectedException exception = ExpectedException.none();
private static final String CONTAINER_ID = RandomStringUtils.randomAlphanumeric(20);
private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private final DockerComposeExecutable dockerComposeExecutor = mock(DockerComposeExecutable.class);
private final DockerExecutable dockerExecutor = mock(DockerExecutable.class);
private final DockerMachine dockerMachine = mock(DockerMachine.class);
private final DockerCompose compose =
new DefaultDockerCompose(dockerComposeExecutor, dockerExecutor, dockerMachine);
private final Process dockerComposeExecutedProcess = mock(Process.class);
private final Process dockerExecutedProcess = mock(Process.class);
private final Container container = mock(Container.class);
@Before
public void before() throws IOException {
when(dockerMachine.getIp()).thenReturn("0.0.0.0");
// Mock successful output in general
when(dockerComposeExecutor.execute(anyVararg())).thenReturn(dockerComposeExecutedProcess);
when(dockerComposeExecutedProcess.getInputStream()).thenReturn(toInputStream("", DEFAULT_CHARSET));
when(dockerComposeExecutedProcess.exitValue()).thenReturn(0);
when(container.getContainerName()).thenReturn("my-container");
}
@Test
public void call_docker_compose_up_with_daemon_flag_on_up() throws IOException, InterruptedException {
compose.up();
verify(dockerComposeExecutor).execute("up", "-d");
}
@Test
public void call_docker_compose_rm_with_force_and_volume_flags_on_rm() throws IOException, InterruptedException {
compose.rm();
verify(dockerComposeExecutor).execute("rm", "--force", "-v");
}
@Test
public void call_docker_compose_stop_on_stop() throws IOException, InterruptedException {
compose.stop(container);
verify(dockerComposeExecutor).execute("stop", "my-container");
}
@Test
public void call_docker_compose_start_on_start() throws IOException, InterruptedException {
compose.start(container);
verify(dockerComposeExecutor).execute("start", "my-container");
}
@Test
public void ps_returns_container_names() throws IOException, InterruptedException {
when(dockerComposeExecutor.execute(anyVararg())).thenReturn(dockerComposeExecutedProcess);
when(dockerComposeExecutedProcess.getInputStream()).thenReturn(toInputStream(CONTAINER_ID, DEFAULT_CHARSET));
when(dockerComposeExecutedProcess.exitValue()).thenReturn(0);
when(dockerExecutor.execute(anyVararg())).thenReturn(dockerExecutedProcess);
when(dockerExecutedProcess.getInputStream()).thenReturn(toInputStream("dir_db_1", DEFAULT_CHARSET));
when(dockerExecutedProcess.exitValue()).thenReturn(0);
List<ContainerName> containerNames = compose.ps();
verify(dockerComposeExecutor).execute("ps", "-q");
verify(dockerExecutor).execute(
"ps", "--no-trunc", "--format", "{{.Names}}", "--filter", String.format("id=%s", CONTAINER_ID));
assertThat(containerNames, contains(ImmutableContainerName.builder().semanticName("db").rawName("dir_db_1").build()));
}
@Test
public void ps_returns_multiple_container_names() throws IOException, InterruptedException {
String containerIdA = RandomStringUtils.randomAlphanumeric(20);
String containerIdB = RandomStringUtils.randomAlphanumeric(20);
String containerIdC = RandomStringUtils.randomAlphanumeric(20);
String containerIdString = Joiner.on("\n").join(containerIdA, containerIdB, containerIdC);
when(dockerComposeExecutor.execute(anyVararg())).thenReturn(dockerComposeExecutedProcess);
when(dockerComposeExecutedProcess.getInputStream()).thenReturn(toInputStream(containerIdString, DEFAULT_CHARSET));
when(dockerComposeExecutedProcess.exitValue()).thenReturn(0);
String containerNameA = "custom.container.name";
String containerNameB = "directory_service_index";
String containerNameC = "directory_service_index_slug";
String containerNameString = Joiner.on("\n").join(containerNameA, containerNameB, containerNameC);
when(dockerExecutor.execute(anyVararg())).thenReturn(dockerExecutedProcess);
when(dockerExecutedProcess.getInputStream()).thenReturn(toInputStream(containerNameString, DEFAULT_CHARSET));
when(dockerExecutedProcess.exitValue()).thenReturn(0);
List<ContainerName> containerNames = compose.ps();
assertThat(containerNames, is(ImmutableList.of(
ImmutableContainerName.builder()
.rawName("custom.container.name")
.semanticName("custom.container.name")
.build(),
ImmutableContainerName.builder()
.rawName("directory_service_index")
.semanticName("service")
.build(),
ImmutableContainerName.builder()
.rawName("directory_service_index_slug")
.semanticName("service")
.build()
)));
verify(dockerComposeExecutor).execute("ps", "-q");
verify(dockerExecutor).execute(
"ps", "--no-trunc", "--format", "{{.Names}}",
"--filter", String.format("id=%s", containerIdA),
"--filter", String.format("id=%s", containerIdB),
"--filter", String.format("id=%s", containerIdC));
}
@Test
public void ps_returns_no_container_names_when_no_container_ids_are_found() throws IOException, InterruptedException {
when(dockerComposeExecutor.execute(anyVararg())).thenReturn(dockerComposeExecutedProcess);
when(dockerComposeExecutedProcess.getInputStream()).thenReturn(toInputStream("", DEFAULT_CHARSET));
when(dockerComposeExecutedProcess.exitValue()).thenReturn(0);
List<ContainerName> containerNames = compose.ps();
assertThat(containerNames, empty());
verify(dockerComposeExecutor).execute("ps", "-q");
verifyZeroInteractions(dockerExecutor);
}
@Test
public void ps_returns_no_container_names_when_no_names_can_be_found_for_container_ids() throws IOException, InterruptedException {
when(dockerComposeExecutor.execute(anyVararg())).thenReturn(dockerComposeExecutedProcess);
when(dockerComposeExecutedProcess.getInputStream()).thenReturn(toInputStream(CONTAINER_ID, DEFAULT_CHARSET));
when(dockerComposeExecutedProcess.exitValue()).thenReturn(0);
when(dockerExecutor.execute(anyVararg())).thenReturn(dockerExecutedProcess);
when(dockerExecutedProcess.getInputStream()).thenReturn(toInputStream("", DEFAULT_CHARSET));
when(dockerExecutedProcess.exitValue()).thenReturn(0);
List<ContainerName> containerNames = compose.ps();
assertThat(containerNames, empty());
verify(dockerComposeExecutor).execute("ps", "-q");
verify(dockerExecutor).execute(
"ps", "--no-trunc", "--format", "{{.Names}}", "--filter", String.format("id=%s", CONTAINER_ID));
}
@Test
public void call_docker_compose_with_no_colour_flag_on_logs() throws IOException {
when(dockerComposeExecutedProcess.getInputStream()).thenReturn(
toInputStream("1.7.0", DEFAULT_CHARSET),
toInputStream("logs", DEFAULT_CHARSET));
ByteArrayOutputStream output = new ByteArrayOutputStream();
compose.writeLogs("db", output);
verify(dockerComposeExecutor).execute("logs", "--no-color", "db");
assertThat(new String(output.toByteArray(), StandardCharsets.UTF_8), is("logs"));
}
@Test
public void call_docker_compose_with_no_container_on_logs() throws IOException {
reset(dockerComposeExecutor);
final Process mockIdProcess = mock(Process.class);
when(mockIdProcess.exitValue()).thenReturn(0);
final Process mockVersionProcess = mock(Process.class);
when(mockVersionProcess.exitValue()).thenReturn(0);
when(mockVersionProcess.getInputStream()).thenReturn(toInputStream("1.7.0", DEFAULT_CHARSET));
when(dockerComposeExecutor.execute("version", "--short")).thenReturn(mockVersionProcess);
when(dockerComposeExecutor.execute("logs", "--no-color", "db")).thenReturn(dockerComposeExecutedProcess);
when(dockerComposeExecutedProcess.getInputStream()).thenReturn(toInputStream("logs", DEFAULT_CHARSET));
ByteArrayOutputStream output = new ByteArrayOutputStream();
compose.writeLogs("db", output);
verify(dockerComposeExecutor).execute("logs", "--no-color", "db");
assertThat(new String(output.toByteArray(), StandardCharsets.UTF_8), is("logs"));
}
@Test
public void fail_if_docker_compose_version_is_prior_1_7_on_logs()
throws IOException, InterruptedException {
when(dockerComposeExecutedProcess.getInputStream()).thenReturn(toInputStream("1.5.6", DEFAULT_CHARSET));
exception.expect(IllegalStateException.class);
exception.expectMessage("You need at least docker-compose 1.7 to run docker-compose exec");
compose.exec(options("-d"), "container_1", arguments("ls"));
}
@Test
public void throw_exception_when_kill_exits_with_a_non_zero_exit_code() throws IOException, InterruptedException {
when(dockerComposeExecutedProcess.exitValue()).thenReturn(1);
exception.expect(DockerExecutionException.class);
exception.expectMessage("'docker-compose kill' returned exit code 1");
compose.kill();
}
@Test
public void not_throw_exception_when_down_fails_because_the_command_does_not_exist()
throws IOException, InterruptedException {
when(dockerComposeExecutedProcess.exitValue()).thenReturn(1);
when(dockerComposeExecutedProcess.getInputStream()).thenReturn(toInputStream("No such command: down", DEFAULT_CHARSET));
compose.down();
}
@Test
public void throw_exception_when_down_fails_for_a_reason_other_than_the_command_not_being_present()
throws IOException, InterruptedException {
when(dockerComposeExecutedProcess.exitValue()).thenReturn(1);
when(dockerComposeExecutedProcess.getInputStream()).thenReturn(toInputStream("", DEFAULT_CHARSET));
exception.expect(DockerExecutionException.class);
compose.down();
}
@Test
public void use_the_remove_volumes_flag_when_down_exists() throws IOException, InterruptedException {
compose.down();
verify(dockerComposeExecutor).execute("down", "--volumes");
}
@Test
public void get_correct_ports() throws IOException, InterruptedException {
when(dockerComposeExecutor.execute(anyVararg())).thenReturn(dockerComposeExecutedProcess);
when(dockerComposeExecutedProcess.getInputStream())
.thenReturn(toInputStream(CONTAINER_ID, DEFAULT_CHARSET));
when(dockerComposeExecutedProcess.exitValue()).thenReturn(0);
when(dockerExecutor.execute(anyVararg())).thenReturn(dockerExecutedProcess);
when(dockerExecutedProcess.getInputStream())
.thenReturn(toInputStream("0.0.0.0:7000->7000/tcp", DEFAULT_CHARSET));
when(dockerExecutedProcess.exitValue()).thenReturn(0);
Ports ports = compose.ports("db");
verify(dockerComposeExecutor).execute("ps", "-q", "db");
verify(dockerExecutor).execute(
"ps", "--no-trunc", "--format", "\"{{ .Ports }}\"", "--filter", String.format("id=%s", CONTAINER_ID));
assertThat(ports, is(new Ports(new DockerPort("0.0.0.0", 7000, 7000))));
}
@Test
public void attempt_to_get_ports_but_service_is_empty() throws IOException, InterruptedException {
exception.expect(IllegalStateException.class);
exception.expectMessage("Service cannot be empty");
compose.ports("");
}
@Test
public void attempt_to_get_ports_but_service_doesnt_exist() throws IOException, InterruptedException {
when(dockerComposeExecutor.execute(anyVararg())).thenReturn(dockerComposeExecutedProcess);
when(dockerComposeExecutedProcess.getInputStream()).thenReturn(toInputStream("", DEFAULT_CHARSET));
when(dockerComposeExecutedProcess.exitValue()).thenReturn(1);
exception.expect(IllegalStateException.class);
exception.expectMessage("No container ID found for service with name 'service_that_doesnt_exist'.");
compose.ports("service_that_doesnt_exist");
}
@Test
public void attempt_to_get_ports_but_all_ports_are_open_for_container() throws IOException, InterruptedException {
when(dockerComposeExecutor.execute(anyVararg())).thenReturn(dockerComposeExecutedProcess);
when(dockerComposeExecutedProcess.getInputStream()).thenReturn(toInputStream(CONTAINER_ID, DEFAULT_CHARSET));
when(dockerComposeExecutedProcess.exitValue()).thenReturn(0);
when(dockerExecutor.execute(anyVararg())).thenReturn(dockerExecutedProcess);
when(dockerExecutedProcess.getInputStream()).thenReturn(toInputStream("", DEFAULT_CHARSET));
when(dockerExecutedProcess.exitValue()).thenReturn(0);
Ports ports = compose.ports("service");
assertThat(ports, is(new Ports(ImmutableList.of())));
}
@Test
public void pass_concatenated_arguments_to_executor_on_docker_compose_exec() throws IOException, InterruptedException {
when(dockerComposeExecutedProcess.getInputStream()).thenReturn(toInputStream("1.25.0-rc4", DEFAULT_CHARSET));
compose.exec(options("-d"), "container_1", arguments("ls"));
verify(dockerComposeExecutor, times(1)).execute("exec", "-T", "-d", "container_1", "ls");
}
@Test
public void fail_if_docker_compose_version_is_prior_1_7_on_docker_compose_exec()
throws IOException, InterruptedException {
when(dockerComposeExecutedProcess.getInputStream()).thenReturn(toInputStream("1.5.6", DEFAULT_CHARSET));
exception.expect(IllegalStateException.class);
exception.expectMessage("You need at least docker-compose 1.7 to run docker-compose exec");
compose.exec(options("-d"), "container_1", arguments("ls"));
}
@Test
public void pass_concatenated_arguments_to_executor_on_docker_compose_run()
throws IOException, InterruptedException {
compose.run(DockerComposeRunOption.options("-d"), "container_1", DockerComposeRunArgument.arguments("ls"));
verify(dockerComposeExecutor, times(1)).execute("run", "-d", "container_1", "ls");
}
@Test
public void return_the_output_from_the_executed_process_on_docker_compose_exec() throws Exception {
String lsString = String.format("-rw-r--r-- 1 user 1318458867 11326 Mar 9 17:47 LICENSE%n"
+ "-rw-r--r-- 1 user 1318458867 12570 May 12 14:51 README.md");
String versionString = "1.7.0-rc1";
DockerComposeExecutable processExecutor = mock(DockerComposeExecutable.class);
addProcessToExecutor(processExecutor, processWithOutput(versionString), "version", "--short");
addProcessToExecutor(processExecutor, processWithOutput(lsString), "exec", "-T", "container_1", "ls", "-l");
DockerCompose processCompose = new DefaultDockerCompose(processExecutor, dockerExecutor, dockerMachine);
assertThat(processCompose.exec(options(), "container_1", arguments("ls", "-l")), is(lsString));
}
@Test
public void return_the_output_from_the_executed_process_on_docker_compose_run() throws Exception {
String lsString = String.format("-rw-r--r-- 1 user 1318458867 11326 Mar 9 17:47 LICENSE%n"
+ "-rw-r--r-- 1 user 1318458867 12570 May 12 14:51 README.md");
DockerComposeExecutable processExecutor = mock(DockerComposeExecutable.class);
addProcessToExecutor(processExecutor, processWithOutput(lsString), "run", "-it", "container_1", "ls", "-l");
DockerCompose processCompose = new DefaultDockerCompose(processExecutor, dockerExecutor, dockerMachine);
assertThat(processCompose.run(DockerComposeRunOption.options("-it"), "container_1", DockerComposeRunArgument.arguments("ls", "-l")), is(lsString));
}
private static void addProcessToExecutor(DockerComposeExecutable dockerComposeExecutable, Process process, String... commands) throws Exception {
when(dockerComposeExecutable.execute(commands)).thenReturn(process);
}
private static Process processWithOutput(String output) {
Process mockedProcess = mock(Process.class);
when(mockedProcess.getInputStream()).thenReturn(toInputStream(output, DEFAULT_CHARSET));
when(mockedProcess.exitValue()).thenReturn(0);
return mockedProcess;
}
}
| 49.704663
| 155
| 0.722871
|
8930508eb152596edc148131a071cfa5d7a3c729
| 1,038
|
package com.harry.alto.learning.sidemo.controller;
import com.harry.alto.learning.sidemo.config.GlobalIdGateway;
import com.harry.alto.learning.sidemo.service.GlobalIdHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
@Slf4j
public class GlobalIdController {
public static final String GLOBAL_ID_ENDPOINT_V1 = "/v1/global-ids";
@Autowired
private GlobalIdGateway globalIdGateway;
@Autowired
private GlobalIdHandler globalIdHandler;
@PostMapping(GLOBAL_ID_ENDPOINT_V1)
@ResponseStatus(HttpStatus.CREATED)
public Mono<Long> getGlobalId() {
return globalIdHandler.getId()
.doOnNext(value -> globalIdGateway.sayHello(value.toString()));
}
}
| 34.6
| 79
| 0.790944
|
c7ab4e392f82fc8236d31f9f7d2d8f6da8955d96
| 126
|
import com.icici.Test;
public class Solution{
public static void main(String []args){
Test t = new Test();
t.m1();
}
}
| 15.75
| 40
| 0.650794
|
dd27f0290e15b80cf59de494bc551e72334562c3
| 1,127
|
package com.freeter;
import java.util.Date;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import com.freeter.modules.sys.entity.SysUserEntity;
import com.freeter.modules.sys.shiro.ShiroUtils;
//@Component
public class MyMetaObjectHandler extends MetaObjectHandler {
protected final static Logger logger = LoggerFactory.getLogger(AdminApplication.class);
@Override
public void insertFill(MetaObject metaObject) {
logger.info("新增的时候干点不可描述的事情");
setFieldValByName("createTime", new Date(), metaObject);
setFieldValByName("createBy", ShiroUtils.getUserEntity().getUsername(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
logger.info("更新的时候干点不可描述的事情");
setFieldValByName("updateTime", new Date(), metaObject);
setFieldValByName("updateBy", ShiroUtils.getUserEntity().getUsername(), metaObject);
}
}
| 32.2
| 93
| 0.748891
|
a80d488638873e3ed11f5c72b7b15d71b407e628
| 561
|
package supplyArtefact;
public class ExploitableArtifact {
public static final double lessMagnitude = 0.30043158095391653;
public static synchronized int existingIndictment() {
double bestAmount;
bestAmount = 0.5504399516963769;
return constitutedFigures;
}
public ExploitableArtifact() {
this.est = constitutedFigures++;
}
private int est;
private static int constitutedFigures;
public synchronized String toString() {
double discover;
discover = 0.738354084540581;
return "ProducibleObject:" + this.est;
}
}
| 22.44
| 65
| 0.736185
|
f9fe9d667066ed1a03367c9a2971a21ec463aefe
| 1,587
|
package org.cryptimeleon.incentive.services.issue;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@AllArgsConstructor
public class IssueController {
private IssueService issueService;
/**
* Endpoint for alive testing etc.
*/
@GetMapping("/")
public ResponseEntity<String> test() {
return new ResponseEntity<>("Hello from Issue service!", HttpStatus.OK);
}
@GetMapping("/issue")
@ApiOperation(value = "Issuing protocol", notes = "Issue a new incentive token.", response = String.class)
@ApiResponses({
@ApiResponse(code = 200, message = "Success", response = String.class),
@ApiResponse(code = 403, message = "Invalid Issuing Request", response = String.class)
})
public ResponseEntity<String> performIssueJoin(
@RequestHeader(value = "join-request") String serializedJoinRequest,
@RequestHeader(value = "public-key") String serializedUserPublicKey
) {
return new ResponseEntity<>(issueService.runIssueJoinProtocol(serializedJoinRequest, serializedUserPublicKey), HttpStatus.OK);
}
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(RuntimeException.class)
public String handleIncentiveException(RuntimeException ex) {
return "An exception occurred!";
}
}
| 36.906977
| 134
| 0.727788
|
6faed4edc4992a7e415293f2672a5a3500b92a34
| 7,216
|
package extracells.item;
import appeng.api.AEApi;
import appeng.api.config.AccessRestriction;
import appeng.api.features.INetworkEncodable;
import appeng.api.implementations.items.IAEItemPowerStorage;
import appeng.api.implementations.tiles.IWirelessAccessPoint;
import appeng.api.networking.IGrid;
import appeng.api.networking.IGridHost;
import appeng.api.networking.IGridNode;
import appeng.api.networking.storage.IStorageGrid;
import appeng.api.storage.IMEMonitor;
import appeng.api.storage.data.IAEFluidStack;
import appeng.api.util.WorldCoord;
import extracells.network.GuiHandler;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.IIcon;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import java.util.List;
public class ItemWirelessTerminalFluid extends Item implements INetworkEncodable, IAEItemPowerStorage {
IIcon icon;
private final int MAX_POWER = 3200000;
public ItemWirelessTerminalFluid() {
setMaxStackSize(1);
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public void getSubItems(Item item, CreativeTabs creativeTab, List itemList) {
itemList.add(new ItemStack(item));
ItemStack itemStack = new ItemStack(item);
injectAEPower(itemStack, MAX_POWER);
itemList.add(itemStack);
}
@SuppressWarnings("unchecked")
@Override
public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer entityPlayer) {
if (world.isRemote)
return itemStack;
NBTTagCompound nbtTagCompound = ensureTagCompound(itemStack);
if (getAECurrentPower(itemStack) <= 0)
return itemStack;
Long key;
try {
key = Long.parseLong(nbtTagCompound.getString("key"));
} catch (Throwable ignored) {
return itemStack;
}
int x = (int) entityPlayer.posX;
int y = (int) entityPlayer.posY;
int z = (int) entityPlayer.posZ;
IGridHost securityTerminal = (IGridHost) AEApi.instance().registries().locateable().findLocateableBySerial(key);
if (securityTerminal == null)
return itemStack;
IGridNode gridNode = securityTerminal.getGridNode(ForgeDirection.UNKNOWN);
if (gridNode == null)
return itemStack;
IGrid grid = gridNode.getGrid();
if (grid == null)
return itemStack;
for (IGridNode node : grid.getMachines((Class<? extends IGridHost>) AEApi.instance().blocks().blockWireless.entity())) {
IWirelessAccessPoint accessPoint = (IWirelessAccessPoint) node.getMachine();
WorldCoord distance = accessPoint.getLocation().subtract(x, y, z);
int squaredDistance = distance.x * distance.x + distance.y * distance.y + distance.z * distance.z;
if (squaredDistance <= accessPoint.getRange() * accessPoint.getRange()) {
IStorageGrid gridCache = grid.getCache(IStorageGrid.class);
if (gridCache != null) {
IMEMonitor<IAEFluidStack> fluidInventory = gridCache.getFluidInventory();
if (fluidInventory != null) {
GuiHandler.launchGui(GuiHandler.getGuiId(1), entityPlayer, fluidInventory);
}
}
}
}
return itemStack;
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public void addInformation(ItemStack itemStack, EntityPlayer player, List list, boolean par4) {
if (!itemStack.hasTagCompound())
itemStack.setTagCompound(new NBTTagCompound());
String encryptionKey = itemStack.getTagCompound().getString("key");
double aeCurrentPower = getAECurrentPower(itemStack);
list.add(StatCollector.translateToLocal("gui.appliedenergistics2.StoredEnergy") + ": " + aeCurrentPower + " AE - " + Math.floor((aeCurrentPower / MAX_POWER) * 1e4) / 1e2 + "%");
list.add(StatCollector.translateToLocal(encryptionKey != null && !encryptionKey.isEmpty() ? "gui.appliedenergistics2.Linked" : "gui.appliedenergistics2.Unlinked"));
}
@Override
public String getUnlocalizedName(ItemStack itemStack) {
return super.getUnlocalizedName(itemStack).replace("item.extracells", "extracells.item");
}
public IIcon getIconFromDamage(int dmg) {
return icon;
}
@Override
public void registerIcons(IIconRegister iconRegister) {
icon = iconRegister.registerIcon("extracells:" + "terminal.fluid.wireless");
}
@Override
public String getEncryptionKey(ItemStack itemStack) {
if (!itemStack.hasTagCompound())
itemStack.setTagCompound(new NBTTagCompound());
return itemStack.getTagCompound().getString("key");
}
@Override
public void setEncryptionKey(ItemStack itemStack, String encKey, String name) {
if (!itemStack.hasTagCompound())
itemStack.setTagCompound(new NBTTagCompound());
NBTTagCompound tagCompound = itemStack.getTagCompound();
tagCompound.setString("key", encKey);
}
@Override
public double injectAEPower(ItemStack itemStack, double amt) {
NBTTagCompound tagCompound = ensureTagCompound(itemStack);
double currentPower = tagCompound.getDouble("power");
double toInject = Math.min(amt, MAX_POWER - currentPower);
tagCompound.setDouble("power", currentPower + toInject);
return toInject;
}
@Override
public double extractAEPower(ItemStack itemStack, double amt) {
NBTTagCompound tagCompound = ensureTagCompound(itemStack);
double currentPower = tagCompound.getDouble("power");
double toExtract = Math.min(amt, currentPower);
tagCompound.setDouble("power", currentPower - toExtract);
return toExtract;
}
@Override
public double getAEMaxPower(ItemStack itemStack) {
return MAX_POWER;
}
@Override
public double getAECurrentPower(ItemStack itemStack) {
NBTTagCompound tagCompound = ensureTagCompound(itemStack);
return tagCompound.getDouble("power");
}
@Override
public AccessRestriction getPowerFlow(ItemStack itemStack) {
return null;
}
private NBTTagCompound ensureTagCompound(ItemStack itemStack) {
if (!itemStack.hasTagCompound())
itemStack.setTagCompound(new NBTTagCompound());
return itemStack.getTagCompound();
}
@Override
public int getDamage(ItemStack itemStack) {
return (int) getAECurrentPower(itemStack);
}
@Override
public int getMaxDamage(ItemStack itemStack) {
return MAX_POWER;
}
@Override
public double getDurabilityForDisplay(ItemStack itemStack) {
return 1 - getAECurrentPower(itemStack) / MAX_POWER;
}
@Override
public boolean showDurabilityBar(ItemStack itemStack) {
return true;
}
}
| 37.978947
| 185
| 0.687916
|
81f55470a1413b14c3b74520c4b1f4af2edca470
| 8,418
|
package io.reactivex.internal.schedulers;
import io.reactivex.Scheduler;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.disposables.EmptyDisposable;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public final class IoScheduler extends Scheduler {
static final RxThreadFactory EVICTOR_THREAD_FACTORY;
private static final String EVICTOR_THREAD_NAME_PREFIX = "RxCachedWorkerPoolEvictor";
private static final long KEEP_ALIVE_TIME = Long.getLong(KEY_KEEP_ALIVE_TIME, 60).longValue();
public static final long KEEP_ALIVE_TIME_DEFAULT = 60;
private static final TimeUnit KEEP_ALIVE_UNIT = TimeUnit.SECONDS;
private static final String KEY_IO_PRIORITY = "rx2.io-priority";
private static final String KEY_KEEP_ALIVE_TIME = "rx2.io-keep-alive-time";
static final CachedWorkerPool NONE;
static final ThreadWorker SHUTDOWN_THREAD_WORKER;
static final RxThreadFactory WORKER_THREAD_FACTORY;
private static final String WORKER_THREAD_NAME_PREFIX = "RxCachedThreadScheduler";
final AtomicReference<CachedWorkerPool> pool;
final ThreadFactory threadFactory;
static {
ThreadWorker threadWorker = new ThreadWorker(new RxThreadFactory("RxCachedThreadSchedulerShutdown"));
SHUTDOWN_THREAD_WORKER = threadWorker;
threadWorker.dispose();
int max = Math.max(1, Math.min(10, Integer.getInteger(KEY_IO_PRIORITY, 5).intValue()));
WORKER_THREAD_FACTORY = new RxThreadFactory(WORKER_THREAD_NAME_PREFIX, max);
EVICTOR_THREAD_FACTORY = new RxThreadFactory(EVICTOR_THREAD_NAME_PREFIX, max);
CachedWorkerPool cachedWorkerPool = new CachedWorkerPool(0, (TimeUnit) null, WORKER_THREAD_FACTORY);
NONE = cachedWorkerPool;
cachedWorkerPool.shutdown();
}
static final class CachedWorkerPool implements Runnable {
final CompositeDisposable allWorkers;
private final ScheduledExecutorService evictorService;
private final Future<?> evictorTask;
private final ConcurrentLinkedQueue<ThreadWorker> expiringWorkerQueue;
private final long keepAliveTime;
private final ThreadFactory threadFactory;
CachedWorkerPool(long j, TimeUnit timeUnit, ThreadFactory threadFactory2) {
ScheduledFuture<?> scheduledFuture;
this.keepAliveTime = timeUnit != null ? timeUnit.toNanos(j) : 0;
this.expiringWorkerQueue = new ConcurrentLinkedQueue<>();
this.allWorkers = new CompositeDisposable();
this.threadFactory = threadFactory2;
ScheduledExecutorService scheduledExecutorService = null;
if (timeUnit != null) {
scheduledExecutorService = Executors.newScheduledThreadPool(1, IoScheduler.EVICTOR_THREAD_FACTORY);
long j2 = this.keepAliveTime;
scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(this, j2, j2, TimeUnit.NANOSECONDS);
} else {
scheduledFuture = null;
}
this.evictorService = scheduledExecutorService;
this.evictorTask = scheduledFuture;
}
public void run() {
evictExpiredWorkers();
}
/* access modifiers changed from: package-private */
public ThreadWorker get() {
if (this.allWorkers.isDisposed()) {
return IoScheduler.SHUTDOWN_THREAD_WORKER;
}
while (!this.expiringWorkerQueue.isEmpty()) {
ThreadWorker poll = this.expiringWorkerQueue.poll();
if (poll != null) {
return poll;
}
}
ThreadWorker threadWorker = new ThreadWorker(this.threadFactory);
this.allWorkers.add(threadWorker);
return threadWorker;
}
/* access modifiers changed from: package-private */
public void release(ThreadWorker threadWorker) {
threadWorker.setExpirationTime(now() + this.keepAliveTime);
this.expiringWorkerQueue.offer(threadWorker);
}
/* access modifiers changed from: package-private */
public void evictExpiredWorkers() {
if (!this.expiringWorkerQueue.isEmpty()) {
long now = now();
Iterator<ThreadWorker> it = this.expiringWorkerQueue.iterator();
while (it.hasNext()) {
ThreadWorker next = it.next();
if (next.getExpirationTime() > now) {
return;
}
if (this.expiringWorkerQueue.remove(next)) {
this.allWorkers.remove(next);
}
}
}
}
/* access modifiers changed from: package-private */
public long now() {
return System.nanoTime();
}
/* access modifiers changed from: package-private */
public void shutdown() {
this.allWorkers.dispose();
Future<?> future = this.evictorTask;
if (future != null) {
future.cancel(true);
}
ScheduledExecutorService scheduledExecutorService = this.evictorService;
if (scheduledExecutorService != null) {
scheduledExecutorService.shutdownNow();
}
}
}
public IoScheduler() {
this(WORKER_THREAD_FACTORY);
}
public IoScheduler(ThreadFactory threadFactory2) {
this.threadFactory = threadFactory2;
this.pool = new AtomicReference<>(NONE);
start();
}
public void start() {
CachedWorkerPool cachedWorkerPool = new CachedWorkerPool(KEEP_ALIVE_TIME, KEEP_ALIVE_UNIT, this.threadFactory);
if (!this.pool.compareAndSet(NONE, cachedWorkerPool)) {
cachedWorkerPool.shutdown();
}
}
public void shutdown() {
CachedWorkerPool cachedWorkerPool;
CachedWorkerPool cachedWorkerPool2;
do {
cachedWorkerPool = this.pool.get();
cachedWorkerPool2 = NONE;
if (cachedWorkerPool == cachedWorkerPool2) {
return;
}
} while (!this.pool.compareAndSet(cachedWorkerPool, cachedWorkerPool2));
cachedWorkerPool.shutdown();
}
public Scheduler.Worker createWorker() {
return new EventLoopWorker(this.pool.get());
}
public int size() {
return this.pool.get().allWorkers.size();
}
static final class EventLoopWorker extends Scheduler.Worker {
final AtomicBoolean once = new AtomicBoolean();
private final CachedWorkerPool pool;
private final CompositeDisposable tasks;
private final ThreadWorker threadWorker;
EventLoopWorker(CachedWorkerPool cachedWorkerPool) {
this.pool = cachedWorkerPool;
this.tasks = new CompositeDisposable();
this.threadWorker = cachedWorkerPool.get();
}
public void dispose() {
if (this.once.compareAndSet(false, true)) {
this.tasks.dispose();
this.pool.release(this.threadWorker);
}
}
public boolean isDisposed() {
return this.once.get();
}
public Disposable schedule(Runnable runnable, long j, TimeUnit timeUnit) {
if (this.tasks.isDisposed()) {
return EmptyDisposable.INSTANCE;
}
return this.threadWorker.scheduleActual(runnable, j, timeUnit, this.tasks);
}
}
static final class ThreadWorker extends NewThreadWorker {
private long expirationTime = 0;
ThreadWorker(ThreadFactory threadFactory) {
super(threadFactory);
}
public long getExpirationTime() {
return this.expirationTime;
}
public void setExpirationTime(long j) {
this.expirationTime = j;
}
}
}
| 38.614679
| 119
| 0.643383
|
527ed30ec79f103e2dd0be7bd3150aed9b43c049
| 4,382
|
package com.evacipated.cardcrawl.modthespire;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
class OutJar
{
public static class FilePathAndBytes
{
public String path;
public byte[] b;
public FilePathAndBytes(String path, byte[] b)
{
this.path = path;
this.b = b;
}
}
/* https://stackoverflow.com/questions/2548384/java-get-a-list-of-all-classes-loaded-in-the-jvm?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa */
private static Iterator<Class<?>> getClassList(ClassLoader CL)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
{
Class<?> CL_class = CL.getClass();
while (CL_class != java.lang.ClassLoader.class) {
CL_class = CL_class.getSuperclass();
}
java.lang.reflect.Field ClassLoader_classes_field = CL_class
.getDeclaredField("classes");
ClassLoader_classes_field.setAccessible(true);
@SuppressWarnings("unchecked")
Vector<Class<?>> classes = (Vector<Class<?>>) ClassLoader_classes_field.get(CL);
return classes.iterator();
}
/* https://stackoverflow.com/questions/22591903/javassist-how-to-inject-a-method-into-a-class-in-jar?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa */
public static class JarHandler
{
public void writeOut(String jarPathAndName, List<FilePathAndBytes> files)
throws IOException
{
File jarFile = new File(jarPathAndName);
try {
JarOutputStream tempJar = new JarOutputStream(new FileOutputStream(jarFile));
try {
// Open the given file.
try {
// Create a jar entry and add it to the temp jar.
for (FilePathAndBytes file : files) {
String fileName = file.path;
byte[] fileByteCode = file.b;
JarEntry entry = new JarEntry(fileName);
tempJar.putNextEntry(entry);
tempJar.write(fileByteCode);
}
} catch (Exception ex) {
System.out.println(ex);
// Add a stub entry here, so that the jar will close
// without an
// exception.
tempJar.putNextEntry(new JarEntry("stub"));
}
} catch (Exception ex) {
System.out.println(ex);
// IMportant so the jar will close without an
// exception.
tempJar.putNextEntry(new JarEntry("stub"));
} finally {
tempJar.close();
}
} finally {
// do I need to do things here
}
}
}
public static void dumpJar(ClassLoader loader, ClassPool pool, String jarPath)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, IOException
{
Iterator<Class<?>> loadedClasses = getClassList(loader);
List<FilePathAndBytes> files = new ArrayList<>();
for (; loadedClasses.hasNext();) {
try {
String className = loadedClasses.next().getName();
CtClass ctClass;
ctClass = pool.get(className);
byte[] b = ctClass.toBytecode();
String classPath = className.replaceAll("\\.", "/") + ".class";
files.add(new FilePathAndBytes(classPath, b));
} catch (NotFoundException | IOException | CannotCompileException e) {
// eat it - just means this isn't a file we've loaded
}
}
JarHandler handler = new JarHandler();
handler.writeOut(jarPath, files);
}
}
| 36.516667
| 180
| 0.576221
|
187fa25bb1e5c363e0f83cd1c2452ff135079ac5
| 565
|
package com.itgowo.httpserver;
/*
* Copyright (c) 2018.
* @author lujianchao
* MiniHttpServer
* Github:https://github.com/hnsugar
* Github:https://github.com/itgowo
* website:http://itgowo.com
*/
public enum HttpMethod {
GET,
PUT,
POST,
DELETE,
HEAD,
OPTIONS,
TRACE,
CONNECT,
PATCH;
static HttpMethod find(String method) {
for (HttpMethod m : HttpMethod.values()) {
if (m.toString().equalsIgnoreCase(method)) {
return m;
}
}
return null;
}
}
| 17.65625
| 56
| 0.564602
|
9b23b6b78d67caac4185fe285ed0be8cb751e673
| 518
|
package com.airbnb.lottie.p095f;
/* renamed from: com.airbnb.lottie.f.d */
/* compiled from: MeanCalculator */
public class C5827d {
/* renamed from: a */
private float f10103a;
/* renamed from: b */
private int f10104b;
/* renamed from: a */
public void mo18185a(float number) {
this.f10103a += number;
this.f10104b++;
int i = this.f10104b;
if (i == Integer.MAX_VALUE) {
this.f10103a /= 2.0f;
this.f10104b = i / 2;
}
}
}
| 21.583333
| 41
| 0.555985
|
c15bb3697ad18ba1b00af3dc61bacaad83577233
| 722
|
package maxhyper.dtbyg.cells.cell;
import com.ferreusveritas.dynamictrees.cells.MatrixCell;
/**
* @author Harley O'Connor
*/
public final class WillowLeafCell extends MatrixCell {
private static final byte[] VAL_MAP = {
0, 1, 2, 3, 4, 5, 6, 7, // D Maps 5 -> 4, * -> *
0, 0, 0, 0, 4, 5, 5, 6, // U Maps 6 -> 6, 7 -> 7, * -> 0
0, 0, 0, 0, 4, 5, 5, 6, // N Maps 6 -> 6, 7 -> 7, * -> 0
0, 0, 0, 0, 4, 5, 5, 6, // S Maps 6 -> 6, 7 -> 7, * -> 0
0, 0, 0, 0, 4, 5, 5, 6, // W Maps 6 -> 6, 7 -> 7, * -> 0
0, 0, 0, 0, 4, 5, 5, 6 // E Maps 6 -> 6, 7 -> 7, * -> 0
};
public WillowLeafCell(int value) {
super(value, VAL_MAP);
}
}
| 30.083333
| 68
| 0.448753
|
24efbcbe693a756bb5599af8b9e9d774a1f41a49
| 3,545
|
package cn.isekai.keycloak.avatar.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
public class ResUtils {
public static Response responseJson(Map<String, Object> entity) {
ObjectMapper mapper = new ObjectMapper();
try {
String jsonStr = mapper.writeValueAsString(entity);
return Response.ok(jsonStr).type(MediaType.APPLICATION_JSON).build();
} catch (JsonProcessingException e) {
return Response.ok("{status:0,error:\"Internal Server Error\"}").type(MediaType.APPLICATION_JSON).build();
}
}
public static Response responseBadRequest(boolean isJson) {
if (isJson) {
Map<String, Object> res = new HashMap<String, Object>();
res.put("status", 500);
res.put("error", "bad request");
res.put("errormsg", "httpBadRequest");
return responseJson(res);
} else {
return Response.status(Response.Status.BAD_REQUEST).entity("400 - Bad request").build();
}
}
public static Response responseInternalServerError(boolean isJson) {
if (isJson) {
Map<String, Object> res = new HashMap<String, Object>();
res.put("status", 500);
res.put("error", "internal server error");
res.put("errormsg", "httpInternalServerError");
return responseJson(res);
} else {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("500 - Internal Server Error").build();
}
}
public static Response responseNotAuthorized(boolean isJson) {
if (isJson) {
Map<String, Object> res = new HashMap<String, Object>();
res.put("status", 403);
res.put("error", "access denied");
res.put("errormsg", "accessDenied");
return responseJson(res);
} else {
return Response.status(Response.Status.FORBIDDEN).entity("403 - Access denied").build();
}
}
public static Response responseNotFound(boolean isJson) {
if (isJson) {
Map<String, Object> res = new HashMap<String, Object>();
res.put("status", 404);
res.put("error", "resource not found");
res.put("errormsg", "avatarNotFound");
return responseJson(res);
} else {
return Response.status(Response.Status.NOT_FOUND).entity("404 - Resource not found").build();
}
}
public static Response responseRedirectTo(String url) {
return Response.status(Response.Status.TEMPORARY_REDIRECT).header("Location", url).build();
}
public static String bin2hex(byte[] input){
BigInteger bigInt = new BigInteger(1, input);
StringBuilder hashText = new StringBuilder(bigInt.toString(16));
while(hashText.length() < 32){
hashText.insert(0, "0");
}
return hashText.toString();
}
public static String md5(String input){
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes(StandardCharsets.UTF_8));
return bin2hex(md.digest());
} catch(Exception e){
return null;
}
}
}
| 34.086538
| 120
| 0.616361
|
d3dad3a05624be741c1d576c1c4c44f9566b2673
| 5,519
|
// Template Source: BaseEntityRequestBuilder.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.externalconnectors.requests;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.externalconnectors.models.ExternalConnection;
import com.microsoft.graph.externalconnectors.requests.ExternalGroupCollectionRequestBuilder;
import com.microsoft.graph.externalconnectors.requests.ExternalGroupRequestBuilder;
import com.microsoft.graph.externalconnectors.requests.ExternalItemCollectionRequestBuilder;
import com.microsoft.graph.externalconnectors.requests.ExternalItemRequestBuilder;
import com.microsoft.graph.externalconnectors.requests.ConnectionOperationCollectionRequestBuilder;
import com.microsoft.graph.externalconnectors.requests.ConnectionOperationRequestBuilder;
import com.microsoft.graph.externalconnectors.requests.SchemaRequestBuilder;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseRequestBuilder;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the External Connection Request Builder.
*/
public class ExternalConnectionRequestBuilder extends BaseRequestBuilder<ExternalConnection> {
/**
* The request builder for the ExternalConnection
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public ExternalConnectionRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions);
}
/**
* Creates the request
*
* @param requestOptions the options for this request
* @return the ExternalConnectionRequest instance
*/
@Nonnull
public ExternalConnectionRequest buildRequest(@Nullable final com.microsoft.graph.options.Option... requestOptions) {
return buildRequest(getOptions(requestOptions));
}
/**
* Creates the request with specific requestOptions instead of the existing requestOptions
*
* @param requestOptions the options for this request
* @return the ExternalConnectionRequest instance
*/
@Nonnull
public ExternalConnectionRequest buildRequest(@Nonnull final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
return new com.microsoft.graph.externalconnectors.requests.ExternalConnectionRequest(getRequestUrl(), getClient(), requestOptions);
}
/**
* Gets a request builder for the ExternalGroup collection
*
* @return the collection request builder
*/
@Nonnull
public ExternalGroupCollectionRequestBuilder groups() {
return new ExternalGroupCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("groups"), getClient(), null);
}
/**
* Gets a request builder for the ExternalGroup item
*
* @return the request builder
* @param id the item identifier
*/
@Nonnull
public ExternalGroupRequestBuilder groups(@Nonnull final String id) {
return new ExternalGroupRequestBuilder(getRequestUrlWithAdditionalSegment("groups") + "/" + id, getClient(), null);
}
/**
* Gets a request builder for the ExternalItem collection
*
* @return the collection request builder
*/
@Nonnull
public ExternalItemCollectionRequestBuilder items() {
return new ExternalItemCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("items"), getClient(), null);
}
/**
* Gets a request builder for the ExternalItem item
*
* @return the request builder
* @param id the item identifier
*/
@Nonnull
public ExternalItemRequestBuilder items(@Nonnull final String id) {
return new ExternalItemRequestBuilder(getRequestUrlWithAdditionalSegment("items") + "/" + id, getClient(), null);
}
/**
* Gets a request builder for the ConnectionOperation collection
*
* @return the collection request builder
*/
@Nonnull
public ConnectionOperationCollectionRequestBuilder operations() {
return new ConnectionOperationCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("operations"), getClient(), null);
}
/**
* Gets a request builder for the ConnectionOperation item
*
* @return the request builder
* @param id the item identifier
*/
@Nonnull
public ConnectionOperationRequestBuilder operations(@Nonnull final String id) {
return new ConnectionOperationRequestBuilder(getRequestUrlWithAdditionalSegment("operations") + "/" + id, getClient(), null);
}
/**
* Gets the request builder for Schema
*
* @return the SchemaRequestBuilder instance
*/
@Nonnull
public SchemaRequestBuilder schema() {
return new SchemaRequestBuilder(getRequestUrlWithAdditionalSegment("schema"), getClient(), null);
}
}
| 40.284672
| 210
| 0.720058
|
ce2a04915ee9b8ad120fb14e57c17d5b7c68fba0
| 403
|
package com.muzzley.model.cards;
/**
* Created by caan on 21-03-2016.
*/
public class Color {
public String background = "FFFFFF";
public String text = "323232";
public String title = "323232";
public Color(){
}
public Color(String background, String text, String title) {
this.background = background;
this.text = text;
this.title = title;
}
}
| 19.190476
| 64
| 0.615385
|
400e331f5978db3c7af44afae2dd7a9a90f00346
| 1,006
|
/*
* 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 DataPersistence;
import Acquaintance.ICase;
import Acquaintance.IInquiry;
import Acquaintance.IDataPersistence;
/**
*
* @author Alexa
*/
public class DataFacade implements IDataPersistence {
private static DataFacade instance;
private CaseDatabaseManager caseDatabase = new CaseDatabaseManager();
private DataFacade() {
}
public static DataFacade getInstance(){
if (instance == null) {
instance = new DataFacade();
}
return instance;
}
@Override
public boolean saveInquiry(IInquiry inquiry) {
return caseDatabase.saveInquiry(inquiry);
}
@Override
public boolean saveCase(ICase case1) {
return caseDatabase.saveCase(case1);
}
}
| 23.395349
| 80
| 0.639165
|
d3eb568d017c3a5fb9c2f3ba7ba9da174ddaea12
| 437
|
package objects;
public class DateBuilder{
public String[] getYears(int yr) {
String[] years = new String[yr];
for (int i = 0; i < 117; i++) {
years[i] = 1900 + i + "";
}
return years;
}
public String[] getDays(int day) {
String[] nichi = new String[day];
for (int i = 0; i < day; i++) {
nichi[i] = 1 + i + "";
}
return nichi;
}
}
| 21.85
| 41
| 0.453089
|
eb859e41223ac79135f8c31ddfa5d8ccbf543964
| 1,050
|
/*
* 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 Fachada;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import modelo.Anuncio;
import modelo.Usuario;
import sessao.LoginLocal;
import sessao.UsuarioFacadeLocal;
/**
*
* @author Breno
*/
@Stateless
public class UsuarioStateless {
@EJB
private UsuarioFacadeLocal usuarioLocal;
@EJB
private LoginLocal loginLocal;
public void create(Usuario usuario){
usuarioLocal.create(usuario);
}
public void edit(Usuario usuario) {
usuarioLocal.edit(usuario);
}
public void remove(Usuario usuario) {
usuarioLocal.remove(usuario);
}
public Usuario find(int id) {
return usuarioLocal.find(id);
}
public List<Usuario> findAll() {
return usuarioLocal.findAll();
}
}
| 21.428571
| 80
| 0.64
|
b6afbc8541bf1e0f4bb16c13efcb4dc28a83a0b0
| 10,948
|
/*
Copyright (c) 2005-2021, Carlos Amengual.
SPDX-License-Identifier: BSD-3-Clause
Licensed under a BSD-style License. You can find the license here:
https://css4j.github.io/LICENSE.txt
*/
package io.sf.carte.doc.style.css.property;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.StringReader;
import org.junit.Test;
import org.w3c.dom.DOMException;
import io.sf.carte.doc.style.css.CSSValue;
import io.sf.carte.doc.style.css.CSSValueSyntax;
import io.sf.carte.doc.style.css.CSSValueSyntax.Match;
import io.sf.carte.doc.style.css.nsac.CSSException;
import io.sf.carte.doc.style.css.nsac.LexicalUnit;
import io.sf.carte.doc.style.css.parser.CSSParser;
import io.sf.carte.doc.style.css.parser.SyntaxParser;
import io.sf.carte.doc.style.css.property.PrimitiveValue.LexicalSetter;
public class StringValueTest {
@Test
public void testSetStringValueShortString() {
StringValue value = createCSSStringValue();
value.setStringValue(CSSValue.Type.STRING, "Some text in \"double quotes\"");
assertEquals("Some text in \"double quotes\"", value.getStringValue());
assertEquals("'Some text in \"double quotes\"'", value.getCssText());
assertEquals("'Some text in \"double quotes\"'", value.getMinifiedCssText(""));
//
value.setStringValue(CSSValue.Type.STRING, "Some text 'in quotes'");
assertEquals("Some text 'in quotes'", value.getStringValue());
assertEquals("\"Some text 'in quotes'\"", value.getCssText());
assertEquals("\"Some text 'in quotes'\"", value.getMinifiedCssText(""));
//
value.setStringValue(CSSValue.Type.STRING, "Some text in \"double quote's\"");
assertEquals("Some text in \"double quote's\"", value.getStringValue());
assertEquals("'Some text in \"double quote\\'s\"'", value.getCssText());
assertEquals("'Some text in \"double quote\\'s\"'", value.getMinifiedCssText(""));
//
value.setStringValue(CSSValue.Type.STRING, "&");
assertEquals("&", value.getStringValue());
assertEquals("'&'", value.getCssText());
assertEquals("'&'", value.getMinifiedCssText(""));
//
value.setStringValue(CSSValue.Type.STRING, "foo");
assertEquals("foo", value.getStringValue());
assertEquals("'foo'", value.getCssText());
assertEquals("'foo'", value.getMinifiedCssText(""));
//
value.setStringValue(CSSValue.Type.STRING, "\\5FAE\u8F6F");
assertEquals("\\5FAE\u8F6F", value.getStringValue());
assertEquals("'\\\\5FAE\u8F6F'", value.getCssText());
assertEquals("'\\\\5FAE\u8F6F'", value.getMinifiedCssText(""));
//
try {
value.setStringValue(CSSValue.Type.STRING, null);
fail("Must throw exception.");
} catch (DOMException e) {
assertEquals(DOMException.INVALID_CHARACTER_ERR, e.code);
}
}
@Test
public void testSetCssTextString() {
StringValue value = createCSSStringValue();
value.setCssText("\"foo\"");
assertEquals("foo", value.getStringValue());
assertEquals("\"foo\"", value.getCssText());
assertEquals("\"foo\"", value.getMinifiedCssText(""));
//
value.setCssText("foo");
assertEquals("foo", value.getStringValue());
assertEquals("\"foo\"", value.getCssText());
assertEquals("\"foo\"", value.getMinifiedCssText(""));
// Syntax matching
SyntaxParser syntaxParser = new SyntaxParser();
CSSValueSyntax syn = syntaxParser.parseSyntax("<string>");
assertEquals(Match.TRUE, value.matches(syn));
syn = syntaxParser.parseSyntax("<custom-ident>");
assertEquals(Match.FALSE, value.matches(syn));
syn = syntaxParser.parseSyntax("*");
assertEquals(Match.TRUE, value.matches(syn));
}
@Test
public void testSetCssTextWhitespace() {
StringValue value = createCSSStringValue();
value.setCssText("\" \"");
assertEquals(" ", value.getStringValue());
assertEquals("\" \"", value.getCssText());
assertEquals("\" \"", value.getMinifiedCssText(""));
}
@Test
public void testSetCssTextDoubleWhitespace() {
StringValue value = createCSSStringValue();
value.setCssText("\" \"");
assertEquals(" ", value.getStringValue());
assertEquals("\" \"", value.getCssText());
assertEquals("\" \"", value.getMinifiedCssText(""));
}
@Test
public void testSetCssTextStringEscaped() {
StringValue value = createCSSStringValue();
value.setCssText("\"â†\u0090\"");
assertEquals("â†\u0090", value.getStringValue());
assertEquals("\"â†\\90 \"", value.getCssText());
assertEquals("\"â†\\90\"", value.getMinifiedCssText(""));
}
@Test
public void testSetCssTextStringEscaped2() {
StringValue value = createCSSStringValue();
value.setCssText("\"\\f107\"");
assertEquals("\\f107", value.getStringValue());
assertEquals("\"\\f107\"", value.getCssText());
assertEquals("\"\\f107\"", value.getMinifiedCssText(""));
}
@Test
public void testSetCssTextStringEscaped3() {
StringValue value = createCSSStringValue();
value.setCssText("\"\u5b8b\u4f53\"");
assertEquals("\u5b8b\u4f53", value.getStringValue());
assertEquals("\"\u5b8b\u4f53\"", value.getCssText());
assertEquals("\"\u5b8b\u4f53\"", value.getMinifiedCssText(""));
value.setStringValue(CSSValue.Type.STRING, value.getStringValue());
assertEquals("\u5b8b\u4f53", value.getStringValue());
assertEquals("\"\u5b8b\u4f53\"", value.getCssText());
assertEquals("\"\u5b8b\u4f53\"", value.getMinifiedCssText(""));
}
@Test
public void testSetCssTextStringEscaped4() {
StringValue value = createCSSStringValue();
value.setCssText("\"\\\\5FAE\\8F6F\"");
assertEquals("\\5FAE\u8F6F", value.getStringValue());
assertEquals("\"\\\\5FAE\\8F6F\"", value.getCssText());
assertEquals("\"\\\\5FAE\u8F6F\"", value.getMinifiedCssText(""));
value.setStringValue(CSSValue.Type.STRING, value.getStringValue());
assertEquals("\\5FAE\u8F6F", value.getStringValue());
assertEquals("\"\\\\5FAE\u8F6F\"", value.getCssText());
assertEquals("\"\\\\5FAE\u8F6F\"", value.getMinifiedCssText(""));
}
@Test
public void testSetCssTextStringEscaped5() {
StringValue value = createCSSStringValue();
value.setCssText("\"a \\A b\"");
assertEquals("a \nb", value.getStringValue());
assertEquals("\"a \\A b\"", value.getCssText());
assertEquals("\"a \\a b\"", value.getMinifiedCssText(""));
}
@Test
public void testLexicalSetter() throws CSSException, IOException {
CSSParser parser = new CSSParser();
StringReader re = new StringReader("\"\\\\5FAE\\8F6F\"");
LexicalUnit lu = parser.parsePropertyValue(re);
assertNotNull(lu);
StringValue value = createCSSStringValue();
LexicalSetter setter = value.newLexicalSetter();
setter.setLexicalUnit(lu);
assertNull(setter.getNextLexicalUnit());
assertEquals("\\5FAE\u8F6F", value.getStringValue());
assertEquals("\"\\\\5FAE\\8F6F\"", value.getCssText());
assertEquals("\"\\\\5FAE\u8F6F\"", value.getMinifiedCssText(""));
}
@Test
public void testLexicalSetter2() throws CSSException, IOException {
CSSParser parser = new CSSParser();
StringReader re = new StringReader("'\\200B'");
LexicalUnit lu = parser.parsePropertyValue(re);
assertNotNull(lu);
StringValue value = createCSSStringValue();
LexicalSetter setter = value.newLexicalSetter();
setter.setLexicalUnit(lu);
assertNull(setter.getNextLexicalUnit());
assertEquals("\u200B", value.getStringValue());
assertEquals("'\\200B'", value.getCssText());
assertEquals("'\\200b'", value.getMinifiedCssText(""));
}
@Test
public void testLexicalSetter3() throws CSSException, IOException {
CSSParser parser = new CSSParser();
StringReader re = new StringReader("\"\\1f4e5\"");
LexicalUnit lu = parser.parsePropertyValue(re);
assertNotNull(lu);
StringValue value = createCSSStringValue();
LexicalSetter setter = value.newLexicalSetter();
setter.setLexicalUnit(lu);
assertNull(setter.getNextLexicalUnit());
assertEquals("\ud83d\udce5", value.getStringValue());
assertEquals("\"\\1f4e5\"", value.getCssText());
assertEquals("\"\\1f4e5\"", value.getMinifiedCssText(""));
}
@Test
public void testSetCssTextStringProgId() {
StringValue value = createCSSStringValue();
value.setCssText("progid\\:DXImageTransform\\.Microsoft\\.gradient\\(enabled\\=false\\)");
assertEquals("progid:DXImageTransform.Microsoft.gradient(enabled=false)", value.getStringValue());
assertEquals("'progid\\:DXImageTransform\\.Microsoft\\.gradient\\(enabled\\=false\\)'", value.getCssText());
}
@Test
public void testSetCssTextStringISO10646() {
StringValue value = createCSSStringValue();
value.setCssText("\\26");
assertEquals("&", value.getStringValue());
assertEquals("'\\26'", value.getCssText());
assertEquals("'&'", value.getMinifiedCssText(""));
value.setCssText("\\200B");
assertEquals("\u200B", value.getStringValue());
assertEquals("'\\200B'", value.getCssText());
assertEquals("'\\200b'", value.getMinifiedCssText(""));
value.setCssText("\\200 B");
assertTrue("Ȁ B".equals(value.getStringValue()));
assertEquals("'\\200 B'", value.getCssText());
assertEquals("'\u0200 B'", value.getMinifiedCssText(""));
value.setCssText("'\\2020'");
assertEquals("\u2020", value.getStringValue());
assertEquals("'\\2020'", value.getCssText());
assertEquals("'\u2020'", value.getMinifiedCssText(""));
}
@Test
public void testGetCssText() {
StringValue value = createCSSStringValue();
value.setCssText("'foo'");
assertEquals("foo", value.getStringValue());
assertEquals("'foo'", value.getCssText());
value.setCssText("\"foo\"");
assertEquals("foo", value.getStringValue());
assertEquals("\"foo\"", value.getCssText());
}
@Test
public void testEquals() {
StringValue value = createCSSStringValue();
value.setCssText("\\26");
StringValue other = createCSSStringValue();
other.setCssText("\\26");
assertTrue(value.equals(other));
assertTrue(value.hashCode() == other.hashCode());
other.setCssText("foo");
assertFalse(value.equals(other));
assertFalse(value.hashCode() == other.hashCode());
//
value.setCssText("\"foo\"");
other.setCssText("'foo'");
assertTrue(value.equals(other));
assertTrue(value.hashCode() == other.hashCode());
other.setCssText("foo");
assertTrue(value.equals(other));
assertTrue(value.hashCode() == other.hashCode());
}
@Test
public void testClone() {
StringValue value = createCSSStringValue();
value.setStringValue(CSSValue.Type.STRING, "Some text in \"double quotes\"");
StringValue clon = value.clone();
assertEquals(value.getCssValueType(), clon.getCssValueType());
assertEquals(value.getPrimitiveType(), clon.getPrimitiveType());
assertEquals(value.getStringValue(), clon.getStringValue());
assertEquals(value.getCssText(), clon.getCssText());
assertEquals(value.getMinifiedCssText(""), clon.getMinifiedCssText(""));
}
private StringValue createCSSStringValue() {
return new StringValue();
}
}
| 37.238095
| 110
| 0.709079
|
540dbe77444fafa4c5448d1905874ecb5f0d926e
| 2,942
|
package prode;
import java.util.*;
import org.javalite.activejdbc.Base;
import static spark.Spark.*;
import spark.*;
import org.javalite.activejdbc.Model;
public class User extends Model {
public User(){ }
public void addSuperUser() {
List<User> busqueda;
if ((busqueda = User.where("superu = ?", true)).size() == 0 ) {
String userlog = "superusuario";
String passlog = "superusuario";
User u = new User();
u.set("username", userlog);
u.set("password", passlog);
u.set("superu", true);
u.saveIt();
}
}
public boolean checkUsername(User user) {
String username = (String) user.get("username");
return !(username == "" || username.length() < 5);
}
public boolean checkPassword(User user) {
String password = (String) user.get("password");
return !(password == "" || password.length() < 5);
}
public boolean checkUser(Request req) throws IllegalArgumentException {
String userlog = req.queryParams("user");
String passlog = req.queryParams("password");
List<User> busqueda = User.where("username = ? and password = ?", userlog, passlog);
Boolean esta = (busqueda.size() != 0);
return esta;
}
public boolean checkUserName(Request req) throws IllegalArgumentException {
String userlog = req.queryParams("user");
List<User> busqueda = User.where("username = ?", userlog);
boolean esta = (busqueda.size() != 0);
return esta;
}
public void addUser(Request req) throws IllegalArgumentException {
String userlog = req.queryParams("user");
String passlog = req.queryParams("password");
User u = new User();
u.set("username", userlog);
u.set("password", passlog);
if (!(u.checkPassword(u) || u.checkUsername(u)))
throw new IllegalArgumentException("Nombre de usuario o contraseña demasiado cortos");
u.set("superu", false);
u.saveIt();
}
public Map getUser(Request req){
String userlog = req.queryParams("user");
String passlog = req.queryParams("password");
Map resultUser = new HashMap();
List<User> busqueda = User.where("username = ? and password = ?", userlog, passlog);
resultUser.put("user", busqueda.get(0).get("id"));
resultUser.put("superu", busqueda.get(0).get("superu"));
return resultUser;
}
public static List<User> listaUserpuntosActuales(int idFecha) {
List<User> Users = User.findBySQL("SELECT username FROM users a JOIN points b ON a.id = b.idUser where b.idFecha = '"+idFecha+"' ORDER BY b.puntajeActual DESC");
return Users;
}
public static List<User> listaUserPuntosTotales() {
List<User> Users = User.findBySQL("SELECT username FROM users a JOIN points b ON a.id = b.idUser ORDER BY b.puntajeActual DESC");
return Users;
}
public int id() {
return this.getInteger("id");//IMPORTANTE
}
public String username() {
return this.getString("username");
}
}
| 31.634409
| 166
| 0.654317
|
1dd1cdcd6cee645337a5dc36a4bc19a6c3d54772
| 5,079
|
package pl.zankowski.iextrading4j.client.socket.request.marketdata.deep;
import com.flextrade.jfixture.JFixture;
import org.junit.Before;
import org.junit.Test;
import pl.zankowski.iextrading4j.api.exception.IEXTradingException;
import pl.zankowski.iextrading4j.api.marketdata.Auction;
import pl.zankowski.iextrading4j.api.marketdata.Book;
import pl.zankowski.iextrading4j.api.marketdata.OpHaltStatus;
import pl.zankowski.iextrading4j.api.marketdata.SecurityEvent;
import pl.zankowski.iextrading4j.api.marketdata.SsrStatus;
import pl.zankowski.iextrading4j.api.marketdata.SystemEvent;
import pl.zankowski.iextrading4j.api.marketdata.Trade;
import pl.zankowski.iextrading4j.api.marketdata.TradingStatus;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
public class DeepConsumerAdapterTest {
private static final String TEST_SYMBOL = "IBM";
private static final Long SEQ = 1L;
private final JFixture fixture = new JFixture();
private DeepConsumerAdapter consumerAdapter;
@Before
public void setUp() {
consumerAdapter = spy(new DeepConsumerAdapter());
}
@Test
public void shouldRedirectToTradingStatusMethod() {
final TradingStatus data = fixture.create(TradingStatus.class);
final DeepAsyncResponse<TradingStatus> response = new DeepAsyncResponse<>(TEST_SYMBOL,
DeepMessageType.TRADING_STATUS.getName(), data, SEQ);
consumerAdapter.accept(response);
verify(consumerAdapter).acceptTradingStatus(any());
}
@Test
public void shouldRedirectToAuctionMethod() {
final Auction data = fixture.create(Auction.class);
final DeepAsyncResponse<Auction> response = new DeepAsyncResponse<>(TEST_SYMBOL,
DeepMessageType.AUCTION.getName(), data, SEQ);
consumerAdapter.accept(response);
verify(consumerAdapter).acceptAuction(any());
}
@Test
public void shouldRedirectToOpHaltStatusMethod() {
final OpHaltStatus data = fixture.create(OpHaltStatus.class);
final DeepAsyncResponse<OpHaltStatus> response = new DeepAsyncResponse<>(TEST_SYMBOL,
DeepMessageType.OP_HALT_STATUS.getName(), data, SEQ);
consumerAdapter.accept(response);
verify(consumerAdapter).acceptOpHaltStatus(any());
}
@Test
public void shouldRedirectToSsrStatusMethod() {
final SsrStatus data = fixture.create(SsrStatus.class);
final DeepAsyncResponse<SsrStatus> response = new DeepAsyncResponse<>(TEST_SYMBOL,
DeepMessageType.SSR_STATUS.getName(), data, SEQ);
consumerAdapter.accept(response);
verify(consumerAdapter).acceptSsrStatus(any());
}
@Test
public void shouldRedirectToSecurityEventMethod() {
final SecurityEvent data = fixture.create(SecurityEvent.class);
final DeepAsyncResponse<SecurityEvent> response = new DeepAsyncResponse<>(TEST_SYMBOL,
DeepMessageType.SECURITY_EVENT.getName(), data, SEQ);
consumerAdapter.accept(response);
verify(consumerAdapter).acceptSecurityEvent(any());
}
@Test
public void shouldRedirectToTradeBreakMethod() {
final Trade data = fixture.create(Trade.class);
final DeepAsyncResponse<Trade> response = new DeepAsyncResponse<>(TEST_SYMBOL,
DeepMessageType.TRADE_BREAK.getName(), data, SEQ);
consumerAdapter.accept(response);
verify(consumerAdapter).acceptTradeBreak(any());
}
@Test
public void shouldRedirectToTradesMethod() {
final Trade data = fixture.create(Trade.class);
final DeepAsyncResponse<Trade> response = new DeepAsyncResponse<>(TEST_SYMBOL,
DeepMessageType.TRADES.getName(), data, SEQ);
consumerAdapter.accept(response);
verify(consumerAdapter).acceptTrades(any());
}
@Test
public void shouldRedirectToBookMethod() {
final Book data = fixture.create(Book.class);
final DeepAsyncResponse<Book> response = new DeepAsyncResponse<>(TEST_SYMBOL,
DeepMessageType.BOOK.getName(), data, SEQ);
consumerAdapter.accept(response);
verify(consumerAdapter).acceptBook(any());
}
@Test
public void shouldRedirectToSystemEventMethod() {
final SystemEvent data = fixture.create(SystemEvent.class);
final DeepAsyncResponse<SystemEvent> response = new DeepAsyncResponse<>(TEST_SYMBOL,
DeepMessageType.SYSTEM_EVENT.getName(), data, SEQ);
consumerAdapter.accept(response);
verify(consumerAdapter).acceptSystemEvent(any());
}
@Test(expected = IEXTradingException.class)
public void shouldThrowAnExceptionForUnknownMessageType() {
final SystemEvent data = fixture.create(SystemEvent.class);
final DeepAsyncResponse<SystemEvent> response = new DeepAsyncResponse<>(TEST_SYMBOL,
DeepMessageType.UNKNOWN.getName(), data, SEQ);
consumerAdapter.accept(response);
}
}
| 35.270833
| 94
| 0.715495
|
07759ead52efad031706dac83abff2262d76e28f
| 13,008
|
/**
* generated by Xtext 2.10.0
*/
package org.refactor.modelEditor.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.refactor.modelEditor.Field;
import org.refactor.modelEditor.Method;
import org.refactor.modelEditor.ModelEditorPackage;
import org.refactor.modelEditor.Supertypes;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Class</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.refactor.modelEditor.impl.ClassImpl#getModifier <em>Modifier</em>}</li>
* <li>{@link org.refactor.modelEditor.impl.ClassImpl#getName <em>Name</em>}</li>
* <li>{@link org.refactor.modelEditor.impl.ClassImpl#getExtends <em>Extends</em>}</li>
* <li>{@link org.refactor.modelEditor.impl.ClassImpl#getImplements <em>Implements</em>}</li>
* <li>{@link org.refactor.modelEditor.impl.ClassImpl#getFields <em>Fields</em>}</li>
* <li>{@link org.refactor.modelEditor.impl.ClassImpl#getMethods <em>Methods</em>}</li>
* </ul>
*
* @generated
*/
public class ClassImpl extends MinimalEObjectImpl.Container implements org.refactor.modelEditor.Class
{
/**
* The default value of the '{@link #getModifier() <em>Modifier</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getModifier()
* @generated
* @ordered
*/
protected static final String MODIFIER_EDEFAULT = null;
/**
* The cached value of the '{@link #getModifier() <em>Modifier</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getModifier()
* @generated
* @ordered
*/
protected String modifier = MODIFIER_EDEFAULT;
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* The cached value of the '{@link #getExtends() <em>Extends</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getExtends()
* @generated
* @ordered
*/
protected Supertypes extends_;
/**
* The cached value of the '{@link #getImplements() <em>Implements</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getImplements()
* @generated
* @ordered
*/
protected Supertypes implements_;
/**
* The cached value of the '{@link #getFields() <em>Fields</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFields()
* @generated
* @ordered
*/
protected EList<Field> fields;
/**
* The cached value of the '{@link #getMethods() <em>Methods</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMethods()
* @generated
* @ordered
*/
protected EList<Method> methods;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ClassImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return ModelEditorPackage.Literals.CLASS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getModifier()
{
return modifier;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setModifier(String newModifier)
{
String oldModifier = modifier;
modifier = newModifier;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ModelEditorPackage.CLASS__MODIFIER, oldModifier, modifier));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName()
{
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName)
{
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ModelEditorPackage.CLASS__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Supertypes getExtends()
{
return extends_;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetExtends(Supertypes newExtends, NotificationChain msgs)
{
Supertypes oldExtends = extends_;
extends_ = newExtends;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ModelEditorPackage.CLASS__EXTENDS, oldExtends, newExtends);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setExtends(Supertypes newExtends)
{
if (newExtends != extends_)
{
NotificationChain msgs = null;
if (extends_ != null)
msgs = ((InternalEObject)extends_).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - ModelEditorPackage.CLASS__EXTENDS, null, msgs);
if (newExtends != null)
msgs = ((InternalEObject)newExtends).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - ModelEditorPackage.CLASS__EXTENDS, null, msgs);
msgs = basicSetExtends(newExtends, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ModelEditorPackage.CLASS__EXTENDS, newExtends, newExtends));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Supertypes getImplements()
{
return implements_;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetImplements(Supertypes newImplements, NotificationChain msgs)
{
Supertypes oldImplements = implements_;
implements_ = newImplements;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ModelEditorPackage.CLASS__IMPLEMENTS, oldImplements, newImplements);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setImplements(Supertypes newImplements)
{
if (newImplements != implements_)
{
NotificationChain msgs = null;
if (implements_ != null)
msgs = ((InternalEObject)implements_).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - ModelEditorPackage.CLASS__IMPLEMENTS, null, msgs);
if (newImplements != null)
msgs = ((InternalEObject)newImplements).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - ModelEditorPackage.CLASS__IMPLEMENTS, null, msgs);
msgs = basicSetImplements(newImplements, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ModelEditorPackage.CLASS__IMPLEMENTS, newImplements, newImplements));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Field> getFields()
{
if (fields == null)
{
fields = new EObjectContainmentEList<Field>(Field.class, this, ModelEditorPackage.CLASS__FIELDS);
}
return fields;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Method> getMethods()
{
if (methods == null)
{
methods = new EObjectContainmentEList<Method>(Method.class, this, ModelEditorPackage.CLASS__METHODS);
}
return methods;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case ModelEditorPackage.CLASS__EXTENDS:
return basicSetExtends(null, msgs);
case ModelEditorPackage.CLASS__IMPLEMENTS:
return basicSetImplements(null, msgs);
case ModelEditorPackage.CLASS__FIELDS:
return ((InternalEList<?>)getFields()).basicRemove(otherEnd, msgs);
case ModelEditorPackage.CLASS__METHODS:
return ((InternalEList<?>)getMethods()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case ModelEditorPackage.CLASS__MODIFIER:
return getModifier();
case ModelEditorPackage.CLASS__NAME:
return getName();
case ModelEditorPackage.CLASS__EXTENDS:
return getExtends();
case ModelEditorPackage.CLASS__IMPLEMENTS:
return getImplements();
case ModelEditorPackage.CLASS__FIELDS:
return getFields();
case ModelEditorPackage.CLASS__METHODS:
return getMethods();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case ModelEditorPackage.CLASS__MODIFIER:
setModifier((String)newValue);
return;
case ModelEditorPackage.CLASS__NAME:
setName((String)newValue);
return;
case ModelEditorPackage.CLASS__EXTENDS:
setExtends((Supertypes)newValue);
return;
case ModelEditorPackage.CLASS__IMPLEMENTS:
setImplements((Supertypes)newValue);
return;
case ModelEditorPackage.CLASS__FIELDS:
getFields().clear();
getFields().addAll((Collection<? extends Field>)newValue);
return;
case ModelEditorPackage.CLASS__METHODS:
getMethods().clear();
getMethods().addAll((Collection<? extends Method>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case ModelEditorPackage.CLASS__MODIFIER:
setModifier(MODIFIER_EDEFAULT);
return;
case ModelEditorPackage.CLASS__NAME:
setName(NAME_EDEFAULT);
return;
case ModelEditorPackage.CLASS__EXTENDS:
setExtends((Supertypes)null);
return;
case ModelEditorPackage.CLASS__IMPLEMENTS:
setImplements((Supertypes)null);
return;
case ModelEditorPackage.CLASS__FIELDS:
getFields().clear();
return;
case ModelEditorPackage.CLASS__METHODS:
getMethods().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case ModelEditorPackage.CLASS__MODIFIER:
return MODIFIER_EDEFAULT == null ? modifier != null : !MODIFIER_EDEFAULT.equals(modifier);
case ModelEditorPackage.CLASS__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case ModelEditorPackage.CLASS__EXTENDS:
return extends_ != null;
case ModelEditorPackage.CLASS__IMPLEMENTS:
return implements_ != null;
case ModelEditorPackage.CLASS__FIELDS:
return fields != null && !fields.isEmpty();
case ModelEditorPackage.CLASS__METHODS:
return methods != null && !methods.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString()
{
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (modifier: ");
result.append(modifier);
result.append(", name: ");
result.append(name);
result.append(')');
return result.toString();
}
} //ClassImpl
| 27.156576
| 153
| 0.636147
|
1de4df5ca836dfd5414c077a7ce27403dd4b44f0
| 6,227
|
package ir.co.bayan.simorq.zal.extractor.model;
import ir.co.bayan.simorq.zal.extractor.core.ExtractedDoc;
import ir.co.bayan.simorq.zal.extractor.evaluation.EvaluationContext;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlIDREF;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A document defines a set of extract-to rules to be used in the extraction process. These rules are evaluated using
* the default evaluation engine specified in the document. Each document may contain several fragments (or itself may
* contain root) which results to generation of multiple sub documents. Each document may inherit its extract-to,
* engine, or fragments from another document. Documents are matched using their url or content type both can be regex.
*
* @author Taha Ghasemi <taha.ghasemi@gmail.com>
*
*/
public class Document extends Fragment {
private static final Logger LOGGER = LoggerFactory.getLogger(Document.class);
private String url;
private Pattern urlPattern;
private String contentType;
private Pattern contentTypePattern;
@XmlAttribute
@XmlID
private String id;
@XmlAttribute
@XmlIDREF
private Document inherits;
@XmlElement
private Filter filter;
@XmlElement(name = "fragment")
private List<Fragment> fragments;
@XmlAttribute
private String engine;
@XmlAttribute
private boolean update = false;
private String every;
private Integer everyInMiliSecond;
@XmlAttribute
private boolean adaptive = true;
/**
* @return the url
*/
public String getUrl() {
return url;
}
/**
* @return the urlPattern
*/
public Pattern getUrlPattern() {
return urlPattern;
}
/**
* @param url
* the url to set
*/
@XmlAttribute
public void setUrl(String url) {
this.url = url;
this.urlPattern = Pattern.compile(url);
}
/**
* @return the contentType
*/
public String getContentType() {
return contentType;
}
/**
* @return the contentTypePatter
*/
public Pattern getContentTypePattern() {
return contentTypePattern;
}
/**
* @param contentType
* the contentType to set
*/
public void setContentType(String contentType) {
this.contentType = contentType;
this.contentTypePattern = Pattern.compile(contentType);
}
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @return the inherits
*/
public Document getInherits() {
return inherits;
}
/**
* @return the filter
*/
public Filter getFilter() {
return filter;
}
/**
* @return the fragments
*/
public List<Fragment> getFragments() {
return fragments;
}
public String getEngine() {
return engine;
}
/**
* @return the update
*/
public boolean isUpdate() {
return update;
}
/**
* @return the every
*/
public String getEvery() {
return every;
}
/**
* @param every
* the fetch schedule
*/
@XmlAttribute
public void setEvery(String every) {
this.every = every;
computeEveryInMiliSecond();
}
private void computeEveryInMiliSecond() {
String every = getInheritedEvery();
if (every == null)
return;
char unit = every.charAt(every.length() - 1);
int amount = Integer.valueOf(every.substring(0, every.length() - 1));
switch (unit) {
case 'm':
everyInMiliSecond = amount * 60 * 1000;
break;
case 'h':
everyInMiliSecond = amount * 60 * 60 * 1000;
break;
case 'd':
everyInMiliSecond = amount * 24 * 60 * 60 * 1000;
break;
default:
throw new IllegalArgumentException("Unknown unit in " + every);
}
}
public Integer getEveryInMiliSecond() {
return everyInMiliSecond;
}
public String getInheritedEvery() {
return getEvery(this);
}
private String getEvery(Document document) {
if (document == null)
return null;
if (!StringUtils.isEmpty(document.getEvery())) {
return document.getEvery();
}
return getEvery(document.getInherits());
}
/**
* Tries to find engine from document hierarchy
*/
public String getInheritedEngine() {
return getEngine(this);
}
/**
* @return the adaptive
*/
public boolean isAdaptive() {
return adaptive;
}
private String getEngine(Document document) {
if (document == null)
return null;
if (!StringUtils.isEmpty(document.getEngine()))
return document.getEngine();
return getEngine(document.getInherits());
}
public List<ExtractedDoc> extract(EvaluationContext context) throws Exception {
List<ExtractedDoc> res = new ArrayList<ExtractedDoc>();
for (Object root : getRoots(context.getMainRoot(), context)) {
ExtractedDoc mainDoc = new ExtractedDoc();
context.setCurrentDoc(mainDoc);
mainDoc.addField(Fragment.URL_FIELD, context.getContent().getUrl().toString());
mainDoc.setUpdate(update);
res.add(mainDoc);
extract(this, mainDoc, res, root, context);
}
return res;
}
private void extract(Document document, ExtractedDoc mainDoc, List<ExtractedDoc> extractedDocs, Object root,
EvaluationContext context) throws Exception {
Document parent = document.getInherits();
if (parent != null) {
extract(parent, mainDoc, extractedDocs, root, context);
}
if (LOGGER.isDebugEnabled())
LOGGER.debug(this.toString());
document.extractFields(root, context, mainDoc);
document.insertSpecialFields(context, mainDoc);
document.extractOutlinks(root, context, mainDoc);
if (document.getFragments() != null) {
for (Fragment fragment : document.getFragments()) {
extractedDocs.addAll(fragment.extract(context.getMainRoot(), context));
}
}
}
public boolean matches(String url, String contentType) {
boolean matches = false;
if (urlPattern != null) {
matches = urlPattern.matcher(url).find();
}
if (!matches && contentTypePattern != null) {
matches = contentTypePattern.matcher(contentType).find();
}
return matches;
}
@Override
public String toString() {
return "Document [url=" + url + ", contentType=" + contentType + ", id=" + id + ", inherits=" + inherits
+ ", engine=" + engine + "]";
}
}
| 22.160142
| 119
| 0.700819
|
a4b63df73d8b0138a5ec0d609555b6e8e4a40aee
| 2,182
|
package net.mgsx.game.examples.openworld.systems;
import com.badlogic.ashley.core.EntitySystem;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.math.CatmullRomSpline;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector3;
import net.mgsx.game.core.GamePipeline;
import net.mgsx.game.core.annotations.Editable;
import net.mgsx.game.core.annotations.EditableSystem;
import net.mgsx.game.core.annotations.Inject;
import net.mgsx.game.core.annotations.Storable;
import net.mgsx.game.examples.openworld.model.OpenWorldPathBuilder;
@Storable("ow.camera.path")
@EditableSystem
public class OpenWorldCameraPathSystem extends EntitySystem
{
@Inject OpenWorldGeneratorSystem generator;
@Inject OpenWorldCameraSystem cameraSystem;
@Editable public float speed = 0.1f;
@Editable public float distance = 5f;
@Editable public float offsetMin = 10f;
@Editable public float offsetRange = 5f;
CatmullRomSpline<Vector3> spline = new CatmullRomSpline<Vector3>();
Vector3 [] controlPoints;
float time = 0;
private float splineLength;
private OpenWorldPathBuilder pathBuilder = new OpenWorldPathBuilder();
public OpenWorldCameraPathSystem() {
super(GamePipeline.BEFORE_INPUT); // actually before other camera
}
@Override
public void update(float deltaTime)
{
Camera camera = cameraSystem.getCamera();
if(camera == null) return;
if(controlPoints != null) time += deltaTime * Math.abs(speed) / splineLength; // avoid negative
if(time > 1 || controlPoints == null)
{
pathBuilder.set(generator, 30, distance, 1);
pathBuilder.resetLimit().groundMin(offsetMin).groundMax(offsetMin + offsetRange);
if(controlPoints == null){
controlPoints = new Vector3[4];
pathBuilder.createPath(controlPoints, camera.position);
}else{
pathBuilder.updateDynamicPath(controlPoints);
time -= 1;
}
spline.set(controlPoints, false);
splineLength = spline.approxLength(100); // TODO precision
}
// quick fix in case of too much time
time = MathUtils.clamp(time, 0, 1);
spline.valueAt(camera.position, time);
camera.update(); // TODO maybe not necessary ...
}
}
| 28.710526
| 97
| 0.746563
|
00f2ef102b58c81a10914dca9305ccdc87478888
| 6,487
|
/*
Copyright 2017 Digital Learning Sciences (DLS) at the
University Corporation for Atmospheric Research (UCAR),
P.O. Box 3000, Boulder, CO 80307
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 edu.ucar.dls.schemedit.ndr.action;
import edu.ucar.dls.schemedit.ndr.util.integration.CIGlobals;
import edu.ucar.dls.schemedit.ndr.util.integration.MappingsManager;
import edu.ucar.dls.schemedit.ndr.util.integration.MappingInfo;
import edu.ucar.dls.schemedit.ndr.action.form.CollectionIntegrationForm;
import edu.ucar.dls.schemedit.action.DCSAction;
import edu.ucar.dls.repository.RepositoryManager;
import edu.ucar.dls.index.reader.XMLDocReader;
import edu.ucar.dls.schemedit.repository.CollectionReaper;
import edu.ucar.dls.schemedit.MetaDataFramework;
import edu.ucar.dls.schemedit.SchemEditUtils;
import edu.ucar.dls.schemedit.config.CollectionConfig;
import edu.ucar.dls.schemedit.dcs.DcsDataRecord;
import edu.ucar.dls.ndr.NdrUtils;
import edu.ucar.dls.ndr.apiproxy.NDRConstants;
import edu.ucar.dls.ndr.request.*;
import edu.ucar.dls.ndr.reader.AgentReader;
import edu.ucar.dls.ndr.reader.MetadataProviderReader;
import edu.ucar.dls.xml.Dom4jUtils;
import edu.ucar.dls.xml.XMLValidator;
import edu.ucar.dls.ndr.apiproxy.InfoXML;
import edu.ucar.dls.ndr.request.NdrRequest;
import java.util.*;
import java.io.*;
import java.net.URL;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionServlet;
import org.dom4j.Element;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.json.XML;
import org.json.JSONObject;
/**
* Action supporing integration of NCS Collect Records and NDR Collections in the NDR
*
*
* @author Jonathan Ostwald <p>
*
*/
public final class CollectionIntegrationAction extends DCSAction {
private static boolean debug = true;
private RepositoryManager rm;
// --------------------------------------------------------- Public Methods
/**
* Processes the specified HTTP request and creates the corresponding HTTP
* response by forwarding to a JSP that will create it.
*
* @param mapping The ActionMapping used to select this instance
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @param form The ActionForm for the given page
* @return The ActionForward instance describing where
* and how control should be forwarded
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet exception occurs
*/
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
/*
* Design note:
* Only one instance of this class gets created for the app and shared by
* all threads. To be thread-safe, use only local variables, not instance
* variables (the JVM will handle these properly using the stack). Pass
* all variables via method signatures rather than instance vars.
*/
ActionErrors errors = initializeFromContext(mapping, request);
if (!errors.isEmpty()) {
saveErrors(request, errors);
return (mapping.findForward("error.page"));
}
CollectionIntegrationForm ciForm = (CollectionIntegrationForm) form;
/* MappingsManager.dataPath = CIGlobals.MAPPINGS_MANAGER_DATA;
MappingsManager mm = MappingsManager.getInstance(); */
MappingsManager mm = (MappingsManager)servlet.getServletContext().getAttribute ("MappingsManager");
if (mm == null)
prtlnErr ("MappingsManager not found in servlet context");
ciForm.setMappingsManager (mm);
String errorMsg = "";
rm = repositoryManager;
SchemEditUtils.showRequestParameters(request);
String command = request.getParameter("command");
try {
if (command != null && command.equals("mappingInfo")) {
String id = request.getParameter("id");
if (request.getParameter ("update") != null) {
mm.update (id);
mm.reset();
// ciForm.setMappingsManager(MappingsManager.getInstance());
}
MappingInfo mappingInfo = (MappingInfo)mm.getIdMap().get(id);
if (mappingInfo == null) {
throw new Exception ("mapping not found for id="+id);
}
ciForm.setMappingInfo (mappingInfo);
return mapping.findForward ("mapping.info");
}
if (command != null && command.equals("resetMappings")) {
prtln ("reinitializing MappingsManager");
mm.reset();
// ciForm.setMappingsManager(MappingsManager.getInstance());
prtln (" ... done");
}
} catch (Exception e) {
prtlnErr("CollectionIntegrationAction caught exception.");
if (e instanceof NullPointerException)
e.printStackTrace();
errors.add("error",
new ActionError("generic.error", "CollectionIntegrationAction caught exception"));
}
saveErrors(request, errors);
return mapping.findForward("ci.mappings");
}
// -------------- Debug ------------------
/**
* Sets the debug attribute of the CollectionIntegrationAction class
*
* @param isDebugOutput The new debug value
*/
public static void setDebug(boolean isDebugOutput) {
debug = isDebugOutput;
}
/**
* Print a line to standard out.
*
* @param s The String to print.
*/
private void prtln(String s) {
if (debug) {
SchemEditUtils.prtln(s, "CollectionIntegrationAction");
}
}
/**
* NOT YET DOCUMENTED
*
* @param s NOT YET DOCUMENTED
*/
private void prtlnErr(String s) {
SchemEditUtils.prtln(s, "CollectionIntegrationAction");
}
}
| 32.435
| 101
| 0.711885
|
ca1d7f13f08375f0e352e7aa67aab96d8307dd3d
| 843
|
package com.cmtt.base.service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.cmtt.base.entity.SsWaterStation;
import com.baomidou.mybatisplus.extension.service.IService;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* <p>
* 水站信息表 服务类
* </p>
*
* @author Andrew.Wen
* @since 2021-01-31
*/
public interface ISsWaterStationService extends IService<SsWaterStation> {
List<Map<Integer, String>> getStationDict(Integer status);
List<Map<String, String>> getRetionInfoDict(Integer status, String parentarea);
public IPage<SsWaterStation> getStationPage(IPage<SsWaterStation> page, @Param(Constants.WRAPPER) Wrapper<SsWaterStation> queryWrapper);
}
| 29.068966
| 140
| 0.782918
|
6afa5df3fa2ec1929f6edc4935db604bcf64e912
| 8,709
|
package cn.topoints.utils.api;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import cn.topoints.utils.api.http.APIRequest;
public class Param {
public static JSONObject getReqContent(APIRequest req) throws ServerException {
String content = req.c;
if (StringUtils.isBlank(content)) {
throw new ServerException(BaseRC.REQUEST_PARSE_ERROR, StringUtils.join("getRequestContent>", "is blank"));
}
try {
return JSON.parseObject(content);
} catch (ClassCastException cce) {
throw new ServerException(BaseRC.REQUEST_PARSE_ERROR,
StringUtils.join("getRequestContent>parse json>", cce.getMessage()));
}
}
public static Object checkNull(Object obj) throws ServerException {
if (null == obj) {
throw new ServerException(BaseRC.SERVER_OBJECT_NULL);
} else {
return obj;
}
}
/**
* 获取Long型SimpleID参数(JS端ID用字符串,服务端ID用Long型)
*/
public static Long getSimpleId(JSONObject jo, String key) throws ServerException {
try {
Long value = Long.parseLong(jo.getString(key));
return value;
} catch (Exception e) {
throw new ServerException(BaseRC.REQUEST_PARAMS_ERROR,
StringUtils.join("getSimpleId>", key, ">", e.getMessage()));
}
}
/**
* 获取对象
*/
public static <T> T getObject(JSONObject jo, String key, Class<T> clazz) throws ServerException {
try {
return jo.getObject(key, clazz);
} catch (ClassCastException cce) {
throw new ServerException(BaseRC.REQUEST_PARSE_ERROR,
StringUtils.join("getObjectNotNull>", key, ">", cce.getMessage()));
}
}
/**
* 获取对象,可以为空,有问题则返回null
*/
public static <T> T getObjectCanNull(JSONObject jo, String key, Class<T> clazz) throws ServerException {
try {
return jo.getObject(key, clazz);
} catch (ClassCastException cce) {
return null;
}
}
/**
* 获取JSON数组参数,不可为空,否则抛出异常
*/
public static JSONArray getArray(JSONObject jo, String key) throws ServerException {
try {
JSONArray array = jo.getJSONArray(key);
if (null == array || array.size() <= 0) {
throw new ServerException(BaseRC.REQUEST_PARAMS_ERROR,
StringUtils.join("getArrayNotEmpty>", key, ">", "is null"));
} else {
return array;
}
} catch (Exception e) {
throw new ServerException(BaseRC.REQUEST_PARAMS_ERROR,
StringUtils.join("getArrayNotEmpty>", key, ">", e.getMessage()));
}
}
/**
* 获取JSON数组参数,如果或者有问题则返回空数组
*/
public static JSONArray getArrayCanEmpty(JSONObject jo, String key) {
try {
JSONArray array = jo.getJSONArray(key);
if (null == array || array.size() <= 0) {
return new JSONArray();
} else {
return array;
}
} catch (Exception e) {
return new JSONArray();
}
}
/**
* 获取字符串参数,不可为空或blank,否则抛出异常
*/
public static String getString(JSONObject jo, String key) throws ServerException {
String value = jo.getString(key);
if (StringUtils.isBlank(value)) {
throw new ServerException(BaseRC.REQUEST_PARAMS_ERROR,
StringUtils.join("getStringNotBlank>", key, ">", "is blank"));
} else {
return value;
}
}
/**
* 获取字符串参数,可以为空,空则返回默认值defaultValue
*/
public static String getStringDFLT(JSONObject jo, String key, String defaultValue) {
String value = jo.getString(key);
if (StringUtils.isBlank(value)) {
return defaultValue;
} else {
return value;
}
}
/**
* 获取Double参数,不可为空,否则抛出异常
*/
public static Double getDouble(JSONObject jo, String key) throws ServerException {
try {
Double value = jo.getDouble(key);
if (null == value) {
throw new ServerException(BaseRC.REQUEST_PARAMS_ERROR,
StringUtils.join("getDoubleNotNull>", key, ">", "is null"));
} else {
return value;
}
} catch (Exception e) {
throw new ServerException(BaseRC.REQUEST_PARAMS_ERROR,
StringUtils.join("getDoubleNotNull>", key, ">", e.getMessage()));
}
}
/**
* 获取Double参数,如果空则使用默认值
*/
public static Double getDoubleDFLT(JSONObject jo, String key, Double d) {
try {
Double value = jo.getDouble(key);
if (null == value) {
if (null == d) {
return null;
} else {
return new Double(d);// 重新构造,避免引用
}
} else {
return value;
}
} catch (Exception e) {
return new Double(d);// 重新构造,避免引用
}
}
/**
* 获取Long参数,不可为空,否则抛出异常
*/
public static Long getLong(JSONObject jo, String key) throws ServerException {
Long value;
try {
value = jo.getLong(key);
} catch (Exception e) {
throw new ServerException(BaseRC.REQUEST_PARAMS_ERROR,
StringUtils.join("getLongNotNull>", key, ">", e.getMessage()));
}
if (null == value) {
throw new ServerException(BaseRC.REQUEST_PARAMS_ERROR,
StringUtils.join("getLongNotNull>", key, ">", "is null"));
} else {
return value;
}
}
/**
* 获取Long参数,如果空则使用默认值
*/
public static Long getLongDFLT(JSONObject jo, String key, Long d) {
try {
Long value = jo.getLong(key);
if (null == value) {
if (null == d) {
return null;
} else {
return new Long(d);// 重新构造,避免引用
}
} else {
return value;
}
} catch (Exception e) {
return new Long(d);// 重新构造,避免引用
}
}
/**
* 获取Integer参数,不可为空,否则抛出异常
*/
public static Integer getInteger(JSONObject jo, String key) throws ServerException {
try {
Integer value = jo.getInteger(key);
if (null == value) {
throw new ServerException(BaseRC.REQUEST_PARAMS_ERROR,
StringUtils.join("getIntegerNotNull>", key, ">", "is null"));
} else {
return value;
}
} catch (Exception e) {
throw new ServerException(BaseRC.REQUEST_PARAMS_ERROR,
StringUtils.join("getIntegerNotNull>", key, ">", e.toString()));
}
}
/**
* 获取Integer参数,如果空则使用默认值
*/
public static Integer getIntegerDFLT(JSONObject jo, String key, Integer d) {
try {
Integer value = jo.getInteger(key);
if (null == value) {
if (null == d) {
return null;
} else {
return new Integer(d);// 重新构造,避免引用
}
} else {
return value;
}
} catch (Exception e) {
return new Integer(d);// 重新构造,避免引用
}
}
/**
* 获取Float参数,不可为空,否则抛出异常
*/
public static Float getFloat(JSONObject jo, String key) throws ServerException {
try {
Float value = jo.getFloat(key);
if (null == value) {
throw new ServerException(BaseRC.REQUEST_PARAMS_ERROR,
StringUtils.join("getFloatNotNull>", key, ">", "is null"));
} else {
return value;
}
} catch (Exception e) {
throw new ServerException(BaseRC.REQUEST_PARAMS_ERROR,
StringUtils.join("getFloatNotNull>", key, ">", e.getMessage()));
}
}
/**
* 获取Float参数,如果空则使用默认值
*/
public static Float getFloatDFLT(JSONObject jo, String key, Float d) {
try {
Float value = jo.getFloat(key);
if (null == value) {
if (null == d) {
return null;
} else {
return new Float(d);// 重新构造,避免引用
}
} else {
return value;
}
} catch (Exception e) {
return new Float(d);// 重新构造,避免引用
}
}
/**
* 获取Byte参数,不可为空,否则抛出异常
*/
public static Byte getByte(JSONObject jo, String key) throws ServerException {
try {
Byte value = jo.getByte(key);
if (null == value) {
throw new ServerException(BaseRC.REQUEST_PARAMS_ERROR,
StringUtils.join("getByteNotNull>", key, ">", "is null"));
} else {
return value;
}
} catch (Exception e) {
throw new ServerException(BaseRC.REQUEST_PARAMS_ERROR,
StringUtils.join("getByteNotNull>", key, ">", e.getMessage()));
}
}
/**
* 获取Byte参数,如果空则使用默认值
*/
public static Byte getByteDFLT(JSONObject jo, String key, Byte d) {
try {
Byte value = jo.getByte(key);
if (null == value) {
if (null == d) {
return null;
} else {
return new Byte(d);// 重新构造,避免引用
}
} else {
return value;
}
} catch (Exception e) {
return new Byte(d);// 重新构造,避免引用
}
}
/**
* 获取Boolean参数,不可为空,否则抛出异常
*/
public static Boolean getBoolean(JSONObject jo, String key) throws ServerException {
try {
Boolean value = jo.getBoolean(key);
if (null == value) {
throw new ServerException(BaseRC.REQUEST_PARAMS_ERROR,
StringUtils.join("getBooleanNotNull>", key, ">", "is null"));
} else {
return value;
}
} catch (Exception e) {
throw new ServerException(BaseRC.REQUEST_PARAMS_ERROR,
StringUtils.join("getBooleanNotNull>", key, ">", e.getMessage()));
}
}
/**
* 获取Boolean参数,如果空则使用默认值
*/
public static Boolean getBooleanDFLT(JSONObject jo, String key, Boolean d) {
try {
Boolean value = jo.getBoolean(key);
if (null == value) {
if (null == d) {
return null;
} else {
return new Boolean(d);// 重新构造,避免引用
}
} else {
return value;
}
} catch (Exception e) {
return new Boolean(d);// 重新构造,避免引用
}
}
}
| 24.259053
| 109
| 0.64795
|
abca9cc3ba408183f331a57c44cac63e0aa93bfe
| 7,813
|
package com.luoqifei.kafka.client;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class Consumer {
private static final Logger logger = LoggerFactory.getLogger(Consumer.class);
private KafkaConsumer<String, String> consumer;
private String topic;
private String bootstrapServer = "";
private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public Consumer(Properties properties) {
consumer = new KafkaConsumer<String, String>(properties);
}
public Consumer(){
Properties properties = new Properties();
properties.put("bootstrap.servers", "localhost:9092");
properties.put("group.id", "count-message-number");
properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
consumer = new KafkaConsumer<String, String>(properties);
}
public Consumer(Properties properties, String topic) {
consumer = new KafkaConsumer<String, String>(properties);
this.topic = topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public void setBootstrapServer(String bootstrapServer){
this.bootstrapServer = bootstrapServer;
}
public Map<TopicPartition, Long> getEndOffsets() {
List<PartitionInfo> partitionInfos = consumer.partitionsFor(topic);
List<TopicPartition> topicPartitions = new ArrayList<>();
for (PartitionInfo partitionInfo : partitionInfos) {
topicPartitions.add(new TopicPartition(partitionInfo.topic(), partitionInfo.partition()));
}
return consumer.endOffsets(topicPartitions);
}
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("bootstrap.servers", "127.0.0.1:9092");
properties.put("group.id", "count-message-number");
properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
Consumer consumer = new Consumer(properties);
String topicName = "test3";
consumer.setTopic(topicName);
long start = 1543368822000L;
long end = 1543368823000L;
logger.info(">>>> There are " + consumer.countMessageNumber(start, end)
+ " messages between " + start + " and " + end + " timestamp.");
}
public long countMessageNumber(long start, long end) {
long result = 0;
if (start >= end) {
logger.error("[startTime]" + start + " >= [endTime]+" + end + " .");
return result;
}
logger.info(">>>> Start timestamp " + start + " = " + df.format(start));
logger.info(">>>> End timestamp " + end + " = " + df.format(end));
try {
// get topic's partition info
List<PartitionInfo> partitionInfos = consumer.partitionsFor(topic);
List<TopicPartition> topicPartitions = new ArrayList<>();
Map<TopicPartition, Long> startTimestampsToSearch = new HashMap<>();
Map<TopicPartition, Long> endTimestampsToSearch = new HashMap<>();
// set timestamp to every partition by timestamps
for (PartitionInfo partitionInfo : partitionInfos) {
topicPartitions.add(new TopicPartition(partitionInfo.topic(), partitionInfo.partition()));
startTimestampsToSearch.put(new TopicPartition(partitionInfo.topic(), partitionInfo.partition()), start);
endTimestampsToSearch.put(new TopicPartition(partitionInfo.topic(), partitionInfo.partition()), end);
}
// consumer.assign(topicPartitions);
/*
Look up the offsets for the given partitions by timestamp.
The returned offset for each partition is the earliest offset
whose timestamp is greater than or equal to the given timestamp in the corresponding partition.
*/
Map<TopicPartition, OffsetAndTimestamp> startTimestampMap = consumer.offsetsForTimes(startTimestampsToSearch);
Map<TopicPartition, OffsetAndTimestamp> endTimestampMap = consumer.offsetsForTimes(endTimestampsToSearch);
logger.info(">>>> Now we get every partition's closest offset before these timestamp area as follow ...");
for (Map.Entry<TopicPartition, OffsetAndTimestamp> entry : startTimestampMap.entrySet()) {
OffsetAndTimestamp offsetTimestamp = entry.getValue();
/* if the timestamp we set for look up offset greater than the largest offset's timestamp,
it will return null
*/
if (offsetTimestamp != null) {
int partition = entry.getKey().partition();
long startTimestamp = offsetTimestamp.timestamp();
long startOffset = offsetTimestamp.offset();
logger.info(" ****** partition-" + partition + ", start-timestamp = " + df.format(new Date(startTimestamp)) +
", offset = " + startOffset);
//get this partition-endTimestamp's map
OffsetAndTimestamp endOffsetAndTimestamp = endTimestampMap.get(entry.getKey());
long dValue = 0;
if (endOffsetAndTimestamp == null) {
logger.warn(" ****** Warn : end time stamp great than the latest time stamp.");
Map<TopicPartition, Long> endOffsetMap = getEndOffsets();
long endOffset = endOffsetMap.get(entry.getKey());
logger.info(" ****** partition-" + partition + "latest offset is " + endOffset);
dValue = (endOffset - startOffset);
} else {
long endTimestamp = endOffsetAndTimestamp.timestamp();
long endOffset = endOffsetAndTimestamp.offset();
logger.info(" ****** partition = " + partition + ", end-timestamp = " + df.format(new Date(endTimestamp)) +
", offset = " + endOffset);
//add the message's number by offset d_value
dValue = (endTimestampMap.get(entry.getKey()).offset() - startOffset);
}
logger.info(" ###### partition-" + partition + " has " + dValue + " messages between timestamp " + start + " and " + end);
result += dValue;
// set offset to get message
//consumer.seek(entry.getKey(), startOffset);
} else {
//logger.error(">>>> The start time stamp great than the latest time stamp.");
logger.error(">>>> can't get the OffsetAndTimestamp by start time "+start);
return 0;
}
}
logger.info(">>>> Finish get offset for every partitions...");
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
} finally {
consumer.close();
}
logger.info(">>>> There are " + result
+ " messages between " + start + " and " + end + " timestamp.");
return result;
}
}
| 49.138365
| 144
| 0.603865
|
0c7d814dbbeb73816f3654334dba404575f2e14d
| 298
|
package org.apache.spark.deploy;
public class DockerId {
// not preceding
public DockerId (java.lang.String id) { throw new RuntimeException(); }
public java.lang.String id () { throw new RuntimeException(); }
public java.lang.String toString () { throw new RuntimeException(); }
}
| 37.25
| 76
| 0.704698
|
9dd89859649d1ef313b09e18411e4874a62439e4
| 362
|
package com.yonyou.iuap.purchaseorder.dao;
import com.yonyou.iuap.purchaseorder.entity.PurchaseOrderDetail;
import com.yonyou.iuap.baseservice.persistence.mybatis.mapper.GenericExMapper;
import com.yonyou.iuap.mybatis.anotation.MyBatisRepository;
@MyBatisRepository
public interface PurchaseOrderDetailMapper extends GenericExMapper<PurchaseOrderDetail> {
}
| 30.166667
| 89
| 0.861878
|
007ec4de90cd1a47a08c2e572648b59e739f92b2
| 2,516
|
package com.blastedstudios.freeboot.world;
import java.util.HashSet;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.utils.Array;
import com.blastedstudios.gdxworld.world.quest.trigger.IQuestTriggerInformationProvider;
import com.blastedstudios.freeboot.input.ActionEnum;
import com.blastedstudios.freeboot.plugin.quest.trigger.beinghit.IBeingHitListener;
import com.blastedstudios.freeboot.ui.gameplay.GameplayScreen;
import com.blastedstudios.freeboot.world.being.Being;
import com.blastedstudios.freeboot.world.weapon.DamageStruct;
public class QuestTriggerInformationProvider implements IQuestTriggerInformationProvider{
private final WorldManager worldManager;
private final HashSet<IBeingHitListener> beingHitListeners = new HashSet<>();
public QuestTriggerInformationProvider(GameplayScreen screen, WorldManager worldManager){
this.worldManager = worldManager;
}
@Override public Vector2 getPlayerPosition() {
try{
return worldManager.getPlayer().getPosition();
}catch(Exception e){
return worldManager.getRespawnLocation();
}
}
@Override public boolean isDead(String name) {
for(Being being : worldManager.getAllBeings().values())
if(being.getName().equalsIgnoreCase(name) && being.isDead())
return true;
return false;
}
@Override public boolean isNear(String origin, String target, float distance) {
Body originBody = null, targetBody = null;
Array<Body> bodyArray = new Array<>(worldManager.getWorld().getBodyCount());
worldManager.getWorld().getBodies(bodyArray);
for(Body body : bodyArray){
if(origin != null && origin.equals(body.getUserData()))
originBody = body;
if(target != null && target.equals(body.getUserData()))
targetBody = body;
}
return originBody.getPosition().dst(targetBody.getPosition()) < distance;
}
@Override public Body getPhysicsObject(String name) {
Array<Body> bodyArray = new Array<>(worldManager.getWorld().getBodyCount());
worldManager.getWorld().getBodies(bodyArray);
for(Body body : bodyArray)
if(name != null && name.equals(body.getUserData()))
return body;
return null;
}
@Override public boolean isAction() {
return ActionEnum.ACTION.isPressed();
}
public void beingHit(DamageStruct damageStruct){
for(IBeingHitListener listener : beingHitListeners)
listener.beingHit(damageStruct);
}
public boolean addBeingHitListener(IBeingHitListener beingHitTrigger) {
return beingHitListeners.add(beingHitTrigger);
}
}
| 34.465753
| 90
| 0.77504
|
578cd3a010e8552cacec946d9795734aabb91659
| 1,160
|
package net.ncguy.tracking.geometry;
import java.util.Objects;
public class GeometryItem {
public transient GeometryItem parent;
public String path;
public GeometryItem left;
public GeometryItem right;
public Model data;
public Model.Operation operation;
public void SetNext(GeometryItem item) {
String lastChar = item.path.substring(item.path.length() - 1);
if(Objects.equals(lastChar, "l") || Objects.equals(lastChar, "r")) {
if(lastChar.equals("l")) {
left = item;
return;
}
if(lastChar.equals("r")) {
right = item;
return;
}
}
if(left == null) {
left = item;
return;
}
if(right == null) {
right = item;
return;
}
System.err.println("Item discarded");
}
public static class GLItem {
public transient int parent;
public transient String path;
public int leftItem;
public int rightItem;
public int data;
public int operation;
}
}
| 20
| 76
| 0.532759
|
68dfd8238f801e25465dd135a1a649915ab9c9dc
| 1,570
|
/*
* 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.
*/
/* $Id: GraphicContextTestCase.java 1732019 2016-02-24 05:01:10Z gadams $ */
package org.apache.xmlgraphics.java2d;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.geom.Point2D;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class GraphicContextTestCase {
@Test
public void testSetPaint() {
GraphicContext gc = new GraphicContext();
Color red = Color.RED;
gc.setPaint(red);
assertEquals(red, gc.getColor());
Point2D start = new Point2D.Float(0, 0);
Point2D end = new Point2D.Float(50, 50);
GradientPaint gp = new GradientPaint(start, Color.RED, end, Color.BLUE);
gc.setPaint(gp);
assertEquals(Color.BLACK, gc.getColor());
}
}
| 34.888889
| 80
| 0.715924
|
30e264dc6c5ee5374dae9bca9f95c8a8923b51f6
| 1,771
|
package sonia.scm.security;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import sonia.scm.repository.RepositoryRole;
import sonia.scm.repository.RepositoryRoleDAO;
import java.util.Collection;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class RepositoryPermissionProviderTest {
@Mock
SystemRepositoryPermissionProvider systemRepositoryPermissionProvider;
@Mock
RepositoryRoleDAO repositoryRoleDAO;
@InjectMocks
RepositoryPermissionProvider repositoryPermissionProvider;
@Test
void shouldReturnVerbsFromSystem() {
List<String> expectedVerbs = asList("verb1", "verb2");
when(systemRepositoryPermissionProvider.availableVerbs()).thenReturn(expectedVerbs);
Collection<String> actualVerbs = repositoryPermissionProvider.availableVerbs();
assertThat(actualVerbs).isEqualTo(expectedVerbs);
}
@Test
void shouldReturnJoinedRolesFromSystemAndDao() {
RepositoryRole systemRole = new RepositoryRole("roleSystem", singletonList("verb1"), "system");
RepositoryRole daoRole = new RepositoryRole("roleDao", singletonList("verb1"), "xml");
when(systemRepositoryPermissionProvider.availableRoles()).thenReturn(singletonList(systemRole));
when(repositoryRoleDAO.getAll()).thenReturn(singletonList(daoRole));
Collection<RepositoryRole> actualRoles = repositoryPermissionProvider.availableRoles();
assertThat(actualRoles).containsExactly(systemRole, daoRole);
}
}
| 34.057692
| 100
| 0.807453
|
301342bac08fd4e3ac2a2be3bf278c5e550cf276
| 1,104
|
package com.hejie.converter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
import com.hejie.entity.PhoneNumber;
public class StringToPhoneNumberConverter implements Converter<String, PhoneNumber>{
// 029-88888888
Pattern patter = Pattern.compile("^(0\\d{2,3})-(\\d{7,8})$");
@Override
public PhoneNumber convert(String source) {
if(!StringUtils.hasLength(source)){
return null;
}
Matcher matcher = patter.matcher(source);
if(matcher.matches()){
PhoneNumber phoneNumber = new PhoneNumber();
phoneNumber.setAreaCode(matcher.group(1));
phoneNumber.setPhone(matcher.group(2));
return phoneNumber;
}else{
// 抛出异常
throw new IllegalArgumentException(String.format("类型转换失败!期望的格式是[0731-76560000], 但是实际格式是[%s]", source));
}
}
public static void main(String[] args) {
StringToPhoneNumberConverter stpnc = new StringToPhoneNumberConverter ();
System.out.println(stpnc.convert("018-88888888"));
}
}
| 28.307692
| 107
| 0.718297
|
da6c81c9309770231cc75cdc9b5e9b9dd74e6900
| 765
|
package com.bumptech.glide.supportapp.github._1140_always_animate;
import android.content.Context;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.*;
import com.bumptech.glide.supportapp.*;
public class TestFragment extends GlideImageFragment {
@Override protected void load(Context context) throws Exception {
Glide
.with(this)
.load(R.drawable.glide)
.animate(new ViewAnimationFactory<GlideDrawable>(context, android.R.anim.slide_in_left) {
@Override public GlideAnimation<GlideDrawable> build(
boolean isFromMemoryCache, boolean isFirstResource) {
return super.build(false, isFirstResource);
}
})
.into(imageView);
}
}
| 31.875
| 93
| 0.76732
|
f4af7ec97bdf0e9df474c14bfdc0a4afccd20c4d
| 195
|
package com.obstacle3.app.model;
/**
* Created by oliverheim on 23.04.16.
*/
public class GeolocationResponse {
public double lat;
public double lon;
public String display_name;
}
| 17.727273
| 37
| 0.707692
|
3b2420baf48a71e11706573f647aaf7c0265a603
| 8,705
|
/*
* Copyright 2013 Yen Pai ypai@reign.io
*
* 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.reign;
import io.reign.conf.ConfService;
import io.reign.coord.CoordinationService;
import io.reign.data.DataService;
import io.reign.mesg.DefaultMessagingService;
import io.reign.mesg.MessagingService;
import io.reign.metrics.MetricsService;
import io.reign.presence.PresenceService;
import io.reign.zk.PathCache;
import io.reign.zk.ResilientZkClient;
import io.reign.zk.SimplePathCache;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.apache.curator.test.TestingServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Convenient way to quickly configure the main framework object.
*
* @author ypai
*
*/
public class ReignMaker {
private static final Logger logger = LoggerFactory.getLogger(ReignMaker.class);
private String zkConnectString;
private int zkSessionTimeout = 30000;
private int pathCacheMaxSize = 1024;
private int pathCacheMaxConcurrencyLevel = 2;
private PathCache pathCache = null;
private ZkClient zkClient = null;
private PathScheme pathScheme = null;
private String frameworkClusterId;
private String frameworkBasePath;
private Integer messagingPort = Reign.DEFAULT_MESSAGING_PORT;
private NodeIdProvider canonicalIdMaker = null;
private final Map<String, Service> serviceMap = new HashMap<String, Service>();
private TestingServer zkTestServer;
private Runnable startHook;
private Runnable stopHook;
public ReignMaker startHook(Runnable startHook) {
this.startHook = startHook;
return this;
}
public ReignMaker stopHook(Runnable stopHook) {
this.stopHook = stopHook;
return this;
}
private ReignMaker core() {
// configure Reign with all core services
presence();
conf();
coord();
data();
mesg();
metrics();
nullService();
return this;
}
private ReignMaker metrics() {
MetricsService metricsService = new MetricsService();
serviceMap.put("metrics", metricsService);
return this;
}
private ReignMaker presence() {
PresenceService presenceService = new PresenceService();
serviceMap.put("presence", presenceService);
// alternate route for more concise messaging
serviceMap.put("P", presenceService);
return this;
}
private ReignMaker nullService() {
NullService nullService = new NullService();
serviceMap.put("null", nullService);
return this;
}
private ReignMaker conf() {
ConfService confService = new ConfService();
serviceMap.put("conf", confService);
// alternate route for more concise messaging
serviceMap.put("F", confService);
return this;
}
private ReignMaker coord() {
CoordinationService coordService = new CoordinationService();
serviceMap.put("coord", coordService);
// alternate route for more concise messaging
serviceMap.put("C", coordService);
return this;
}
private ReignMaker data() {
DataService dataService = new DataService();
serviceMap.put("data", dataService);
// alternate route for more concise messaging
serviceMap.put("D", dataService);
return this;
}
private ReignMaker mesg() {
MessagingService messagingService = new DefaultMessagingService();
serviceMap.put("mesg", messagingService);
if (messagingPort == null) {
messagingService.setPort(Reign.DEFAULT_MESSAGING_PORT);
} else {
messagingService.setPort(messagingPort);
}
// alternate route for more concise messaging
serviceMap.put("M", messagingService);
return this;
}
public ReignMaker messagingPort(Integer messagingPort) {
if (messagingPort == null) {
throw new IllegalArgumentException("Invalid argument: 'messagingPort' cannot be null!");
}
this.messagingPort = messagingPort;
// set messaging port if message service has already been configured
MessagingService messagingService = (MessagingService) serviceMap.get("messaging");
if (messagingService != null) {
messagingService.setPort(messagingPort);
}
return this;
}
public ReignMaker canonicalIdMaker(NodeIdProvider canonicalIdMaker) {
this.canonicalIdMaker = canonicalIdMaker;
return this;
}
public ReignMaker zkClient(String zkConnectString, int zkSessionTimeout) {
this.zkConnectString = zkConnectString;
this.zkSessionTimeout = zkSessionTimeout;
return this;
}
public ReignMaker zkConnectString(String zkConnectString) {
this.zkConnectString = zkConnectString;
return this;
}
public ReignMaker zkSessionTimeout(int zkSessionTimeout) {
this.zkSessionTimeout = zkSessionTimeout;
return this;
}
public String zkConnectString() {
return this.zkConnectString;
}
public int zkSessionTimeout() {
return this.zkSessionTimeout;
}
public ReignMaker zkClientTestMode(int zkPort, int zkSessionTimeout) {
logger.debug("Starting in-process ZooKeeper server on port {} -- meant for testing only!", zkPort);
try {
String dataDirectory = System.getProperty("java.io.tmpdir");
if (!dataDirectory.endsWith("/")) {
dataDirectory += File.separator;
}
dataDirectory += UUID.randomUUID().toString();
logger.debug("ZK dataDirectory={}", dataDirectory);
File dir = new File(dataDirectory, "zookeeper").getAbsoluteFile();
zkTestServer = new TestingServer(zkPort, dir);
this.zkConnectString = "localhost:" + zkPort;
this.zkSessionTimeout = 30000;
} catch (Exception e) {
logger.error("Trouble starting test ZooKeeper instance: " + e, e);
}
return this;
}
public ReignMaker registerService(String serviceName, Service service) {
serviceMap.put(serviceName, service);
return this;
}
public ReignMaker pathCache(int maxSize, int concurrencyLevel) {
this.pathCacheMaxSize = maxSize;
this.pathCacheMaxConcurrencyLevel = concurrencyLevel;
return this;
}
public ReignMaker pathCache(PathCache pathCache) {
this.pathCache = pathCache;
return this;
}
public ReignMaker zkClient(ZkClient zkClient) {
this.zkClient = zkClient;
return this;
}
public ReignMaker frameworkBasePath(String frameworkBasePath) {
this.frameworkBasePath = frameworkBasePath;
return this;
}
public ReignMaker frameworkClusterId(String frameworkClusterId) {
this.frameworkClusterId = frameworkClusterId;
return this;
}
public Reign get() {
Reign s = null;
// always add core services
core();
// see if we need to set defaults
if (frameworkClusterId == null) {
frameworkClusterId = Reign.DEFAULT_FRAMEWORK_CLUSTER_ID;
}
if (frameworkBasePath == null) {
frameworkBasePath = Reign.DEFAULT_FRAMEWORK_BASE_PATH;
}
if (pathCache == null) {
pathCache = defaultPathCache();
}
if (zkClient == null) {
zkClient = defaultZkClient(pathCache);
}
if (pathScheme == null) {
pathScheme = defaultPathScheme(frameworkBasePath, frameworkClusterId);
}
if (canonicalIdMaker == null) {
canonicalIdMaker = defaultCanonicalIdMaker();
}
// build
s = new Reign(zkClient, pathScheme, canonicalIdMaker, zkTestServer);
s.registerServices(serviceMap);
s.setStartHook(startHook);
s.setStopHook(stopHook);
return s;
}
ZkClient defaultZkClient(PathCache pathCache) {
if (zkConnectString == null || zkSessionTimeout <= 0) {
throw new ReignException("zkConnectString and zkSessionTimeout not configured!");
}
ZkClient zkClient = null;
try {
zkClient = new ResilientZkClient(zkConnectString, zkSessionTimeout);
} catch (IOException e) {
throw new ReignException("Fatal error: could not initialize Zookeeper client!", e);
}
return zkClient;
}
PathCache defaultPathCache() {
if (pathCacheMaxSize < 1 || pathCacheMaxConcurrencyLevel < 1) {
throw new ReignException(
"zkClient, pathCacheMaxSize, and pathCacheMaxConcurrencyLevel must be configured to create default path cache!");
}
return new SimplePathCache(this.pathCacheMaxSize, this.pathCacheMaxConcurrencyLevel);
}
PathScheme defaultPathScheme(String basePath, String frameworkClusterId) {
return new DefaultPathScheme(basePath, frameworkClusterId);
}
NodeIdProvider defaultCanonicalIdMaker() {
DefaultNodeIdProvider idMaker = new DefaultNodeIdProvider(messagingPort);
return idMaker;
}
}
| 25.678466
| 124
| 0.748076
|
9264e14bccdb6c796765cd627d135fd3ad43b797
| 26,951
|
package org.swtk.commons.dict.wiktionary.terms; import java.util.Collection; import java.util.Set; import java.util.TreeSet; import org.swtk.commons.dict.wiktionary.generated.a.a.c.*;
import org.swtk.commons.dict.wiktionary.generated.a.a.d.*;
import org.swtk.commons.dict.wiktionary.generated.a.a.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.a.n.*;
import org.swtk.commons.dict.wiktionary.generated.a.a.r.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.b.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.d.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.e.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.f.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.g.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.h.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.i.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.j.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.k.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.m.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.n.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.r.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.s.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.u.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.v.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.w.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.x.*;
import org.swtk.commons.dict.wiktionary.generated.a.b.y.*;
import org.swtk.commons.dict.wiktionary.generated.a.c.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.c.c.*;
import org.swtk.commons.dict.wiktionary.generated.a.c.e.*;
import org.swtk.commons.dict.wiktionary.generated.a.c.h.*;
import org.swtk.commons.dict.wiktionary.generated.a.c.i.*;
import org.swtk.commons.dict.wiktionary.generated.a.c.k.*;
import org.swtk.commons.dict.wiktionary.generated.a.c.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.c.m.*;
import org.swtk.commons.dict.wiktionary.generated.a.c.n.*;
import org.swtk.commons.dict.wiktionary.generated.a.c.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.c.q.*;
import org.swtk.commons.dict.wiktionary.generated.a.c.r.*;
import org.swtk.commons.dict.wiktionary.generated.a.c.t.*;
import org.swtk.commons.dict.wiktionary.generated.a.c.u.*;
import org.swtk.commons.dict.wiktionary.generated.a.c.y.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.d.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.e.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.h.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.i.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.j.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.m.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.n.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.p.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.r.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.s.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.u.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.v.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.w.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.y.*;
import org.swtk.commons.dict.wiktionary.generated.a.d.z.*;
import org.swtk.commons.dict.wiktionary.generated.a.e.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.e.c.*;
import org.swtk.commons.dict.wiktionary.generated.a.e.d.*;
import org.swtk.commons.dict.wiktionary.generated.a.e.g.*;
import org.swtk.commons.dict.wiktionary.generated.a.e.n.*;
import org.swtk.commons.dict.wiktionary.generated.a.e.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.e.q.*;
import org.swtk.commons.dict.wiktionary.generated.a.e.r.*;
import org.swtk.commons.dict.wiktionary.generated.a.e.s.*;
import org.swtk.commons.dict.wiktionary.generated.a.e.t.*;
import org.swtk.commons.dict.wiktionary.generated.a.e.v.*;
import org.swtk.commons.dict.wiktionary.generated.a.f.c.*;
import org.swtk.commons.dict.wiktionary.generated.a.f.f.*;
import org.swtk.commons.dict.wiktionary.generated.a.f.g.*;
import org.swtk.commons.dict.wiktionary.generated.a.f.i.*;
import org.swtk.commons.dict.wiktionary.generated.a.f.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.f.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.f.r.*;
import org.swtk.commons.dict.wiktionary.generated.a.f.t.*;
import org.swtk.commons.dict.wiktionary.generated.a.f.z.*;
import org.swtk.commons.dict.wiktionary.generated.a.g.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.g.d.*;
import org.swtk.commons.dict.wiktionary.generated.a.g.e.*;
import org.swtk.commons.dict.wiktionary.generated.a.g.f.*;
import org.swtk.commons.dict.wiktionary.generated.a.g.g.*;
import org.swtk.commons.dict.wiktionary.generated.a.g.i.*;
import org.swtk.commons.dict.wiktionary.generated.a.g.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.g.n.*;
import org.swtk.commons.dict.wiktionary.generated.a.g.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.g.r.*;
import org.swtk.commons.dict.wiktionary.generated.a.g.u.*;
import org.swtk.commons.dict.wiktionary.generated.a.h.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.h.i.*;
import org.swtk.commons.dict.wiktionary.generated.a.h.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.h.m.*;
import org.swtk.commons.dict.wiktionary.generated.a.h.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.h.w.*;
import org.swtk.commons.dict.wiktionary.generated.a.i.b.*;
import org.swtk.commons.dict.wiktionary.generated.a.i.c.*;
import org.swtk.commons.dict.wiktionary.generated.a.i.d.*;
import org.swtk.commons.dict.wiktionary.generated.a.i.g.*;
import org.swtk.commons.dict.wiktionary.generated.a.i.k.*;
import org.swtk.commons.dict.wiktionary.generated.a.i.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.i.m.*;
import org.swtk.commons.dict.wiktionary.generated.a.i.n.*;
import org.swtk.commons.dict.wiktionary.generated.a.i.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.i.r.*;
import org.swtk.commons.dict.wiktionary.generated.a.i.s.*;
import org.swtk.commons.dict.wiktionary.generated.a.i.t.*;
import org.swtk.commons.dict.wiktionary.generated.a.i.w.*;
import org.swtk.commons.dict.wiktionary.generated.a.j.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.j.m.*;
import org.swtk.commons.dict.wiktionary.generated.a.j.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.j.v.*;
import org.swtk.commons.dict.wiktionary.generated.a.k.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.k.h.*;
import org.swtk.commons.dict.wiktionary.generated.a.k.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.k.s.*;
import org.swtk.commons.dict.wiktionary.generated.a.k.u.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.b.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.c.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.d.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.e.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.f.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.g.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.h.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.i.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.j.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.k.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.m.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.p.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.r.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.s.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.t.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.u.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.v.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.w.*;
import org.swtk.commons.dict.wiktionary.generated.a.l.y.*;
import org.swtk.commons.dict.wiktionary.generated.a.m.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.m.b.*;
import org.swtk.commons.dict.wiktionary.generated.a.m.e.*;
import org.swtk.commons.dict.wiktionary.generated.a.m.f.*;
import org.swtk.commons.dict.wiktionary.generated.a.m.h.*;
import org.swtk.commons.dict.wiktionary.generated.a.m.i.*;
import org.swtk.commons.dict.wiktionary.generated.a.m.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.m.m.*;
import org.swtk.commons.dict.wiktionary.generated.a.m.n.*;
import org.swtk.commons.dict.wiktionary.generated.a.m.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.m.p.*;
import org.swtk.commons.dict.wiktionary.generated.a.m.r.*;
import org.swtk.commons.dict.wiktionary.generated.a.m.s.*;
import org.swtk.commons.dict.wiktionary.generated.a.m.t.*;
import org.swtk.commons.dict.wiktionary.generated.a.m.u.*;
import org.swtk.commons.dict.wiktionary.generated.a.m.y.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.c.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.d.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.e.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.f.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.g.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.h.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.i.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.k.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.n.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.s.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.t.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.u.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.x.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.y.*;
import org.swtk.commons.dict.wiktionary.generated.a.n.z.*;
import org.swtk.commons.dict.wiktionary.generated.a.o.r.*;
import org.swtk.commons.dict.wiktionary.generated.a.o.t.*;
import org.swtk.commons.dict.wiktionary.generated.a.p.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.p.e.*;
import org.swtk.commons.dict.wiktionary.generated.a.p.f.*;
import org.swtk.commons.dict.wiktionary.generated.a.p.h.*;
import org.swtk.commons.dict.wiktionary.generated.a.p.i.*;
import org.swtk.commons.dict.wiktionary.generated.a.p.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.p.n.*;
import org.swtk.commons.dict.wiktionary.generated.a.p.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.p.p.*;
import org.swtk.commons.dict.wiktionary.generated.a.p.r.*;
import org.swtk.commons.dict.wiktionary.generated.a.p.s.*;
import org.swtk.commons.dict.wiktionary.generated.a.p.t.*;
import org.swtk.commons.dict.wiktionary.generated.a.p.u.*;
import org.swtk.commons.dict.wiktionary.generated.a.p.y.*;
import org.swtk.commons.dict.wiktionary.generated.a.q.u.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.b.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.c.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.d.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.e.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.f.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.g.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.h.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.i.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.k.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.m.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.n.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.p.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.q.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.r.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.s.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.t.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.u.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.v.*;
import org.swtk.commons.dict.wiktionary.generated.a.r.y.*;
import org.swtk.commons.dict.wiktionary.generated.a.s.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.s.b.*;
import org.swtk.commons.dict.wiktionary.generated.a.s.c.*;
import org.swtk.commons.dict.wiktionary.generated.a.s.e.*;
import org.swtk.commons.dict.wiktionary.generated.a.s.h.*;
import org.swtk.commons.dict.wiktionary.generated.a.s.i.*;
import org.swtk.commons.dict.wiktionary.generated.a.s.k.*;
import org.swtk.commons.dict.wiktionary.generated.a.s.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.s.p.*;
import org.swtk.commons.dict.wiktionary.generated.a.s.s.*;
import org.swtk.commons.dict.wiktionary.generated.a.s.t.*;
import org.swtk.commons.dict.wiktionary.generated.a.s.u.*;
import org.swtk.commons.dict.wiktionary.generated.a.s.y.*;
import org.swtk.commons.dict.wiktionary.generated.a.t.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.t.e.*;
import org.swtk.commons.dict.wiktionary.generated.a.t.h.*;
import org.swtk.commons.dict.wiktionary.generated.a.t.i.*;
import org.swtk.commons.dict.wiktionary.generated.a.t.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.t.m.*;
import org.swtk.commons.dict.wiktionary.generated.a.t.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.t.p.*;
import org.swtk.commons.dict.wiktionary.generated.a.t.r.*;
import org.swtk.commons.dict.wiktionary.generated.a.t.t.*;
import org.swtk.commons.dict.wiktionary.generated.a.t.y.*;
import org.swtk.commons.dict.wiktionary.generated.a.u.b.*;
import org.swtk.commons.dict.wiktionary.generated.a.u.c.*;
import org.swtk.commons.dict.wiktionary.generated.a.u.d.*;
import org.swtk.commons.dict.wiktionary.generated.a.u.f.*;
import org.swtk.commons.dict.wiktionary.generated.a.u.g.*;
import org.swtk.commons.dict.wiktionary.generated.a.u.k.*;
import org.swtk.commons.dict.wiktionary.generated.a.u.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.u.n.*;
import org.swtk.commons.dict.wiktionary.generated.a.u.r.*;
import org.swtk.commons.dict.wiktionary.generated.a.u.s.*;
import org.swtk.commons.dict.wiktionary.generated.a.u.t.*;
import org.swtk.commons.dict.wiktionary.generated.a.u.v.*;
import org.swtk.commons.dict.wiktionary.generated.a.u.x.*;
import org.swtk.commons.dict.wiktionary.generated.a.v.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.v.e.*;
import org.swtk.commons.dict.wiktionary.generated.a.v.g.*;
import org.swtk.commons.dict.wiktionary.generated.a.v.i.*;
import org.swtk.commons.dict.wiktionary.generated.a.v.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.v.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.w.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.w.e.*;
import org.swtk.commons.dict.wiktionary.generated.a.w.k.*;
import org.swtk.commons.dict.wiktionary.generated.a.w.n.*;
import org.swtk.commons.dict.wiktionary.generated.a.x.h.*;
import org.swtk.commons.dict.wiktionary.generated.a.x.i.*;
import org.swtk.commons.dict.wiktionary.generated.a.x.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.x.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.y.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.y.m.*;
import org.swtk.commons.dict.wiktionary.generated.a.y.r.*;
import org.swtk.commons.dict.wiktionary.generated.a.y.u.*;
import org.swtk.commons.dict.wiktionary.generated.a.z.a.*;
import org.swtk.commons.dict.wiktionary.generated.a.z.b.*;
import org.swtk.commons.dict.wiktionary.generated.a.z.e.*;
import org.swtk.commons.dict.wiktionary.generated.a.z.i.*;
import org.swtk.commons.dict.wiktionary.generated.a.z.l.*;
import org.swtk.commons.dict.wiktionary.generated.a.z.o.*;
import org.swtk.commons.dict.wiktionary.generated.a.z.t.*;
import org.swtk.commons.dict.wiktionary.generated.a.z.u.*; public final class WiktionaryTermsA { public static Collection<String> terms() { Set<String> set = new TreeSet<String>(); set.addAll(WiktionaryAAC000.terms());
set.addAll(WiktionaryAAD000.terms());
set.addAll(WiktionaryAAL000.terms());
set.addAll(WiktionaryAAN000.terms());
set.addAll(WiktionaryAAR000.terms());
set.addAll(WiktionaryABA000.terms());
set.addAll(WiktionaryABB000.terms());
set.addAll(WiktionaryABD000.terms());
set.addAll(WiktionaryABE000.terms());
set.addAll(WiktionaryABF000.terms());
set.addAll(WiktionaryABG000.terms());
set.addAll(WiktionaryABH000.terms());
set.addAll(WiktionaryABI000.terms());
set.addAll(WiktionaryABJ000.terms());
set.addAll(WiktionaryABK000.terms());
set.addAll(WiktionaryABL000.terms());
set.addAll(WiktionaryABM000.terms());
set.addAll(WiktionaryABN000.terms());
set.addAll(WiktionaryABO000.terms());
set.addAll(WiktionaryABR000.terms());
set.addAll(WiktionaryABS000.terms());
set.addAll(WiktionaryABU000.terms());
set.addAll(WiktionaryABV000.terms());
set.addAll(WiktionaryABW000.terms());
set.addAll(WiktionaryABX000.terms());
set.addAll(WiktionaryABY000.terms());
set.addAll(WiktionaryACA000.terms());
set.addAll(WiktionaryACC000.terms());
set.addAll(WiktionaryACE000.terms());
set.addAll(WiktionaryACH000.terms());
set.addAll(WiktionaryACI000.terms());
set.addAll(WiktionaryACK000.terms());
set.addAll(WiktionaryACL000.terms());
set.addAll(WiktionaryACM000.terms());
set.addAll(WiktionaryACN000.terms());
set.addAll(WiktionaryACO000.terms());
set.addAll(WiktionaryACQ000.terms());
set.addAll(WiktionaryACR000.terms());
set.addAll(WiktionaryACT000.terms());
set.addAll(WiktionaryACU000.terms());
set.addAll(WiktionaryACY000.terms());
set.addAll(WiktionaryADA000.terms());
set.addAll(WiktionaryADD000.terms());
set.addAll(WiktionaryADE000.terms());
set.addAll(WiktionaryADH000.terms());
set.addAll(WiktionaryADI000.terms());
set.addAll(WiktionaryADJ000.terms());
set.addAll(WiktionaryADL000.terms());
set.addAll(WiktionaryADM000.terms());
set.addAll(WiktionaryADN000.terms());
set.addAll(WiktionaryADO000.terms());
set.addAll(WiktionaryADP000.terms());
set.addAll(WiktionaryADR000.terms());
set.addAll(WiktionaryADS000.terms());
set.addAll(WiktionaryADU000.terms());
set.addAll(WiktionaryADV000.terms());
set.addAll(WiktionaryADW000.terms());
set.addAll(WiktionaryADY000.terms());
set.addAll(WiktionaryADZ000.terms());
set.addAll(WiktionaryAEA000.terms());
set.addAll(WiktionaryAEC000.terms());
set.addAll(WiktionaryAED000.terms());
set.addAll(WiktionaryAEG000.terms());
set.addAll(WiktionaryAEN000.terms());
set.addAll(WiktionaryAEO000.terms());
set.addAll(WiktionaryAEQ000.terms());
set.addAll(WiktionaryAER000.terms());
set.addAll(WiktionaryAES000.terms());
set.addAll(WiktionaryAET000.terms());
set.addAll(WiktionaryAEV000.terms());
set.addAll(WiktionaryAFC000.terms());
set.addAll(WiktionaryAFF000.terms());
set.addAll(WiktionaryAFG000.terms());
set.addAll(WiktionaryAFI000.terms());
set.addAll(WiktionaryAFL000.terms());
set.addAll(WiktionaryAFO000.terms());
set.addAll(WiktionaryAFR000.terms());
set.addAll(WiktionaryAFT000.terms());
set.addAll(WiktionaryAFZ000.terms());
set.addAll(WiktionaryAGA000.terms());
set.addAll(WiktionaryAGD000.terms());
set.addAll(WiktionaryAGE000.terms());
set.addAll(WiktionaryAGF000.terms());
set.addAll(WiktionaryAGG000.terms());
set.addAll(WiktionaryAGI000.terms());
set.addAll(WiktionaryAGL000.terms());
set.addAll(WiktionaryAGN000.terms());
set.addAll(WiktionaryAGO000.terms());
set.addAll(WiktionaryAGR000.terms());
set.addAll(WiktionaryAGU000.terms());
set.addAll(WiktionaryAHA000.terms());
set.addAll(WiktionaryAHI000.terms());
set.addAll(WiktionaryAHL000.terms());
set.addAll(WiktionaryAHM000.terms());
set.addAll(WiktionaryAHO000.terms());
set.addAll(WiktionaryAHW000.terms());
set.addAll(WiktionaryAIB000.terms());
set.addAll(WiktionaryAIC000.terms());
set.addAll(WiktionaryAID000.terms());
set.addAll(WiktionaryAIG000.terms());
set.addAll(WiktionaryAIK000.terms());
set.addAll(WiktionaryAIL000.terms());
set.addAll(WiktionaryAIM000.terms());
set.addAll(WiktionaryAIN000.terms());
set.addAll(WiktionaryAIO000.terms());
set.addAll(WiktionaryAIR000.terms());
set.addAll(WiktionaryAIS000.terms());
set.addAll(WiktionaryAIT000.terms());
set.addAll(WiktionaryAIW000.terms());
set.addAll(WiktionaryAJA000.terms());
set.addAll(WiktionaryAJM000.terms());
set.addAll(WiktionaryAJO000.terms());
set.addAll(WiktionaryAJV000.terms());
set.addAll(WiktionaryAKA000.terms());
set.addAll(WiktionaryAKH000.terms());
set.addAll(WiktionaryAKO000.terms());
set.addAll(WiktionaryAKS000.terms());
set.addAll(WiktionaryAKU000.terms());
set.addAll(WiktionaryALA000.terms());
set.addAll(WiktionaryALB000.terms());
set.addAll(WiktionaryALC000.terms());
set.addAll(WiktionaryALD000.terms());
set.addAll(WiktionaryALE000.terms());
set.addAll(WiktionaryALF000.terms());
set.addAll(WiktionaryALG000.terms());
set.addAll(WiktionaryALH000.terms());
set.addAll(WiktionaryALI000.terms());
set.addAll(WiktionaryALJ000.terms());
set.addAll(WiktionaryALK000.terms());
set.addAll(WiktionaryALL000.terms());
set.addAll(WiktionaryALM000.terms());
set.addAll(WiktionaryALO000.terms());
set.addAll(WiktionaryALP000.terms());
set.addAll(WiktionaryALR000.terms());
set.addAll(WiktionaryALS000.terms());
set.addAll(WiktionaryALT000.terms());
set.addAll(WiktionaryALU000.terms());
set.addAll(WiktionaryALV000.terms());
set.addAll(WiktionaryALW000.terms());
set.addAll(WiktionaryALY000.terms());
set.addAll(WiktionaryAMA000.terms());
set.addAll(WiktionaryAMB000.terms());
set.addAll(WiktionaryAME000.terms());
set.addAll(WiktionaryAMF000.terms());
set.addAll(WiktionaryAMH000.terms());
set.addAll(WiktionaryAMI000.terms());
set.addAll(WiktionaryAML000.terms());
set.addAll(WiktionaryAMM000.terms());
set.addAll(WiktionaryAMN000.terms());
set.addAll(WiktionaryAMO000.terms());
set.addAll(WiktionaryAMP000.terms());
set.addAll(WiktionaryAMR000.terms());
set.addAll(WiktionaryAMS000.terms());
set.addAll(WiktionaryAMT000.terms());
set.addAll(WiktionaryAMU000.terms());
set.addAll(WiktionaryAMY000.terms());
set.addAll(WiktionaryANA000.terms());
set.addAll(WiktionaryANC000.terms());
set.addAll(WiktionaryAND000.terms());
set.addAll(WiktionaryANE000.terms());
set.addAll(WiktionaryANF000.terms());
set.addAll(WiktionaryANG000.terms());
set.addAll(WiktionaryANH000.terms());
set.addAll(WiktionaryANI000.terms());
set.addAll(WiktionaryANK000.terms());
set.addAll(WiktionaryANL000.terms());
set.addAll(WiktionaryANN000.terms());
set.addAll(WiktionaryANO000.terms());
set.addAll(WiktionaryANS000.terms());
set.addAll(WiktionaryANT000.terms());
set.addAll(WiktionaryANU000.terms());
set.addAll(WiktionaryANX000.terms());
set.addAll(WiktionaryANY000.terms());
set.addAll(WiktionaryANZ000.terms());
set.addAll(WiktionaryAOR000.terms());
set.addAll(WiktionaryAOT000.terms());
set.addAll(WiktionaryAPA000.terms());
set.addAll(WiktionaryAPE000.terms());
set.addAll(WiktionaryAPF000.terms());
set.addAll(WiktionaryAPH000.terms());
set.addAll(WiktionaryAPI000.terms());
set.addAll(WiktionaryAPL000.terms());
set.addAll(WiktionaryAPN000.terms());
set.addAll(WiktionaryAPO000.terms());
set.addAll(WiktionaryAPP000.terms());
set.addAll(WiktionaryAPR000.terms());
set.addAll(WiktionaryAPS000.terms());
set.addAll(WiktionaryAPT000.terms());
set.addAll(WiktionaryAPU000.terms());
set.addAll(WiktionaryAPY000.terms());
set.addAll(WiktionaryAQU000.terms());
set.addAll(WiktionaryARA000.terms());
set.addAll(WiktionaryARB000.terms());
set.addAll(WiktionaryARC000.terms());
set.addAll(WiktionaryARD000.terms());
set.addAll(WiktionaryARE000.terms());
set.addAll(WiktionaryARF000.terms());
set.addAll(WiktionaryARG000.terms());
set.addAll(WiktionaryARH000.terms());
set.addAll(WiktionaryARI000.terms());
set.addAll(WiktionaryARK000.terms());
set.addAll(WiktionaryARM000.terms());
set.addAll(WiktionaryARN000.terms());
set.addAll(WiktionaryARO000.terms());
set.addAll(WiktionaryARP000.terms());
set.addAll(WiktionaryARQ000.terms());
set.addAll(WiktionaryARR000.terms());
set.addAll(WiktionaryARS000.terms());
set.addAll(WiktionaryART000.terms());
set.addAll(WiktionaryARU000.terms());
set.addAll(WiktionaryARV000.terms());
set.addAll(WiktionaryARY000.terms());
set.addAll(WiktionaryASA000.terms());
set.addAll(WiktionaryASB000.terms());
set.addAll(WiktionaryASC000.terms());
set.addAll(WiktionaryASE000.terms());
set.addAll(WiktionaryASH000.terms());
set.addAll(WiktionaryASI000.terms());
set.addAll(WiktionaryASK000.terms());
set.addAll(WiktionaryASO000.terms());
set.addAll(WiktionaryASP000.terms());
set.addAll(WiktionaryASS000.terms());
set.addAll(WiktionaryAST000.terms());
set.addAll(WiktionaryASU000.terms());
set.addAll(WiktionaryASY000.terms());
set.addAll(WiktionaryATA000.terms());
set.addAll(WiktionaryATE000.terms());
set.addAll(WiktionaryATH000.terms());
set.addAll(WiktionaryATI000.terms());
set.addAll(WiktionaryATL000.terms());
set.addAll(WiktionaryATM000.terms());
set.addAll(WiktionaryATO000.terms());
set.addAll(WiktionaryATP000.terms());
set.addAll(WiktionaryATR000.terms());
set.addAll(WiktionaryATT000.terms());
set.addAll(WiktionaryATY000.terms());
set.addAll(WiktionaryAUB000.terms());
set.addAll(WiktionaryAUC000.terms());
set.addAll(WiktionaryAUD000.terms());
set.addAll(WiktionaryAUF000.terms());
set.addAll(WiktionaryAUG000.terms());
set.addAll(WiktionaryAUK000.terms());
set.addAll(WiktionaryAUL000.terms());
set.addAll(WiktionaryAUN000.terms());
set.addAll(WiktionaryAUR000.terms());
set.addAll(WiktionaryAUS000.terms());
set.addAll(WiktionaryAUT000.terms());
set.addAll(WiktionaryAUV000.terms());
set.addAll(WiktionaryAUX000.terms());
set.addAll(WiktionaryAVA000.terms());
set.addAll(WiktionaryAVE000.terms());
set.addAll(WiktionaryAVG000.terms());
set.addAll(WiktionaryAVI000.terms());
set.addAll(WiktionaryAVL000.terms());
set.addAll(WiktionaryAVO000.terms());
set.addAll(WiktionaryAWA000.terms());
set.addAll(WiktionaryAWE000.terms());
set.addAll(WiktionaryAWK000.terms());
set.addAll(WiktionaryAWN000.terms());
set.addAll(WiktionaryAXH000.terms());
set.addAll(WiktionaryAXI000.terms());
set.addAll(WiktionaryAXL000.terms());
set.addAll(WiktionaryAXO000.terms());
set.addAll(WiktionaryAYA000.terms());
set.addAll(WiktionaryAYM000.terms());
set.addAll(WiktionaryAYR000.terms());
set.addAll(WiktionaryAYU000.terms());
set.addAll(WiktionaryAZA000.terms());
set.addAll(WiktionaryAZB000.terms());
set.addAll(WiktionaryAZE000.terms());
set.addAll(WiktionaryAZI000.terms());
set.addAll(WiktionaryAZL000.terms());
set.addAll(WiktionaryAZO000.terms());
set.addAll(WiktionaryAZT000.terms());
set.addAll(WiktionaryAZU000.terms()); return set; } }
| 49.091075
| 226
| 0.783051
|
b54a4c6b4682368aed353859e8b37529ec3a9323
| 1,502
|
package org.aion.zero.impl.valid;
import java.math.BigInteger;
import java.util.List;
import org.aion.crypto.HashUtil;
import org.aion.mcf.blockchain.BlockHeader;
import org.aion.zero.impl.types.A0BlockHeader;
/** Checks proof value against its boundary for the block header */
public class AionPOWRule implements BlockHeaderRule {
@Override
public boolean validate(BlockHeader header, List<RuleError> errors) {
A0BlockHeader minedHeader = (A0BlockHeader) header;
return (validate(minedHeader, errors));
}
public boolean validate(A0BlockHeader header, List<RuleError> errors) {
BigInteger boundary = header.getPowBoundaryBI();
byte[] hdrBytes = header.getMineHash();
byte[] input = new byte[32 + 32 + 1408]; // H(Hdr) + nonce + solution
int pos = 0;
System.arraycopy(hdrBytes, 0, input, pos, hdrBytes.length);
System.arraycopy(header.getNonce(), 0, input, pos += 32, 32);
System.arraycopy(header.getSolution(), 0, input, pos += 32, 1408);
BigInteger hash = new BigInteger(1, HashUtil.h256(input));
if (hash.compareTo(boundary) >= 0) {
BlockHeaderValidatorUtil.addError(formatError(hash, boundary), this.getClass(), errors);
return false;
}
return true;
}
private static String formatError(BigInteger actual, BigInteger boundary) {
return "computed output (" + actual + ") violates boundary condition (" + boundary + ")";
}
}
| 35.761905
| 100
| 0.669774
|
0a1a744a1568ea5326f319adce3c2541fb16d9d7
| 2,825
|
/*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.unitime.timetable.model;
import java.util.Hashtable;
import java.util.List;
import org.unitime.timetable.model.base.BaseCurriculumProjectionRule;
import org.unitime.timetable.model.dao.CurriculumProjectionRuleDAO;
/**
* @author Tomas Muller
*/
public class CurriculumProjectionRule extends BaseCurriculumProjectionRule {
private static final long serialVersionUID = 1L;
/*[CONSTRUCTOR MARKER BEGIN]*/
public CurriculumProjectionRule () {
super();
}
/**
* Constructor for primary key
*/
public CurriculumProjectionRule (java.lang.Long uniqueId) {
super(uniqueId);
}
/*[CONSTRUCTOR MARKER END]*/
public static List<CurriculumProjectionRule> findAll(Long sessionId) {
return CurriculumProjectionRuleDAO.getInstance().getSession()
.createQuery("select r from CurriculumProjectionRule r where r.academicArea.session.uniqueId=:sessionId")
.setLong("sessionId", sessionId)
.setCacheable(true).list();
}
public static List<CurriculumProjectionRule> findByAcademicArea(Long acadAreaId) {
return CurriculumProjectionRuleDAO.getInstance().getSession()
.createQuery("select r from CurriculumProjectionRule r where r.academicArea.uniqueId=:acadAreaId")
.setLong("acadAreaId", acadAreaId)
.setCacheable(true).list();
}
public static Hashtable<String, Float> getProjections(Long acadAreaId, Long acadClasfId) {
Hashtable<String, Float> ret = new Hashtable<String, Float>();
for (CurriculumProjectionRule r: (List<CurriculumProjectionRule>)CurriculumProjectionRuleDAO.getInstance().getSession()
.createQuery("select r from CurriculumProjectionRule r where r.academicArea.uniqueId=:acadAreaId and r.academicClassification.uniqueId=:acadClasfId")
.setLong("acadAreaId", acadAreaId)
.setLong("acadClasfId", acadClasfId)
.setCacheable(true).list()) {
ret.put(r.getMajor() == null ? "" : r.getMajor().getCode(), r.getProjection());
}
return ret;
}
}
| 37.171053
| 156
| 0.738053
|
75d16249913b1229aca5400bb5995b07fc1fd620
| 604
|
package com.egoveris.te.base.model;
import java.util.ArrayList;
import java.util.List;
public class EjecucionDeTarea {
TareaMigracionDTO tareaDeEjecucion;
List<String> errores;
public TareaMigracionDTO getTareaDeEjecucion() {
return tareaDeEjecucion;
}
public void setTareaDeEjecucion(TareaMigracionDTO tareaDeEjecucion) {
this.tareaDeEjecucion = tareaDeEjecucion;
}
public List<String> getErrores() {
return errores;
}
public void setErrores(List<String> errores) {
this.errores = errores;
}
public EjecucionDeTarea(){
this.errores = new ArrayList<String>();
}
}
| 17.764706
| 70
| 0.751656
|
dea4aecf07fd3684af691a59f787abe16777b7ed
| 388
|
package contagionJVM.Placeable.StorageContainer;
import contagionJVM.IScriptEventHandler;
import contagionJVM.System.StorageSystem;
import org.nwnx.nwnx2.jvm.NWObject;
@SuppressWarnings("unused")
public class StorageContainer_OnDisturbed implements IScriptEventHandler {
@Override
public void runScript(NWObject oChest) {
StorageSystem.OnChestDisturbed(oChest);
}
}
| 27.714286
| 74
| 0.806701
|
50d5b378421f081051e186c6c1db172ab9340fe0
| 222
|
package dev.wycobar.starlines.web;
import org.springframework.boot.SpringApplication;
public class WebServer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
| 22.2
| 55
| 0.738739
|
64849efc11f2f94e473dc3cedd791167a5077d77
| 1,318
|
package com.reactnative.googlecast.types;
import androidx.annotation.Nullable;
import com.google.android.gms.cast.HlsSegmentFormat;
public class RNGCHlsSegmentFormat {
public static @Nullable String fromJson(final @Nullable String value) {
if (value == null) return null;
switch (value) {
case "AAC":
return HlsSegmentFormat.AAC;
case "AC3":
return HlsSegmentFormat.AC3;
case "E-AC3":
return HlsSegmentFormat.E_AC3;
case "FMP4":
return HlsSegmentFormat.FMP4;
case "MP3":
return HlsSegmentFormat.MP3;
case "TS":
return HlsSegmentFormat.TS;
case "TS-AAC":
return HlsSegmentFormat.TS_AAC;
default:
return null;
}
}
public static @Nullable String toJson(@Nullable final String value) {
if (value == null) return null;
switch (value) {
case HlsSegmentFormat.AAC:
return "AAC";
case HlsSegmentFormat.AC3:
return "AC3";
case HlsSegmentFormat.E_AC3:
return "E-AC3";
case HlsSegmentFormat.FMP4:
return "FMP4";
case HlsSegmentFormat.MP3:
return "MP3";
case HlsSegmentFormat.TS:
return "TS";
case HlsSegmentFormat.TS_AAC:
return "TS-AAC";
default:
return null;
}
}
}
| 24.407407
| 73
| 0.622155
|
f0bce0b63e8d758a161f02d9b2d88541d680ed2b
| 4,187
|
package dj.sangu.ditsaadhaar.activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import dj.sangu.ditsaadhaar.R;
import dj.sangu.ditsaadhaar.modal.AdminModal;
import dj.sangu.ditsaadhaar.modal.responses.LoginResponse;
import dj.sangu.ditsaadhaar.network.ApiClient;
import dj.sangu.ditsaadhaar.utils.Utils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class AddAdminActivity extends AppCompatActivity implements View.OnClickListener {
private TextView etName;
private EditText etPhone;
private EditText etEmail;
private Button btnSubmit;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_admin);
initViews();
}
private void initViews() {
etName = findViewById(R.id.etName);
etPhone = findViewById(R.id.etPhone);
etEmail = findViewById(R.id.etEmail);
progressBar = findViewById(R.id.progressBar);
btnSubmit = findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(this);
Utils.setToolbar(this, (Toolbar) findViewById(R.id.toolbar), "Add Admin");
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btnSubmit) {
Utils.hideKeyboard(getApplicationContext(),v);
verifyAndSubmit();
}
}
private void verifyAndSubmit() {
String name = etName.getText().toString();
String email = etEmail.getText().toString();
String phone = etPhone.getText().toString();
if (TextUtils.isEmpty(name)) {
etName.setError("Required");
etName.requestFocus();
return;
}
if (name.trim().length() < 3) {
etName.setError("Invalid Name");
etName.requestFocus();
return;
}
if (TextUtils.isEmpty(phone)) {
etPhone.setError("Required");
etPhone.requestFocus();
return;
}
if (TextUtils.getTrimmedLength(phone) < 10) {
etPhone.setError("Invalid Phone");
etPhone.requestFocus();
return;
}
AdminModal request = new AdminModal();
request.setAdminEmail(email);
request.setAdminPhone(phone);
request.setAdminName(name);
request.setAdminType("2");
request.setAdminPassword(phone);
progressBar.setVisibility(View.VISIBLE);
btnSubmit.setVisibility(View.GONE);
ApiClient.getClient().addAdmin(request).enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (response.isSuccessful()) {
if (response.body().getSuccess()) {
Toast.makeText(AddAdminActivity.this, "Account Successfully Created", Toast.LENGTH_LONG).show();
onBackPressed();
} else {
Toast.makeText(AddAdminActivity.this, response.body().getError(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
btnSubmit.setVisibility(View.VISIBLE);
}
}
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
t.printStackTrace();
Toast.makeText(AddAdminActivity.this, "Internet Not Available", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
btnSubmit.setVisibility(View.VISIBLE);
}
});
}
@Override
public void onBackPressed() {
finish();
overridePendingTransition(R.anim.right_in, R.anim.right_out);
}
}
| 33.230159
| 120
| 0.624552
|
85574a0858f3dc357c65c7f3f97ca67e6243f939
| 4,333
|
/*
* Copyright (c) 2015-2022 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Attribution Notice under the terms of the Apache License 2.0
*
* This work was created by the collective efforts of the openCypher community.
* Without limiting the terms of Section 6, any Derivative Work that is not
* approved by the public consensus process of the openCypher Implementers Group
* should not be described as “Cypher” (and Cypher® is a registered trademark of
* Neo4j Inc.) or as "openCypher". Extensions by implementers or prototypes or
* proposals for change that have been documented or implemented should only be
* described as "implementation extensions to Cypher" or as "proposed changes to
* Cypher that are not yet approved by the openCypher community".
*/
package org.opencypher.tools.tck.reporting.cucumber;
import io.cucumber.plugin.event.Event;
import io.cucumber.plugin.event.SnippetsSuggestedEvent;
import io.cucumber.plugin.event.StepDefinedEvent;
import io.cucumber.plugin.event.TestCaseEvent;
import io.cucumber.plugin.event.TestRunFinished;
import io.cucumber.plugin.event.TestRunStarted;
import io.cucumber.plugin.event.TestSourceRead;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
class CanonicalEventOrder implements Comparator<Event> {
private static final CanonicalEventOrder.FixedEventOrderComparator fixedOrder = new CanonicalEventOrder.FixedEventOrderComparator();
private static final CanonicalEventOrder.TestCaseEventComparator testCaseOrder = new CanonicalEventOrder.TestCaseEventComparator();
CanonicalEventOrder() {
}
public int compare(Event a, Event b) {
int fixedOrder = CanonicalEventOrder.fixedOrder.compare(a, b);
if (fixedOrder != 0) {
return fixedOrder;
} else {
return a instanceof TestCaseEvent && b instanceof TestCaseEvent ? testCaseOrder.compare((TestCaseEvent)a, (TestCaseEvent)b) : fixedOrder;
}
}
private static final class TestCaseEventComparator implements Comparator<TestCaseEvent> {
private TestCaseEventComparator() {
}
public int compare(TestCaseEvent a, TestCaseEvent b) {
int uri = a.getTestCase().getUri().compareTo(b.getTestCase().getUri());
if (uri != 0) {
return uri;
} else {
int line = Integer.compare(a.getTestCase().getLine(), b.getTestCase().getLine());
return line != 0 ? line : a.getInstant().compareTo(b.getInstant());
}
}
}
private static final class FixedEventOrderComparator implements Comparator<Event> {
private final List<Class<? extends Event>> fixedOrder;
private FixedEventOrderComparator() {
this.fixedOrder = Arrays.asList(TestRunStarted.class, TestSourceRead.class, SnippetsSuggestedEvent.class, StepDefinedEvent.class, TestCaseEvent.class, TestRunFinished.class);
}
public int compare(Event a, Event b) {
return Integer.compare(this.requireInFixOrder(a.getClass()), this.requireInFixOrder(b.getClass()));
}
private int requireInFixOrder(Class<? extends Event> o) {
int index = this.findInFixedOrder(o);
if (index < 0) {
throw new IllegalStateException(o + " was not in " + this.fixedOrder);
} else {
return index;
}
}
private int findInFixedOrder(Class<? extends Event> o) {
for(int i = 0; i < this.fixedOrder.size(); ++i) {
if (((Class)this.fixedOrder.get(i)).isAssignableFrom(o)) {
return i;
}
}
return -1;
}
}
}
| 42.067961
| 186
| 0.68636
|
31f0145967fcca3d5c0c6672f1d1160cf0f9a5ff
| 10,266
|
package io.cucumber.core.options;
import gherkin.GherkinDialect;
import gherkin.GherkinDialectProvider;
import gherkin.IGherkinDialectProvider;
import io.cucumber.core.exception.CucumberException;
import io.cucumber.core.feature.FeatureWithLines;
import io.cucumber.core.feature.GluePath;
import io.cucumber.datatable.DataTable;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static io.cucumber.core.options.ObjectFactoryParser.parseObjectFactory;
import static io.cucumber.core.options.OptionsFileParser.parseFeatureWithLinesFile;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.joining;
final class RuntimeOptionsParser {
static final String VERSION = ResourceBundle.getBundle("io.cucumber.core.version").getString("cucumber-jvm.version");
// IMPORTANT! Make sure USAGE.txt is always uptodate if this class changes.
private static final String USAGE_RESOURCE = "/io/cucumber/core/options/USAGE.txt";
static String usageText;
RuntimeOptionsParser() {
}
private static void printUsage() {
loadUsageTextIfNeeded();
System.out.println(usageText);
}
static void loadUsageTextIfNeeded() {
if (usageText == null) {
InputStream usageResourceStream = RuntimeOptionsParser.class.getResourceAsStream(USAGE_RESOURCE);
try (BufferedReader br = new BufferedReader(new InputStreamReader(usageResourceStream, UTF_8))) {
usageText = br.lines().collect(joining(System.lineSeparator()));
} catch (Exception e) {
usageText = "Could not load usage text: " + e.toString();
}
}
}
private static int printI18n(String language) {
IGherkinDialectProvider dialectProvider = new GherkinDialectProvider();
List<String> languages = dialectProvider.getLanguages();
if (language.equalsIgnoreCase("help")) {
if (language.equalsIgnoreCase("help")) {
List<GherkinDialect> dialects = new ArrayList<>();
for (String code : languages) {
GherkinDialect dialect = dialectProvider.getDialect(code, null);
dialects.add(dialect);
}
int widestLanguage = findWidest(dialects, GherkinDialect::getLanguage);
int widestName = findWidest(dialects, GherkinDialect::getName);
int widestNativeName = findWidest(dialects, GherkinDialect::getNativeName);
for (GherkinDialect dialect : dialects) {
printDialect(dialect, widestLanguage, widestName, widestNativeName);
}
return 0;
}
}
if (languages.contains(language)) {
return printKeywordsFor(dialectProvider.getDialect(language, null));
}
System.err.println("Unrecognised ISO language code");
return 1;
}
private static int findWidest(List<GherkinDialect> dialects, Function<GherkinDialect, String> getNativeName) {
return dialects.stream()
.map(getNativeName)
.mapToInt(String::length)
.max()
.orElse(0);
}
private static int printKeywordsFor(GherkinDialect dialect) {
StringBuilder builder = new StringBuilder();
List<List<String>> table = new ArrayList<>();
addKeywordRow(table, "feature", dialect.getFeatureKeywords());
addKeywordRow(table, "background", dialect.getBackgroundKeywords());
addKeywordRow(table, "scenario", dialect.getScenarioKeywords());
addKeywordRow(table, "scenario outline", dialect.getScenarioOutlineKeywords());
addKeywordRow(table, "examples", dialect.getExamplesKeywords());
addKeywordRow(table, "given", dialect.getGivenKeywords());
addKeywordRow(table, "when", dialect.getWhenKeywords());
addKeywordRow(table, "then", dialect.getThenKeywords());
addKeywordRow(table, "and", dialect.getAndKeywords());
addKeywordRow(table, "but", dialect.getButKeywords());
addCodeKeywordRow(table, "given", dialect.getGivenKeywords());
addCodeKeywordRow(table, "when", dialect.getWhenKeywords());
addCodeKeywordRow(table, "then", dialect.getThenKeywords());
addCodeKeywordRow(table, "and", dialect.getAndKeywords());
addCodeKeywordRow(table, "but", dialect.getButKeywords());
DataTable.create(table).print(builder);
System.out.println(builder.toString());
return 0;
}
private static void addCodeKeywordRow(List<List<String>> table, String key, List<String> keywords) {
List<String> codeKeywordList = new ArrayList<>(keywords);
codeKeywordList.remove("* ");
List<String> codeWords = codeKeywordList.stream()
.map(keyword -> keyword.replaceAll("[\\s',!]", ""))
.collect(Collectors.toList());
addKeywordRow(table, key + " (code)", codeWords);
}
private static void addKeywordRow(List<List<String>> table, String key, List<String> keywords) {
table.add(asList(key, keywords.stream().map(o -> '"' + o + '"').collect(joining(", "))));
}
private static void printDialect(GherkinDialect dialect, int widestLanguage, int widestName, int widestNativeName) {
String langCode = rightPad(dialect.getLanguage(), widestLanguage);
String name = rightPad(dialect.getName(), widestName);
String nativeName = rightPad(dialect.getNativeName(), widestNativeName);
System.out.println(langCode + name + nativeName);
}
private static String rightPad(String text, int maxWidth) {
int padding = 7;
int width = maxWidth + padding;
return String.format("%" + -width + "s", text);
}
RuntimeOptionsBuilder parse(List<String> args) {
args = new ArrayList<>(args);
RuntimeOptionsBuilder parsedOptions = new RuntimeOptionsBuilder();
while (!args.isEmpty()) {
String arg = args.remove(0).trim();
if (arg.equals("--help") || arg.equals("-h")) {
printUsage();
System.exit(0);
} else if (arg.equals("--version") || arg.equals("-v")) {
System.out.println(VERSION);
System.exit(0);
} else if (arg.equals("--i18n")) {
String nextArg = removeArgFor(arg, args);
System.exit(printI18n(nextArg));
} else if (arg.equals("--threads")) {
int threads = Integer.parseInt(removeArgFor(arg, args));
if (threads < 1) {
throw new CucumberException("--threads must be > 0");
}
parsedOptions.setThreads(threads);
} else if (arg.equals("--glue") || arg.equals("-g")) {
String gluePath = removeArgFor(arg, args);
URI parse = GluePath.parse(gluePath);
parsedOptions.addGlue(parse);
} else if (arg.equals("--tags") || arg.equals("-t")) {
parsedOptions.addTagFilter(removeArgFor(arg, args));
} else if (arg.equals("--plugin") || arg.equals("--add-plugin") || arg.equals("-p")) {
parsedOptions.addPluginName(removeArgFor(arg, args), arg.equals("--add-plugin"));
} else if (arg.equals("--no-dry-run") || arg.equals("--dry-run") || arg.equals("-d")) {
parsedOptions.setDryRun(!arg.startsWith("--no-"));
} else if (arg.equals("--no-strict") || arg.equals("--strict") || arg.equals("-s")) {
parsedOptions.setStrict(!arg.startsWith("--no-"));
} else if (arg.equals("--no-monochrome") || arg.equals("--monochrome") || arg.equals("-m")) {
parsedOptions.setMonochrome(!arg.startsWith("--no-"));
} else if (arg.equals("--snippets")) {
String nextArg = removeArgFor(arg, args);
parsedOptions.setSnippetType(SnippetTypeParser.parseSnippetType(nextArg));
} else if (arg.equals("--name") || arg.equals("-n")) {
String nextArg = removeArgFor(arg, args);
Pattern pattern = Pattern.compile(nextArg);
parsedOptions.addNameFilter(pattern);
} else if (arg.equals("--wip") || arg.equals("-w")) {
parsedOptions.setWip(true);
} else if (arg.equals("--order")) {
parsedOptions.setPickleOrder(PickleOrderParser.parse(removeArgFor(arg, args)));
} else if (arg.equals("--count")) {
int count = Integer.parseInt(removeArgFor(arg, args));
if (count < 1) {
throw new CucumberException("--count must be > 0");
}
parsedOptions.setCount(count);
} else if (arg.equals("--object-factory")) {
String objectFactoryClassName = removeArgFor(arg, args);
parsedOptions.setObjectFactoryClass(parseObjectFactory(objectFactoryClassName));
} else if (arg.startsWith("-")) {
printUsage();
throw new CucumberException("Unknown option: " + arg);
} else if (!arg.isEmpty()) {
if (arg.startsWith("@")) {
Path rerunFile = Paths.get(arg.substring(1));
parsedOptions.addRerun(parseFeatureWithLinesFile(rerunFile));
} else {
FeatureWithLines featureWithLines = FeatureWithLines.parse(arg);
parsedOptions.addFeature(featureWithLines);
}
}
}
return parsedOptions;
}
private String removeArgFor(String arg, List<String> args) {
if (!args.isEmpty()) {
return args.remove(0);
}
printUsage();
throw new CucumberException("Missing argument for " + arg);
}
}
| 44.829694
| 121
| 0.616598
|
cf33f2ac8d6aba96e3c419e0fa309c644d5c06a0
| 1,244
|
package com.zhiyu.config.constant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author wengzhiyu
* @date 2020/01/07
*/
@Component
public class Constants {
/**
* header字段
*/
public static final String TOKEN_HEADER = "Authorization";
public static final String TOKEN_PREFIX = "Bearer ";
@Value("${custom.jwt.secret-key}")
public void setJwtSecretKey(String jwtSecretKey) {
JWT_SECRET_KEY = jwtSecretKey;
}
/**
* SECRET
*/
public static String JWT_SECRET_KEY ;
/**
* 后台登录令牌
*/
public static final String LOGIN_TOKEN = "login_token:";
/**
* 后台登录用户
*/
public static final String LOGIN_USER = "login_user:";
/**
* 并发控制key
*/
public static final String KICK_OUT_LOGIN = "kick_out_login:";
/**
* 并发登陆key
*/
public static final String KICK_OUT_SIGN= "kick_out_sign:";
/**
* 登陆用户分布式锁
*/
public static final String LOGIN_LOCK = "login_lock:";
/**
* 返回登录令牌
*/
public static final String TOKEN = "token";
/**
* session 过期时间
*/
public static final Long SESSION_TIMEOUT = 60L;
}
| 17.521127
| 66
| 0.610932
|
58fef09f58af891c17bb8477533376927e98bec2
| 2,397
|
package jp.terasoluna.batch.honoka.dto;
import jp.terasoluna.fw.file.annotation.FileFormat;
import jp.terasoluna.fw.file.annotation.InputFileColumn;
import jp.terasoluna.fw.file.annotation.OutputFileColumn;
@FileFormat(overWriteFlg = true, fileEncoding = "MS932")
public class ProgramData {
/**
* 番組ID
*/
@InputFileColumn(columnIndex = 0)
@OutputFileColumn(columnIndex = 0)
private int program_id;
/**
* タイトルID
*/
@InputFileColumn(columnIndex = 1)
@OutputFileColumn(columnIndex = 1)
private int title_id;
/**
* サブタイトル
*/
@InputFileColumn(columnIndex = 2)
@OutputFileColumn(columnIndex = 2)
private String subtitle;
/**
* 放送回
*/
@InputFileColumn(columnIndex = 3)
@OutputFileColumn(columnIndex = 3)
private String count;
/**
* 放送チャンネル
*/
@InputFileColumn(columnIndex = 4)
@OutputFileColumn(columnIndex = 4)
private int ch_id;
/**
* 録画開始時間
*/
@InputFileColumn(columnIndex = 5)
@OutputFileColumn(columnIndex = 5)
private String start_time;
/**
* 録画終了時間
*/
@InputFileColumn(columnIndex = 6)
@OutputFileColumn(columnIndex = 6)
private String end_time;
/**
* 論理削除フラグ
*/
@InputFileColumn(columnIndex = 7)
@OutputFileColumn(columnIndex = 7)
private String delete_flag;
public int getProgram_id() {
return program_id;
}
public void setProgram_id(int program_id) {
this.program_id = program_id;
}
public int getTitle_id() {
return title_id;
}
public void setTitle_id(int title_id) {
this.title_id = title_id;
}
public String getSubtitle() {
return subtitle;
}
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public int getCh_id() {
return ch_id;
}
public void setCh_id(int ch_id) {
this.ch_id = ch_id;
}
public String getStart_time() {
return start_time;
}
public void setStart_time(String start_time) {
this.start_time = start_time;
}
public String getEnd_time() {
return end_time;
}
public void setEnd_time(String end_time) {
this.end_time = end_time;
}
public String getDelete_flag() {
return delete_flag;
}
public void setDelete_flag(String delete_flag) {
this.delete_flag = delete_flag;
}
}
| 18.159091
| 58
| 0.671673
|
1ea1bf7f33f2eaf59934923a4c87b4789f81e24d
| 210
|
public class Siamese extends Cat{
private double earSize;
public Siamese(String name, double earSize) {
super(name);
this.earSize = earSize;
}
public double getEarSize() {
return earSize;
}
}
| 13.125
| 46
| 0.695238
|
6e2aaa7309457cce24817e53ce4a855470321319
| 10,237
|
/**
* Copyright (c) 2014 Virtue Studios
*
* 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.virtue.utility.text;
import java.nio.ByteBuffer;
import org.virtue.config.util.TextConvert;
import org.virtue.network.event.buffer.InboundBuffer;
import org.virtue.network.event.buffer.OutboundBuffer;
/**
* @author Im Frizzy <skype:kfriz1998>
* @since Oct 20, 2014
*/
public class Huffman {
static Huffman huffman;
public static void setHuffman(Huffman huffman) {
Huffman.huffman = huffman;
}
/**
* Compresses the specified chat message and packs it into the stream, using the huffman codec
* @param stream The stream to pack the message into
* @param message The message to pack
* @return The size of the encrypted message
*/
public static int compress(OutboundBuffer buffer, String message) {
int offset = buffer.offset();
byte[] msgData = TextConvert.encodeCp1252(message);
buffer.putSmartS(msgData.length);
buffer.checkPosition(buffer.offset() + msgData.length*2);//Eh, there's not really any easier way...
//System.out.println("Checking position: "+(buffer.offset() + msgData.length)+", strlen="+message.length()+", blen="+msgData.length);
buffer.offset(huffman.encode(msgData, 0, msgData.length,
buffer.buffer(), buffer.offset()) + buffer.offset());
//System.out.println("Encoded size="+(buffer.offset() - offset));
return buffer.offset() - offset;
}
/**
* Decompresses the chat message contained within the specified stream, using the huffman codec
* @param stream The stream containing the chat message
* @return The decrypted message
*/
public static String decompress(InboundBuffer stream) {
return decompress(stream, 32767);
}
/**
* Decompresses the chat message contained within the specified stream, using the huffman codec
* @param stream The stream containing the chat message
* @param maxSize The maximum size for the decrypted message
* @return The decrypted message
*/
public static String decompress(InboundBuffer buffer, int maxlen) {
String message;
try {
int decompressedSize = buffer.getSmartS();
if (decompressedSize > maxlen) {
decompressedSize = maxlen;
}
byte[] decompressed = new byte[decompressedSize];
buffer.offset(huffman.decode(buffer.buffer(),
buffer.offset(), decompressed, 0, decompressedSize) + buffer.offset());
message = TextConvert.decodeCp1252(decompressed, 0, decompressedSize);
} catch (Exception exception) {
return "Cabbage";
}
return message;
}
int[] huffmanAlgorithm3;
int[] huffmanAlgorithm1;
byte[] huffmanAlgorithm2;
int encode(byte[] messageData, int messageDataOffset, int messageDataLength,
byte[] streamBuffer, int streamOffset) {
int i_11_ = 0;
int i_12_ = streamOffset << 3;
for (messageDataLength += messageDataOffset; messageDataOffset < messageDataLength; messageDataOffset++) {
int value = messageData[messageDataOffset] & 0xff;
int codeword = huffmanAlgorithm1[value];
int codewordSize = huffmanAlgorithm2[value];
if (0 == codeword) {
throw new RuntimeException(new StringBuilder().append("No codeword for data value: ").append(value).toString());
}
int streamPointer = i_12_ >> 3;
int i_17_ = i_12_ & 0x7;
i_11_ &= -i_17_ >> 31;
int i_18_ = (codewordSize + i_17_ - 1 >> 3) + streamPointer;
i_17_ += 24;
streamBuffer[streamPointer] = (byte) (i_11_ |= codeword >>> i_17_);
if (streamPointer < i_18_) {
streamPointer++;
i_17_ -= 8;
streamBuffer[streamPointer] = (byte) (i_11_ = codeword >>> i_17_);
if (streamPointer < i_18_) {
streamPointer++;
i_17_ -= 8;
streamBuffer[streamPointer] = (byte) (i_11_ = codeword >>> i_17_);
if (streamPointer < i_18_) {
streamPointer++;
i_17_ -= 8;
streamBuffer[streamPointer] = (byte) (i_11_ = codeword >>> i_17_);
if (streamPointer < i_18_) {
streamPointer++;
i_17_ -= 8;
streamBuffer[streamPointer] = (byte) (i_11_ = codeword << -i_17_);
}
}
}
}
i_12_ += codewordSize;
}
return (7 + i_12_ >> 3) - streamOffset;
}
int decode(byte[] compressed, int streamOffset, byte[] decompressed,
int messageDataOffset, int decodedSize) {
if (decodedSize == 0) {
return 0;
}
int pointer = 0;
decodedSize += messageDataOffset;
int outputSize = streamOffset;
for (;;) {
byte codeword = compressed[outputSize];
if (codeword < 0) {
pointer = huffmanAlgorithm3[pointer];
} else {
pointer++;
}
int value;
if ((value = huffmanAlgorithm3[pointer]) < 0) {
decompressed[messageDataOffset++] = (byte) (value ^ 0xffffffff);
if (messageDataOffset >= decodedSize) {
break;
}
pointer = 0;
}
if (0 != (codeword & 0x40)) {
pointer = huffmanAlgorithm3[pointer];
} else {
pointer++;
}
if ((value = huffmanAlgorithm3[pointer]) < 0) {
decompressed[messageDataOffset++] = (byte) (value ^ 0xffffffff);
if (messageDataOffset >= decodedSize) {
break;
}
pointer = 0;
}
if ((codeword & 0x20) != 0) {
pointer = huffmanAlgorithm3[pointer];
} else {
pointer++;
}
if ((value = huffmanAlgorithm3[pointer]) < 0) {
decompressed[messageDataOffset++] = (byte) (value ^ 0xffffffff);
if (messageDataOffset >= decodedSize) {
break;
}
pointer = 0;
}
if (0 != (codeword & 0x10)) {
pointer = huffmanAlgorithm3[pointer];
} else {
pointer++;
}
if ((value = huffmanAlgorithm3[pointer]) < 0) {
decompressed[messageDataOffset++] = (byte) (value ^ 0xffffffff);
if (messageDataOffset >= decodedSize) {
break;
}
pointer = 0;
}
if (0 != (codeword & 0x8)) {
pointer = huffmanAlgorithm3[pointer];
} else {
pointer++;
}
if ((value = huffmanAlgorithm3[pointer]) < 0) {
decompressed[messageDataOffset++] = (byte) (value ^ 0xffffffff);
if (messageDataOffset >= decodedSize) {
break;
}
pointer = 0;
}
if (0 != (codeword & 0x4)) {
pointer = huffmanAlgorithm3[pointer];
} else {
pointer++;
}
if ((value = huffmanAlgorithm3[pointer]) < 0) {
decompressed[messageDataOffset++] = (byte) (value ^ 0xffffffff);
if (messageDataOffset >= decodedSize) {
break;
}
pointer = 0;
}
if (0 != (codeword & 0x2)) {
pointer = huffmanAlgorithm3[pointer];
} else {
pointer++;
}
if ((value = huffmanAlgorithm3[pointer]) < 0) {
decompressed[messageDataOffset++] = (byte) (value ^ 0xffffffff);
if (messageDataOffset >= decodedSize) {
break;
}
pointer = 0;
}
if ((codeword & 0x1) != 0) {
pointer = huffmanAlgorithm3[pointer];
} else {
pointer++;
}
if ((value = huffmanAlgorithm3[pointer]) < 0) {
decompressed[messageDataOffset++] = (byte) (value ^ 0xffffffff);
if (messageDataOffset >= decodedSize) {
break;
}
pointer = 0;
}
outputSize++;
}
return 1 + outputSize - streamOffset;
}
public Huffman(ByteBuffer buffer) {
byte[] data = new byte[buffer.capacity()];
buffer.get(data);
int i = data.length;
huffmanAlgorithm1 = new int[i];
huffmanAlgorithm2 = data;
int[] is_49_ = new int[33];
huffmanAlgorithm3 = new int[8];
int i_50_ = 0;
for (int i_51_ = 0; i_51_ < i; i_51_++) {
int i_52_ = data[i_51_];
if (i_52_ != 0) {
int i_53_ = 1 << 32 - i_52_;
int i_54_ = is_49_[i_52_];
huffmanAlgorithm1[i_51_] = i_54_;
int i_55_;
if ((i_54_ & i_53_) != 0) {
i_55_ = is_49_[i_52_ - 1];
} else {
i_55_ = i_54_ | i_53_;
for (int i_56_ = i_52_ - 1; i_56_ >= 1; i_56_--) {
int i_57_ = is_49_[i_56_];
if (i_54_ != i_57_) {
break;
}
int i_58_ = 1 << 32 - i_56_;
if ((i_57_ & i_58_) != 0) {
is_49_[i_56_] = is_49_[i_56_ - 1];
break;
}
is_49_[i_56_] = i_57_ | i_58_;
}
}
is_49_[i_52_] = i_55_;
for (int i_59_ = i_52_ + 1; i_59_ <= 32; i_59_++) {
if (is_49_[i_59_] == i_54_) {
is_49_[i_59_] = i_55_;
}
}
int i_60_ = 0;
for (int i_61_ = 0; i_61_ < i_52_; i_61_++) {
int i_62_ = -2147483648 >>> i_61_;
if (0 != (i_54_ & i_62_)) {
if (huffmanAlgorithm3[i_60_] == 0) {
huffmanAlgorithm3[i_60_] = i_50_;
}
i_60_ = huffmanAlgorithm3[i_60_];
} else {
i_60_++;
}
if (i_60_ >= huffmanAlgorithm3.length) {
int[] is_63_ = new int[2 * huffmanAlgorithm3.length];
for (int i_64_ = 0; i_64_ < huffmanAlgorithm3.length; i_64_++) {
is_63_[i_64_] = huffmanAlgorithm3[i_64_];
}
huffmanAlgorithm3 = is_63_;
}
i_62_ >>>= 1;
}
huffmanAlgorithm3[i_60_] = i_51_ ^ 0xffffffff;
if (i_60_ >= i_50_) {
i_50_ = i_60_ + 1;
}
}
}
}
}
| 32.39557
| 135
| 0.613949
|
add9fdc45dfad303c79bda1f890a2439faab61f4
| 491
|
package com.github.lwhite1.tablesaw.api.plot;
import com.github.lwhite1.tablesaw.api.Table;
/**
* Basic sample box plot. It shows the distribution of the number of people injured in tornadoes, broken out
* by the scale of the Tornado.
*/
public class BoxExample {
public static void main(String[] args) throws Exception {
Table table = Table.createFromCsv("data/tornadoes_1950-2014.csv");
Box.show("Tornado Injuries by Scale", table, "injuries", "scale");
}
}
| 28.882353
| 108
| 0.712831
|
02052678014c492c3bc7a04f991d6415ec9f9bbb
| 1,835
|
/*
*
* This file is automatically generated on Mon Aug 07 14:08:46 CST 2017
*/
package org.shaolin.bmdp.persistence.be2;
import org.shaolin.bmdp.runtime.be.IExtensibleEntity;
import org.shaolin.bmdp.runtime.be.IPersistentEntity;
/**
* null
*
* This code is generated automatically, any change will be replaced after rebuild.
*
*
*/
public interface IOrganization
extends IPersistentEntity, IExtensibleEntity
{
public final static String ENTITY_NAME = "org.shaolin.vogerp.commonmodel.be.Organization";
/**
* get parentId
*
* @return parentId
*/
public long getParentId();
/**
* get orgCode
*
* @return orgCode
*/
public java.lang.String getOrgCode();
/**
* get name
*
* @return name
*/
public java.lang.String getName();
/**
* get description
*
* @return description
*/
public java.lang.String getDescription();
/**
* get addressId
*
* @return addressId
*/
public long getAddressId();
/**
* get verifierId
*
* @return verifierId
*/
public long getVerifierId();
/**
* set parentId
*/
public void setParentId(long parentId);
/**
* set orgCode
*/
public void setOrgCode(java.lang.String orgCode);
/**
* set name
*/
public void setName(java.lang.String name);
/**
* set description
*/
public void setDescription(java.lang.String description);
/**
* set addressId
*/
public void setAddressId(long addressId);
/**
* set verifierId
*/
public void setVerifierId(long verifierId);
}
| 17.990196
| 95
| 0.546594
|
bef4cac5a4d7b536c8d54cc5fd50d78440cbab48
| 490
|
package de.skuzzle.ghpromexporter.scrape;
/**
* Raw results of a single repository scrape.
*
* @author Simon Taddiken
*/
public record ScrapeResult(
long totalAdditions,
long totalDeletions,
int commitsToMainBranch,
int stargazersCount,
int forkCount,
int openIssueCount,
int subscriberCount,
int watchersCount,
int sizeInKb,
/* Note: this field must always occur last */
long scrapeDuration) {}
| 23.333333
| 53
| 0.640816
|
df524460be0872937058de06ffd7f546956a7b78
| 192
|
package org.jplus.osgi.loader.handler;
/**
* 资源被加载后的处理
* Created by hyberbin on 15/11/14.
*/
public interface ResourceLoadedHandler {
void loadedResource(String name,byte[] bytes);
}
| 17.454545
| 50
| 0.723958
|
b8f3807616712740a18b7432900f4e61f7e1d003
| 1,971
|
package com.project.fileparser.utils;
import com.project.fileparser.modal.RegexComment;
public class RegexProvider {
public static final String REGEX_BLOCK_COMMENT_START = "(([^\"//]*\"[^\"//]*\")*[^\"]*)(\\/\\*.*)";
public static final String REGEX_BLOCK_COMMENT_END = "(([^\"//]*\"[^\"//]*\")*[^\"]*)(\\*\\/)(.*)";
public static final String REGEX_SINGLE_LINE_COMMENT = "(([^\"]*\"[^\"]*\")*[^\"]*)(//.*)";
//php line comment
public static final String PHP_REGEX_SINGLE_LINE_COMMENT = "(([^\"(?://|#)]*\"[^\"(?://|#)]*\")*[^\"(?://|#)]*)((?://|#).*)";
// python comment
public static final String PYTHON_REGEX_BLOCK_COMMENT_START = "(([^\"#]*\"[^\"#]*\")*[^\"#]*)(\"\"\".*)";
public static final String PYTHON_REGEX_BLOCK_COMMENT_END = "(([^\"#]*\"[^\"#]*\")*[^\"#]*)(\"\"\")(.*)";
public static final String PYTHON_REGEX_SINGLE_LINE_COMMENT = "(([^\"]*\"[^\"]*\")*[^\"]*)(#.*)";
public static RegexComment getRegex(String extension) {
if (extension == null) {
return null;
}
if (extension.equals(FileType.JAVA) || extension.equals(FileType.CPP) || extension.equals(FileType.C)
|| extension.equals(FileType.JAVASCRIPT)) {
return new RegexComment(REGEX_SINGLE_LINE_COMMENT,
REGEX_BLOCK_COMMENT_START,
REGEX_BLOCK_COMMENT_END);
}
else if (extension.equals(FileType.PHP)) {
return new RegexComment(PHP_REGEX_SINGLE_LINE_COMMENT,
REGEX_BLOCK_COMMENT_START,
REGEX_BLOCK_COMMENT_END);
}
else if (extension.equals(FileType.PYTHON)) {
return new RegexComment(PYTHON_REGEX_SINGLE_LINE_COMMENT,
PYTHON_REGEX_BLOCK_COMMENT_START,
PYTHON_REGEX_BLOCK_COMMENT_END);
}
return null;
}
}
| 46.928571
| 129
| 0.533232
|
f4b3086c9ee4393abcfd877bb74780a3b821f00f
| 20,588
|
package com.bjghhnt.app.treatmentdevice.activities;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.view.ContextThemeWrapper;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.bjghhnt.app.treatmentdevice.BuildConfig;
import com.bjghhnt.app.treatmentdevice.R;
import com.bjghhnt.app.treatmentdevice.TreatmentApplication;
import com.bjghhnt.app.treatmentdevice.utils.Channels;
import com.bjghhnt.app.treatmentdevice.utils.serials.ComplexHandler;
import com.bjghhnt.app.treatmentdevice.utils.serials.SerialFrame;
import com.bjghhnt.app.treatmentdevice.utils.serials.SerialHandler;
import com.bjghhnt.app.treatmentdevice.views.TreatingMeterView;
import com.orhanobut.logger.Logger;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
import android_serialport_api.SerialPort;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.carbswang.android.numberpickerview.library.NumberPickerView;
/**
* 每路对应的治疗设置界面
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class MeterSetActivity extends MinorActivity implements
NumberPicker.OnValueChangeListener, SharedPreferences.OnSharedPreferenceChangeListener,
NumberPickerView.OnValueChangeListener{
@BindView(R.id.btn_meter_set_plus)
Button btnMeterSetPlus;
@BindView(R.id.btn_meter_final_confirm)
Button btnMeterFinalConfirm;
@BindView(R.id.btn_add)
Button mBtnAdd;
@BindView(R.id.btn_minus)
Button mBtnMinus;
@BindView(R.id.linear_layout_settings)
LinearLayout mLinearLayout;
@BindView(R.id.custom_view_in_settings)
TreatingMeterView mChnView;
@BindView(R.id.numPicker_meter_hr)
NumberPickerView mNumberPickerHr;
@BindView(R.id.numPicker_meter_min)
NumberPickerView mNumberPickerMin;
@BindView(R.id.btn_meter_settings_reset)
Button mButtonReset;
@BindView(R.id.btn_meter_settings_confirm_time)
ToggleButton mToggleButtonConfirmTime;
@BindView(R.id.linear_layout_level_setter)
View mViewLevelSetter;
@BindView(R.id.text_meter_set_level)
TextView mTextViewLevel;
@BindView(R.id.tv_time)
TextView tvTimeMeterSet;
private static final String TAG = "MeterSetActivity";
private final ComplexHandler mComplexHandler = new SingleMeterHandler(this);
// private SerialConnectable mSerialPort;
private static boolean mUseKnob;
private int mChannelSelected;
private int mLevelToSet;
private int mSessionTime = -1;
private static SharedPreferences mSharedPreferences;
// private SerialportControler serialportControler;
//test
private OutputStream outputStream;
private InputStream inputStream;
private SerialPort mSerialPort1;
private AlertDialog alertDialog;
//更新时间
@Override
protected void upDateTime() {
tvTimeMeterSet.setText(formatTime);
// Logger.d("time_FullPanel:" + tvTimeMeterSet.getText());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meter_set);
ButterKnife.bind(this);
mSharedPreferences = TreatmentApplication.getSharedPreferences();
mUseKnob = mSharedPreferences.getBoolean(Channels.KEY_ALL_USE_KNOB, false);
}
@Override
protected void onStart() {
super.onStart();
init();
mSharedPreferences.registerOnSharedPreferenceChangeListener(this);
if (mLinearLayout.getVisibility() == View.GONE) {
mLevelToSet = mSharedPreferences.getInt("STRONG_STATUE", 0);
System.out.println(mLevelToSet);
}
}
@Override
protected SerialHandler setHandler() {
return mComplexHandler;
}
@Override
protected void onStop() {
super.onStop();
// Unregister the listener, otherwise OnSharedPreferenceChanged() may be invoked,
// while a finished instance of MeterSetActivity is not GCed.
mSharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
}
private void init() {
Bundle extras = getIntent().getExtras();
mChannelSelected = (int) extras.get(Channels.INTENT_KEY_CHANNEL_NUMBER);
mChnView.setChanelNo(mChannelSelected);
mNumberPickerHr.setDisplayedValues(new String[]{"0", "1", "2", "3"});
mNumberPickerHr.setMinValue(Channels.CHN_MIN_VALUE_OF_EVERYTHING);
mNumberPickerHr.setMaxValue(Channels.CHN_MAX_HRS);
// mNumberPickerHr.setValue(Channels.CHN_MIN_VALUE_OF_EVERYTHING);
mNumberPickerHr.setWrapSelectorWheel(true);
mNumberPickerHr.setOnValueChangedListener(this);
// disable manual input to the number picker
// mNumberPickerHr.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
String[] minDisplayedValues = new String[60];
for (int i = 0; i < minDisplayedValues.length; i++) {
minDisplayedValues[i] = "" + i;
}
mNumberPickerMin.setDisplayedValues(minDisplayedValues);
mNumberPickerMin.setMinValue(Channels.CHN_MIN_VALUE_OF_EVERYTHING);
mNumberPickerMin.setMaxValue(Channels.CHN_MAX_MIN);
mNumberPickerMin.setWrapSelectorWheel(true);
mNumberPickerMin.setOnValueChangedListener(this);
// set the visibilities of the settings linear layout
// if the channel is closed, the linear layout is invisible
setLayoutVisibility(!mSharedPreferences.getBoolean(
Channels.KEY_CHN_IS_OPEN_PREFIX + mChannelSelected, false), mUseKnob);
mChnView.setSessionTime(mSharedPreferences
.getInt(Channels.KEY_CHN_SESSION_TIME_PREFIX + mChannelSelected, 0));
mChnView.setLevel(mSharedPreferences
.getInt(Channels.KEY_CHN_LEVEL_PREFIX + mChannelSelected, 0));
if (mChnView.getMagnitude() != 0) {
mChnView.setRemainingTime(TreatingMeterView.REMAINING_TIME_UNAVAILABLE);
}
}
private void setLayoutVisibility(boolean isSettingWidgetsVisible, boolean useKnob) {
if (isSettingWidgetsVisible) {
mButtonReset.setVisibility(View.GONE);
mLinearLayout.setVisibility(View.VISIBLE);
mBtnAdd.setVisibility(View.GONE);
mBtnMinus.setVisibility(View.GONE);
} else {
mLinearLayout.setVisibility(View.GONE);
mButtonReset.setVisibility(View.VISIBLE);
if (!mUseKnob) {
mBtnAdd.setVisibility(View.VISIBLE);
mBtnMinus.setVisibility(View.VISIBLE);
}
}
if (useKnob) {
mViewLevelSetter.setVisibility(View.GONE);
}
}
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
switch (picker.getId()) {
case R.id.numPicker_meter_hr:
if (newVal == Channels.CHN_MAX_HRS) {
mNumberPickerMin.setMaxValue(Channels.CHN_MIN_VALUE_OF_EVERYTHING);
} else if (oldVal == Channels.CHN_MAX_HRS) {
mNumberPickerMin.setMaxValue(Channels.CHN_MAX_MIN);
}
break;
default:
break;
}
}
/**
* only do something about the display when the prefs associated with
* the channel selected is changed
**/
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// should unregister onSharedPreferenceChangedListener in onStop(),
// otherwise this method might be accidentally called
if (!key.substring(key.length() - 1).equals(String.valueOf(mChannelSelected))) {
return;
}
if (key.contains(Channels.KEY_CHN_LEVEL_PREFIX)) {
mChnView.setLevel(sharedPreferences.getInt(key, 0));
}
}
@Override
public void onValueChange(NumberPickerView picker, int oldVal, int newVal) {
switch (picker.getId()) {
case R.id.numPicker_meter_hr:
if (newVal == Channels.CHN_MAX_HRS) {
mNumberPickerMin.setMaxValue(Channels.CHN_MIN_VALUE_OF_EVERYTHING);
} else if (oldVal == Channels.CHN_MAX_HRS) {
mNumberPickerMin.setMaxValue(Channels.CHN_MAX_MIN);
}
break;
default:
break;
}
}
@OnClick({R.id.btn_add, R.id.btn_minus})
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_add:
if (mLevelToSet == Channels.CHN_MAX_LEVEL) return;
mLevelToSet++;
updateLevelForPrefsAndViewAndSendFrame(mLevelToSet);
break;
case R.id.btn_minus:
if (mLevelToSet == Channels.CHN_MIN_VALUE_OF_EVERYTHING) return;
mLevelToSet--;
updateLevelForPrefsAndViewAndSendFrame(mLevelToSet);
break;
}
}
private static class SingleMeterHandler extends ComplexHandler {
public SingleMeterHandler(MeterSetActivity activity) {
super(activity);
}
@Override
protected boolean isChannelDisplayed(int channelNo) {
return channelNo == ((MeterSetActivity) mActivity).mChannelSelected;
}
@Override
protected void onReceiveSetProgressDisplay(int frameValue, int channelNo) {
((MeterSetActivity) mActivity).mChnView.setRemainingTimeAndProgress(frameValue);
}
@Override
protected void onReceiveSetLevelDisplay(int frameValue, int channelNo) {
((MeterSetActivity) mActivity).mChnView.setLevel(frameValue);
mSharedPreferences.edit()
.putInt(Channels.KEY_CHN_LEVEL_PREFIX + channelNo, frameValue).apply();
Log.d(TAG, "onReceiveSetLevelDisplay: ");
}
@Override
protected void changeLayout() {
((MeterSetActivity) mActivity).setLayoutVisibility(true, mUseKnob);
}
@Override
protected void getPotentiometerValue(int value, int channelNo) {
}
@Override
protected void onReceiveBatteryFrame(int[] value) {
//TODO this should be populated
}
@Override
protected void getPotentiometerMode(Boolean b) {
}
}
@OnClick(R.id.btn_meter_settings_back)
void LeaveSettings() {
super.finish();
}
//重置
@OnClick(R.id.btn_meter_settings_reset)
void resetTreatment() {
// new AlertDialog.Builder(this)
// do nothing
alertDialog = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom))
.setTitle("您要终止此次疗程吗?")
.setMessage(" ")
.setNegativeButton(" 取消 ", (dialog, which) -> {
// do nothing
})
.setPositiveButton(" 终止 ", (dialog, which) -> {
resetPrefsAndViewAndSendFrame();
setLayoutVisibility(true, mUseKnob);
})
// .setIcon(android.R.drawable.ic_dialog_alert)
.setIcon(R.drawable.ic_dialog_warn)
.setCancelable(false)
.show();
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(0XEE336633);
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextSize(50);
alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(0XEE336633);
alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextSize(50);
//设置alertDialog宽高
WindowManager.LayoutParams params = alertDialog.getWindow().getAttributes();
params.width = 700;
params.height = 300;
alertDialog.getWindow().setAttributes(params);
}
@Override
protected void onPause() {
super.onPause();
mSharedPreferences.edit().putInt("STRONG_STATUE", mLevelToSet).apply();
if (alertDialog != null) {
alertDialog.cancel();
}
}
//重置操作
private void resetPrefsAndViewAndSendFrame() {
/** reset the corresponding preferences and reset the view **/
((TreatmentApplication) getApplication())
.resetPreferenceOfOneChn(mChannelSelected);
/** setRemainingTimeAndProgress needs to be done here
* don't need setSessionTime here because it is done by the OnPreferencesChangedListener**/
mChnView.setRemainingTimeAndProgress(Channels.CHN_MIN_VALUE_OF_EVERYTHING);
/** send stopping command via serialPort **/
SerialFrame.setChannelIndex(mChannelSelected);
if (BuildConfig.MIPS) {
mSerialPort.sendData(SerialFrame
.makeTimingFrameToSend(Channels.CHN_MIN_VALUE_OF_EVERYTHING), "HEX");
mSerialPort.sendData(SerialFrame
.makeLevelFrameToSend(Channels.CHN_MIN_VALUE_OF_EVERYTHING), "HEX");
} else if (BuildConfig.ROCKCHIP) {
serialportControler.sendData(SerialFrame
.makeTimingFrameToSend(Channels.CHN_MIN_VALUE_OF_EVERYTHING), "HEX");
serialportControler.sendData(SerialFrame
.makeLevelFrameToSend(Channels.CHN_MIN_VALUE_OF_EVERYTHING), "HEX");
}
System.out.println(SerialFrame
.makeTimingFrameToSend(Channels.CHN_MIN_VALUE_OF_EVERYTHING));
/** TODO the dummy serial port is faulty, it keeps counting down for 2 minutes
after this button is clicked
**/
}
/**
* 向串口发送数据
*
* @param level
*/
private void updateLevelForPrefsAndViewAndSendFrame(int level) {
/** reset the corresponding preferences and reset the view **/
mSharedPreferences.edit()
.putInt(Channels.KEY_CHN_LEVEL_PREFIX + mChannelSelected, level)
.apply();
/** update the level to display in the meter **/
mChnView.setLevel(level);
/** send stopping command via serialPort **/
SerialFrame.setChannelIndex(mChannelSelected);
if (BuildConfig.MIPS) {
mSerialPort.sendData(SerialFrame.makeLevelFrameToSend(level), "HEX");
} else if (BuildConfig.ROCKCHIP) {
serialportControler.sendData(SerialFrame.makeLevelFrameToSend(level), "HEX");
Logger.d(level + "-----" + SerialFrame.makeLevelFrameToSend(level));
}
// Toast.makeText(this, "发送到串口前的数据::"+SerialFrame.makeLevelFrameToSend(level), Toast.LENGTH_SHORT).show();
System.out.println(level + ":yykk-----发送的数据::" + SerialFrame.makeLevelFrameToSend(level));
}
private void responseToToggleBtn(Boolean isChecked) {
mToggleButtonConfirmTime.setText((isChecked) ? "停止" : "开始");
mNumberPickerMin.setEnabled(!isChecked);
mNumberPickerHr.setEnabled(!isChecked);
//TODO there is a redundant View.INVISIBLE or GONE somewhere added today
mViewLevelSetter.setVisibility((isChecked && !mUseKnob) ? View.VISIBLE : View.INVISIBLE);
}
//开始or停止
@OnClick(R.id.btn_meter_settings_confirm_time)
void confirmTime() {
if (mToggleButtonConfirmTime.isChecked()) {
int sessionTime = mNumberPickerHr.getValue() * 60 + mNumberPickerMin.getValue();
// if sessionTime == 0, un-check the toggle button and return
// pretend nothing happened
Logger.d("sessionTime:"+sessionTime);
if (sessionTime == Channels.CHN_MIN_VALUE_OF_EVERYTHING) {
mToggleButtonConfirmTime.setChecked(false);
return;
}
/** update the corresponding preferences (sessionTime, startTime, isOpen) and the view.
* the dummy serial port has implemented OnSharedPreferencesChangedListener **/
mSharedPreferences.edit()
.putInt(Channels.KEY_CHN_SESSION_TIME_PREFIX + mChannelSelected, sessionTime)
.putInt(Channels.KEY_CHN_START_TIME_PREFIX + mChannelSelected,
TreatmentApplication.getCurrentTimeMillis())
.putBoolean(Channels.KEY_CHN_IS_OPEN_PREFIX + mChannelSelected, true)
.apply();
//TODO is this correct?
mChnView.setSessionTime(sessionTime);
mChnView.setRemainingTimeAndProgress(sessionTime);
/** send set session time command via serialPort **/
SerialFrame.setChannelIndex(mChannelSelected);
if (BuildConfig.MIPS) {
mSerialPort.sendData(SerialFrame.makeTimingFrameToSend(sessionTime), "HEX");
} else if (BuildConfig.ROCKCHIP) {
serialportControler.sendData(SerialFrame.makeTimingFrameToSend(sessionTime), "HEX");
}
responseToToggleBtn(true);
if (mUseKnob) {
Logger.d("旋钮状态发报文?" + mUseKnob);
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
if (BuildConfig.MIPS) {
mSerialPort.sendData(SerialFrame.makeUseKnobFrame(), "HEX");
} else if (BuildConfig.ROCKCHIP) {
serialportControler.sendData(SerialFrame.makeUseKnobFrame(), "HEX");
Logger.d("旋钮状态发报文内容---" + SerialFrame.makeUseKnobFrame());
}
}
} else {
Logger.d("旋钮状态发报文" + mUseKnob);
resetPrefsAndViewAndSendFrame();
responseToToggleBtn(false);
/**reset the display and record of level as well**/
mLevelToSet = Channels.CHN_MIN_VALUE_OF_EVERYTHING;
mTextViewLevel.setText(String.format(Locale.US, "%1$d", mLevelToSet));
}
}
@OnClick(R.id.btn_meter_set_minus)
void decreaseLevel() {
if (mLevelToSet == Channels.CHN_MIN_VALUE_OF_EVERYTHING) {
return;
}
mLevelToSet--;
mTextViewLevel.setText(String.format(Locale.US, "%1$d", mLevelToSet));
//TODO send setting level frame and change shared prefs and display
updateLevelForPrefsAndViewAndSendFrame(mLevelToSet);
isLevelZero();
}
@OnClick(R.id.btn_meter_set_plus)
void increaseLevel() {
if (mLevelToSet == Channels.CHN_MAX_LEVEL) {
return;
}
mLevelToSet++;
mTextViewLevel.setText(String.format(Locale.US, "%1$d", mLevelToSet));
//TODO send setting level frame and change shared prefs and display
updateLevelForPrefsAndViewAndSendFrame(mLevelToSet);
isLevelZero();
}
//判断强度是否为零
private void isLevelZero() {
String text = (String) mTextViewLevel.getText();
Logger.d("强度等级---" + text);
if (text.equals("0")) {
btnMeterFinalConfirm.setVisibility(View.GONE);
} else {
btnMeterFinalConfirm.setVisibility(View.VISIBLE);
}
}
//确定
@OnClick(R.id.btn_meter_final_confirm)
void restoreView() {
/**First hide the whole settings layout and only show reset button**/
setLayoutVisibility(false, mUseKnob);
//if magnitude == 0 close this channel and tell shared prefs
if (mLevelToSet == 0) {
resetPrefsAndViewAndSendFrame();
}
/**Then reset all the settings display**/
// reset the record and text for the level to set
// mLevelToSet = Channels.CHN_MIN_VALUE_OF_EVERYTHING;
mTextViewLevel.setText(String.format(Locale.US, "%1$d", mLevelToSet));
// reset the visibility and text shown on the toggle button
responseToToggleBtn(false);
// If the user reset the channel more than once in the same instance of this activity,
// the toggle button should first shown as unchecked every time it appears
mToggleButtonConfirmTime.setChecked(false);
// the number picker should show 0'0" every time after the reset button is clicked.
mNumberPickerHr.setValue(Channels.CHN_MIN_VALUE_OF_EVERYTHING);
mNumberPickerMin.setValue(Channels.CHN_MIN_VALUE_OF_EVERYTHING);
}
}
| 40.132554
| 113
| 0.656062
|
9865517d97c4e8fe13e5a87f674ad94599aae6c5
| 4,376
|
/* ###
* IP: GHIDRA
*
* 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 ghidra.app.util.pcodeInject;
import ghidra.app.plugin.processors.sleigh.PcodeEmit;
import ghidra.app.plugin.processors.sleigh.SleighLanguage;
import ghidra.program.model.address.AddressSpace;
import ghidra.program.model.lang.InjectContext;
import ghidra.program.model.lang.InjectPayload;
import ghidra.program.model.lang.Register;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.Program;
import ghidra.program.model.pcode.PcodeOp;
import ghidra.program.model.pcode.Varnode;
import ghidra.util.xml.SpecXmlUtils;
import ghidra.xml.*;
/**
* The "uponentry" injection for a eBPF function.
* This injects the function prologue which creates the stack frame of size 0x1000.
* Copied from DEX injection library and modified.
*/
public class InjectPayloadEBPFPrologue implements InjectPayload {
private String name;
private String sourceName;
private InjectParameter[] noParams;
public InjectPayloadEBPFPrologue(String nm, String srcName) {
name = nm;
sourceName = srcName;
noParams = new InjectParameter[0];
}
@Override
public String getName() {
return name;
}
@Override
public int getType() {
return CALLMECHANISM_TYPE;
}
@Override
public String getSource() {
return sourceName;
}
@Override
public int getParamShift() {
return 0;
}
@Override
public InjectParameter[] getInput() {
return noParams;
}
@Override
public InjectParameter[] getOutput() {
return noParams;
}
@Override
public boolean isErrorPlaceholder() {
return false;
}
@Override
public void inject(InjectContext context, PcodeEmit emit) {
// not used
}
@Override
public PcodeOp[] getPcode(Program program, InjectContext con) {
PcodeOp[] resOps;
Function func = program.getFunctionManager().getFunctionContaining(con.baseAddr);
Register fp = con.language.getRegister("R10");
Register sp = con.language.getRegister("R11");
AddressSpace constSpace = program.getAddressFactory().getConstantSpace();
resOps = new PcodeOp[2];
// add pcode ops that create the stack frame
// R10 = R11;
// R11 = R11 - 0x1000;
PcodeOp op0 = new PcodeOp(con.baseAddr, 0, PcodeOp.COPY);
op0.setInput(new Varnode(sp.getAddress(), sp.getBitLength()/8), 0);
op0.setOutput(new Varnode(fp.getAddress(), fp.getBitLength()/8));
resOps[0] = op0;
PcodeOp op = new PcodeOp(con.baseAddr, 0, PcodeOp.INT_SUB);
op.setInput(new Varnode(sp.getAddress(), sp.getBitLength()/8), 0);
op.setInput(new Varnode(constSpace.getAddress(0x1000), 8), 1);
op.setOutput(new Varnode(sp.getAddress(), sp.getBitLength()/8));
resOps[1] = op;
return resOps;
}
@Override
public boolean isFallThru() {
return true;
}
@Override
public boolean isIncidentalCopy() {
return false;
}
@Override
public void saveXml(StringBuilder buffer) {
// Provide a minimal tag so decompiler can call-back
buffer.append("<pcode");
SpecXmlUtils.encodeStringAttribute(buffer, "inject", "uponentry");
SpecXmlUtils.encodeBooleanAttribute(buffer, "dynamic", true);
buffer.append("/>\n");
}
@Override
public void restoreXml(XmlPullParser parser, SleighLanguage language) throws XmlParseException {
XmlElement el = parser.start();
String injectString = el.getAttribute("inject");
if (injectString == null || !injectString.equals("uponentry")) {
throw new XmlParseException("Expecting inject=\"uponentry\" attribute");
}
boolean isDynamic = SpecXmlUtils.decodeBoolean(el.getAttribute("dynamic"));
if (!isDynamic) {
throw new XmlParseException("Expecting dynamic attribute");
}
parser.end(el);
}
@Override
public boolean equals(Object obj) {
return (obj instanceof InjectPayloadEBPFPrologue); // All instances are equal
}
@Override
public int hashCode() {
return 125474219; // All instances are equal
}
}
| 28.051282
| 97
| 0.737888
|
228033c16c89335f4c73b1ded35c34809e03afa2
| 6,992
|
package com.airbnb.android.react.maps;
import android.content.Context;
import android.graphics.Color;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.TileOverlay;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.maps.android.heatmaps.Gradient;
import com.google.maps.android.heatmaps.HeatmapTileProvider;
import com.google.maps.android.heatmaps.WeightBasedHeatmapTileProvider;
import com.google.maps.android.heatmaps.WeightedLatLng;
import org.apache.commons.math3.analysis.interpolation.LinearInterpolator;
import org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction;
import java.util.ArrayList;
import java.util.List;
public class AirMapHeatmap extends AirMapFeature {
private static final String POINTS_DENSITY = "POINTS_DENSITY";
private static final String POINTS_WEIGHT = "POINTS_WEIGHT";
private TileOverlayOptions tileOverlayOptions;
private TileOverlay tileOverlay;
private HeatmapTileProvider heatmapTileProvider;
private WeightBasedHeatmapTileProvider weightBasedHeatmapTileProvider;
private List<WeightedLatLng> points;
private int radius;
private Gradient gradient;
private double opacity;
private double maxIntensity;
private double gradientSmoothing;
private float cameraZoom;
private String heatmapMode;
public static final int MIN_RADIUS = 10;
private PolynomialSplineFunction radiusForZoomFunction;
public AirMapHeatmap(Context context) {
super(context);
}
public void refreshMap() {
if (tileOverlay != null) {
tileOverlay.clearTileCache();
}
}
public void setPoints(ReadableArray points) {
this.points = new ArrayList<>(points.size());
for (int i = 0; i < points.size(); i++) {
ReadableMap point = points.getMap(i);
WeightedLatLng weightedLatLng;
LatLng latLng = new LatLng(point.getDouble("latitude"), point.getDouble("longitude"));
weightedLatLng = new WeightedLatLng(latLng, point.getDouble("weight"));
this.points.add(i, weightedLatLng);
}
if (heatmapTileProvider != null) {
heatmapTileProvider.setWeightedData(this.points);
} else if (weightBasedHeatmapTileProvider != null) {
weightBasedHeatmapTileProvider.setWeightedData(this.points);
}
refreshMap();
}
public void setRadius(int radius) {
this.radius = radius;
if (radius < MIN_RADIUS) this.radius = MIN_RADIUS;
if (heatmapTileProvider != null) {
heatmapTileProvider.setRadius(this.radius);
refreshMap();
} else if (weightBasedHeatmapTileProvider != null) {
weightBasedHeatmapTileProvider.setRadius(this.radius);
refreshMap();
}
}
public void setGradient(ReadableMap gradient) {
ReadableArray rawColors = gradient.getArray("colors");
ReadableArray rawValues = gradient.getArray("values");
int[] colors = new int[rawColors.size()];
float[] values = new float[rawColors.size()];
for (int i = 0; i < rawColors.size(); i++) {
colors[i] = Color.parseColor(rawColors.getString(i));
values[i] = ((float) rawValues.getDouble(i));
}
this.gradient = new Gradient(colors, values);
if (heatmapTileProvider != null) {
heatmapTileProvider.setGradient(this.gradient);
refreshMap();
} else if (weightBasedHeatmapTileProvider != null) {
weightBasedHeatmapTileProvider.setGradient(this.gradient);
refreshMap();
}
}
public void setOpacity(double opacity) {
this.opacity = opacity;
if (heatmapTileProvider != null) {
heatmapTileProvider.setOpacity(opacity);
refreshMap();
} else if (weightBasedHeatmapTileProvider != null) {
weightBasedHeatmapTileProvider.setOpacity(opacity);
refreshMap();
}
}
public void setMaxIntensity(double maxIntensity) {
this.maxIntensity = maxIntensity;
if (weightBasedHeatmapTileProvider != null) {
weightBasedHeatmapTileProvider.setMaxIntensity(maxIntensity);
}
}
public void setGradientSmoothing(double gradientSmoothing) {
this.gradientSmoothing = gradientSmoothing;
}
public void setHeatmapMode(String heatmapMode) {
this.heatmapMode = heatmapMode;
}
public void setOnZoomRadiusChange(ReadableMap onZoomRadiusChange) {
ReadableArray rawZooms = onZoomRadiusChange.getArray("zoom");
ReadableArray rawRadiuses = onZoomRadiusChange.getArray("radius");
if (rawZooms.size() > 0) {
double[] zooms = new double[rawZooms.size()];
double[] radiuses = new double[rawZooms.size()];
for (int i = 0; i < rawZooms.size(); i++) {
zooms[i] = rawZooms.getDouble(i);
radiuses[i] = rawRadiuses.getDouble(i);
}
LinearInterpolator interp = new LinearInterpolator();
radiusForZoomFunction = interp.interpolate(zooms, radiuses);
}
}
public TileOverlayOptions getTileOverlayOptions() {
if (tileOverlayOptions == null) {
tileOverlayOptions = createHeatmapOptions();
}
return tileOverlayOptions;
}
private TileOverlayOptions createHeatmapOptions() {
TileOverlayOptions options = new TileOverlayOptions();
switch (this.heatmapMode) {
case POINTS_DENSITY:
if (heatmapTileProvider == null) {
heatmapTileProvider = new HeatmapTileProvider.Builder()
.weightedData(this.points)
.radius(this.radius)
.gradient(this.gradient)
.opacity(this.opacity)
.build();
}
options.tileProvider(heatmapTileProvider);
break;
case POINTS_WEIGHT:
if (weightBasedHeatmapTileProvider == null) {
int currentRadius = radius;
if(radiusForZoomFunction != null) currentRadius = (int) radiusForZoomFunction.value(cameraZoom);
weightBasedHeatmapTileProvider = new WeightBasedHeatmapTileProvider.Builder()
.weightedData(this.points)
.radius(currentRadius)
.gradient(this.gradient)
.opacity(this.opacity)
.gradientSmoothing(this.gradientSmoothing)
.maxIntensity(this.maxIntensity)
.build();
}
options.tileProvider(weightBasedHeatmapTileProvider);
break;
}
return options;
}
@Override
public void addToMap(GoogleMap map) {
cameraZoom = map.getCameraPosition().zoom;
tileOverlay = map.addTileOverlay(getTileOverlayOptions());
}
@Override
public void removeFromMap(GoogleMap map) {
if (tileOverlay != null) {
tileOverlay.remove();
}
}
@Override
public Object getFeature() {
return tileOverlay;
}
public WeightBasedHeatmapTileProvider getWeightBasedHeatmapTileProvider() {
return weightBasedHeatmapTileProvider;
}
public PolynomialSplineFunction getRadiusForZoomFunction() {
return this.radiusForZoomFunction;
}
}
| 33.295238
| 106
| 0.70881
|
981219d182f9f1f4f7aa0665bf968a51e3660206
| 3,569
|
package io.nutz.nutzsite.module.sys.models;
import io.nutz.nutzsite.common.base.BaseModel;
import io.nutz.nutzsite.common.utils.excel.annotation.ExcelField;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.nutz.dao.entity.annotation.*;
import org.nutz.plugins.validation.annotation.Validations;
import java.io.Serializable;
import java.util.Date;
/**
* 系统参数表 sys_config
*
* @author haiming
* @date 2019-04-17
*/
@Table("sys_config")
public class Config extends BaseModel implements Serializable {
private static final long serialVersionUID = 1L;
@Name
@Column("config_key")
@Comment("配置项 ")
@ColDefine(type = ColType.VARCHAR, width = 200)
@ExcelField(title="配置项", type=1, align=2, sort=1)
@Validations(required=true,errorMsg = "配置项不能为空")
private String configKey;
/**
* 参数值
*/
@Column("config_value")
@Comment("参数值")
@ColDefine(type = ColType.VARCHAR, width = 500)
@ExcelField(title="参数值", align=2, sort=20)
@Validations(required=true,errorMsg = "参数值不能为空")
private String configValue;
/**
* 说明
*/
@Column("note")
@Comment("说明 ")
@ExcelField(title="说明", align=2, sort=20)
private String note;
/**
* 创建者
*/
@Column("create_by")
@Comment("创建者 ")
@Prev(els = @EL("$me.uid()"))
private String createBy;
/**
* 创建时间
*/
@Column("create_time")
@Comment("创建时间 ")
@Prev(els = {@EL("$me.now()")})
private Date createTime;
/**
* 更新者
*/
@Column("update_by")
@Comment("更新者 ")
@Prev(els = @EL("$me.uid()"))
private String updateBy;
/**
* 更新时间
*/
@Column("update_time")
@Comment("更新时间 ")
@Prev(els = {@EL("$me.now()")})
private Date updateTime;
public String getConfigKey() {
return configKey;
}
public void setConfigKey(String configKey) {
this.configKey = configKey;
}
public String getConfigValue() {
return configValue;
}
public void setConfigValue(String configValue) {
this.configValue = configValue;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@Override
public String getCreateBy() {
return createBy;
}
@Override
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
@Override
public Date getCreateTime() {
return createTime;
}
@Override
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String getUpdateBy() {
return updateBy;
}
@Override
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
@Override
public Date getUpdateTime() {
return updateTime;
}
@Override
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("configKey", getConfigKey())
.append("configValue", getConfigValue())
.append("note", getNote())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.toString();
}
}
| 21.895706
| 72
| 0.601289
|
205028fc0535b3c0331035d8e3e6eeeb721b8f2a
| 5,941
|
/*
* Copyright (C) 2012 United States Government as represented by the Administrator of the
* National Aeronautics and Space Administration.
* All Rights Reserved.
*/
package gov.nasa.worldwind.formats.nmea;
import gov.nasa.worldwind.tracks.TrackPoint;
import gov.nasa.worldwind.util.Logging;
import gov.nasa.worldwind.geom.Position;
/**
* @author tag
* @version $Id: NmeaTrackPoint.java 1171 2013-02-11 21:45:02Z dcollins $
*/
public class NmeaTrackPoint implements TrackPoint
{
private double latitude;
private double longitude;
private double altitude;
private double geoidHeight;
private String time;
/**
* @param words
* @throws IllegalArgumentException if <code>words</code> is null or has length less than 1
*/
public NmeaTrackPoint(String[] words)
{
if (words == null)
{
String msg = Logging.getMessage("nullValue.ArrayIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
if (words.length < 1)
{
String msg = Logging.getMessage("generic.ArrayInvalidLength", words.length);
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
if (words[0].equalsIgnoreCase("GPGGA"))
this.doGGA(words);
else if (words[0].equalsIgnoreCase("GPRMC"))
this.doRMC(words);
}
/**
* @param words
* @throws IllegalArgumentException if <code>words</code> is null or has length less than 6
*/
private void doGGA(String[] words)
{
// words won't be null, but it could be the wrong length
if (words.length < 6)
{
String msg = Logging.getMessage("generic.ArrayInvalidLength", words.length);
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
this.time = words[1];
this.latitude = this.parseLatitude(words[2], words[3]);
this.longitude = this.parseLongitude(words[4], words[5]);
if (words.length >= 11)
this.altitude = this.parseElevation(words[9], words[10]);
if (words.length >= 13)
this.geoidHeight = this.parseElevation(words[11], words[12]);
}
private void doRMC(String[] words)
{
}
private double parseLatitude(String angle, String direction)
{
if (angle.length() == 0)
return 0;
double minutes = angle.length() > 2 ? Double.parseDouble(angle.substring(2, angle.length())) : 0d;
double degrees = Double.parseDouble(angle.substring(0, 2)) + minutes / 60d;
return direction.equalsIgnoreCase("S") ? -degrees : degrees;
}
private double parseLongitude(String angle, String direction)
{
if (angle.length() == 0)
return 0;
double minutes = angle.length() > 3 ? Double.parseDouble(angle.substring(3, angle.length())) : 0d;
double degrees = Double.parseDouble(angle.substring(0, 3)) + minutes / 60d;
return direction.equalsIgnoreCase("W") ? -degrees : degrees;
}
private double parseElevation(String height, String units)
{
if (height.length() == 0)
return 0;
return Double.parseDouble(height) * unitsToMeters(units);
}
private double unitsToMeters(String units)
{
double f;
if (units.equals("M")) // meters
f = 1d;
else if (units.equals("f")) // feet
f = 3.2808399;
else if (units.equals("F")) // fathoms
f = 0.5468066528;
else
f = 1d;
return f;
}
public double getLatitude()
{
return latitude;
}
/**
* @param latitude
* @throws IllegalArgumentException if <code>latitude</code> is less than -90 or greater than 90
*/
public void setLatitude(double latitude)
{
if (latitude > 90 || latitude < -90)
{
String msg = Logging.getMessage("generic.AngleOutOfRange", latitude);
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
this.latitude = latitude;
}
public double getLongitude()
{
return longitude;
}
/**
* @param longitude
* @throws IllegalArgumentException if <code>longitude</code> is less than -180 or greater than 180
*/
public void setLongitude(double longitude)
{
if (longitude > 180 || longitude < -180)
{
String msg = Logging.getMessage("generic.AngleOutOfRange", longitude);
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
this.longitude = longitude;
}
public Position getPosition()
{
return Position.fromDegrees(this.latitude, this.longitude, this.altitude);
}
public void setPosition(Position position)
{
if (position == null)
{
String msg = Logging.getMessage("nullValue.PositionIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
this.latitude = position.getLatitude().getDegrees();
this.longitude = position.getLongitude().getDegrees();
this.altitude = position.getElevation();
}
public double getElevation()
{
return this.altitude + this.geoidHeight;
}
public void setElevation(double elevation)
{
this.altitude = elevation;
this.geoidHeight = 0;
}
public String getTime()
{
return time;
}
public void setTime(String time)
{
this.time = time;
}
@Override
public String toString()
{
return String.format("(%10.8f\u00B0, %11.8f\u00B0, %10.4g m, %10.4g m, %s)", this.latitude, this.longitude,
this.altitude, this.geoidHeight, this.time);
}
}
| 28.156398
| 115
| 0.598552
|
e7e54622ccac88263c1b18ecce27ee7936c3ba17
| 2,337
|
/*
* Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.saml.metadata;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.Logger;
import pl.edu.icm.unity.base.utils.Log;
import pl.edu.icm.unity.engine.api.utils.ExecutorsService;
import xmlbeans.org.oasis.saml2.metadata.EntityDescriptorDocument;
/**
* Returns metadata read from file. The contents is parsed to check syntax. The file is automatically
* checked for updates.
* @author K. Benedyczak
*/
public class FileMetadataProvider implements MetadataProvider
{
private Logger log = Log.getLogger(Log.U_SERVER_SAML, FileMetadataProvider.class);
private File file;
private Date lastModification;
private ScheduledExecutorService scheduler;
private EntityDescriptorDocument document;
private boolean stopped = false;
private Runnable task;
public FileMetadataProvider(ExecutorsService executorsService, final File file) throws IOException
{
this.file = file;
scheduler = executorsService.getService();
load();
task = () -> {
reloadTask();
};
reschedule();
}
private synchronized void reloadTask()
{
try
{
if (file.lastModified() > lastModification.getTime())
{
log.info("Metadata file modification detected, reloading " + file);
load();
}
} catch (IOException e)
{
log.error("Can not load the metadata from the configured file " + file, e);
}
reschedule();
}
private synchronized void load() throws IOException
{
try
{
document = EntityDescriptorDocument.Factory.parse(file);
lastModification = new Date();
} catch (Exception e)
{
throw new IOException("Metadata file can not be loaded", e);
}
}
@Override
public synchronized EntityDescriptorDocument getMetadata()
{
return document;
}
@Override
public synchronized Date getLastmodification()
{
return lastModification;
}
@Override
public synchronized void stop()
{
this.stopped = true;
}
private synchronized boolean isStopped()
{
return stopped ;
}
private void reschedule()
{
if (!isStopped())
scheduler.schedule(task, 20, TimeUnit.SECONDS);
}
}
| 22.04717
| 102
| 0.732991
|
45d8edaa7c50e75078b0f0a8fa25d6bcb1ca1c32
| 13,716
|
package parsers;
import Model.TemplateUpdate;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class XmlHandler {
final private String dynamicTemplateUpdaterName = "visualizer_updater_AUTO_GENERATED_DO_NOT_CHANGE";
private Document document;
private String filepath;
public XmlHandler(String _filepath) throws ParserConfigurationException, IOException, SAXException {
//Find and prepare document
filepath = _filepath;
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
//TODO: This disables all validation of the xml file. If dtd file cannot be reached, everything fails.
documentFactory.setValidating(false);
documentFactory.setNamespaceAware(true);
documentFactory.setFeature("http://xml.org/sax/features/namespaces", false);
documentFactory.setFeature("http://xml.org/sax/features/validation", false);
documentFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
documentFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
document = documentBuilder.parse(filepath);
document.getDocumentElement().normalize();
}
/**
* Finds the global declarations entry
* @return returns the global declarations
*/
public String getGlobalDeclarations() {
return getGlobalDeclsElement().getFirstChild().getNodeValue();
}
/**
* Set the global declarations
* @param input is the new value
* @throws TransformerException
*/
public void setGlobalDeclarations(String input) throws TransformerException {
Element firstElement = getGlobalDeclsElement();
firstElement.getFirstChild().setNodeValue(input);
writeXML();
}
public void setDeclarations(HashMap<String, String> allDelcs) throws TransformerException {
NodeList listOfDecls = document.getElementsByTagName("declaration");
listOfDecls.item(0).getFirstChild().setNodeValue(allDelcs.get(null));// Global decls
for (int i = 1; i < listOfDecls.getLength(); i++) {
NodeList templateElements = listOfDecls.item(i).getParentNode().getChildNodes();
String scopeOfDecls = getNameOfTemplate(templateElements);
listOfDecls.item(i).getFirstChild().setNodeValue(allDelcs.get(scopeOfDecls));
}
writeXML();
}
//Find the global declarations element
private Element getGlobalDeclsElement() {
NodeList listOfDecls = document.getElementsByTagName("declaration");
Node GlobalDecls = listOfDecls.item(0);
if(GlobalDecls.getNodeType() == Node.ELEMENT_NODE) {
return (Element) GlobalDecls;
}
return null;
}
public HashMap<String, String> getAllDeclarations() {
NodeList listOfDecls = document.getElementsByTagName("declaration");
HashMap<String, String> allDecls = new HashMap<>();
allDecls.put(null, listOfDecls.item(0).getFirstChild().getNodeValue()); // Global decls
for (int i = 1; i < listOfDecls.getLength(); i++) {
NodeList templateElements = listOfDecls.item(i).getParentNode().getChildNodes();
String scopeOfDecls = getNameOfTemplate(templateElements);
allDecls.put(scopeOfDecls, listOfDecls.item(i).getFirstChild().getNodeValue());
}
return allDecls;
}
public String getParamaterForTemplate(String template) {
NodeList templates = document.getElementsByTagName("template");
for (int i = 0; i < templates.getLength(); i++) {
NodeList templateNodes = templates.item(i).getChildNodes();
if (getNameOfTemplate(templateNodes).equals(template)) {
String typeNameAndId = getTagOfTemplate("parameter", templateNodes); //ex: node_id id
if (typeNameAndId == null)
return null;
if(typeNameAndId.startsWith("const")){
typeNameAndId = typeNameAndId.replace("const", "");
}
return RegexHelper.getFirstMatchedValueFromRegex("(\\w+)", typeNameAndId); //node_id
}
}
return null;
}
private String getNameOfTemplate(NodeList templateElements) {
return getTagOfTemplate("name", templateElements);
}
private String getTagOfTemplate(String tag, NodeList templateElements) {
for (int j=0; j < templateElements.getLength(); j++ ){
if (templateElements.item(j).getNodeName().equals(tag)){
return templateElements.item(j).getFirstChild().getNodeValue();
}
}
return null;
}
public void writeXMLToFilePath(String newPath) throws TransformerException {
filepath = newPath;
writeXML();
}
// write the content into xml file
private void writeXML() throws TransformerException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
}
public void addTemplateUpdatesToModel(List<TemplateUpdate> templateUpdates) throws TransformerException {
Node n = getDynamicTemplate();
if(n != null) {
n.getParentNode().removeChild(n);
}
addUpdatesToNode(document.getDocumentElement(), templateUpdates);
addDynUpdateSystemDecl();
writeXML();
}
private void addDynUpdateSystemDecl() {
Node systemDecls = document.getElementsByTagName("system").item(0).getFirstChild();
String sysDeclsValue = systemDecls.getNodeValue();
StringBuilder stringBuilder = new StringBuilder();
if(!sysDeclsValue.contains(dynamicTemplateUpdaterName)) {
String[] systemLines = sysDeclsValue.split("\\n");
for(String line : systemLines) {
if(line.startsWith("system ")&&line.contains(";")){
stringBuilder.append(line.replace(";", ", " + dynamicTemplateUpdaterName + ";"));
}
else {
stringBuilder.append(line+"\n");
}
}
systemDecls.setNodeValue(stringBuilder.toString());
}
}
private void addUpdatesToNode(Node parent, List<TemplateUpdate> templateUpdates) {
/*TODO: This method has too many memory leaks, and will crash the program if we
Load a GPS log with millions of template updates. A better solution could
maybe just to write all the XML by ourself, using a stringbuilder instead? */
Node template = document.createElement("template");
Node name = document.createElement("name");
name.setTextContent(dynamicTemplateUpdaterName);
template.appendChild(name);
Node decl = document.createElement("declaration");
String clockName = "visualizer_updater_clock";
decl.setTextContent("clock " + clockName + ";");
template.appendChild(decl);
int startId = 2000;
int nextId = startId;
int yPos = 0;
for(int i = 0; i <= templateUpdates.size(); i++) {
Node location = document.createElement("location");
((Element)location).setAttribute("id", "id" + nextId++);
((Element)location).setAttribute("x", "0");
((Element)location).setAttribute("y", String.valueOf(yPos));
if(i < templateUpdates.size()) {
Node label = document.createElement("label");
((Element) label).setAttribute("kind", "invariant");
((Element) label).setAttribute("x", "20");
((Element) label).setAttribute("y", String.valueOf(yPos));
label.setTextContent(clockName + " <= " + templateUpdates.get(i).getTime());
location.appendChild(label);
}
yPos += 70;
template.appendChild(location);
}
Node initLoc = document.createElement("init");
((Element)initLoc).setAttribute("ref", "id" + startId);
template.appendChild(initLoc);
yPos = 0;
for(int i = 0; i < templateUpdates.size(); i++) {
Node transition = document.createElement("transition");
Node src = document.createElement("source");
((Element)src).setAttribute("ref", "id" + (startId + i));
transition.appendChild(src);
Node target = document.createElement("target");
((Element)target).setAttribute("ref", "id" + (startId + i + 1));
transition.appendChild(target);
Node label1 = document.createElement("label");
((Element)label1).setAttribute("kind", "guard");
((Element)label1).setAttribute("x", "20");
((Element)label1).setAttribute("y", String.valueOf(yPos + 15));
label1.setTextContent(clockName + " == " + templateUpdates.get(i).getTime());
transition.appendChild(label1);
Node label2 = document.createElement("label");
((Element)label2).setAttribute("kind", "assignment");
((Element)label2).setAttribute("x", "20");
((Element)label2).setAttribute("y", String.valueOf(yPos + 30));
label2.setTextContent(templateUpdates.get(i).getVariableName() + " = " + templateUpdates.get(i).getTheValue());
transition.appendChild(label2);
yPos += 70;
template.appendChild(transition);
}
NodeList templateList = document.getElementsByTagName("template");
parent.insertBefore(template, templateList.item(0));
}
private Node getDynamicTemplate() {
NodeList templateList = document.getElementsByTagName("template");
String name = null;
Node n = templateList.item(0).getFirstChild();
//In case of new new line etc. Skip it
if(n.getFirstChild() == null) {
n = n.getNextSibling();
}
if(n.hasChildNodes()) {
name = n.getFirstChild().getNodeValue();
}
if(name != null && name.equals(dynamicTemplateUpdaterName))
return templateList.item(0);
else
return null;
}
public String getSystemDeclaration (){
NodeList systemNode = document.getElementsByTagName("system");
return systemNode.item(0).getFirstChild().getNodeValue();
}
public boolean existVisualizerTemplate() {
return (getDynamicTemplate() != null);
}
public int getTemplateCount() {
return document.getElementsByTagName("template").getLength();
}
public ArrayList<TemplateUpdate> getVisualizerUpdates() {
Node node = getDynamicTemplate().getFirstChild();
ArrayList<TemplateUpdate> outputUpdates = new ArrayList<>();
while(node != null) {
if(node.getNodeName().equals("transition")) {
Node child = node.getFirstChild();
String guard = "",
assignment = "";
while(child != null) {
if(child.getNodeName().equals("label")) {
NamedNodeMap attributes = child.getAttributes();
String labelKind = attributes.getNamedItem("kind").getNodeValue();
if(labelKind.equals("guard")) {
guard = child.getFirstChild().getNodeValue();
} else if(labelKind.equals("assignment")) {
assignment = child.getFirstChild().getNodeValue();
}
}
child = child.getNextSibling();
}
outputUpdates.add(parseGuardAndAssignment(guard, assignment));
}
node = node.getNextSibling();
}
return outputUpdates;
}
private TemplateUpdate parseGuardAndAssignment(String guard, String assignment) {
String[] guardParts = guard.replace(" ", "").split("==");
String[] assigmentParts = assignment.replace(" ", "").split("=");
return new TemplateUpdate(assigmentParts[0],
assigmentParts[1],
Integer.parseInt(guardParts[1]));
}
}
| 39.30086
| 124
| 0.610382
|
3a8774007a341efcd765b9a3b4323d3b9c8a057a
| 530
|
package com.wenc.core.model;
import java.util.List;
public class ExcelModelT<T> {
private List<ExcelColModel> headerList;
private List<T> rowdataList;
public List<ExcelColModel> getHeaderList() {
return headerList;
}
public void setHeaderList(List<ExcelColModel> headerList) {
this.headerList = headerList;
}
public List<T> getRowdataList() {
return rowdataList;
}
public void setRowdataList(List<T> rowdataList) {
this.rowdataList = rowdataList;
}
}
| 20.384615
| 63
| 0.669811
|
3e854b13111c14e34ac716ed4577ea8f80afaf8b
| 289
|
package com.incognia;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
public class PostFeedbackRequestBody {
FeedbackEvent event;
Long timestamp;
String accountId;
String externalId;
String installationId;
String paymentId;
String loginId;
String signupId;
}
| 16.055556
| 38
| 0.775087
|
ab236357ffbb8c219c6d316cf3acd881c8b0220c
| 937
|
package algorithm.base.sort;
import java.io.IOException;
public class LeanBubbleSort {
public static void main(String[] args) throws IOException {
int[] arr = new int[] {12, 1, 99, 78, 54, 32, 91, 1001, 97};
bubbleSort(arr);
System.out.println("bubbleSort Result: " + java.util.Arrays.toString(arr));
}
public static void bubbleSort(int arr[]) {
int length = arr.length;
//冒泡
for (int i = 0; i < length; i++) {
//外层循环,遍历次数
for (int j = 0; j < length - i - 1; j++) {
//内层循环,升序(如果前一个值比后一个值大,则交换)
//内层循环一次,获取一个最大值
if (arr[j] > arr[j + 1]) {
int temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
System.out.println("bubbleSort[" + i + "]: " + java.util.Arrays.toString(arr));
}
}
}
| 28.393939
| 91
| 0.469584
|
bb1ea4c52016f7ce2ca4fda9a07bfc429a865726
| 451
|
package xyz.staffjoy.faraday.core.trace;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpStatus;
import static xyz.staffjoy.faraday.core.utils.BodyConverter.convertBodyToString;
public class ReceivedResponse extends HttpEntity {
@Getter
@Setter
protected HttpStatus status;
@Getter
@Setter
protected byte[] body;
public String getBodyAsString() { return convertBodyToString(body); }
}
| 21.47619
| 80
| 0.764967
|
6dac40f7d4150d8d74b87a5ce827bac132d096ff
| 24,491
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.cache.tier.sockets;
import static java.lang.Thread.yield;
import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.AttributesFactory;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.CacheWriterException;
import org.apache.geode.cache.EntryEvent;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionAttributes;
import org.apache.geode.cache.Scope;
import org.apache.geode.cache.client.Pool;
import org.apache.geode.cache.client.PoolManager;
import org.apache.geode.cache.client.internal.PoolImpl;
import org.apache.geode.cache.server.CacheServer;
import org.apache.geode.cache.util.CacheListenerAdapter;
import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.internal.AvailablePort;
import org.apache.geode.internal.cache.CacheServerImpl;
import org.apache.geode.internal.cache.ClientServerObserverAdapter;
import org.apache.geode.internal.cache.ClientServerObserverHolder;
import org.apache.geode.internal.cache.GemFireCacheImpl;
import org.apache.geode.internal.cache.HARegion;
import org.apache.geode.internal.cache.ha.HAHelper;
import org.apache.geode.internal.cache.ha.HARegionQueue;
import org.apache.geode.test.awaitility.GeodeAwaitility;
import org.apache.geode.test.dunit.Assert;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.LogWriterUtils;
import org.apache.geode.test.dunit.NetworkUtils;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.WaitCriterion;
import org.apache.geode.test.dunit.internal.JUnit4DistributedTestCase;
import org.apache.geode.test.junit.categories.ClientSubscriptionTest;
/**
* This test verifies the conflation functionality of the dispatcher.
*
* A sequence of create, put, put, put, destroy is sent and a total of three operations should be
* sent to the client from the server and not all the five.
*
* The test has two regions. In one scenario they share a common bridgewriter and in the second
* scenario, each has a unique bridgewriter.
*/
@Category({ClientSubscriptionTest.class})
public class ConflationDUnitTest extends JUnit4DistributedTestCase {
VM vm0 = null;
VM vm2 = null;
private static Cache cache = null;
private int PORT;
private static final String REGION_NAME1 = "ConflationDUnitTest_region1";
private static final String REGION_NAME2 = "ConflationDUnitTest_region2";
static final String MARKER = "markerKey";
private static HashMap statMap = new HashMap();
@Override
public final void postSetUp() throws Exception {
disconnectAllFromDS();
final Host host = Host.getHost(0);
vm0 = host.getVM(0);
vm2 = host.getVM(2);
PORT = ((Integer) vm0.invoke(() -> ConflationDUnitTest.createServerCache())).intValue();
}
private Cache createCache(Properties props) throws Exception {
DistributedSystem ds = getSystem(props);
Cache cache = CacheFactory.create(ds);
if (cache == null) {
throw new Exception("CacheFactory.create() returned null ");
}
return cache;
}
/**
* test more messages are not sent to client from server
*
*/
@Test
public void testNotMoreMessagesSent() throws Exception {
vm0.invoke(() -> ConflationDUnitTestHelper.setIsSlowStart());
Host host = Host.getHost(0);
createClientCache1CommonWriterTest3(NetworkUtils.getServerHostName(host), new Integer(PORT));
vm2.invoke(() -> ConflationDUnitTest.createClientCache2CommonWriterTest3(
NetworkUtils.getServerHostName(host), new Integer(PORT)));
vm2.invoke(() -> ConflationDUnitTest.setClientServerObserverForBeforeInterestRecovery());
vm2.invoke(() -> ConflationDUnitTest.setAllCountersZero());
vm2.invoke(() -> ConflationDUnitTest.assertAllCountersZero());
vm2.invoke(() -> ConflationDUnitTest.registerInterest());
create();
put200();
createMarker();
vm2.invoke(() -> ConflationDUnitTest.waitForMarker());
vm2.invoke(() -> ConflationDUnitTest.assertValue());
vm2.invoke(() -> ConflationDUnitTest.destroyMarker());
destroy();
createMarker();
vm2.invoke(() -> ConflationDUnitTest.waitForMarker());
vm2.invoke(() -> ConflationDUnitTest.assertCounterSizesLessThan200());
vm0.invoke(() -> ConflationDUnitTest.getStatsOnServer());
vm0.invoke(() -> ConflationDUnitTest.assertConflationStatus());
}
/**
* create properties for a loner VM
*/
private static Properties createProperties1() {
Properties props = new Properties();
props.setProperty(MCAST_PORT, "0");
props.setProperty(LOCATORS, "");
return props;
}
/**
* create pool for a client
*
* @return created pool
*/
private static Pool createPool(String host, String name, Integer port, boolean enableQueue) {
return PoolManager.createFactory().addServer(host, port.intValue())
.setSubscriptionEnabled(enableQueue).setSubscriptionRedundancy(-1).setReadTimeout(10000)
.setSocketBufferSize(32768).setMinConnections(3).setThreadLocalConnections(true)
// .setRetryInterval(10000)
// .setRetryAttempts(5)
.create("ConflationUnitTestPool" + name);
}
/**
* create a client with 2 regions sharing a common writer
*
*/
public static void createClientCache1CommonWriter(String host, Integer port) throws Exception {
ConflationDUnitTest test = new ConflationDUnitTest();
cache = test.createCache(createProperties1());
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
factory.setPoolName(createPool(host, "p1", port, true).getName());
RegionAttributes attrs = factory.create();
cache.createRegion(REGION_NAME1, attrs);
cache.createRegion(REGION_NAME2, attrs);
}
/**
* create a client with 2 regions sharing a common writer
*
*/
public static void createClientCache1CommonWriterTest3(String host, Integer port)
throws Exception {
ConflationDUnitTest test = new ConflationDUnitTest();
cache = test.createCache(createProperties1());
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
factory.setPoolName(createPool(host, "p1", port, false).getName());
RegionAttributes attrs = factory.create();
cache.createRegion(REGION_NAME1, attrs);
cache.createRegion(REGION_NAME2, attrs);
}
/**
* create client 2 with 2 regions with sharing a common writer and having a common listener
*
*/
public static void createClientCache2CommonWriter(String host, Integer port) throws Exception {
ConflationDUnitTest test = new ConflationDUnitTest();
cache = test.createCache(createProperties1());
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
factory.setPoolName(createPool(host, "p1", port, true).getName());
factory.addCacheListener(new CacheListenerAdapter() {
public void afterCreate(EntryEvent event) {
LogWriterUtils.getLogWriter().info("Listener received event " + event);
String val = (String) event.getNewValue();
synchronized (ConflationDUnitTest.class) {
if (val.equals(MARKER)) {
count++;
} else {
counterCreate++;
}
if (2 == count) {
ConflationDUnitTest.class.notify();
}
}
}
public void afterUpdate(EntryEvent event) {
LogWriterUtils.getLogWriter().info("Listener received event " + event);
synchronized (this) {
counterUpdate++;
}
}
public void afterDestroy(EntryEvent event) {
LogWriterUtils.getLogWriter().info("Listener received event " + event);
synchronized (this) {
if (!event.getKey().equals(MARKER)) {
counterDestroy++;
}
}
}
});
RegionAttributes attrs = factory.create();
cache.createRegion(REGION_NAME1, attrs);
cache.createRegion(REGION_NAME2, attrs);
}
public static void createClientCache2CommonWriterTest3(String host, Integer port)
throws Exception {
ConflationDUnitTest test = new ConflationDUnitTest();
cache = test.createCache(createProperties1());
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
factory.setPoolName(createPool(host, "p1", port, true).getName());
factory.addCacheListener(new CacheListenerAdapter() {
public void afterCreate(EntryEvent event) {
LogWriterUtils.getLogWriter().info("Listener received event " + event);
String val = (String) event.getNewValue();
synchronized (ConflationDUnitTest.class) {
if (val.equals(MARKER)) {
count++;
} else {
counterCreate++;
}
if (2 == count) {
ConflationDUnitTest.class.notify();
}
}
}
public void afterUpdate(EntryEvent event) {
LogWriterUtils.getLogWriter().info("Listener received event " + event);
synchronized (this) {
counterUpdate++;
}
}
public void afterDestroy(EntryEvent event) {
LogWriterUtils.getLogWriter().info("Listener received event " + event);
synchronized (this) {
if (!event.getKey().equals(MARKER)) {
counterDestroy++;
}
}
}
});
RegionAttributes attrs = factory.create();
cache.createRegion(REGION_NAME1, attrs);
cache.createRegion(REGION_NAME2, attrs);
}
/**
* create a client with 2 regions each having its own writer
*
*/
public static void createClientCache1UniqueWriter(String host, Integer port) throws Exception {
ConflationDUnitTest test = new ConflationDUnitTest();
cache = test.createCache(createProperties1());
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
factory.setPoolName(createPool(host, "p1", port, true).getName());
RegionAttributes attrs = factory.create();
cache.createRegion(REGION_NAME1, attrs);
factory.setPoolName(createPool(host, "p2", port, true).getName());
attrs = factory.create();
cache.createRegion(REGION_NAME2, attrs);
}
/**
* create client 2 with 2 regions each with a unique writer but both having a common listener
*
*/
public static void createClientCache2UniqueWriter(String host, Integer port) throws Exception {
ConflationDUnitTest test = new ConflationDUnitTest();
cache = test.createCache(createProperties1());
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.LOCAL);
factory.setPoolName(createPool(host, "p1", port, true).getName());
factory.addCacheListener(new CacheListenerAdapter() {
public void afterCreate(EntryEvent event) {
String val = (String) event.getNewValue();
LogWriterUtils.getLogWriter().info("Listener received event " + event);
synchronized (ConflationDUnitTest.class) {
if (val.equals(MARKER)) {
count++;
} else {
counterCreate++;
}
if (2 == count) {
ConflationDUnitTest.class.notify();
}
}
}
public void afterUpdate(EntryEvent event) {
synchronized (this) {
counterUpdate++;
}
}
public void afterDestroy(EntryEvent event) {
synchronized (this) {
if (!event.getKey().equals(MARKER)) {
counterDestroy++;
}
}
}
});
RegionAttributes attrs = factory.create();
cache.createRegion(REGION_NAME1, attrs);
factory.setPoolName(createPool(host, "p2", port, true).getName());
attrs = factory.create();
cache.createRegion(REGION_NAME2, attrs);
}
/**
* variables to count operations (messages received on client from server)
*/
static volatile int count = 0;
static volatile int counterCreate = 0;
static volatile int counterUpdate = 0;
static volatile int counterDestroy = 0;
/**
* assert all the counters are zero
*
*/
public static void assertAllCountersZero() {
assertEquals(0, count);
assertEquals(0, counterCreate);
assertEquals(0, counterUpdate);
assertEquals(0, counterDestroy);
}
/**
* set all the counters to zero
*
*/
public static void setAllCountersZero() {
count = 0;
counterCreate = 0;
counterUpdate = 0;
counterDestroy = 0;
}
/**
* reset all counters to zero before interest recovery
*
*/
public static void setClientServerObserverForBeforeInterestRecovery() {
PoolImpl.BEFORE_RECOVER_INTEREST_CALLBACK_FLAG = true;
ClientServerObserverHolder.setInstance(new ClientServerObserverAdapter() {
public void beforeInterestRecovery() {
setAllCountersZero();
}
});
}
/**
* assert the counters size are as expected (2)
*
*/
public static void assertCounterSizes() {
WaitCriterion ev = new WaitCriterion() {
public boolean done() {
return counterCreate == 2;
}
public String description() {
return "Expected counterCreate to be 2. Instead it was " + counterCreate + ".";
}
};
GeodeAwaitility.await().untilAsserted(ev);
ev = new WaitCriterion() {
public boolean done() {
return counterUpdate == 2;
}
public String description() {
return "Expected counterUpdate to be 2. Instead it was " + counterUpdate + ".";
}
};
GeodeAwaitility.await().untilAsserted(ev);
ev = new WaitCriterion() {
public boolean done() {
return counterDestroy == 2;
}
public String description() {
return "Expected counterDestroy to be 2. Instead it was " + counterDestroy + ".";
}
};
GeodeAwaitility.await().untilAsserted(ev);
}
/**
* assert the counters size less than 20000
*
*/
public static void assertCounterSizesLessThan200() {
WaitCriterion ev = new WaitCriterion() {
public boolean done() {
yield(); // TODO is this necessary?
return counterCreate == 2;
}
public String description() {
return null;
}
};
GeodeAwaitility.await().untilAsserted(ev);
// assertIndexDetailsEquals("creates", 2, counterCreate);
ev = new WaitCriterion() {
public boolean done() {
yield(); // TODO is this necessary?
return counterDestroy == 2;
}
public String description() {
return null;
}
};
GeodeAwaitility.await().untilAsserted(ev);
// assertIndexDetailsEquals("destroys", 2, counterDestroy);
// assertTrue("updates", 20000 >= counterUpdate);
ev = new WaitCriterion() {
public boolean done() {
yield(); // TODO is this necessary?
return counterUpdate <= 200;
}
public String description() {
return null;
}
};
GeodeAwaitility.await().untilAsserted(ev);
}
public static void waitForMarker() {
cache.getRegion(Region.SEPARATOR + REGION_NAME1);
cache.getRegion(Region.SEPARATOR + REGION_NAME2);
long giveUpTime = System.currentTimeMillis() + 30000;
synchronized (ConflationDUnitTest.class) {
while (count != 2) {
if (System.currentTimeMillis() > giveUpTime) {
assertTrue("Count (" + count + ") failed to reach 2", count == 2);
}
try {
ConflationDUnitTest.class.wait(1000);
} catch (InterruptedException e) {
fail("interrupted");
}
}
}
}
/**
* assert that the final value is 33
*
*/
public static void assertValue() {
try {
Region r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME1);
Region r2 = cache.getRegion(Region.SEPARATOR + REGION_NAME2);
assertTrue(r1.containsKey("key-1"));
assertTrue(r1.get("key-1").equals("33"));
assertTrue(r2.containsKey("key-1"));
assertTrue(r2.get("key-1").equals("33"));
} catch (Exception e) {
fail("Exception in trying to get due to " + e);
}
}
/**
* assert Conflation Status
*
*/
public static void assertConflationStatus() {
assertNotNull(statMap);
Long confCount = (Long) statMap.get("eventsConflated");
assertTrue("No Conflation found: eventsConflated value is " + confCount.longValue(),
confCount.longValue() > (0));
assertTrue("Error in Conflation found: eventsConflated value is " + confCount.longValue(),
confCount.longValue() <= (200));
}
/**
* create a server cache and start the server
*
*/
public static Integer createServerCache() throws Exception {
ConflationDUnitTest test = new ConflationDUnitTest();
cache = test.createCache(new Properties());
AttributesFactory factory = new AttributesFactory();
factory.setScope(Scope.DISTRIBUTED_ACK);
factory.setEnableConflation(true);
RegionAttributes attrs = factory.create();
cache.createRegion(REGION_NAME1, attrs);
cache.createRegion(REGION_NAME2, attrs);
CacheServer server = cache.addCacheServer();
int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
server.setPort(port);
server.setNotifyBySubscription(true);
server.setSocketBufferSize(32768);
server.start();
return new Integer(server.getPort());
}
/**
* close the cache
*
*/
public static void closeCache() {
if (cache != null && !cache.isClosed()) {
cache.close();
cache.getDistributedSystem().disconnect();
}
}
/**
* register interest with the server on ALL_KEYS
*
*/
public static void registerInterest() {
try {
Region region1 = cache.getRegion(Region.SEPARATOR + REGION_NAME1);
Region region2 = cache.getRegion(Region.SEPARATOR + REGION_NAME2);
assertTrue(region1 != null);
assertTrue(region2 != null);
region1.registerInterest("ALL_KEYS");
region2.registerInterest("ALL_KEYS");
} catch (CacheWriterException e) {
fail("test failed due to " + e);
}
}
/**
* register interest with the server on ALL_KEYS
*
*/
public static void unregisterInterest() {
try {
Region region1 = cache.getRegion(Region.SEPARATOR + REGION_NAME1);
Region region2 = cache.getRegion(Region.SEPARATOR + REGION_NAME2);
region1.unregisterInterest("ALL_KEYS");
region2.unregisterInterest("ALL_KEYS");
} catch (CacheWriterException e) {
fail("test failed due to " + e);
}
}
/**
* Create an entry on two region with key : key-1 and value
*
*/
public static void create() {
try {
Region r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME1);
Region r2 = cache.getRegion(Region.SEPARATOR + REGION_NAME2);
r1.create("key-1", "value");
r2.create("key-1", "value");
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail("failed while region.create()", ex);
}
}
/**
* do three puts on key-1
*
*/
public static void put() {
try {
Region r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME1);
Region r2 = cache.getRegion(Region.SEPARATOR + REGION_NAME2);
r1.put("key-1", "11");
r1.put("key-1", "22");
r1.put("key-1", "33");
r2.put("key-1", "11");
r2.put("key-1", "22");
r2.put("key-1", "33");
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail("failed while region.put()", ex);
}
}
public static void createMarker() {
try {
Region r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME1);
Region r2 = cache.getRegion(Region.SEPARATOR + REGION_NAME2);
r1.put(MARKER, MARKER);
r2.put(MARKER, MARKER);
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail("failed while region.create() marker", ex);
}
}
/**
* do 200 puts on key-1
*
*/
public static void put200() {
try {
Region r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME1);
Region r2 = cache.getRegion(Region.SEPARATOR + REGION_NAME2);
for (int i = 1; i < 100; i++) {
r1.put("key-1", "11");
r2.put("key-1", "11");
}
r1.put("key-1", "33");
r2.put("key-1", "33");
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail("failed while region.put()", ex);
}
}
/**
* getting conflation Stats on server
*
*/
public static void getStatsOnServer() {
Cache cache = GemFireCacheImpl.getInstance();
Iterator itr = cache.getCacheServers().iterator();
CacheServerImpl server = (CacheServerImpl) itr.next();
Iterator iter_prox =
server.getAcceptor().getCacheClientNotifier().getClientProxies().iterator();
int ccpCount = 0;
while (iter_prox.hasNext()) {
ccpCount++;
CacheClientProxy proxy = (CacheClientProxy) iter_prox.next();
if (HaHelper.checkPrimary(proxy)) {
HARegion region = (HARegion) proxy.getHARegion();
assertNotNull(region);
HARegionQueue haRegionQueue = HAHelper.getRegionQueue(region);
statMap.put("eventsConflated",
new Long(HAHelper.getRegionQueueStats(haRegionQueue).getEventsConflated()));
LogWriterUtils.getLogWriter().info("new Stats Map : " + statMap.toString());
}
}
assertTrue("CCP Count is not 1 ", ccpCount == 1);
// }
}
/**
* do a get on region1
*
*/
public static void get() {
try {
Region r = cache.getRegion(Region.SEPARATOR + REGION_NAME1);
r.get("key-1");
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail("failed while region.get()", ex);
}
}
/**
* destroy the regions
*
*/
public static void destroyRegion() {
try {
Region region1 = cache.getRegion("/region1");
if (region1 != null) {
region1.destroyRegion();
}
Region region2 = cache.getRegion("/region1");
if (region2 != null) {
region2.destroyRegion();
}
} catch (Exception e) {
e.printStackTrace();
fail("test failed due to exception in destroy region" + e);
}
}
/**
* destroy key-1
*
*/
public static void destroy() {
try {
Region region1 = cache.getRegion(Region.SEPARATOR + REGION_NAME1);
Region region2 = cache.getRegion(Region.SEPARATOR + REGION_NAME2);
region1.destroy("key-1");
region2.destroy("key-1");
} catch (Exception e) {
e.printStackTrace();
fail("test failed due to exception in destroy ");
}
}
/**
* destroy marker
*
*/
public static void destroyMarker() {
try {
Region region1 = cache.getRegion(Region.SEPARATOR + REGION_NAME1);
Region region2 = cache.getRegion(Region.SEPARATOR + REGION_NAME2);
region1.destroy(MARKER);
region2.destroy(MARKER);
count = 0;
} catch (Exception e) {
e.printStackTrace();
fail("test failed due to exception in destroy ");
}
}
/**
* close the cache in tearDown
*/
@Override
public final void preTearDown() throws Exception {
// close client
closeCache();
vm2.invoke(() -> ConflationDUnitTest.closeCache());
// close server
vm0.invoke(() -> ConflationDUnitTest.closeCache());
}
}
| 31.683053
| 100
| 0.663836
|
4c3a90db10bfc6386ebfff2402556cfce14608db
| 6,454
|
/*
* Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.gateway.handlers.streaming.sse;
import org.apache.axiom.util.UIDGenerator;
import org.apache.axis2.context.MessageContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.SynapseConstants;
import org.apache.synapse.transport.passthru.DefaultStreamInterceptor;
import org.apache.synapse.transport.passthru.PassThroughConstants;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.common.analytics.collectors.impl.GenericRequestDataCollector;
import org.wso2.carbon.apimgt.common.analytics.exceptions.AnalyticsException;
import org.wso2.carbon.apimgt.gateway.handlers.Utils;
import org.wso2.carbon.apimgt.gateway.handlers.streaming.sse.analytics.SseResponseEventDataProvider;
import org.wso2.carbon.apimgt.gateway.handlers.streaming.sse.throttling.ThrottleInfo;
import org.wso2.carbon.apimgt.gateway.handlers.streaming.sse.utils.SseUtils;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static org.wso2.carbon.apimgt.gateway.handlers.streaming.sse.SseApiConstants.SSE_ANALYTICS_INFO;
import static org.wso2.carbon.apimgt.gateway.handlers.streaming.sse.SseApiConstants.SSE_THROTTLE_DTO;
import static org.wso2.carbon.apimgt.gateway.handlers.streaming.sse.utils.SseUtils.isThrottled;
/**
* This is used for handling throttling, and analytics event publishing of sse apis (subset of streaming apis).
*/
public class SseResponseStreamInterceptor extends DefaultStreamInterceptor {
private static final Log log = LogFactory.getLog(SseResponseStreamInterceptor.class);
private static final String SSE_STREAM_DELIMITER = "\n\n";
private static final int DEFAULT_NO_OF_THROTTLE_PUBLISHER_EXECUTORS = 100;
private String charset = StandardCharsets.UTF_8.name();
private ExecutorService throttlePublisherService;
private int noOfExecutorThreads = DEFAULT_NO_OF_THROTTLE_PUBLISHER_EXECUTORS;
public SseResponseStreamInterceptor() {
throttlePublisherService = Executors.newFixedThreadPool(noOfExecutorThreads);
}
@Override
public boolean interceptTargetResponse(MessageContext axisCtx) {
Object artifactType = axisCtx.getProperty(PassThroughConstants.SYNAPSE_ARTIFACT_TYPE);
return APIConstants.API_TYPE_SSE.equals(artifactType);
}
@Override
public boolean targetResponse(ByteBuffer buffer, MessageContext axis2Ctx) {
int eventCount = getEventCount(buffer);
if (log.isDebugEnabled()) {
log.debug("No. of events =" + eventCount);
}
if (eventCount > 0) {
return handleThrottlingAndAnalytics(eventCount, axis2Ctx);
}
return true;
}
@SuppressWarnings("unused")
public void setNoOfExecutorThreads(int executorThreads) {
this.noOfExecutorThreads = executorThreads;
}
private int getEventCount(ByteBuffer stream) {
Charset charsetValue = Charset.forName(this.charset);
String text = charsetValue.decode(stream).toString();
return StringUtils.countMatches(text, SSE_STREAM_DELIMITER);
}
private boolean handleThrottlingAndAnalytics(int eventCount, MessageContext axi2Ctx) {
Object throttleObject = axi2Ctx.getProperty(SSE_THROTTLE_DTO);
if (throttleObject != null) {
String messageId = UIDGenerator.generateURNString();
ThrottleInfo throttleInfo = (ThrottleInfo) throttleObject;
String remoteIP = throttleInfo.getRemoteIp();
JSONObject propertiesMap = new JSONObject();
Utils.setRemoteIp(propertiesMap, remoteIP);
boolean isThrottled = isThrottled(throttleInfo.getSubscriberTenantDomain(),
throttleInfo.getResourceLevelThrottleKey(),
throttleInfo.getSubscriptionLevelThrottleKey(),
throttleInfo.getApplicationLevelThrottleKey());
if (isThrottled) {
log.warn("Request is throttled out");
return false;
}
throttlePublisherService.execute(
() -> SseUtils.publishNonThrottledEvent(eventCount, messageId, throttleInfo, propertiesMap));
if (APIUtil.isAnalyticsEnabled()) {
try {
publishAnalyticsData(eventCount, axi2Ctx);
} catch (AnalyticsException e) {
log.error("Error while publishing analytics data", e);
}
}
return true;
} else {
log.error("Throttle object cannot be null.");
}
return true;
}
private void publishAnalyticsData(int eventCount, MessageContext axi2Ctx) throws AnalyticsException {
Object responseEventProvider = axi2Ctx.getProperty(SSE_ANALYTICS_INFO);
if (responseEventProvider == null) {
log.error("SSE Analytics event provider is null.");
return;
}
SseResponseEventDataProvider provider = (SseResponseEventDataProvider) responseEventProvider;
provider.setResponseCode((int) axi2Ctx.getProperty(SynapseConstants.HTTP_SC));
GenericRequestDataCollector dataCollector = new GenericRequestDataCollector(provider);
for (int count = 0; count < eventCount; count++) {
dataCollector.collectData();
}
}
public void setCharset(String charset) {
this.charset = charset;
}
}
| 44.205479
| 113
| 0.713201
|
d874414ef3d1ed75bf76183d40bc75f3cbb8cf40
| 2,401
|
package io.kestra.core.models.triggers;
import lombok.*;
import lombok.experimental.SuperBuilder;
import io.kestra.core.models.executions.Execution;
import io.kestra.core.models.flows.Flow;
import java.time.Instant;
import java.util.Arrays;
import io.micronaut.core.annotation.Nullable;
import javax.validation.constraints.NotNull;
@SuperBuilder
@ToString
@EqualsAndHashCode
@Getter
@NoArgsConstructor
public class Trigger extends TriggerContext {
@NotNull
private String executionId;
@Nullable
private Instant updatedDate;
public String uid() {
return uid(this);
}
public static String uid(Trigger trigger) {
return String.join("_", Arrays.asList(
trigger.getNamespace(),
trigger.getFlowId(),
trigger.getTriggerId()
));
}
public static String uid(Execution execution) {
return String.join("_", Arrays.asList(
execution.getNamespace(),
execution.getFlowId(),
execution.getTrigger().getId()
));
}
public static String uid(Flow flow, AbstractTrigger abstractTrigger) {
return String.join("_", Arrays.asList(
flow.getNamespace(),
flow.getId(),
abstractTrigger.getId()
));
}
public static Trigger of(Flow flow, AbstractTrigger abstractTrigger) {
return Trigger.builder()
.namespace(flow.getNamespace())
.flowId(flow.getId())
.flowRevision(flow.getRevision())
.triggerId(abstractTrigger.getId())
.build();
}
public static Trigger of(TriggerContext triggerContext, Execution execution) {
return Trigger.builder()
.namespace(triggerContext.getNamespace())
.flowId(triggerContext.getFlowId())
.flowRevision(triggerContext.getFlowRevision())
.triggerId(triggerContext.getTriggerId())
.date(triggerContext.getDate())
.executionId(execution.getId())
.updatedDate(Instant.now())
.build();
}
public Trigger resetExecution() {
return Trigger.builder()
.namespace(this.getNamespace())
.flowId(this.getFlowId())
.flowRevision(this.getFlowRevision())
.triggerId(this.getTriggerId())
.date(this.getDate())
.build();
}
}
| 28.583333
| 82
| 0.624323
|
c63a2d278a764d57bf7ee0a8daee48d7f6b58b97
| 4,010
|
/*
* org.riverock.portlet - Portlet Library
*
* Copyright (C) 2006, Riverock Software, All Rights Reserved.
*
* Riverock - The Open-source Java Development Community
* http://www.riverock.org
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.riverock.portlet.faq;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.ArrayList;
import org.apache.log4j.Logger;
import org.riverock.common.tools.RsetTools;
import org.riverock.interfaces.portlet.member.PortletGetList;
import org.riverock.interfaces.portlet.member.ClassQueryItem;
import org.riverock.interfaces.portal.spi.PortalSpiProvider;
/**
* Author: Serg Malyukov
* Date: Aug 24, 2002
* Time: 2:41:03 AM
* <p/>
* $Id: FaqGroup.java 1400 2007-09-04 20:25:29Z serg_main $
*/
public class FaqGroup implements PortletGetList {
private final static Logger log = Logger.getLogger(FaqGroup.class);
static String sql_ = null;
static {
sql_ =
"select FAQ_CODE, NAME_FAQ from WM_PORTLET_FAQ where ID_SITE_PORTLET_FAQ=?";
}
static String sql1_ = null;
static {
sql1_ =
"select * from WM_PORTLET_FAQ_LIST where ID_SITE_PORTLET_FAQ=? " +
"ORDER BY ORDER_FIELD asc, DATE_POST DESC";
}
public String faqGroupName = "";
public Long id = null;
public String faqCode = "";
public List<FaqItem> v = new ArrayList<FaqItem>();
public String getFaqGroupName() {
return faqGroupName;
}
public List getFaqItem() {
return v;
}
public FaqGroup() {
}
public FaqGroup( Long id_) throws Exception {
PreparedStatement ps = null;
ResultSet rs = null;
id = id_;
try {
// ps = adapter.prepareStatement(sql_);
RsetTools.setLong(ps, 1, id);
rs = ps.executeQuery();
if (rs.next()) {
faqGroupName = RsetTools.getString(rs, "NAME_FAQ");
faqCode = RsetTools.getString(rs, "FAQ_CODE");
initList();
}
}
catch (Exception e) {
log.error("Exception in FaqGroup()", e);
throw e;
}
catch (Error e) {
log.error("Error in FaqGroup()", e);
throw e;
}
}
public void initList() throws Exception {
if (log.isDebugEnabled())
log.debug("#10.07.01 " + id);
if (id == null)
return;
PreparedStatement ps = null;
ResultSet rs = null;
if (log.isDebugEnabled())
log.debug("#10.07.02 ");
// ps = db_.prepareStatement(sql1_);
RsetTools.setLong(ps, 1, id);
rs = ps.executeQuery();
while (rs.next()) {
Long idFaqGroupItem = RsetTools.getLong(rs, "ID_SITE_PORTLET_FAQ_LIST");
if (log.isDebugEnabled())
log.debug("#10.07.03 " + idFaqGroupItem);
FaqItem fi = new FaqItem(idFaqGroupItem);
fi.datePost = RsetTools.getCalendar(rs, "DATE_POST");
v.add(fi);
}
}
public List<ClassQueryItem> getList(Long idSiteCtxLangCatalog, Long idContext) {
return null;
}
public void setPortalDaoProvider(PortalSpiProvider provider) {
}
}
| 29.057971
| 88
| 0.618204
|
f2abd484ded4fd67d26f8b755cd8b4128adb838c
| 3,865
|
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2007, 2008, 2009, 2010, 2011, 2013, 2014, 2016 Synacor, Inc.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software Foundation,
* version 2 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program.
* If not, see <https://www.gnu.org/licenses/>.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.cs.account.callback;
import java.util.Map;
import com.zimbra.common.service.ServiceException;
import com.zimbra.common.util.ZimbraLog;
import com.zimbra.cs.account.Account;
import com.zimbra.cs.account.Identity;
import com.zimbra.cs.account.AttributeCallback;
import com.zimbra.cs.account.Entry;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.account.Signature;
import com.zimbra.cs.account.callback.CallbackContext.DataKey;
public class MailSignature extends AttributeCallback {
/**
* check to make sure zimbraPrefMailSignature is shorter than the limit
*/
@Override
public void preModify(CallbackContext context, String attrName, Object value,
Map attrsToModify, Entry entry)
throws ServiceException {
SingleValueMod mod = singleValueMod(attrName, value);
if (mod.unsetting())
return;
if (entry != null &&
!((entry instanceof Account)||(entry instanceof Identity)||(entry instanceof Signature))) {
return;
}
long maxLen = -1;
String maxInContext = context.getData(DataKey.MAX_SIGNATURE_LEN);
if (maxInContext != null) {
try {
maxLen = Integer.parseInt(maxInContext);
} catch (NumberFormatException e) {
ZimbraLog.account.warn("encountered invalid " +
DataKey.MAX_SIGNATURE_LEN.name() + ": " + maxInContext);
}
}
if (maxLen == -1) {
String maxInAttrsToModify = (String) attrsToModify.get(Provisioning.A_zimbraMailSignatureMaxLength);
if (maxInAttrsToModify != null) {
try {
maxLen = Integer.parseInt(maxInAttrsToModify);
} catch (NumberFormatException e) {
ZimbraLog.account.warn("encountered invalid " +
Provisioning.A_zimbraMailSignatureMaxLength + ": " +
maxInAttrsToModify);
}
}
}
if (maxLen == -1) {
if (entry == null) {
return;
}
Account account;
if (entry instanceof Account) {
account = (Account)entry;
} else if (entry instanceof Identity) {
account = ((Identity)entry).getAccount();
} else if (entry instanceof Signature) {
account = ((Signature)entry).getAccount();
} else {
return;
}
maxLen = account.getMailSignatureMaxLength();
}
// 0 means unlimited
if (maxLen != 0 && ((String)value).length() > maxLen) {
throw ServiceException.INVALID_REQUEST(
Provisioning.A_zimbraPrefMailSignature +
" is longer than the limited value " + maxLen, null);
}
}
@Override
public void postModify(CallbackContext context, String attrName, Entry entry) {
}
}
| 36.121495
| 112
| 0.601552
|
fb25da3e238b7fcf453783e06a583dd483c24b7b
| 32,516
|
package com.github.roxanne_rosjava.roxanne_rosjava_core.control.acting;
import com.github.roxanne_rosjava.roxanne_rosjava_core.control.acting.ex.ActingAgentInitializationException;
import com.github.roxanne_rosjava.roxanne_rosjava_core.control.platform.RosJavaPlatformProxyBuilder;
import it.cnr.istc.pst.platinum.ai.deliberative.Planner;
import it.cnr.istc.pst.platinum.ai.executive.Executive;
import it.cnr.istc.pst.platinum.ai.executive.lang.failure.ExecutionFailureCause;
import it.cnr.istc.pst.platinum.ai.executive.pdb.ExecutionNode;
import it.cnr.istc.pst.platinum.ai.executive.pdb.ExecutionNodeStatus;
import it.cnr.istc.pst.platinum.ai.framework.domain.PlanDataBaseBuilder;
import it.cnr.istc.pst.platinum.ai.framework.domain.component.ComponentValue;
import it.cnr.istc.pst.platinum.ai.framework.domain.component.Decision;
import it.cnr.istc.pst.platinum.ai.framework.domain.component.DomainComponent;
import it.cnr.istc.pst.platinum.ai.framework.domain.component.PlanDataBase;
import it.cnr.istc.pst.platinum.ai.framework.domain.component.ex.DecisionPropagationException;
import it.cnr.istc.pst.platinum.ai.framework.domain.component.ex.RelationPropagationException;
import it.cnr.istc.pst.platinum.ai.framework.microkernel.lang.ex.NoSolutionFoundException;
import it.cnr.istc.pst.platinum.ai.framework.microkernel.lang.ex.SynchronizationCycleException;
import it.cnr.istc.pst.platinum.ai.framework.microkernel.lang.plan.SolutionPlan;
import it.cnr.istc.pst.platinum.ai.framework.microkernel.lang.relations.Relation;
import it.cnr.istc.pst.platinum.ai.framework.microkernel.lang.relations.RelationType;
import it.cnr.istc.pst.platinum.ai.framework.microkernel.lang.relations.parameter.BindParameterRelation;
import it.cnr.istc.pst.platinum.ai.framework.parameter.lang.constraints.BindParameterConstraint;
import it.cnr.istc.pst.platinum.ai.framework.utils.properties.FilePropertyReader;
import it.cnr.istc.pst.platinum.control.lang.*;
import it.cnr.istc.pst.platinum.control.lang.ex.PlatformException;
import it.cnr.istc.pst.platinum.control.platform.PlatformObserver;
import it.cnr.istc.pst.platinum.control.platform.PlatformProxy;
import org.apache.commons.logging.Log;
import org.ros.node.ConnectedNode;
import java.util.*;
/**
*
*/
public class GoalOrientedActingAgent implements PlatformObserver {
private final Object lock; // lock state;
private ActingAgentStatus status; // agent status
private final Map<GoalStatus, List<Goal>> queue; // goal queue
private String ddl; // path to the domain specification file
private PlanDataBase pdb; // internal plan database representation
private List<Thread> processes; // goal oriented processes
private DeliberativeProcess deliberative; // internal deliberative process
private Class<? extends Planner> pClass; // planner class
private boolean displayPlan; // display plan flag
private ExecutiveProcess executive; // internal executive process
private ContingencyHandlerProcess contingencyHandler; // internal contingency handler process
private Class<? extends Executive> eClass; // executive class
protected PlatformProxy proxy;
private FilePropertyReader properties;
private Log log;
/**
*
* @param propertyFile
* @param node
* @throws ActingAgentInitializationException
*/
public GoalOrientedActingAgent(String propertyFile, ConnectedNode node)
throws ActingAgentInitializationException {
try {
// set the log
this.log = node.getLog();
// set lock and status
this.lock = new Object();
// set status
this.status = ActingAgentStatus.OFFLINE;
// set goal buffer
this.queue = new HashMap<>();
// set goal queue
for (GoalStatus s : GoalStatus.values()) {
this.queue.put(s, new ArrayList<Goal>());
}
// set internal plan database representation
this.pdb = null;
// set platform
this.processes = null;
// get agent property file
this.properties = new FilePropertyReader(propertyFile);
// get DDL file
String path = this.properties.getProperty("model");
// set absolute path to the file
this.ddl = path.replace("~", System.getenv("HOME"));
// check if null
if (this.ddl == null || this.ddl.equals("")) {
throw new ActingAgentInitializationException("You need to specify an acting model of the agent in \"etc/agent.properties\"!");
}
// read the class name of the planner
String plannerClassName = this.properties.getProperty("planner");
// set planner class
this.pClass = (Class<? extends Planner>) Class.forName(plannerClassName);
// set display plan flag
this.displayPlan = this.properties.getProperty("display_plan").equals("1") ? true : false;
// read the class name of the executive
String executiveClassName = this.properties.getProperty("executive");
// set executive class
this.eClass = (Class<? extends Executive>) Class.forName(executiveClassName);
// read the class of the platform
String platformClassName = this.properties.getProperty("platform");
// check if a platform is necessary
if (platformClassName != null && !platformClassName.equals("")) {
// get platform configuration file
String pCfgPath = this.properties.getProperty("platform_config_file");
// set absolute path to file
String configFile = pCfgPath.replace("~", System.getenv("HOME"));
// check platform configuration file
if (configFile == null || configFile.equals("")) {
throw new ActingAgentInitializationException("Specify a configuration file for the platform in \"" + propertyFile + "\"!");
}
// create platform PROXY
Class<? extends PlatformProxy> clazz = (Class<? extends PlatformProxy>)
Class.forName(platformClassName);
// create PROXY
this.proxy = RosJavaPlatformProxyBuilder.build(clazz, node, configFile);
}
// setup deliberative and executive processes
this.setupProcesses();
} catch (PlatformException | ClassNotFoundException ex) {
throw new ActingAgentInitializationException(ex.getMessage());
}
}
/**
*
*/
private void setupProcesses() {
// set the list of processes
this.processes = new ArrayList<>();
// set goal listener thread
this.processes.add(new Thread(new Runnable() {
/**
*
*/
@Override
public void run() {
boolean running = true;
while(running) {
try {
// check buffered goals
Goal goal = waitGoal(GoalStatus.BUFFERED);
// simply select the extracted goal
select(goal);
} catch (InterruptedException ex) {
running = false;
}
}
}
}));
// set goal deliberative
this.deliberative = new DeliberativeProcess(this.pClass, this.displayPlan, this);
this.processes.add(new Thread(this.deliberative));
// set goal executive
this.executive = new ExecutiveProcess(this.eClass, this, this.log);
this.processes.add(new Thread(this.executive));
// set goal failure handler
this.contingencyHandler = new ContingencyHandlerProcess(this);
this.processes.add(new Thread(this.contingencyHandler));
// register agent to the proxy
if (this.proxy != null) {
// register to platform events
this.proxy.register(this);
}
}
/**
*
* @return
*/
public synchronized ActingAgentStatus getStatus() {
return status;
}
/**
*
* @param task
*/
@Override
public void task(AgentTaskDescription task) {
// buffer received task request
this.buffer(task);
}
/**
*
* @param platformFeedback
*/
@Override
public void feedback(PlatformFeedback platformFeedback) {
// nothing to do
}
/**
*
* @param platformObservation
*/
@Override
public void observation(PlatformObservation<?> platformObservation) {
// nothing to do
}
/**
* Trigger acting process by buffering a description of a goal to plan and execute for
*
* @param description
*/
public void buffer(AgentTaskDescription description) {
// protect access to the queue
synchronized (this.queue) {
// create goal
Goal goal = new Goal(description);
// set goal status
goal.setStatus(GoalStatus.BUFFERED);
// add a goal to the queue
this.queue.get(goal.getStatus()).add(goal);
this.log.info("[GoalOrientedActingAgent] Received task request:\n" +
"- Request-ID: " + description.getId() + "\n" +
"- Number of buffered requests: " + this.queue.get(GoalStatus.BUFFERED).size() + "\n");
// send signal
this.queue.notifyAll();
}
}
/**
* Blocking call returning a list of finished or aborted goals.
*
* @return
* @throws InterruptedException
*/
public List<Goal> getResults()
throws InterruptedException {
// wait some finished or aborted goal
List<Goal> goals = new ArrayList<>();
synchronized (this.queue) {
while (this.queue.get(GoalStatus.ABORTED).isEmpty() &&
this.queue.get(GoalStatus.FINISHED).isEmpty()) {
// wait
this.queue.wait();
}
// take aborted goals
goals.addAll(this.queue.get(GoalStatus.ABORTED));
// clear queue
this.queue.get(GoalStatus.ABORTED).clear();
// take finished goals
goals.addAll(this.queue.get(GoalStatus.FINISHED));
// clear queue
this.queue.get(GoalStatus.FINISHED).clear();
// send signal
this.queue.notifyAll();
}
// get finished and aborted goals
return goals;
}
/**
*
*/
protected void select(Goal goal) {
// protect access to the queue
synchronized (this.queue) {
// set goal status
goal.setStatus(GoalStatus.SELECTED);
// add goal to the queue
this.queue.get(goal.getStatus()).add(goal);
log.info("[GoalOrientedActingAgent] Selecting goal from input buffer:\n" +
"- Selected Request-ID: " + goal.getTaskDescription().getId() + "\n" +
"- Number of buffered requests: " + this.queue.get(GoalStatus.BUFFERED).size() + "\n" +
"- Number of selected goals: " + this.queue.get(GoalStatus.SELECTED).size() + "\n");
// send signal
this.queue.notifyAll();
}
}
/**
*
*/
protected void commit(Goal goal) {
// protect access to the queue
synchronized (this.queue) {
// set goal status
goal.setStatus(GoalStatus.COMMITTED);
// add goal to the queue
this.queue.get(goal.getStatus()).add(goal);
// send signal
this.queue.notifyAll();
}
}
/**
*
*/
protected void suspend(Goal goal) {
// protect access to the queue
synchronized (this.queue) {
// set goal status
goal.setStatus(GoalStatus.SUSPENDED);
// add goal to the queue
this.queue.get(goal.getStatus()).add(goal);
// send signal
this.queue.notifyAll();
}
}
/**
*
*/
protected void finish(Goal goal) {
// protect access to the queue
synchronized (this.queue) {
// set goal status
goal.setStatus(GoalStatus.FINISHED);
// add goal to the queue
this.queue.get(goal.getStatus()).add(goal);
// send signal
this.queue.notifyAll();
}
}
/**
*
*/
protected void abort(Goal goal) {
// protect access to the queue
synchronized (this.queue) {
// set goal status
goal.setStatus(GoalStatus.ABORTED);
// add goal to the queue
this.queue.get(goal.getStatus()).add(goal);
// send signal
this.queue.notifyAll();
}
}
/**
*
* @throws InterruptedException
*/
public void start()
throws InterruptedException {
synchronized (this.lock) {
while (!this.status.equals(ActingAgentStatus.OFFLINE)) {
// wait
this.lock.wait();
}
// change status
this.status = ActingAgentStatus.STARTING;
// send signal
this.lock.notifyAll();
}
// start all internal processes
for (Thread p : this.processes) {
p.start();
}
synchronized (this.lock) {
// change status
this.status = ActingAgentStatus.RUNNING;
// notify all
this.lock.notifyAll();
}
}
/**
*
* @throws InterruptedException
*/
public void stop()
throws InterruptedException, PlatformException {
synchronized (this.lock) {
while (!this.status.equals(ActingAgentStatus.READY) &&
!this.status.equals(ActingAgentStatus.RUNNING)) {
// wait
this.lock.wait();
}
// change status
this.status = ActingAgentStatus.STOPPING;
// send signal
this.lock.notifyAll();
}
// interrupt internal processes and wait termination
for (Thread p : this.processes) {
p.interrupt();
p.join();
}
/*
* TODO : close platform PROXY
*/
synchronized (this.lock) {
// change status
this.status = ActingAgentStatus.OFFLINE;
// notify all
this.lock.notifyAll();
}
}
/**
*
* @throws ActingAgentInitializationException
*/
public void initialize()
throws ActingAgentInitializationException {
// ready flag
boolean ready = false;
try {
synchronized (this.lock) {
while (!this.status.equals(ActingAgentStatus.RUNNING)) {
// wait a signal
this.lock.wait();
}
// change status
this.status = ActingAgentStatus.INITIALIZING;
// send signal
this.lock.notifyAll();
}
/**
* TODO : do initialization steps
*/
// set flag
ready = true;
} catch (InterruptedException ex) {
throw new ActingAgentInitializationException(ex.getMessage());
} finally {
synchronized (this.lock) {
// change status
if (ready) {
this.status = ActingAgentStatus.READY;
}
else {
// simply set as running
this.status = ActingAgentStatus.RUNNING;
}
// send signal
this.lock.notifyAll();
}
}
}
/**
*
* @throws InterruptedException
*/
public void clear()
throws InterruptedException {
synchronized (this.lock) {
while (!this.status.equals(ActingAgentStatus.FAILURE) &&
!this.status.equals(ActingAgentStatus.READY)) {
// wait
this.lock.wait();
}
// change status
this.status = ActingAgentStatus.CLEARNING;
// send signal
this.lock.notifyAll();
}
// clear queue
this.queue.clear();
// clear domain file specification
this.ddl = null;
// clear plan database
this.pdb = null;
// clear PROXY
this.proxy = null;
synchronized (this.lock) {
// change status
this.status = ActingAgentStatus.RUNNING;
// send signal
this.lock.notifyAll();
}
}
/**
*
* @param task
* @param goals
* @param facts
* @param activatedRelations
* @throws DecisionPropagationException
* @throws RelationPropagationException
*/
private void propagate(AgentTaskDescription task, List<Decision> goals, List<Decision> facts, List<Relation> activatedRelations)
throws DecisionPropagationException, RelationPropagationException {
// fact ID
int factId = 0;
// set known information concerning components
for (TokenDescription f : task.getFacts()) {
// get domain component
DomainComponent component = this.pdb.getComponentByName(f.getComponent());
// get goal referred value
ComponentValue value = component.getValueByName(f.getValue());
// check start time bound
long[] start = f.getStart();
if (start == null) {
start = new long[] {
this.pdb.getOrigin(),
this.pdb.getHorizon()
};
}
// check end time bound
long[] end = f.getEnd();
if (end == null) {
end = new long[] {
this.pdb.getOrigin(),
this.pdb.getHorizon()
};
}
// check duration bound
long[] duration = f.getDuration();
if (duration == null) {
duration = new long[] {
value.getDurationLowerBound(),
value.getDurationUpperBound()
};
}
// set labels
String[] labels = new String[] {};
// get parameters
String[] params = f.getLabels();
if (params != null && params.length > 0) {
// set parameter labels
labels = new String[params.length];
for (int i = 0; i < params.length; i++) {
// create parameter label
labels[i] = "?f" + factId + "l" + i;
}
}
// create fact decision
Decision decision = component.create(
value,
labels,
start,
end,
duration);
// also activate fact decision
component.activate(decision);
// bind parameter labels
for (int i = 0; i < params.length; i++) {
// get parameter label
String pLabel = labels[i];
// get parameter value
String pValue = params[i];
// create BIND parameter relation
BindParameterRelation pRel = component.create(RelationType.BIND_PARAMETER, decision, decision);
// set relation data
pRel.setReferenceParameterLabel(pLabel);
pRel.setValue(pValue);
// activate relation
component.activate(pRel);
// add activated relation
activatedRelations.add(pRel);
}
// add decision to fact list
facts.add(decision);
// increment fact ID
factId++;
}
// goal ID counter
int goalId = 0;
// set planning goals
for (TokenDescription g : task.getGoals())
{
// get domain component
DomainComponent component = this.pdb.getComponentByName(g.getComponent());
// get goal referred value
ComponentValue value = component.getValueByName(g.getValue());
// check start time bound
long[] start = g.getStart();
if (start == null) {
start = new long[] {
this.pdb.getOrigin(),
this.pdb.getHorizon()
};
}
// check end time bound
long[] end = g.getEnd();
if (end == null) {
end = new long[] {
this.pdb.getOrigin(),
this.pdb.getHorizon()
};
}
// check duration bound
long[] duration = g.getDuration();
if (duration == null) {
duration = new long[] {
value.getDurationLowerBound(),
value.getDurationUpperBound()
};
}
// set labels
String[] labels = new String[] {};
// get parameters
String[] params = g.getLabels();
if (params != null && params.length > 0) {
// set parameter labels
labels = new String[params.length];
for (int i = 0; i < params.length; i++) {
// create parameter label
labels[i] = "?g" + goalId + "l" + i;
}
}
// create goal decision
Decision decision = component.create(
value,
labels,
start,
end,
duration);
// bind parameter labels
for (int i = 0; i < params.length; i++) {
// get parameter label
String pLabel = labels[i];
// get parameter value
String pValue = params[i];
// create BIND parameter relation
BindParameterRelation pRel = component.create(RelationType.BIND_PARAMETER, decision, decision);
// set relation data
pRel.setReferenceParameterLabel(pLabel);
pRel.setValue(pValue);
// activate relation
component.activate(pRel);
// add activated relation
activatedRelations.add(pRel);
}
// add decision to goal list
goals.add(decision);
// increment goal ID
goalId++;
}
}
/**
*
* @return
* @throws InterruptedException
* @throws NoSolutionFoundException
*/
protected boolean plan(Goal goal)
throws InterruptedException {
// wait when planning can be actually performed if necessary
synchronized (this.lock) {
while (!this.status.equals(ActingAgentStatus.READY)) {
// wait
this.lock.wait();
}
// change status
this.status = ActingAgentStatus.DELIBERATING;
// send signal
this.lock.notifyAll();
}
// planning process result
boolean success = true;
// list of goal decisions
List<Decision> goals = new ArrayList<>();
// list of fact decisions
List<Decision> facts = new ArrayList<>();
// list of created (and activated) relations
List<Relation> activatedRelations = new ArrayList<>();
// start planning time
long now = System.currentTimeMillis();
try {
// first create a clear data structure
this.log.info("Setup timeline-based specification \n" + this.ddl + "\n");
// set plan database on the given planning domain
this.pdb = PlanDataBaseBuilder.createAndSet(this.ddl);
// get task description
AgentTaskDescription task = goal.getTaskDescription();
// propagate task description state
this.propagate(task, goals, facts, activatedRelations);
// start planning time
now = System.currentTimeMillis();
// start planning
this.log.info("Start planning on goal:\n-" +
"" + goal + "\n");
// deliberate on the current status of the plan database
SolutionPlan plan = this.deliberative.doPlan(this.pdb);
// set generated plan
goal.setPlan(plan);
// solution found
this.log.info("Solution found after " + ((System.currentTimeMillis() - now) / 1000) + " seconds:\n" +
"- Solution plan:\n" +
"" + plan + "\n\n");
} catch (SynchronizationCycleException | DecisionPropagationException | RelationPropagationException ex) {
// problem setup error
success = false;
// deactivate and remove relations
for (Relation rel : activatedRelations) {
DomainComponent comp = rel.getReference().getComponent();
// deactivate relation
comp.deactivate(rel);
// remove relation
comp.delete(rel);
}
// remove and deactivate facts
for (Decision f : facts) {
f.getComponent().deactivate(f);
f.getComponent().free(f);
}
// remove and deactivate goals
for (Decision g : goals) {
g.getComponent().deactivate(g);
g.getComponent().free(g);
}
// print an error message
this.log.error("Error while propagating initial facts from task description:\n"
+ "\t- message: " + ex.getMessage() + "\n");
} catch (NoSolutionFoundException ex) {
// no solution found
this.log.warn("No solution found on goal:\n" +
"" + goal + "\n\n");
// failure - no plan can be found
success = false;
// remove and deactivate facts
for (Decision f : facts) {
f.getComponent().deactivate(f);
f.getComponent().free(f);
}
// remove and deactivate goals
for (Decision g : goals) {
g.getComponent().deactivate(g);
g.getComponent().free(g);
}
} finally {
// compute actual planning time
long time = System.currentTimeMillis() - now;
// add planning time attempt to the goal
goal.addPlanningAttempt(time);
}
// update agent status
synchronized (this.lock) {
// update status according to the result of the planning process
if (success) {
this.status = ActingAgentStatus.PREPARING_EXECUTION;
} else {
// failure
this.status = ActingAgentStatus.FAILURE;
}
// send signal
this.lock.notifyAll();
}
// return planning process result
return success;
}
/**
*
* @param goal
* @return
* @throws InterruptedException
*/
protected boolean execute(Goal goal)
throws InterruptedException {
synchronized (this.lock) {
while (!this.status.equals(ActingAgentStatus.PREPARING_EXECUTION)) {
// wait
this.lock.wait();
}
// update status
this.status = ActingAgentStatus.EXECUTING;
// send signal
this.lock.notifyAll();
}
// execution result
boolean complete = true;
// start execution time
long now = System.currentTimeMillis();
try {
// ready to start execution
this.log.info("Ready to execute (timeline-based) plan for goal\n" +
"" + goal + "\n");
// execute the plan
this.executive.doExecute(goal);
// successful execution
this.log.info("Plan successfully executed...");
} catch (Exception ex) {
// execution failure
complete = false;
// successful execution
this.log.info("Plan execution failure!");
} finally {
// compute actual execution time
long time = System.currentTimeMillis() - now;
// add execution attempt time
goal.addExecutionAttempt(time);
}
// update agent status
synchronized (this.lock) {
// update status according to the execution results
if (complete) {
// agent ready to execute another plan
this.status = ActingAgentStatus.READY;
} else {
// suspend executive
this.status = ActingAgentStatus.SUSPENDING;
}
// send signal
this.lock.notifyAll();
}
// return execution result
return complete;
}
/**
*
* @param goal
* @return
* @throws InterruptedException
*/
protected boolean repair(Goal goal)
throws InterruptedException {
synchronized (this.lock) {
while (!this.status.equals(ActingAgentStatus.SUSPENDING)) {
// wait
this.lock.wait();
}
// update status
this.status = ActingAgentStatus.REPAIRING;
// send signal
this.lock.notifyAll();
}
/*
// repairing result
boolean success = true;
// start contingency handling time
long now = System.currentTimeMillis();
try {
// repair plan data
this.log.warn("Clearing plan structure before re-planning");
// list of kept decisions
List<Decision> kept = new ArrayList<>();
// clear domain components
for (DomainComponent comp : this.pdb.getComponents()) {
// clear component
this.log.info("Clearing component \"" + comp.getName() + "\"");
// list of pending decisions
List<Decision> pendings = comp.getPendingDecisions();
for (Decision pending : pendings) {
// completely remove decision and related relations
this.log.info("\tClearing PENDING component decision \"" + pending + "\" ...");
comp.deactivate(pending);
comp.free(pending);
}
// get execution trace
List<ExecutionNode> trace = goal.getExecutionTraceByComponentName(comp.getName());
// remove active decisions that have not been executed
this.log.info("Check ACTIVE decisions of the component");
// list of active decisions
List<Decision> actives = comp.getActiveDecisions();
for (Decision active : actives) {
boolean executed = false;
for (ExecutionNode node : trace) {
// check if the temporal interval has been executed
if (node.getInterval().equals(active.getToken().getInterval())){
executed = true;
break;
}
}
// check flag
if (executed) {
// keep the decision as active
this.log.info("\tKeep ACTIVE decision \"" + active + "\" since completely executed ... ");
kept.add(active);
}
else {
// clear and remove decision and related relations
this.log.info("\tClear ACTIVE decision \"" + active + "\" and related relations since not executed yet");
comp.deactivate(active);
comp.free(active);
}
}
}
// check execution failure cause
ExecutionFailureCause cause = goal.getFailureCause();
this.log.info("Check cause of execution failure");
// check type
switch (cause.getType())
{
case NODE_DURATION_OVERFLOW : {
// keep the decision as active and consider it as executed
this.log.info("Handle DURATION OVERFLOW failure ...");
ExecutionNode node = cause.getInterruptionNode();
// find the related decision
for (DomainComponent comp : this.pdb.getComponents()) {
// get active decisions
List<Decision> actives = comp.getActiveDecisions();
for (Decision active : actives) {
// check temporal intervals
if (node.getInterval().equals(active.getToken().getInterval())) {
// keep the decision as active
this.log.debug("\tKeep active decision \"" + active + "\"");
kept.add(active);
}
}
}
}
break;
case NODE_EXECUTION_ERROR :
case NODE_START_OVERFLOW : {
// remove decisions they are going to be re-planned
this.log.warn("Handle START OVERFLOW or TOKEN EXECUTION ERROR failures ...\n");
ExecutionNode node = cause.getInterruptionNode();
// find the related decision
for (DomainComponent comp : this.pdb.getComponents()) {
// get active decisions
List<Decision> actives = comp.getActiveDecisions();
for (Decision active : actives) {
// check temporal intervals
if (node.getInterval().equals(active.getToken().getInterval())) {
// keep the decision as active
this.log.debug("\tClear ACTIVE decision \"" + active + "\"");
comp.deactivate(active);
comp.free(active);
}
}
}
}
break;
default:
throw new RuntimeException("Unknown Execution Failure Cause \"" + cause.getType() + "\"");
}
// get task description
AgentTaskDescription task = goal.getTaskDescription();
// set planning goals
for (TokenDescription g : task.getGoals()) {
// get domain component
DomainComponent component = this.pdb.getComponentByName(g.getComponent());
// get goal referred value
ComponentValue value = component.getValueByName(g.getValue());
// check start time bound
long[] start = g.getStart();
if (start == null) {
start = new long[] {
this.pdb.getOrigin(),
this.pdb.getHorizon()
};
}
// check end time bound
long[] end = g.getEnd();
if (end == null) {
end = new long[] {
this.pdb.getOrigin(),
this.pdb.getHorizon()
};
}
// check duration bound
long[] duration = g.getDuration();
if (duration == null) {
duration = new long[] {
value.getDurationLowerBound(),
value.getDurationUpperBound()
};
}
// check labels
String[] labels = g.getLabels();
if (labels == null) {
labels = new String[] {};
}
// TODO : check parameter relations
// create goal decision
Decision decision = component.create(
value,
labels,
start,
end,
duration,
ExecutionNodeStatus.IN_EXECUTION);
// add decision to goal list
this.log.info("Start re-planning for goal : [" + decision.getId() +"]:" + decision.getComponent().getName() + "." + decision.getValue().getLabel() + " "
+ "AT [" + decision.getStart()[0] + ", " + decision.getStart()[1] + "] "
+ "[" + decision.getEnd()[0] + ", " + decision.getEnd()[1] + "] "
+ "[" + decision.getDuration()[0] + ", " + decision.getDuration()[1] + "]");
}
// deliberate on the current status of the plan database
SolutionPlan plan = this.contingencyHandler.doHandle(this.pClass, this.pdb);
// set repaired plan
goal.setPlan(plan);
// set goal as repaired
goal.setRepaired(true);
// set the tick the execution will start
goal.setExecutionTick(goal.getFailureCause().getInterruptionTick());
// clear execution trace
goal.clearExecutionTrace();
} catch (Exception ex) {
// error while repairing
success = false;
// error message
this.log.error("Error while trying to repair the plan\n"
+ "\t- message: " + ex.getMessage() + "\n");
// completely clear all the plan database
for (DomainComponent comp : this.pdb.getComponents()) {
// remove all pending decisions
List<Decision> pendings = comp.getPendingDecisions();
for (Decision pending : pendings) {
comp.deactivate(pending);
comp.free(pending);
}
// remove all active decisions
List<Decision> actives = comp.getActiveDecisions();
for (Decision active : actives) {
comp.deactivate(active);
comp.free(active);
}
// completely clear component
comp.clear();
}
} finally {
// compute actual planning time
long time = System.currentTimeMillis() - now;
// add planning time attempt to the goal
goal.addContingencyHandlingAttempt(time);
goal.addPlanningAttempt(time);
}
*/
// force abort without a recovery strategy
boolean success = false;
synchronized (this.lock) {
// update status according to the execution results
this.status = ActingAgentStatus.READY;
// send signal
this.lock.notifyAll();
}
// return execution result
return success;
}
/**
*
* @param status
* @throws InterruptedException
*/
protected Goal waitGoal(GoalStatus status)
throws InterruptedException {
// goal
Goal goal = null;
// wait a selected goal
synchronized (this.queue) {
// check selected buffer
while (this.queue.get(status).isEmpty()) {
// wait a selected goal
this.queue.wait();
}
// print the number of committed goals
this.log.info("[GoalOrientedActingAgent] Checking available goals to be processed\n" +
"- Goal status: " + status + "\n" +
"- Number of queued goals: " + this.queue.get(status).size() + "\n");
// remove the first selected goal from the queue
goal = this.queue.get(status).remove(0);
// send signal
this.queue.notifyAll();
}
// get extracted goal
return goal;
}
}
| 26.159292
| 156
| 0.656139
|
4337ed61b4d4df5324c9652d5fe74a79dce8192b
| 1,565
|
package io.coin.ccbc.api.web.filter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class AuthenticationFilter extends OncePerRequestFilter {
public static final String CLIENT_ID = "clientId";
@Value("${app.auth.token}")
private String token;
private final AntPathMatcher antPathMatcher;
public AuthenticationFilter() {
this.antPathMatcher = new AntPathMatcher();
}
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain
) throws ServletException, IOException {
String token = request.getParameter(CLIENT_ID);
if (!this.token.equals(token)) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
return;
}
filterChain.doFilter(request, response);
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
String path = request.getServletPath();
return !this.antPathMatcher.match("/api/v1/operation/**", path);
}
}
| 32.604167
| 72
| 0.736102
|
ff3c8b372741acf4b4b9c7bfbc72b68afa223107
| 805
|
package org.blab.mde.eve.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.blab.mde.core.annotation.Mixin;
import org.blab.mde.core.annotation.Property;
import org.blab.mde.eve.EventEngine;
import org.blab.mde.eve.core.TypedEvent;
@Mixin
public interface SpringEventMixin {
@Autowired
@Property
EventEngine getEventEngine();
void setEventEngine(EventEngine eventEngine);
default void syncPost(TypedEvent event) {
getEventEngine().getEventBus().post(event);
}
default void asyncPost(TypedEvent event) {
getEventEngine().getAsyncEventBus().post(event);
}
default void register(Class<?> listener) {
getEventEngine().register(listener);
}
default void deregister(Class<?> listener) {
getEventEngine().unregister(listener);
}
}
| 22.361111
| 62
| 0.751553
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.