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 |
|---|---|---|---|---|---|
a9c0077e2f413c703226497b1152e87d9192a57a | 2,707 | package com.omgren.apps.smsgcm.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.LinkedList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class SendMessageServlet extends BaseServlet {
static final String ATTRIBUTE_STATUS = "status";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException
{
String address = req.getParameter("address");
String message = req.getParameter("message");
String dump = req.getParameter("dump");
String list = req.getParameter("list");
boolean page_reload = address != null && message != null && address.length() > 0;
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
/* print a form and be nice */
if( !page_reload ){
resp.setContentType("text/html");
out.print("<html><head><title>send stuff</title></head>");
out.print("<body onload=\"document.forms[0].address.focus();\"><form action=\"\" method=\"get\">");
out.print("<input type=\"text\" name=\"address\" />");
out.print("<input type=\"text\" name=\"message\" />");
out.print("<input type=\"hidden\" name=\"list\" value=\"1\" />");
out.print("<input type=\"submit\" name=\"submit\" />");
out.print("</form></body></html>");
resp.setStatus(HttpServletResponse.SC_OK);
return;
}
/* TODO: find the right phone */
DSDevice phone = Datastore.lookupUser(req).getDevice(0);
/* tell there is no phone */
if( phone == null ){
resp.setContentType("text/plain");
out.print("no devices connected");
resp.setStatus(HttpServletResponse.SC_OK);
return;
}
/* queue up the message and notify the phone */
phone.queueMessage(address, message);
List<String> devices = new LinkedList();
devices.add(phone.getDeviceId());
GCMNotify.notify(req, devices);
/* list or dump set, forward request to /received */
if( list != null || dump != null ){
String url = "/received";
resp.setContentType("application/json");
getServletContext().getRequestDispatcher(url).include(req, resp);
resp.setStatus(HttpServletResponse.SC_OK);
return;
}
/* say okay if message sent successfully */
resp.setContentType("text/plain");
out.print("OK");
resp.setStatus(HttpServletResponse.SC_OK);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
doGet(req, resp);
}
}
| 31.476744 | 105 | 0.665312 |
7c273405fdb35a801b5c7adbfa4ddf78a13a93f4 | 177 | package com.eshare.dto;
import lombok.Data;
/**
* 产品额度强制解冻命令
* @Author Evan Leung
**/
@Data
public class ProductQuotaForcedUnfreezeCmd extends BaseQuotaStatusChangeCmd {
}
| 14.75 | 77 | 0.762712 |
3c087e7f31e82297c6ab436fa5d4537e3db12ff3 | 3,194 | /*
* 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.dolphinscheduler.dao.datasource;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.common.enums.DbType;
import org.apache.dolphinscheduler.common.utils.CommonUtils;
import org.apache.dolphinscheduler.common.utils.HiveConfUtils;
import org.apache.dolphinscheduler.common.utils.StringUtils;
import java.sql.Connection;
/**
* data source of hive
*/
public class HiveDataSource extends BaseDataSource {
/**
* gets the JDBC url for the data source connection
* @return jdbc url
*/
@Override
public String driverClassSelector() {
return Constants.ORG_APACHE_HIVE_JDBC_HIVE_DRIVER;
}
/**
* @return db type
*/
@Override
public DbType dbTypeSelector() {
return DbType.HIVE;
}
/**
* build hive jdbc params,append : ?hive_conf_list
*
* hive jdbc url template:
*
* jdbc:hive2://<host1>:<port1>,<host2>:<port2>/dbName;initFile=<file>;sess_var_list?hive_conf_list#hive_var_list
*
* @param otherParams otherParams
* @return filter otherParams
*/
@Override
protected String filterOther(String otherParams) {
if (StringUtils.isBlank(otherParams)) {
return "";
}
StringBuilder hiveConfListSb = new StringBuilder();
hiveConfListSb.append("?");
StringBuilder sessionVarListSb = new StringBuilder();
String[] otherArray = otherParams.split(";", -1);
for (String conf : otherArray) {
if (HiveConfUtils.isHiveConfVar(conf)) {
hiveConfListSb.append(conf).append(";");
} else {
sessionVarListSb.append(conf).append(";");
}
}
// remove the last ";"
if (sessionVarListSb.length() > 0) {
sessionVarListSb.deleteCharAt(sessionVarListSb.length() - 1);
}
if (hiveConfListSb.length() > 0) {
hiveConfListSb.deleteCharAt(hiveConfListSb.length() - 1);
}
return sessionVarListSb.toString() + hiveConfListSb.toString();
}
/**
* the data source test connection
* @return Connection Connection
* @throws Exception Exception
*/
@Override
public Connection getConnection() throws Exception {
CommonUtils.loadKerberosConf();
return super.getConnection();
}
}
| 30.711538 | 117 | 0.666562 |
edde141c5de7884a5cc4e8c1000c20a4e1baabb4 | 361 | package com.jeradmeisner.audioserver.dto;
import com.jeradmeisner.audioserver.interfaces.StateObject;
import com.jeradmeisner.audioserver.state.Client;
import java.util.List;
public class ClientStateObject implements StateObject {
public List<Client> clients;
public ClientStateObject(List<Client> clients) {
this.clients = clients;
}
}
| 24.066667 | 59 | 0.775623 |
ecb83bdd9647f0fdfb10c2e30f97190c06c4d859 | 1,899 | /*
* Copyright (c) 2017. All rights reserved
*/
package fr.techad.edc.client.util;
import fr.techad.edc.client.model.InvalidUrlException;
/**
* This class generate the url according to the context.
*/
public interface UrlUtil {
/**
* Return the home url for the help client
*
* @return the home url
* @throws InvalidUrlException If the base url is not defined
*/
String getHomeUrl() throws InvalidUrlException;
/**
* Return the error url for the help client
*
* @return the home url
* @throws InvalidUrlException If the base url is not defined
*/
String getErrorUrl() throws InvalidUrlException;
/**
* Build the web help context url for the brick defined with the keys, the language and the index of the article to display
*
* @param publicationId the identifier of the publication
* @param mainKey the main key
* @param subKey the sub key
* @param languageCode the language code
* @param articleIndex the article index to display
* @return the url
* @throws InvalidUrlException If the url is malformed
*/
String getContextUrl(String publicationId, String mainKey, String subKey, String languageCode, int articleIndex) throws InvalidUrlException;
/**
* Build the web help documentation url for the document defined by the identifier, the language code,
* and the publication identifier if present
*
* @param id the idenitifer of the documentation
* @param languageCode the 2 letters code of the language (en, fr..)
* @param srcPublicationId the identifier of the publication from where navigation will start
* @return the url
* @throws InvalidUrlException If the url is malformed
*/
String getDocumentationUrl(Long id, String languageCode, String srcPublicationId) throws InvalidUrlException;
}
| 33.910714 | 144 | 0.695629 |
b0005eab565e20ef408e63d0569c052bb1c4f37e | 9,177 | /*
* Copyright (c) 2010-2012 LinkedIn, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package krati.core.array.basic;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.log4j.Logger;
import krati.Mode;
import krati.array.Array;
import krati.array.DynamicArray;
import krati.core.OperationAbortedException;
import krati.core.array.AddressArray;
import krati.core.array.entry.Entry;
import krati.core.array.entry.EntryLongFactory;
import krati.core.array.entry.EntryPersistListener;
import krati.core.array.entry.EntryValueLong;
/**
* IOTypeLongArray
*
* @author jwu
*
* <p>
* 06/24, 2011 - Fixed the water marks of underlying ArrayFile. <br/>
*/
public class IOTypeLongArray extends AbstractRecoverableArray<EntryValueLong> implements AddressArray, DynamicArray {
private final static int _subArrayBits = DynamicConstants.SUB_ARRAY_BITS;
private final static int _subArraySize = DynamicConstants.SUB_ARRAY_SIZE;
private final static Logger _logger = Logger.getLogger(IOTypeLongArray.class);
private final Array.Type _type;
private float _expandRate = 0;
/**
* The mode can only be <code>Mode.INIT</code>, <code>Mode.OPEN</code> and <code>Mode.CLOSED</code>.
*/
private volatile Mode _mode = Mode.INIT;
public IOTypeLongArray(Array.Type type, int length, int batchSize, int numSyncBatches, File directory) throws Exception {
super(length, 8 /* elementSize */, batchSize, numSyncBatches, directory, new EntryLongFactory());
this._type = (type != null) ? type : Array.Type.DYNAMIC;
this._mode = Mode.OPEN;
}
@Override
protected Logger getLogger() {
return _logger;
}
@Override
protected void loadArrayFileData() {
long maxScn = _arrayFile.getLwmScn();
_entryManager.setWaterMarks(maxScn, maxScn);
}
/**
* Sync-up the high water mark to a given value.
*
* @param endOfPeriod
*/
@Override
public void saveHWMark(long endOfPeriod) {
if(getHWMark() < endOfPeriod) {
try {
set(0, get(0), endOfPeriod);
} catch(Exception e) {
_logger.error("Failed to saveHWMark " + endOfPeriod, e);
}
} else if(0 < endOfPeriod && endOfPeriod < getLWMark()) {
try {
_entryManager.sync();
} catch(Exception e) {
_logger.error("Failed to saveHWMark" + endOfPeriod, e);
}
_entryManager.setWaterMarks(endOfPeriod, endOfPeriod);
}
}
@Override
public void clear() {
// Clear the entry manager
_entryManager.clear();
// Clear the underlying array file
try {
_arrayFile.resetAll(0L, _entryManager.getHWMark());
} catch(IOException e) {
_logger.error(e.getMessage(), e);
}
}
protected long getPosition(int index) {
return ArrayFile.ARRAY_HEADER_LENGTH + ((long)index << 3);
}
@Override
public long get(int index) {
if(index < 0 || index >= _length) {
throw new ArrayIndexOutOfBoundsException(index);
}
try {
return _arrayFile.getBasicIO().readLong(getPosition(index));
} catch (IOException e) {
throw new OperationAbortedException("Read aborted at index " + index, e);
}
}
@Override
public void set(int index, long value, long scn) throws Exception {
if(index < 0) {
throw new ArrayIndexOutOfBoundsException(index);
}
if(_type == Array.Type.DYNAMIC) {
expandCapacity(index);
} else if(_type == Array.Type.STATIC && index >= _length) {
throw new ArrayIndexOutOfBoundsException(index);
}
_arrayFile.getBasicIO().writeLong(getPosition(index), value);
_entryManager.addToPreFillEntryLong(index, value, scn);
}
@Override
public void setCompactionAddress(int index, long address, long scn) throws Exception {
if(index < 0) {
throw new ArrayIndexOutOfBoundsException(index);
}
expandCapacity(index);
_arrayFile.getBasicIO().writeLong(getPosition(index), address);
_entryManager.addToPreFillEntryLongCompaction(index, address, scn);
}
@Override
public long[] getInternalArray() {
try {
return _arrayFile.loadLongArray();
} catch (IOException e) {
throw new OperationAbortedException(e);
}
}
@Override
public EntryPersistListener getPersistListener() {
return getEntryManager().getPersistListener();
}
@Override
public void setPersistListener(EntryPersistListener persistListener) {
getEntryManager().setPersistListener(persistListener);
}
@Override
public float getExpandRate() {
return _expandRate;
}
@Override
public void setExpandRate(float rate) {
if(rate < 0 || rate > 1) {
throw new IllegalArgumentException("invalid value: " + rate);
}
this._expandRate = rate;
}
@Override
public void expandCapacity(int index) throws Exception {
if(index < _length) return;
// No expansion on static array
if(_type == Array.Type.STATIC) {
throw new UnsupportedOperationException("Array is of type " + _type);
}
// Choose the larger capacity between linear growth and exponential growth
long capacity = ((index >> _subArrayBits) + 1L) * _subArraySize;
long expandTo = ((_length + (long)(_length * getExpandRate())) >> _subArrayBits) * _subArraySize;
if(capacity < expandTo) {
capacity = expandTo;
}
// Cap length to Integer.MAX_VALUE
int newLength = (capacity < Integer.MAX_VALUE) ? (int)capacity : Integer.MAX_VALUE;
// Expand array file on disk
_arrayFile.setArrayLength(newLength, null /* do not rename */);
// Reset _length
_length = newLength;
// Add to logging
_logger.info("Expanded: _length=" + _length);
}
@Override
public synchronized void close() throws IOException {
if(_mode == Mode.CLOSED) {
return;
}
try {
sync();
_entryManager.clear();
_arrayFile.close();
} catch(Exception e) {
throw (e instanceof IOException) ? (IOException)e : new IOException(e);
} finally {
_arrayFile = null;
_length = 0;
_mode = Mode.CLOSED;
}
}
@Override
public synchronized void open() throws IOException {
if(_mode == Mode.OPEN) {
return;
}
File file = new File(_directory, "indexes.dat");
_arrayFile = openArrayFile(file, _length /* initial length */, 8);
_length = _arrayFile.getArrayLength();
this.init();
this._mode = Mode.OPEN;
getLogger().info("length:" + _length +
" batchSize:" + _entryManager.getMaxEntrySize() +
" numSyncBatches:" + _entryManager.getMaxEntries() +
" directory:" + _directory.getAbsolutePath() +
" arrayFile:" + _arrayFile.getName());
}
@Override
public boolean isOpen() {
return _mode == Mode.OPEN;
}
@Override
public void updateArrayFile(List<Entry<EntryValueLong>> entryList) throws IOException {
if(_arrayFile != null) {
if(isOpen()) {
_arrayFile.flush();
// Find maxScn
long maxScn = 0;
if(entryList != null && entryList.size() > 0) {
for (Entry<?> e : entryList) {
maxScn = Math.max(e.getMaxScn(), maxScn);
}
} else {
maxScn = this.getHWMark();
}
// update arrayFile lwmScn and hwmScn to maxScn
if(maxScn > 0) {
_arrayFile.setWaterMarks(maxScn, maxScn);
}
} else {
// IOTypeLongArray instantiation goes here.
_arrayFile.update(entryList);
}
}
}
@Override
public final Type getType() {
return _type;
}
}
| 31.644828 | 125 | 0.583524 |
8060e8154c097457943f754f61efc6048b1f785e | 1,193 | package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorEx;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.HardwareMap;
@Disabled
public class Lift extends LinearOpMode {
public DcMotorEx lift;
public enum liftSpeed {
FAST,
SLOW,
IDLE
}
liftSpeed speed;
double DOWN_TARGET = 1000;
double MIDDLE_TARGET = 2000;
public void init(HardwareMap hardwareMap){
lift = hardwareMap.get(DcMotorEx.class,"lift");
lift.setDirection(DcMotorSimple.Direction.FORWARD);
}
public void useEncoder(){
lift.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
}
public void runOpMode(){
switch (speed){
case FAST:
lift.setPower(0.8);
break;
case SLOW:
lift.setPower(0.4);
break;
case IDLE:
lift.setPower(0);
break;
}
}
}
| 21.303571 | 60 | 0.629505 |
f6bc83d3a8c8a6d02ed03780f85f1a37ed37afdd | 764 | package nilm;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.*;
public class NormalizationMapper extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {
String valueString = value.toString(); //one line/row data in Spring
String[] SingleData = valueString.split(","); //split that one line data by comma into array of string
output.collect(new Text(SingleData[9]), one); //activePower data (array no 9)
}
}
| 38.2 | 129 | 0.774869 |
28abb332cf213f0c8f481c55da686618dce1b799 | 1,563 | package com.mrthomas20121.libs;
import c4.conarm.lib.materials.ArmorMaterials;
import c4.conarm.lib.materials.CoreMaterialStats;
import c4.conarm.lib.materials.PlatesMaterialStats;
import c4.conarm.lib.materials.TrimMaterialStats;
import slimeknights.tconstruct.library.TinkerRegistry;
import slimeknights.tconstruct.library.materials.Material;
import slimeknights.tconstruct.library.traits.AbstractTrait;
public class ArmorRegistryLib extends RegistryLib {
private CoreMaterialStats coreStats;
private PlatesMaterialStats platesStats;
private TrimMaterialStats trimStats;
public ArmorRegistryLib(Material mat) {
super(mat);
}
public void setCoreStats(float durability, float defence) {
this.coreStats = new CoreMaterialStats(durability, defence);
}
public void setPlatesStats(float modifier, float durability, float toughness) {
this.platesStats = new PlatesMaterialStats(modifier, durability, toughness);
}
public void setTrimStats(float extradurability) {
this.trimStats = new TrimMaterialStats(extradurability);
}
@Override
public void registerMaterialTrait(AbstractTrait trait, String dependency) {
ArmorMaterials.addArmorTrait(this.getMat(), trait, dependency);
}
@Override
public void registerMaterialTrait(AbstractTrait trait) {
ArmorMaterials.addArmorTrait(this.getMat(), trait);
}
public void registerArmor() {
TinkerRegistry.addMaterialStats(this.getMat(), this.coreStats, this.platesStats, this.trimStats);
}
}
| 34.733333 | 105 | 0.760717 |
a4604ba31253f7f5b3d9ac7355c4d288ad541617 | 676 | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package org.achartengine.model;
import java.io.Serializable;
public final class Point
implements Serializable
{
private float a;
private float b;
public Point()
{
}
public Point(float f, float f1)
{
a = f;
b = f1;
}
public float getX()
{
return a;
}
public float getY()
{
return b;
}
public void setX(float f)
{
a = f;
}
public void setY(float f)
{
b = f;
}
}
| 14.695652 | 62 | 0.56213 |
fe6b2f8019d2e152b0ec04faedc016d7bd7269b5 | 2,036 | /*
* Copyright 2018 OmniFaces
*
* 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.omnifaces.utils.stream;
import static java.util.Collections.emptySet;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
class FindLastCollector<T> implements Collector<T, FindLastCollector.LastEncounteredElemement<T>, Optional<T>> {
static class LastEncounteredElemement<T> {
private boolean set;
private T element;
void nextElement(T nextElement) {
set = true;
element = nextElement;
}
LastEncounteredElemement<T> combine(LastEncounteredElemement<T> other) {
if (other.set) {
return other;
}
return this;
}
Optional<T> toOptional() {
if (set) {
return Optional.of(element);
}
return Optional.empty();
}
}
@Override
public Supplier<LastEncounteredElemement<T>> supplier() {
return LastEncounteredElemement::new;
}
@Override
public BiConsumer<LastEncounteredElemement<T>, T> accumulator() {
return LastEncounteredElemement::nextElement;
}
@Override
public BinaryOperator<LastEncounteredElemement<T>> combiner() {
return LastEncounteredElemement::combine;
}
@Override
public Function<LastEncounteredElemement<T>, Optional<T>> finisher() {
return LastEncounteredElemement::toOptional;
}
@Override
public Set<Characteristics> characteristics() {
return emptySet();
}
}
| 26.102564 | 118 | 0.750982 |
757f56d98eb3dcf12028a7d1f8e2c0e5000aecbe | 912 | package de.protubero.beanstore.api;
import java.util.function.Consumer;
import de.protubero.beanstore.base.tx.TransactionEvent;
/**
* An executable transaction is explicitly executed by client code,
* in contrast to e.g. migration transactions.
*/
public interface ExecutableBeanStoreTransaction extends BeanStoreTransaction {
/**
* Enqueue the transaction. The calling thread immediately returns.
*/
default void executeAsync() {
executeAsync(null);
}
/**
* Enqueue the transaction. The calling thread immediately returns.
* After the transaction has been executed, the callback code is invoked.
*/
void executeAsync(Consumer<TransactionEvent> consumer);
/**
* Execute the transaction.
* The calling thread is blocked until the execution finished.
*
* @return Information about the executed transaction, e.g. if it was successful.
*/
TransactionEvent execute();
}
| 25.333333 | 82 | 0.747807 |
2db2d11a16473d3c8f74661104100aa88fc710ea | 4,744 | package net.mahdilamb.colormap.tests;
import net.mahdilamb.colormap.Colors;
import org.junit.jupiter.api.Test;
import java.awt.*;
import static org.junit.jupiter.api.Assertions.*;
public class ColorTests {
/**
* Compare the results to EasyRGB.com for primary and secondary colors
*/
@Test
public void RGBToXYZIsCalculatedCorrectlyTest() {
assertArrayEquals(new float[]{0, 0, 0}, Colors.RGBToXYZ(0, 0, 0), 0.01f);
assertArrayEquals(new float[]{41.246f, 21.267f, 1.933f}, Colors.RGBToXYZ(1, 0, 0), 0.01f);
assertArrayEquals(new float[]{35.758f, 71.515f, 11.919f}, Colors.RGBToXYZ(0, 1, 0), 0.01f);
assertArrayEquals(new float[]{18.044f, 7.217f, 95.03f}, Colors.RGBToXYZ(0, 0, 1), 0.01f);
assertArrayEquals(new float[]{53.801f, 78.733f, 106.950f}, Colors.RGBToXYZ(0, 1, 1), 0.01f);
assertArrayEquals(new float[]{59.289f, 28.485f, 96.964f}, Colors.RGBToXYZ(1, 0, 1), 0.01f);
assertArrayEquals(new float[]{77.003f, 92.783f, 13.85f}, Colors.RGBToXYZ(1, 1, 0), 0.01f);
assertArrayEquals(new float[]{95.047f, 100.000f, 108.883f}, Colors.RGBToXYZ(1, 1, 1), 0.01f);
}
@Test
public void XYZToRGBIsCalculatedCorrectlyTest() {
assertArrayEquals(new float[]{0, 0, 0}, Colors.XYZToRGB(0, 0, 0), 0.01f);
assertArrayEquals(new float[]{1, 0, 0}, Colors.XYZToRGB(41.246f, 21.267f, 1.933f), 0.01f);
assertArrayEquals(new float[]{0, 1, 0}, Colors.XYZToRGB(35.758f, 71.515f, 11.919f), 0.01f);
assertArrayEquals(new float[]{0, 0, 1}, Colors.XYZToRGB(18.044f, 7.217f, 95.03f), 0.01f);
assertArrayEquals(new float[]{0, 1, 1}, Colors.XYZToRGB(53.801f, 78.733f, 106.950f), 0.01f);
assertArrayEquals(new float[]{1, 0, 1}, Colors.XYZToRGB(59.289f, 28.485f, 96.964f), 0.01f);
assertArrayEquals(new float[]{1, 1, 0}, Colors.XYZToRGB(77.003f, 92.783f, 13.85f), 0.01f);
assertArrayEquals(new float[]{1, 1, 1}, Colors.XYZToRGB(95.047f, 100.000f, 108.883f), 0.01f);
}
@Test
public void RGBToLabIsCalculatedCorrectlyTest() {
assertArrayEquals(new float[]{0, 0, 0}, Colors.RGBToLab(0,0,0), 0.01f);
assertArrayEquals(new float[]{53.241f, 80.092f, 67.203f}, Colors.RGBToLab(1.f, 0, 0), 0.01f);
assertArrayEquals(new float[]{87.735f, -86.183f, 83.179f}, Colors.RGBToLab(0, 1.f, 0), 0.01f);
assertArrayEquals(new float[]{32.297f, 79.188f, -107.860f}, Colors.RGBToLab(0, 0, 1.f), 0.01f);
assertArrayEquals(new float[]{91.113f, -48.088f, -14.131f}, Colors.RGBToLab(0, 1, 1.f), 0.01f);
assertArrayEquals(new float[]{60.324f, 98.234f, -60.825f}, Colors.RGBToLab(1, 0, 1.f), 0.01f);
assertArrayEquals(new float[]{97.139f, -21.554f, 94.478f}, Colors.RGBToLab(1, 1, 0.f), 0.01f);
assertArrayEquals(new float[]{100.000f, 0.000f, -0.000f}, Colors.RGBToLab(1, 1, 1.f), 0.01f);
}
@Test
public void LabToRGBsCalculatedCorrectlyTest() {
assertArrayEquals(new float[]{0, 0, 0}, Colors.RGBToLab(0, 0, 0), 0.01f);
assertArrayEquals(new float[]{1, 0, 0}, Colors.LabToRGB(53.241f, 80.092f, 67.203f), 0.01f);
assertArrayEquals(new float[]{0, 1, 0}, Colors.LabToRGB(87.735f, -86.183f, 83.179f), 0.01f);
assertArrayEquals(new float[]{0, 0, 1}, Colors.LabToRGB(32.297f, 79.188f, -107.860f), 0.01f);
assertArrayEquals(new float[]{0, 1, 1}, Colors.LabToRGB(91.113f, -48.088f, -14.131f), 0.01f);
assertArrayEquals(new float[]{1, 0, 1}, Colors.LabToRGB(60.324f, 98.234f, -60.825f), 0.01f);
assertArrayEquals(new float[]{1, 1, 0}, Colors.LabToRGB(97.139f, -21.554f, 94.478f), 0.01f);
assertArrayEquals(new float[]{1, 1, 1}, Colors.LabToRGB(100.000f, 0.000f, -0.000f), 0.01f);
}
@Test
public void HexSanitizationTest() {
try {
Colors.sanitizeRGBA("#00ff00");
Colors.sanitizeRGBA("#00ff00ff");
Colors.sanitizeRGBA("00ff00");
Colors.sanitizeRGBA("00ff00ff");
Colors.sanitizeRGB("#00ff00");
Colors.sanitizeRGB("#00ff00ff");
Colors.sanitizeRGB("00ff00");
Colors.sanitizeRGB("00ff00ff");
} catch (Exception e) {
fail("Should not have thrown any exception");
}
}
@Test
public void HexSanitizationAltTest() {
assertThrows(UnsupportedOperationException.class,() -> {
Colors.sanitizeRGBA("#00ff0");
Colors.sanitizeRGBA("#00f00ff");
Colors.sanitizeRGBA("00f00");
Colors.sanitizeRGBA("f00ff");
Colors.sanitizeRGB("#0ff00");
Colors.sanitizeRGB("#0f0ff");
Colors.sanitizeRGB("0ff00");
Colors.sanitizeRGB("f00ff");
});
}
}
| 46.970297 | 103 | 0.621627 |
4e8ef0692dce8fc2da2f285041e86893f79f25a3 | 808 | package com.patika.service;
import com.patika.model.Student;
import com.patika.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
public interface StudentService{
public List<Student> findAll();
public Optional<Student> findById(int id);
public void saveToDatabase(Student object);
public void deleteFromDatabase(Student object);
public void deleteFromDatabase(int id);
public void updateOnDatabase(Student object);
public Optional<Student> findByGender(String gender);
}
| 26.933333 | 66 | 0.77104 |
0923d4de62e1931729c1a63200f3bd2f57767632 | 1,977 | /*
* Copyright 2015 Akyruu (akyruu@hotmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.avaryuon.fwk.core.bean.context.holder;
import java.util.HashMap;
import java.util.Map;
import org.jboss.weld.context.BoundContext;
import org.jboss.weld.context.ManagedContext;
/**
* <b>title</b>
* <p>
* description
* </p>
*
* @author Akyruu (akyruu@hotmail.com)
* @version 0.1
*/
public abstract class SimpleScopedHolder< C extends ManagedContext& BoundContext< Map< String, Object >>> {
/* STATIC FIELDS ======================================================= */
// Nothing here
/* FIELDS ============================================================== */
private Map< String, Object > storage;
/* CONSTRUCTORS ======================================================== */
public SimpleScopedHolder() {
storage = new HashMap< String, Object >();
}
/* METHODS ============================================================= */
/* Access -------------------------------------------------------------- */
protected abstract C getContext();
/* Life-cycle ---------------------------------------------------------- */
public void start() {
C context = getContext();
storage.clear();
context.associate( storage );
context.activate();
}
public void end() {
C context = getContext();
try {
context.invalidate();
context.deactivate();
} finally {
storage.clear();
context.dissociate( storage );
}
}
}
| 29.073529 | 107 | 0.564997 |
663147d30dd266ada43a92bdf9be63bbbb5d81a8 | 1,086 | package com.robin.basis.model;
import com.robin.core.base.annotation.MappingField;
import com.robin.core.base.model.BaseObject;
import java.time.LocalDateTime;
public abstract class AbstractModel extends BaseObject {
@MappingField
private LocalDateTime createTm;
@MappingField
private LocalDateTime modifyTm;
@MappingField
private Long createUser;
@MappingField
private Long modifyUser;
public LocalDateTime getCreateTm() {
return createTm;
}
public void setCreateTm(LocalDateTime createTm) {
this.createTm = createTm;
}
public LocalDateTime getModifyTm() {
return modifyTm;
}
public void setModifyTm(LocalDateTime modifyTm) {
this.modifyTm = modifyTm;
}
public Long getCreateUser() {
return createUser;
}
public void setCreateUser(Long createUser) {
this.createUser = createUser;
}
public Long getModifyUser() {
return modifyUser;
}
public void setModifyUser(Long modifyUser) {
this.modifyUser = modifyUser;
}
}
| 20.884615 | 56 | 0.6814 |
1f7a072922bef8281c97e689daa0464f8f44da7b | 132 | package everyos.browser.webicity.webribbon.gui.box;
public interface MutableInlineLevelBox extends InlineLevelBox, MutableBox {
}
| 22 | 75 | 0.840909 |
0756002463802174064bb7646512df4070c2bbd9 | 3,514 | /*
* 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 co.edu.uniandes.csw.mascotas.ejb;
import co.edu.uniandes.csw.mascotas.entities.EventoEntity;
import co.edu.uniandes.csw.mascotas.exceptions.BusinessLogicException;
import co.edu.uniandes.csw.mascotas.persistence.EventoPersistence;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
/**
*
* @author Daniela Gonzalez
*/
@Stateless
public class EventoLogic {
@Inject
private EventoPersistence persistence;
/**
* Crea un evento a partir de la entidad ingresada por parámetro
* @param evento
* @return entidad del evento creado
* @throws BusinessLogicException
*/
public EventoEntity crearEvento(EventoEntity evento) throws BusinessLogicException{
//Validacion reglas de negocio
if(evento.getNombre()== null){
throw new BusinessLogicException("Un evento debe tener un nombre");
}
if(evento.getDescripcion()== null){
throw new BusinessLogicException("Un evento debe tener una descripcion");
}
if(evento.getFechaInicio().compareTo(evento.getFechaFin())>0){
throw new BusinessLogicException("La fecha de inicio debe ser antes de la fecha de fin");
}
evento = persistence.create(evento);
return evento;
}
/**
* Busca un evento por su id
* @param eventoId Llave del evento
* @return elEvento
*/
public EventoEntity encontrarEventoPorId(Long eventoId){
EventoEntity elEvento = persistence.find(eventoId);
return elEvento;
}
/**
* Busca todos los eventos
* @return eventos
*/
public List<EventoEntity> encontrarTodosEventos(){
List<EventoEntity> eventos = persistence.findAll();
return eventos;
}
/**
*
* Actualizar un evento.
*
* @param id: id del evento que se quiere actualizar para buscarlo en la base de
* datos.
* @param nuevo: evento con los cambios para ser actualizado.
* Por ejemplo el titulo.
* @throws BusinessLogicException si la informacion nueva no cumple las reglas de negocio.
* @return el evento con los cambios actualizados en la base de datos.
*/
public EventoEntity actualizarEvento(Long id, EventoEntity nuevo) throws BusinessLogicException{
//Validacion reglas de negocio
if(nuevo.getNombre()== null){
throw new BusinessLogicException("El nuevo nombre debe ser valido");
}
if(nuevo.getDescripcion()== null){
throw new BusinessLogicException("La nueva descripcion debe ser valida");
}
if(nuevo.getFechaInicio().compareTo(nuevo.getFechaFin())>0){
throw new BusinessLogicException("La fecha de inicio debe ser antes de la fecha final");
}
nuevo.setId(id);
EventoEntity cambiado = persistence.actualizarEvento(nuevo);
return cambiado;
}
/**
* Borrar un evento
*
* @param id: id del evento a borrar.
*/
public void eliminarEvento(Long id) {
persistence.delete(id);
}
}
| 31.097345 | 104 | 0.617814 |
0e7b6651503cf373a5f4399ea27490cf624fc3b1 | 2,238 | // automatically generated by the FlatBuffers compiler, do not modify
package edu.ucsc.soe.sys;
import java.nio.*;
import java.lang.*;
import com.google.flatbuffers.*;
@SuppressWarnings("unused")
public final class Extent extends Table {
public static Extent getRootAsExtent(ByteBuffer _bb) { return getRootAsExtent(_bb, new Extent()); }
public static Extent getRootAsExtent(ByteBuffer _bb, Extent obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
public void __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; }
public Extent __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
public long from() { int o = __offset(4); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
public long to() { int o = __offset(6); return o != 0 ? bb.getLong(o + bb_pos) : 0L; }
public String replicas(int j) { int o = __offset(8); return o != 0 ? __string(__vector(o) + j * 4) : null; }
public int replicasLength() { int o = __offset(8); return o != 0 ? __vector_len(o) : 0; }
public static int createExtent(FlatBufferBuilder builder,
long from,
long to,
int replicasOffset) {
builder.startObject(3);
Extent.addTo(builder, to);
Extent.addFrom(builder, from);
Extent.addReplicas(builder, replicasOffset);
return Extent.endExtent(builder);
}
public static void startExtent(FlatBufferBuilder builder) { builder.startObject(3); }
public static void addFrom(FlatBufferBuilder builder, long from) { builder.addLong(0, from, 0L); }
public static void addTo(FlatBufferBuilder builder, long to) { builder.addLong(1, to, 0L); }
public static void addReplicas(FlatBufferBuilder builder, int replicasOffset) { builder.addOffset(2, replicasOffset, 0); }
public static int createReplicasVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); }
public static void startReplicasVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); }
public static int endExtent(FlatBufferBuilder builder) {
int o = builder.endObject();
return o;
}
}
| 49.733333 | 222 | 0.713584 |
72b28543515f80a965c2f54859f4196107b3e83e | 445 | package org.liwang.dao.manager;
import org.liwang.entity.Operate;
import org.liwang.manager.DefaultDaoManager;
import org.springframework.stereotype.Component;
/**
* 操作明细daomanager
* @author liwang
*
*/
@Component
public class OperateDaoManager extends DefaultDaoManager<Operate>{
/**
* 加权限因为在新增时数据的权限默认与操作对象的权限一致
*/
@Override
protected void preOperate(Operate entity, String operatFlag) {
setGroupStr(entity, operatFlag);
}
}
| 18.541667 | 66 | 0.770787 |
46bd1fcf7d0704a6e51e68cce7a824b6f6db1773 | 1,187 | package com.myproject.imageprocessing;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class splash extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
TextView logo = (TextView) findViewById(R.id.logo);
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 5 seconds
sleep(4*1000);
// After 5 seconds redirect to another intent
Intent i=new Intent(getBaseContext(),Dashboard.class);
startActivity(i);
//Remove activity
finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();
Toast.makeText(getApplicationContext(),"WELCOME",Toast.LENGTH_LONG).show();
}
}
| 29.675 | 84 | 0.562763 |
5acb5cfe12d2c37dac8b6a5c5a9c794ed08b216c | 3,263 | /**
* Copyright (c) 2014 Technische Universitat Wien (TUW), Distributed Systems Group E184 (http://dsg.tuwien.ac.at)
*
* This work was partially supported by the EU FP7 FET SmartSociety (http://www.smart-society-project.eu/).
*
* 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 at.ac.tuwien.dsg.smartcom.manager.auth;
import at.ac.tuwien.dsg.smartcom.broker.MessageBroker;
import at.ac.tuwien.dsg.smartcom.model.Identifier;
import at.ac.tuwien.dsg.smartcom.model.Message;
import at.ac.tuwien.dsg.smartcom.utils.PicoHelper;
import at.ac.tuwien.dsg.smartcom.utils.PredefinedMessageHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* @author Philipp Zeppezauer (philipp.zeppezauer@gmail.com)
* @version 1.0
*/
public abstract class AuthenticationRequestHandlerTestClass {
PicoHelper pico;
AuthenticationRequestHandler handler;
MessageBroker broker;
@Before
public void setUp() throws Exception {
handler = pico.getComponent(AuthenticationRequestHandler.class);
broker = pico.getComponent(MessageBroker.class);
pico.start();
}
@After
public void tearDown() throws Exception {
pico.stop();
}
@Test
public void testOnMessage() throws Exception {
//the content should be either "true" or "false".
//Because the PMCallback will return either true or false depending on the content of the message
//if the content is empty or anything else, it will throw an error
broker.publishAuthRequest(PredefinedMessageHelper.createAuthenticationRequestMessage(Identifier.peer("test1"), "true"));
Message message = broker.receiveControl();
assertNotNull(message);
assertNotNull(message.getContent());
assertNotNull(message.getSenderId());
assertEquals("AUTH", message.getType());
assertEquals("REPLY", message.getSubtype());
broker.publishAuthRequest(PredefinedMessageHelper.createAuthenticationRequestMessage(Identifier.peer("test1"), "false"));
message = broker.receiveControl();
assertNotNull(message);
assertNotNull(message.getSenderId());
assertEquals("AUTH", message.getType());
assertEquals("FAILED", message.getSubtype());
broker.publishAuthRequest(PredefinedMessageHelper.createAuthenticationRequestMessage(Identifier.peer("test1"), "error"));
message = broker.receiveControl();
assertNotNull(message);
assertNotNull(message.getSenderId());
assertEquals("AUTH", message.getType());
assertEquals("ERROR", message.getSubtype());
}
}
| 38.388235 | 129 | 0.715599 |
023a5c982b3582f3b06b1be04a90260be2f79e4b | 9,346 | package info.u_team.music_player.gui.controls;
import static info.u_team.music_player.init.MusicPlayerLocalization.GUI_CONTROLS_VOLUME;
import static info.u_team.music_player.init.MusicPlayerLocalization.getTranslation;
import java.util.ArrayList;
import java.util.List;
import com.mojang.blaze3d.matrix.MatrixStack;
import info.u_team.music_player.gui.BetterNestedGui;
import info.u_team.music_player.gui.GuiMusicPlayer;
import info.u_team.music_player.gui.settings.GuiMusicPlayerSettings;
import info.u_team.music_player.gui.util.GuiTrackUtils;
import info.u_team.music_player.init.MusicPlayerColors;
import info.u_team.music_player.init.MusicPlayerResources;
import info.u_team.music_player.lavaplayer.api.queue.ITrackManager;
import info.u_team.music_player.musicplayer.MusicPlayerManager;
import info.u_team.music_player.musicplayer.MusicPlayerUtils;
import info.u_team.music_player.musicplayer.settings.Repeat;
import info.u_team.music_player.musicplayer.settings.Settings;
import info.u_team.u_team_core.gui.elements.ImageActivatableButton;
import info.u_team.u_team_core.gui.elements.ImageButton;
import info.u_team.u_team_core.gui.elements.ImageToggleButton;
import info.u_team.u_team_core.gui.renderer.ScrollingTextRenderer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FocusableGui;
import net.minecraft.client.gui.IGuiEventListener;
import net.minecraft.client.gui.IRenderable;
import net.minecraft.client.gui.screen.IngameMenuScreen;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.Widget;
import net.minecraft.util.text.ITextComponent;
public class GuiControls extends FocusableGui implements BetterNestedGui, IRenderable {
private final int middleX;
private final int y, width;
private final int buttonSize, halfButtonSize;
private final List<Widget> buttons;
private final List<Widget> disableButtons;
private final List<IGuiEventListener> children;
private final ITrackManager manager;
private final ImageToggleButton playButton;
private final GuiMusicProgressBar songProgress;
private final ScrollingTextRenderer titleRender;
private final ScrollingTextRenderer authorRender;
public GuiControls(Screen gui, int y, int width) {
this.y = y;
this.width = width;
middleX = width / 2;
buttons = new ArrayList<>();
disableButtons = new ArrayList<>();
children = new ArrayList<>();
manager = MusicPlayerManager.getPlayer().getTrackManager();
final Minecraft mc = Minecraft.getInstance();
final boolean isSettings = gui instanceof GuiMusicPlayerSettings;
final boolean isIngame = gui instanceof IngameMenuScreen;
final boolean small = isIngame;
buttonSize = small ? 15 : 20;
halfButtonSize = buttonSize / 2;
// Play button
playButton = addButton(new ImageToggleButton(middleX - halfButtonSize, y, buttonSize, buttonSize, MusicPlayerResources.TEXTURE_PLAY, MusicPlayerResources.TEXTURE_PAUSE, !manager.isPaused()));
playButton.setPressable(() -> {
final boolean play = playButton.isToggled();
manager.setPaused(!play);
});
// Skip forward
final ImageButton skipForwardButton = addButton(new ImageButton(middleX + halfButtonSize + 5, y, buttonSize, buttonSize, MusicPlayerResources.TEXTURE_SKIP_FORWARD));
skipForwardButton.setPressable(() -> {
MusicPlayerUtils.skipForward();
});
// Skip back
final ImageButton skipBackButton = addButton(new ImageButton(middleX - (buttonSize + halfButtonSize + 5), y, buttonSize, buttonSize, MusicPlayerResources.TEXTURE_SKIP_BACK));
skipBackButton.setPressable(() -> {
MusicPlayerUtils.skipBack();
});
final Settings settings = MusicPlayerManager.getSettingsManager().getSettings();
// Shuffle button
final ImageActivatableButton shuffleButton = addButton(new ImageActivatableButton(middleX - (2 * buttonSize + halfButtonSize + 10), y, buttonSize, buttonSize, MusicPlayerResources.TEXTURE_SHUFFLE, settings.isShuffle(), MusicPlayerColors.LIGHT_GREEN));
shuffleButton.setPressable(() -> {
settings.setShuffle(!settings.isShuffle());
shuffleButton.setActivated(settings.isShuffle());
});
// Repeat button
final ImageActivatableButton repeatButton = addButton(new ImageActivatableButton(middleX + +buttonSize + halfButtonSize + 10, y, buttonSize, buttonSize, MusicPlayerResources.TEXTURE_REPEAT, settings.getRepeat().isActive(), MusicPlayerColors.LIGHT_GREEN));
repeatButton.setImage(settings.getRepeat().getResource());
repeatButton.setPressable(() -> {
settings.setRepeat(Repeat.forwardCycle(settings.getRepeat()));
repeatButton.setActivated(settings.getRepeat().isActive());
repeatButton.setImage(settings.getRepeat().getResource());
});
// Song progress
songProgress = new GuiMusicProgressBar(manager, middleX - (small ? 50 : 100), y + (small ? 20 : 30), small ? 100 : 200, small ? 3 : 5, small ? 0.5F : 1);
children.add(songProgress);
// Open Settings
if (!isSettings) {
final ImageButton settingsButton = addButtonNonDisable(new ImageButton(width - (15 + 1), 1, 15, 15, MusicPlayerResources.TEXTURE_SETTINGS));
settingsButton.setPressable(() -> mc.displayGuiScreen(new GuiMusicPlayerSettings(gui)));
}
// Open musicplayer gui
if (isIngame) {
final ImageButton guiButton = addButtonNonDisable(new ImageButton(width - (15 * 2 + 2), 1, 15, 15, MusicPlayerResources.TEXTURE_OPEN));
guiButton.setPressable(() -> mc.displayGuiScreen(new GuiMusicPlayer()));
}
// Volume
final int volumeY = width - (70 + (isIngame ? 15 * 2 + 3 : (!isSettings ? 15 + 2 : 1)));
addButtonNonDisable(new GuiVolumeSlider(volumeY, 1, 70, 15, ITextComponent.getTextComponentOrEmpty(getTranslation(GUI_CONTROLS_VOLUME) + ": "), ITextComponent.getTextComponentOrEmpty("%"), 0, 100, settings.getVolume(), false, true, false, 0.7F, slider -> {
settings.setVolume(slider.getValueInt());
MusicPlayerManager.getPlayer().setVolume(settings.getVolume());
}));
final int textRenderWidth = middleX - (2 * buttonSize + halfButtonSize + 10) - (small ? 15 : 35);
final int textRenderY = small ? y : y + 2;
// Render playing track
// Title and author
titleRender = new ScrollingTextRenderer(mc.fontRenderer, () -> GuiTrackUtils.getValueOfPlayingTrack(track -> track.getInfo().getFixedTitle()), small ? 10 : 25, textRenderY);
titleRender.setWidth(textRenderWidth);
titleRender.setStepSize(0.5F);
titleRender.setColor(MusicPlayerColors.YELLOW);
titleRender.setSpeedTime(35);
authorRender = new ScrollingTextRenderer(mc.fontRenderer, () -> GuiTrackUtils.getValueOfPlayingTrack(track -> track.getInfo().getFixedAuthor()), small ? 10 : 25, textRenderY + 10);
authorRender.setWidth(textRenderWidth);
authorRender.setStepSize(0.5F);
authorRender.setColor(MusicPlayerColors.YELLOW);
authorRender.setScale(0.75F);
authorRender.setSpeedTime(35);
// Disable all buttons first
disableButtons.forEach(button -> button.active = false);
// Add all buttons to children
buttons.forEach(children::add);
}
@Override
public boolean isMouseOver(double mouseX, double mouseY) {
return true; // Return always true here to mouseRelease is always called to our entry
}
public void tick() {
if (manager.getCurrentTrack() == null) {
disableButtons.forEach(button -> button.active = false);
} else {
disableButtons.forEach(button -> button.active = true);
}
playButton.setToggled(!manager.isPaused());
}
@Override
public List<? extends IGuiEventListener> getEventListeners() {
return children;
}
@Override
public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
buttons.forEach(button -> button.render(matrixStack, mouseX, mouseY, partialTicks));
songProgress.render(matrixStack, mouseX, mouseY, partialTicks);
titleRender.render(matrixStack, mouseX, mouseY, partialTicks);
authorRender.render(matrixStack, mouseX, mouseY, partialTicks);
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
if (manager.getCurrentTrack() != null && button == 0 && (checkClick(titleRender, mouseX, mouseY) || checkClick(authorRender, mouseX, mouseY))) {
if (GuiTrackUtils.openURI(manager.getCurrentTrack().getInfo().getURI())) {
return true;
}
}
return super.mouseClicked(mouseX, mouseY, button);
}
private boolean checkClick(ScrollingTextRenderer renderer, double mouseX, double mouseY) {
return mouseX >= renderer.getX() && mouseY >= renderer.getY() && mouseX < renderer.getX() + renderer.getWidth() && mouseY < renderer.getY() + (Minecraft.getInstance().fontRenderer.FONT_HEIGHT + 1) * renderer.getScale();
}
private <B extends Widget> B addButton(B button) {
buttons.add(button);
disableButtons.add(button);
return button;
}
private <B extends Widget> B addButtonNonDisable(B button) {
buttons.add(button);
return button;
}
public int getY() {
return y;
}
public int getWidth() {
return width;
}
public ScrollingTextRenderer getTitleRender() {
return titleRender;
}
public ScrollingTextRenderer getAuthorRender() {
return authorRender;
}
public void copyTitleRendererState(ScrollingTextRenderer renderer) {
titleRender.copyState(renderer);
}
public void copyAuthorRendererState(ScrollingTextRenderer renderer) {
authorRender.copyState(renderer);
}
}
| 39.104603 | 258 | 0.760111 |
216dd204f7a46b0fcdac8a7929181727cc97b679 | 1,698 | package solution;
import java.util.Iterator;
import java.util.LinkedList;
/**
* Author:Berlin
* Problem 6:从尾到头打印链表。
* 题目描述:输入一个链表的头结点,从尾到头反过来打印出每个结点的值。
*/
public class PrintLinkedList {
private static class ListNode {
int value;
ListNode next;
public ListNode(int value) {
this.value = value;
next = null;
}
}
// 方法1:时间复杂度:O(n),空间复杂度:O(n)。
// 这道题我们不去改变链表本身的结构(如果可以改变链表本身的结构,就可以翻转链表然后再遍历),
// 然后题目是从尾到头去遍历每个结点的值,我们不可能从头到尾每次去取一个结点的值,所以我们用到一个栈,
// 从头到尾每次读取一个结点的值,然后把结点的值存储到一个栈里面,最后再遍历这个栈就可以了。
// 因为用了标准库中的LinkedList数据结构,所以无法使用递归来做。
public static void inReversedOrder(LinkedList<Integer> list) {
if (list == null || list.isEmpty()) {
return;
}
LinkedList<Integer> stack = new LinkedList<>();
Iterator<Integer> iter = list.iterator();
while (iter.hasNext()) {
stack.push(iter.next());
}
while (!stack.isEmpty()) {
System.out.print(stack.pop() + " ");
}
System.out.println();
}
// 方法2:时间复杂度:O(n),空间复杂度:O(n)。
// 这里我们不使用自带的LinkedList,而是我们自己构造一个结点。
public static void inReversedOrderRecursively(ListNode head) {
ListNode p = head;
if (p != null) {
inReversedOrderRecursively(p.next);
System.out.print(p.value + " "); // 这里也可以用一个额外的ArrayList来存储元素,最后ArrayList存储的就是逆序的链表元素。
}
}
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
inReversedOrder(list);
}
}
| 23.260274 | 101 | 0.583628 |
6ce4cd7946898ad80dd2be7b34bfe3472e56232a | 1,536 | package cn.edu.hust.dao;
import cn.edu.hust.domain.Users;
import cn.edu.hust.mapper.UsersMapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.HashMap;
@Repository
public class UsersDaoImpl implements UsersMapper{
@Autowired
private SqlSessionFactory sqlSessionFactory;
@Override
public int deleteByPrimaryKey(String id) {
return 0;
}
@Override
public int insert(Users record) {
String sql="cn.edu.hust.mapper.UsersMapper.insert";
return this.sqlSessionFactory.openSession().insert(sql,record);
}
@Override
public int insertSelective(Users record) {
return 0;
}
@Override
public Users selectByPrimaryKey(String id) {
return null;
}
@Override
public int updateByPrimaryKeySelective(Users record) {
return 0;
}
@Override
public int updateByPrimaryKey(Users record) {
return 0;
}
@Override
public Users findUsersByUserName(String username) {
String sql="cn.edu.hust.mapper.UsersMapper.findUsersByUserName";
return this.sqlSessionFactory.openSession().selectOne(sql,username);
}
@Override
public Users findUserByUserAndPassword(HashMap<String, String> map) {
String sql="cn.edu.hust.mapper.UsersMapper.findUserByUserAndPassword";
return this.sqlSessionFactory.openSession().selectOne(sql,map);
}
}
| 25.180328 | 78 | 0.707682 |
690cf97ac2438b28aff892124d6779d3322233ff | 2,179 | package org.rowinson.healthcheck.application;
import io.vertx.core.Future;
import org.rowinson.healthcheck.application.interfaces.ServiceRepository;
import org.rowinson.healthcheck.domain.Service;
import java.util.ArrayList;
/**
* Manages all the logic related to the service handling
*/
public class ServiceApplication {
private ServiceRepository repo;
/**
* Constructor
*
* @param repo
*/
public ServiceApplication(ServiceRepository repo) {
this.repo = repo;
}
/**
* Return the list of services that belong to the given user
*
* @param userId
* @param offset
* @param size
* @param orderBy
* @param orderAsc
* @return
*/
public Future<ArrayList<Service>> getBelongingServices(Long userId, int offset, int size, String orderBy, String orderAsc) {
return repo.getPaginatedServices(userId, offset, size, orderBy, orderAsc);
}
/**
* Return all the services
*
* @return
*/
public Future<ArrayList<Service>> getRegisteredServices() {
return repo.getAllServices();
}
/**
* Creates a new service for the user
*
* @param userId
* @param service
* @return
*/
public Future<Long> addServiceToUser(Long userId, Service service) {
service.setUserId(userId);
return repo.createService(service);
}
/**
* Get a service from the user by the given service id
*
* @param userId
* @param serviceId
* @return
*/
public Future<Service> getServiceById(Long userId, Long serviceId) {
return repo.getService(userId, serviceId);
}
/**
* Delete a service from the user
*
* @param userId
* @param serviceId
* @return
*/
public Future<Void> deleteServiceFromUser(Long userId, Long serviceId) {
return repo.deleteService(userId, serviceId);
}
/**
* Changes the status of the service
*
* @param service
* @return
*/
public Future<Void> changeServiceStatus(Service service, String status) {
service.setStatus(status);
// For time constrains we're using this, but ideally in the
// repository it should be just a single SQL query for a single value
return repo.updateService(service);
}
}
| 22.936842 | 126 | 0.680128 |
d137d0df7082b3256a97f3107f246194bdc14c40 | 23,214 | package ui.view;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import data.Volunteer;
import ui.FGFrame;
import util.Util;
@SuppressWarnings("serial")
public class VolInfoView extends View {
private final JLabel subLabel;
private ContentPanel contentPanel;
private static final Object[] ages;
private class ContentPanel extends JScrollPane {
private final GridBagConstraints cpgbc = new GridBagConstraints();
private final ImageIcon editusericon;
private final JPanel content;
// 0 for creating new
// 1 for admin editing vol
// 2 for non editable vol show (admin or not)
int type = -1;
private final JLabel nameLabel = new JLabel();
private JTextField nameField;
private final JLabel idLabel = new JLabel();
private JPanel idoptionpanel = new JPanel();
private JRadioButton chooseIDrb = new JRadioButton("Custom ID");
private JRadioButton generateIDrb = new JRadioButton("Generate random ID");
private JRadioButton phonenumIDrb = new JRadioButton("Use last 4 digits of phone number");
private JTextField idField;
private JRadioButton lastIDrb = null;
// focus listener to track if id is valid
private final JLabel genderLabel = new JLabel();
private JPanel genderoptionpanel = new JPanel();
private JRadioButton malerb = new JRadioButton("Male");
private JRadioButton femalerb = new JRadioButton("Female");
private JLabel genderField;
private final JLabel ageLabel = new JLabel();
private JLabel ageFieldLabel;
private JComboBox<Object> ageBox;
private final JLabel phoneLabel = new JLabel();
private JTextField phoneField;
private final JLabel emailLabel = new JLabel();
private JTextField emailField;
private final JLabel addressLabel = new JLabel();
private JTextField addressField;
private final JButton createApplyButton = new JButton();
private final JButton totalHoursButton = new JButton();
private final ActionListener createVolListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!viewcnfg.admin)
return;
Volunteer newvol = createNewVolunteer();
if (newvol == null)
return;
Volunteer.volunteers.add(newvol);
viewcnfg.vol = newvol;
createApplyButton.setEnabled(false);
parent.replaceCurrentView(VolInfoView.this, viewcnfg);
}
};
private final ActionListener saveChangesListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!viewcnfg.admin)
return;
boolean crash = saveAllChanges();
if (!crash) {
viewcnfg.editnow = false;
createApplyButton.setEnabled(false);
parent.replaceCurrentView(VolInfoView.this, viewcnfg);
}
}
};
private final ActionListener editVolListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!viewcnfg.admin)
return;
viewcnfg.editnow = true;
parent.replaceCurrentView(VolInfoView.this, viewcnfg);
}
};
public ContentPanel() {
super();
content = new JPanel();
content.setLayout(new GridBagLayout());
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridBagLayout());
Insets padbtwnfields = new Insets(0, 0, 30, 0);
Insets toppad = new Insets(15, 0, 0, 0);
Insets noinsets = new Insets(0, 0, 0, 0);
cpgbc.fill = GridBagConstraints.BOTH;
cpgbc.weightx = 1.0;
cpgbc.weighty = 1.0;
cpgbc.gridx = 0;
cpgbc.gridy = 0;
cpgbc.ipady = 0;
cpgbc.gridwidth = 2;
if (viewcnfg.vol == null && viewcnfg.admin) {
// creating new vol
type = 0;
nameField = new JTextField();
idField = new JTextField();
ageBox = new JComboBox<Object>(ages);
phoneField = new JTextField();
emailField = new JTextField();
addressField = new JTextField();
} else if (viewcnfg.vol != null && viewcnfg.admin && viewcnfg.editnow) {
// admin editing
type = 1;
nameField = new JTextField();
idField = new JTextField();
ageBox = new JComboBox<Object>(ages);
phoneField = new JTextField();
emailField = new JTextField();
addressField = new JTextField();
} else if (viewcnfg.vol != null) {
// showing volunteer stuff not editable
type = 2;
nameField = new JTextField();
idField = new JTextField();
ageFieldLabel = new JLabel("0");
genderField = new JLabel();
phoneField = new JTextField();
emailField = new JTextField();
addressField = new JTextField();
}
if (type == 2 && viewcnfg.admin) {
editusericon = Util.getScaledImage("edit_user.png", 100, 100);
} else {
editusericon = null;
}
nameLabel.setFont(Util.standoutFont);
nameLabel.setText("<html>   Name" + (type < 2 ? " <font color=\"red\">*</font>" : "") + "</html>");
idLabel.setFont(Util.standoutFont);
idLabel.setText("<html>   ID" + (type < 2 ? " <font color=\"red\">*</font>" : "") + "</html>");
genderLabel.setFont(Util.standoutFont);
genderLabel
.setText("<html>   Gender" + (type < 2 ? " <font color=\"red\">*</font>" : "") + "</html>");
ageLabel.setFont(Util.standoutFont);
ageLabel.setText("<html>   Age" + (type < 2 ? " <font color=\"red\">*</font>" : "") + "</html>");
phoneLabel.setFont(Util.standoutFont);
phoneLabel.setText("<html>   Phone number</html>");
emailLabel.setFont(Util.standoutFont);
emailLabel.setText("<html>   Email</html>");
addressLabel.setFont(Util.standoutFont);
addressLabel.setText("<html>   Address</html>");
cpgbc.insets = toppad;
centerPanel.add(nameLabel, cpgbc);
cpgbc.insets = noinsets;
cpgbc.gridy++;
cpgbc.insets = padbtwnfields;
centerPanel.add(nameField, cpgbc);
cpgbc.gridy++;
cpgbc.insets = noinsets;
centerPanel.add(idLabel, cpgbc);
cpgbc.gridy++;
if (type != 2) {
ButtonGroup idbg = new ButtonGroup();
idbg.add(chooseIDrb);
idbg.add(generateIDrb);
idbg.add(phonenumIDrb);
idField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
if (idField.getText().length() > 4) {
e.consume();
}
}
});
generateIDrb.setVerticalAlignment(SwingConstants.BOTTOM);
generateIDrb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
lastIDrb = generateIDrb;
idField.setEnabled(false);
idField.setText(Util.generateRandomID());
}
});
phonenumIDrb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
lastIDrb = phonenumIDrb;
idField.setEnabled(false);
idField.setText("Last 4 of phone number");
}
});
chooseIDrb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (lastIDrb == phonenumIDrb) {
idField.setText("");
}
lastIDrb = chooseIDrb;
idField.setEnabled(true);
}
});
phonenumIDrb.doClick();
idoptionpanel.setLayout(new GridLayout(3, 1));
idoptionpanel.add(chooseIDrb);
idoptionpanel.add(generateIDrb);
idoptionpanel.add(phonenumIDrb);
centerPanel.add(idoptionpanel, cpgbc);
cpgbc.gridy++;
}
cpgbc.insets = padbtwnfields;
centerPanel.add(idField, cpgbc);
cpgbc.gridy++;
cpgbc.insets = noinsets;
centerPanel.add(genderLabel, cpgbc);
cpgbc.gridy++;
if (type == 2) {
cpgbc.insets = padbtwnfields;
centerPanel.add(genderField, cpgbc);
} else {
ButtonGroup genderbg = new ButtonGroup();
genderbg.add(malerb);
genderbg.add(femalerb);
genderoptionpanel.setLayout(new GridLayout(2, 1));
genderoptionpanel.add(malerb);
genderoptionpanel.add(femalerb);
cpgbc.insets = padbtwnfields;
centerPanel.add(genderoptionpanel, cpgbc);
}
cpgbc.gridy++;
cpgbc.insets = noinsets;
centerPanel.add(ageLabel, cpgbc);
cpgbc.gridy++;
cpgbc.insets = padbtwnfields;
centerPanel.add(type < 2 ? ageBox : ageFieldLabel, cpgbc);
cpgbc.gridy++;
cpgbc.insets = noinsets;
centerPanel.add(phoneLabel, cpgbc);
cpgbc.gridy++;
phoneField.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
try {
phoneField.setText(Util.formatPhoneNumber(phoneField.getText()));
} catch (RuntimeException ex) {
// JOptionPane.showMessageDialog(VolInfoView.content,
// "<html><div style=\"text-align:
// center;\"><strong>Warning</strong><br>That is not a
// valid phone number</html>",
// "Not a valid phone number",
// JOptionPane.WARNING_MESSAGE, null);
}
}
});
phoneField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
if ((e.getKeyChar() < '0' || e.getKeyChar() > '9')) {
e.consume();
}
if (phoneField.getText().length() > 9) {
e.consume();
}
}
});
cpgbc.insets = padbtwnfields;
centerPanel.add(phoneField, cpgbc);
cpgbc.gridy++;
cpgbc.insets = noinsets;
centerPanel.add(emailLabel, cpgbc);
cpgbc.gridy++;
emailField.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
if (!Util.isValidEmail(emailField.getText())) {
// JOptionPane.showMessageDialog(VolInfoView.content,
// "<html><div style=\"text-align:
// center;\"><strong>Warning</strong><br>That is not a
// valid email</html>",
// "Not a valid email", JOptionPane.WARNING_MESSAGE,
// null);
}
}
});
cpgbc.insets = padbtwnfields;
centerPanel.add(emailField, cpgbc);
cpgbc.gridy++;
cpgbc.insets = noinsets;
centerPanel.add(addressLabel, cpgbc);
cpgbc.gridy++;
cpgbc.insets = padbtwnfields;
centerPanel.add(addressField, cpgbc);
cpgbc.gridy++;
cpgbc.ipady = 100;
cpgbc.weightx = 5;
cpgbc.weighty = 0;
cpgbc.gridwidth = viewcnfg.admin ? 1 : 2;
if (type > 0) {
totalHoursButton.setFont(Util.standoutFont);
totalHoursButton.setText("<html><div style=\"text-align: center;\">Total Hours:<br>"
+ Util.formatTime(viewcnfg.vol.getTotalVolunteeringTime()) + "</html>");
totalHoursButton.setHorizontalAlignment(SwingConstants.CENTER);
totalHoursButton.setToolTipText(
(viewcnfg.admin) ? "See the time chart for content volunteer" : "See your time chart");
JPanel totalHoursHolder = new JPanel();
totalHoursHolder.setLayout(new GridBagLayout());
if (type != 1) {
totalHoursHolder.add(totalHoursButton);
}
centerPanel.add(totalHoursHolder, cpgbc);
} else {
centerPanel.add(new JComponent() {
}, cpgbc);
}
if (viewcnfg.admin) {
cpgbc.gridx = 1;
cpgbc.weightx = 1;
createApplyButton.setFont(Util.standoutFont);
centerPanel.add(createApplyButton, cpgbc);
cpgbc.gridy++;
}
JLabel blank1 = new JLabel();
JLabel blank2 = new JLabel();
GridBagConstraints maingbc = new GridBagConstraints();
maingbc.fill = GridBagConstraints.BOTH;
maingbc.weightx = 1.0;
maingbc.weighty = 1.0;
maingbc.gridx = 0;
maingbc.gridy = 0;
content.add(blank1, maingbc);
maingbc.gridx++;
maingbc.weightx = 0;
maingbc.ipadx = 210;
content.add(centerPanel, maingbc);
maingbc.gridx++;
maingbc.weightx = 1;
maingbc.ipadx = 0;
content.add(blank2, maingbc);
maingbc.gridx++;
createApplyButton.setText(
(viewcnfg.vol == null) ? "Create New Volunteer" : "<html>Save Changes<br>to Volunteer</html>");
createApplyButton.setToolTipText((viewcnfg.vol == null) ? "Enter the new volunteer to the database"
: "<html>Save all changes made to the record</html>");
if (type == 0) {
createApplyButton.setText("Create New Volunteer");
createApplyButton.setToolTipText("Enter the new volunteer to the database");
Util.setActionListener(createApplyButton, createVolListener);
} else if (type == 1) {
createApplyButton.setText("<html>Save Changes<br>to Volunteer</html>");
createApplyButton.setToolTipText("Save all changes made to the record");
Util.setActionListener(createApplyButton, saveChangesListener);
} else if (type == 2) {
if (viewcnfg.admin) {// admin show
createApplyButton.setText("");
createApplyButton.setIcon(editusericon);
createApplyButton.setToolTipText("<html>Edit volunteer record</html>");
Util.setActionListener(createApplyButton, editVolListener);
} else {// vol show
createApplyButton.setText("THIS SHOULDNT SHOW UP");
}
}
nameField.setEditable(type < 2);
idField.setEditable(type < 2);
phoneField.setEditable(type < 2);
emailField.setEditable(type < 2);
addressField.setEditable(type < 2);
totalHoursButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showTimeChart();
}
});
setViewportView(content);
}
}
static {
ages = new Object[121];
ages[0] = "None given";
// 1-120
// 5-120 //116
for (int i = 1; i < ages.length; i++) {
ages[i] = i;
}
}
public VolInfoView(FGFrame parent) {
super(parent);
subLabel = new JLabel();
subLabel.setFont(Util.subtitleFont);
subLabel.setHorizontalAlignment(SwingConstants.CENTER);
layoutView();
}
@Override
public void layoutView() {
setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 0;
this.add(titleLabel, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
subPanel.removeAll();
subPanel.add(subLabel);
this.add(subPanel, gbc);
}
/**
* Configures the VolInfoView for either a new Volunteer(admin=true,
* vol=null) or an existing one(vol!=null)
*/
@Override
public void cnfgFor(ViewCnfg cnfg) {
super.cnfgFor(cnfg);
contentPanel = new ContentPanel();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.weighty = 1;
this.add(contentPanel, gbc);
JScrollBar horbar = contentPanel.getHorizontalScrollBar();
horbar.setPreferredSize(new Dimension(0, 30));
horbar.setUnitIncrement(10);
JScrollBar bar = contentPanel.getVerticalScrollBar();
bar.setPreferredSize(new Dimension(30, 0));
bar.setUnitIncrement(10);
if (cnfg.vol == null) {
titleLabel.setText("New Volunteer");
subLabel.setText("<html>You must put an entry for all boxes labeled <font color=\"red\">*</font></html>");
} else {
if (cnfg.admin) {
titleLabel.setText("Volunteer Information");
subLabel.setText(Util.formatName(cnfg.vol));
} else {
titleLabel.setText(cnfg.vol.getName());
subLabel.setText(cnfg.vol.getID());
}
}
revalidate();
}
@Override
public void beforeClose() {
if (contentPanel.type == 2) {
this.remove(contentPanel);
return;
} else if (contentPanel.type == 0) {
// creating new vol
if (!contentPanel.createApplyButton.isEnabled()) {
this.remove(contentPanel);
return;
}
int result = JOptionPane.showConfirmDialog(this, "Would you like to cancel creating the new Volunteer?",
"Volunteer Creation Canceling", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null);
if (result == JOptionPane.YES_OPTION) {
this.remove(contentPanel);
return;
} else if (result == JOptionPane.NO_OPTION) {
parent.cancelTransition();
return;
}
} else if (contentPanel.type == 1) {
// saving vol
if (!contentPanel.createApplyButton.isEnabled()) {
this.remove(contentPanel);
return;
}
int result = JOptionPane.showConfirmDialog(this, "Would you like to save changes to the volunteer record?",
"Unsaved Changes", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null);
if (result == JOptionPane.YES_OPTION) {
boolean crash = saveAllChanges();
if (crash) {
parent.cancelTransition();
return;
}
this.remove(contentPanel);
return;
} else if (result == JOptionPane.CANCEL_OPTION) {
parent.cancelTransition();
return;
} else if (result == JOptionPane.NO_OPTION) {
this.remove(contentPanel);
return;
}
}
}
@Override
public void afterDisplay() {
// sets fields as necessary
if (contentPanel.type == 0) {// creating new
contentPanel.nameField.setText("");
contentPanel.idField.setText("");
contentPanel.ageBox.setSelectedIndex(0);
contentPanel.phoneField.setText("");
contentPanel.emailField.setText("");
contentPanel.addressField.setText("");
contentPanel.phonenumIDrb.doClick();
contentPanel.createApplyButton.setEnabled(true);
} else if (contentPanel.type == 1) {// admin edit
contentPanel.nameField.setText(viewcnfg.vol.getName());
contentPanel.chooseIDrb.doClick();
contentPanel.idField.setText(viewcnfg.vol.getID());
(viewcnfg.vol.getGender() == Volunteer.MALE ? contentPanel.malerb : contentPanel.femalerb).doClick();
contentPanel.ageBox.setSelectedIndex(viewcnfg.vol.getAge());
contentPanel.phoneField.setText(viewcnfg.vol.getPhoneNumber());
contentPanel.emailField.setText(viewcnfg.vol.getEmail());
contentPanel.addressField.setText(viewcnfg.vol.getAddress());
contentPanel.createApplyButton.setEnabled(true);
} else if (contentPanel.type == 2) {// no edit
contentPanel.nameField.setText(viewcnfg.vol.getName());
contentPanel.idField.setText(viewcnfg.vol.getID());
contentPanel.genderField.setText(viewcnfg.vol.getGender() == Volunteer.MALE ? "Male" : "Female");
contentPanel.ageFieldLabel.setText(viewcnfg.vol.getAge() + "");
contentPanel.phoneField.setText(viewcnfg.vol.getPhoneNumber());
contentPanel.emailField.setText(viewcnfg.vol.getEmail());
contentPanel.addressField.setText(viewcnfg.vol.getAddress());
contentPanel.createApplyButton.setEnabled(!viewcnfg.editnow);
}
}
@Override
public void saveMem() {
contentPanel = null;
}
/**
* will return null if crash
*
* @return
*/
private Volunteer createNewVolunteer() {
Volunteer vol = new Volunteer("", "");
// need to check if name is empty
// id is alright (if custom id is select)
// id is alright if last 4 of pn (if pn = null)
// phone number is parsable(in case)
if (contentPanel.nameField.getText().equals("")) {
tellLeftBlank(this);
return null;
}
String id = contentPanel.idField.getText();
if (contentPanel.phonenumIDrb.isSelected()) {
String pn = contentPanel.phoneField.getText();
try {
pn = pn.substring(pn.length() - 4);
if (Util.idIsTaken(pn)) {
tellIDIsTaken(this, pn);
return null;
}
id = pn;
} catch (IndexOutOfBoundsException e) {
JOptionPane.showMessageDialog(this, "Can't find the last 4 digits of phone number",
"Need phone number for ID", JOptionPane.ERROR_MESSAGE, null);
return null;
}
}
if (!(contentPanel.malerb.isSelected() || contentPanel.femalerb.isSelected())) {
tellLeftBlank(this);
return null;
}
if (contentPanel.chooseIDrb.isSelected() && id.equals("")) {
tellLeftBlank(this);
return null;
} else if (Util.idIsTaken(id)) {
tellIDIsTaken(this, id);
return null;
}
if (contentPanel.ageBox.getSelectedIndex() == 0) {
tellLeftBlank(VolInfoView.this);
return null;
}
vol.setName(contentPanel.nameField.getText());
vol.setID(id);
vol.setGender(contentPanel.malerb.isSelected() ? Volunteer.MALE : Volunteer.FEMALE);
vol.setAge(contentPanel.ageBox.getSelectedIndex());
String phone = contentPanel.phoneField.getText();
vol.setPhoneNumber((phone.equals("") ? "Not given" : phone));
String email = contentPanel.emailField.getText();
vol.setEmail((email.equals("") ? "Not given" : email));
String address = contentPanel.addressField.getText();
vol.setAddress((address.equals("") ? "Not given" : address));
return vol;
}
public boolean saveAllChanges() {
// need to check if name is empty
// id is alright (if custom id is select)
// id is alright if last 4 of pn (if pn = null)
// phone number is parsable(in case)
if (contentPanel.nameField.getText().equals("")) {
tellLeftBlank(this);
return true;
}
String id = contentPanel.idField.getText();
if (contentPanel.phonenumIDrb.isSelected()) {
String pn = contentPanel.phoneField.getText();
try {
pn = pn.substring(pn.length() - 4);
if (Util.idIsTaken(pn) && !id.equals(viewcnfg.vol.getID())) {
tellIDIsTaken(this, pn);
return true;
}
id = pn;
} catch (IndexOutOfBoundsException e) {
JOptionPane.showMessageDialog(this, "Can't find the last 4 digits of phone number",
"Need phone number for ID", JOptionPane.ERROR_MESSAGE, null);
return true;
}
}
if (contentPanel.chooseIDrb.isSelected() && id.equals("")) {
tellLeftBlank(this);
return true;
} else if (Util.idIsTaken(id) && !id.equals(viewcnfg.vol.getID())) {
tellIDIsTaken(this, id);
return true;
}
if (contentPanel.ageBox.getSelectedIndex() == 0) {
tellLeftBlank(VolInfoView.this);
return true;
}
viewcnfg.vol.setName(contentPanel.nameField.getText());
viewcnfg.vol.setID(id);
viewcnfg.vol.setGender(contentPanel.malerb.isSelected() ? Volunteer.MALE : Volunteer.FEMALE);
viewcnfg.vol.setAge(contentPanel.ageBox.getSelectedIndex());
String phone = contentPanel.phoneField.getText();
viewcnfg.vol.setPhoneNumber(phone.equals("") ? "Not given" : phone);
String email = contentPanel.emailField.getText();
viewcnfg.vol.setEmail(email.equals("") ? "Not given" : email);
String address = contentPanel.addressField.getText();
viewcnfg.vol.setAddress(address.equals("") ? "Not given" : address);
return false;
}
public void showTimeChart() {
parent.showNextView(parent.tcview, viewcnfg);
}
private static void tellIDIsTaken(VolInfoView view, String id) {
JOptionPane.showMessageDialog(view,
"The ID " + id + " is already being used by someone. Please choose a different ID.",
"ID is already taken", JOptionPane.ERROR_MESSAGE, null);
}
private static void tellLeftBlank(VolInfoView view) {
JOptionPane.showMessageDialog(view, "There's no entry for some required fields. Please fill everything out.",
"Required fields not filled out", JOptionPane.ERROR_MESSAGE, null);
}
@Override
public String getFrameTitleString() {
return (viewcnfg.vol == null ? "Creating New Volunteer"
: "Volunteer Information for " + Util.formatName(viewcnfg.vol));
}
@Override
public String getBackString() {
return (viewcnfg.vol == null ? "Creating New Volunteer" : "Volunteer Information");
}
} | 29.534351 | 111 | 0.685362 |
ea1ffd775b48e96e8da8a68a8dec9fcc544610db | 213 | package de.uxnr.tsoexpert.game.communication.vo;
import de.uxnr.amf.v3.AMF3_Object;
public class NumberVO extends AMF3_Object {
private double value;
public double getValue() {
return this.value;
}
}
| 17.75 | 48 | 0.746479 |
a0be869e075390ee4fd40a576c88cefb6cdb2eee | 175 | package cn.shijinshi.redis.common.registry;
/**
* 用于监听节点下的数据
*
* @author Gui Jiahai
*/
public interface DataListener {
void dataChanged(String path, byte[] data);
}
| 14.583333 | 47 | 0.697143 |
249279943c94e9d3f0251cfe06b177b8409b088b | 1,612 | package ru.stqa.pft.addressbook.tests;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.ContactData;
import ru.stqa.pft.addressbook.model.Contacts;
import ru.stqa.pft.addressbook.model.GroupData;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertEquals;
public class ContactDeletionTests extends TestBase {
@BeforeMethod
public void ensurePreconditions() {
app.goTo().homePage();
if (app.db().contacts().size() == 0) {
app.goTo().groupPage();
if (app.db().groups().size() == 0) {
app.group().create(new GroupData().withName("test1"));
}
app.goTo().homePage();
app.contact().createContact(new ContactData().withFirstName("Farrukh").withLastName("Khamidov").
withAddress("Uzbekistan, Tashkent, Bobur street, 4/1").
withHomePhone("111").withMobilePhone("222").withWorkPhone("333").withEmail("tester@gmail.com"));
}
}
@Test
public void testContactDeletion() {
Contacts before = app.db().contacts();
ContactData deletedContact = before.iterator().next();
app.contact().delete(deletedContact);
assertThat(app.contact().count(), equalTo(before.size() - 1));
Contacts after = app.db().contacts();
assertThat(after, equalTo(before.without(deletedContact)));
verifyContactListInUI();
}
}
| 35.822222 | 116 | 0.658189 |
d64f44bf36dff572a7be167ea684179d6b4a9e50 | 8,094 | /*
* Copyright (c) 2021 dzikoysk
*
* 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 panda.interpreter.resource.mappings.java;
import panda.interpreter.architecture.module.Module;
import panda.interpreter.architecture.module.TypeLoader;
import panda.interpreter.architecture.packages.Package;
import panda.interpreter.architecture.type.Autocast;
import panda.interpreter.architecture.type.Kind;
import panda.interpreter.architecture.type.PandaType;
import panda.interpreter.architecture.type.Reference;
import panda.interpreter.architecture.type.Type;
import panda.interpreter.architecture.type.Visibility;
import panda.interpreter.architecture.type.generator.TypeGenerator;
import panda.interpreter.architecture.type.member.method.PandaMethod;
import panda.interpreter.architecture.type.signature.GenericSignature;
import panda.interpreter.architecture.type.signature.Relation;
import panda.interpreter.architecture.type.signature.Signature;
import panda.interpreter.architecture.type.signature.TypedSignature;
import panda.interpreter.source.ClassSource;
import panda.interpreter.token.PandaSnippet;
import panda.interpreter.resource.Mappings;
import panda.interpreter.resource.Mappings.CustomInitializer;
import panda.utilities.ClassUtils;
import panda.std.reactive.Completable;
import java.util.Collections;
@Mappings(pkg = "panda", author = "panda", module = Package.DEFAULT_MODULE, commonPackage= "java.lang", classes = {
"Iterable"
})
public final class JavaModule implements CustomInitializer {
@Override
public void initialize(Module module, TypeGenerator typeGenerator, TypeLoader typeLoader) {
Type primitiveVoid = primitive(typeGenerator, module, "Void", void.class);
Type voidType = associated(typeLoader, typeGenerator, primitiveVoid);
typeLoader.load(primitiveVoid, voidType);
Type primitiveInt = primitive(typeGenerator, module, "Int", int.class);
Type primitiveBool = primitive(typeGenerator, module, "Bool", boolean.class);
Type primitiveChar = primitive(typeGenerator, module, "Char", char.class);
Type primitiveByte = primitive(typeGenerator, module, "Byte", byte.class);
Type primitiveShort = primitive(typeGenerator, module, "Short", short.class);
Type primitiveLong = primitive(typeGenerator, module, "Long", long.class);
Type primitiveFloat = primitive(typeGenerator, module, "Float", float.class);
Type primitiveDouble = primitive(typeGenerator, module, "Double", double.class);
Type objectType = generate(typeLoader, typeGenerator, module, Object.class);
typeLoader.load(objectType);
Type stringType = generate(typeLoader, typeGenerator, module, String.class);
typeLoader.load(stringType);
Type numberType = generate(typeLoader, typeGenerator, module, Number.class);
typeLoader.load(numberType);
Type boolType = associated(typeLoader, typeGenerator, primitiveBool);
Type charType = associated(typeLoader, typeGenerator, primitiveChar);
Type byteType = associated(typeLoader, typeGenerator, primitiveByte);
Type shortType = associated(typeLoader, typeGenerator, primitiveShort);
Type intType = associated(typeLoader, typeGenerator, primitiveInt);
Type longType = associated(typeLoader, typeGenerator, primitiveLong);
Type floatType = associated(typeLoader, typeGenerator, primitiveFloat);
Type doubleType = associated(typeLoader, typeGenerator, primitiveDouble);
intType.addAutocast(longType.getReference(), (Autocast<Number, Long>) (originalType, object, resultType) -> object.longValue());
intType.addAutocast(doubleType.getReference(), (Autocast<Number, Double>) (originalType, object, resultType) -> object.doubleValue());
intType.addAutocast(floatType.getReference(), (Autocast<Number, Float>) (originalType, object, resultType) -> object.floatValue());
floatType.addAutocast(doubleType.getReference(), (Autocast<Number, Double>) (originalType, object, resultType) -> object.doubleValue());
charType.addAutocast(intType.getReference(), (Autocast<Character, Integer>) (originalType, object, resultType) -> Character.getNumericValue(object));
byteType.addAutocast(intType.getReference(), (Autocast<Number, Integer>) (originalType, object, resultType) -> object.intValue());
shortType.addAutocast(intType.getReference(), (Autocast<Number, Integer>) (originalType, object, resultType) -> object.intValue());
typeLoader.load(
primitiveBool, boolType,
primitiveByte, byteType,
primitiveShort, shortType,
primitiveChar, charType,
primitiveInt, intType,
primitiveLong, longType,
primitiveFloat, floatType,
primitiveDouble, doubleType
);
Type java = generate(typeLoader, typeGenerator, module, Java.class);
java.getMethods().declare(PandaMethod.builder()
.name("null")
.parameters(Collections.emptyList())
.customBody((property, stack, instance, arguments) -> null)
.visibility(Visibility.OPEN)
.isStatic(true)
.location(new ClassSource(module, Java.class).toLocation())
.returnType(new GenericSignature(typeLoader, null, "T", null, new Signature[0], Relation.DIRECT, PandaSnippet.empty()))
.build());
typeLoader.load(java);
}
private Type primitive(TypeGenerator typeGenerator, Module module, String name, Class<?> primitiveClass) {
Completable<Type> futureType = new Completable<>();
Reference reference = new Reference(
futureType,
module,
"Primitive" + name,
Visibility.OPEN,
Kind.TYPE,
new ClassSource(module, primitiveClass).toLocation());
Type type = PandaType.builder()
.name(reference.getSimpleName())
.module(module)
.signature(new TypedSignature(null, reference, new Signature[0], Relation.DIRECT, PandaSnippet.empty()))
.associatedType(Completable.completed(primitiveClass))
.kind(reference.getKind())
.location(reference.getLocation())
.build();
futureType.complete(typeGenerator.allocate(primitiveClass, type));
module.add(reference);
return type;
}
private Type associated(TypeLoader typeLoader, TypeGenerator typeGenerator, Type primitive) {
Type type = generate(typeLoader, typeGenerator, primitive.getModule(), primitive.getSimpleName().replace("Primitive", ""), ClassUtils.getNonPrimitiveClass(primitive.getAssociated().get()));
type.addAutocast(primitive.getReference(), (originalType, object, resultType) -> object);
primitive.addAutocast(type.getReference(), (originalType, object, resultType) -> object);
return type;
}
public static Type generate(TypeLoader typeLoader, TypeGenerator typeGenerator, Module module, Class<?> type) {
return generate(typeLoader, typeGenerator, module, type.getSimpleName(), type);
}
public static Type generate(TypeLoader typeLoader, TypeGenerator typeGenerator, Module module, String name, Class<?> javaType) {
Reference reference= typeGenerator.generate(typeLoader, module, name, javaType);
module.add(reference);
return reference.fetchType();
}
}
| 50.273292 | 197 | 0.707314 |
e8dd154a7cfd2c0128aac1f0509756b43840cb7f | 45,865 | /**
* Scaffolding file used to store all the setups needed to run
* tests automatically generated by EvoSuite
* Tue Aug 20 10:18:19 GMT 2019
*/
package de.komoot.photon.nominatim;
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
import org.junit.AfterClass;
import org.evosuite.runtime.sandbox.Sandbox;
import org.evosuite.runtime.sandbox.Sandbox.SandboxMode;
@EvoSuiteClassExclude
public class DBUtils_ESTest_scaffolding {
@org.junit.Rule
public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule();
private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone();
private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000);
@BeforeClass
public static void initEvoSuiteFramework() {
org.evosuite.runtime.RuntimeSettings.className = "de.komoot.photon.nominatim.DBUtils";
org.evosuite.runtime.GuiSupport.initialize();
org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100;
org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000;
org.evosuite.runtime.RuntimeSettings.mockSystemIn = true;
org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED;
org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT();
org.evosuite.runtime.classhandling.JDKClassResetter.init();
setSystemProperties();
initializeClasses();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
}
@AfterClass
public static void clearEvoSuiteFramework(){
Sandbox.resetDefaultSecurityManager();
java.lang.System.setProperties((java.util.Properties) defaultProperties.clone());
}
@Before
public void initTestCase(){
threadStopper.storeCurrentThreads();
threadStopper.startRecordingTime();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler();
org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode();
setSystemProperties();
org.evosuite.runtime.GuiSupport.setHeadless();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
org.evosuite.runtime.agent.InstrumentingAgent.activate();
}
@After
public void doneWithTestCase(){
threadStopper.killAndJoinClientThreads();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks();
org.evosuite.runtime.classhandling.JDKClassResetter.reset();
resetClasses();
org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode();
org.evosuite.runtime.agent.InstrumentingAgent.deactivate();
org.evosuite.runtime.GuiSupport.restoreHeadlessMode();
}
public static void setSystemProperties() {
java.lang.System.setProperties((java.util.Properties) defaultProperties.clone());
java.lang.System.setProperty("file.encoding", "UTF-8");
java.lang.System.setProperty("java.awt.headless", "true");
java.lang.System.setProperty("java.io.tmpdir", "/tmp");
java.lang.System.setProperty("user.country", "SG");
java.lang.System.setProperty("user.dir", "/home/cgzhu/projects/gitslice/resources/facts/evosuite-eval-pipeline/gen-tests/photon/org.openstreetmap.osmosis=osmosis-hstore-jdbc");
java.lang.System.setProperty("user.home", "/home/cgzhu");
java.lang.System.setProperty("user.language", "en");
java.lang.System.setProperty("user.name", "cgzhu");
java.lang.System.setProperty("user.timezone", "Asia/Singapore");
}
private static void initializeClasses() {
org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(DBUtils_ESTest_scaffolding.class.getClassLoader() ,
"org.elasticsearch.common.util.CancellableThreads$ExecutionCancelledException",
"org.joda.time.DateTimeZone",
"org.elasticsearch.ElasticsearchSecurityException",
"com.google.common.collect.ImmutableMultimap$Itr",
"org.elasticsearch.index.snapshots.IndexShardRestoreException",
"org.elasticsearch.common.joda.Joda$1",
"com.vividsolutions.jts.algorithm.CentroidLine",
"com.google.common.collect.Collections2",
"org.elasticsearch.http.BindHttpException",
"org.elasticsearch.common.unit.SizeValue",
"org.elasticsearch.ElasticsearchException$ElasticsearchExceptionHandle",
"org.elasticsearch.index.engine.SnapshotFailedEngineException",
"org.elasticsearch.common.joda.Joda$2",
"org.postgresql.core.ResultHandler",
"org.joda.time.field.AbstractPartialFieldProperty",
"org.elasticsearch.cluster.routing.IllegalShardRoutingStateException",
"org.elasticsearch.transport.ActionTransportException",
"org.joda.time.DateTimeFieldType$StandardDateTimeFieldType",
"com.google.common.collect.ImmutableMap$IteratorBasedImmutableMap$1EntrySetImpl",
"com.google.common.collect.NullsLastOrdering",
"com.google.common.collect.RegularImmutableMultiset",
"com.google.common.collect.RegularImmutableMap",
"com.google.common.collect.RegularImmutableBiMap",
"org.postgresql.core.v2.ProtocolConnectionImpl",
"org.elasticsearch.common.io.FastStringReader",
"com.vividsolutions.jts.algorithm.CentroidPoint",
"org.postgis.binary.ByteSetter",
"org.joda.time.field.UnsupportedDurationField",
"org.joda.time.DateMidnight$Property",
"com.google.common.collect.RegularImmutableMultiset$ElementSet",
"org.elasticsearch.common.CheckedFunction",
"org.elasticsearch.index.engine.DeleteFailedEngineException",
"org.postgresql.core.ResultCursor",
"org.openstreetmap.osmosis.hstore.PGHStore",
"com.google.common.collect.ImmutableBiMap$Builder",
"org.joda.time.format.PeriodFormatterBuilder",
"org.elasticsearch.snapshots.SnapshotException",
"org.apache.lucene.util.Accountable",
"org.joda.time.chrono.ISOChronology",
"com.vividsolutions.jts.geom.CoordinateFilter",
"com.google.common.collect.ImmutableSet$Indexed$1",
"org.joda.time.format.PeriodFormatterBuilder$FieldFormatter",
"org.elasticsearch.transport.TransportException",
"org.elasticsearch.indices.IndexPrimaryShardNotAllocatedException",
"org.elasticsearch.ElasticsearchParseException",
"com.google.common.base.Joiner",
"org.elasticsearch.index.mapper.MapperException",
"org.elasticsearch.indices.InvalidTypeNameException",
"org.elasticsearch.index.shard.IndexShardClosedException",
"org.joda.time.field.BaseDateTimeField",
"com.google.common.collect.NullsFirstOrdering",
"org.joda.time.field.ZeroIsMaxDateTimeField",
"com.vividsolutions.jts.util.Assert",
"org.elasticsearch.common.io.stream.Streamable",
"org.joda.time.base.BaseInterval",
"org.elasticsearch.indices.recovery.RecoverFilesRecoveryException",
"org.elasticsearch.cluster.NotMasterException",
"org.joda.time.Duration",
"org.elasticsearch.common.settings.Setting$Key",
"com.vividsolutions.jts.algorithm.InteriorPointPoint",
"org.elasticsearch.common.io.stream.BytesStreamOutput",
"org.joda.time.format.DateTimePrinterInternalPrinter",
"com.google.common.collect.RegularImmutableMultiset$NonTerminalEntry",
"org.elasticsearch.index.translog.TranslogCorruptedException",
"org.elasticsearch.cluster.node.DiscoveryNode",
"org.postgresql.fastpath.Fastpath",
"com.google.common.collect.Multisets$ImmutableEntry",
"org.joda.time.base.AbstractInstant",
"org.elasticsearch.search.fetch.FetchPhaseExecutionException",
"org.postgis.jts.JtsGeometry",
"com.google.common.collect.ImmutableSortedSet$Builder",
"org.elasticsearch.common.xcontent.XContentParser$Token$10",
"org.joda.time.LocalDateTime",
"com.google.common.base.Equivalence$Equals",
"org.joda.time.field.PreciseDateTimeField",
"org.elasticsearch.common.joda.FormatDateTimeFormatter",
"org.elasticsearch.common.util.concurrent.EsRejectedExecutionException",
"com.google.common.base.Equivalence$Wrapper",
"com.google.common.collect.ImmutableMapEntry$NonTerminalImmutableMapEntry",
"com.google.common.collect.ImmutableSortedSetFauxverideShim",
"org.elasticsearch.common.xcontent.ObjectParser$NamedObjectParser",
"org.elasticsearch.Build",
"com.google.common.collect.ImmutableMapValues",
"com.google.common.collect.ImmutableEntry",
"org.elasticsearch.snapshots.SnapshotMissingException",
"com.google.common.base.Joiner$1",
"com.google.common.base.Joiner$2",
"com.google.common.base.Converter$ConverterComposition",
"com.google.common.collect.EmptyImmutableSetMultimap",
"org.elasticsearch.common.xcontent.XContentBuilder$Writer",
"com.google.common.collect.AbstractNavigableMap",
"com.google.common.collect.ImmutableEnumMap",
"com.google.common.collect.ImmutableCollection",
"org.elasticsearch.common.blobstore.BlobStoreException",
"org.postgresql.largeobject.BlobOutputStream",
"org.elasticsearch.common.settings.Settings",
"org.joda.time.DateTime$Property",
"org.elasticsearch.common.settings.Setting$AffixKey",
"org.elasticsearch.common.geo.GeoPoint",
"org.openstreetmap.osmosis.hstore.PGHStore$Parser",
"org.elasticsearch.script.GeneralScriptException",
"org.apache.lucene.util.AttributeSource",
"org.joda.time.DateTimeField",
"org.elasticsearch.repositories.RepositoryException",
"com.google.common.collect.ImmutableSetMultimap",
"org.elasticsearch.common.lease.Releasable",
"org.elasticsearch.transport.ReceiveTimeoutTransportException",
"org.elasticsearch.search.aggregations.AggregationExecutionException",
"com.google.common.collect.ImmutableCollection$Builder",
"org.postgis.binary.ValueGetter$XDR",
"org.elasticsearch.search.aggregations.AggregationInitializationException",
"com.vividsolutions.jts.geom.Geometry$1",
"org.joda.time.chrono.GJDayOfWeekDateTimeField",
"com.google.common.collect.ImmutableMapValues$1",
"com.google.common.collect.ImmutableMapValues$2",
"org.joda.time.format.DateTimeFormatterBuilder$Composite",
"org.elasticsearch.common.util.set.Sets",
"org.joda.time.format.PeriodFormatterBuilder$IgnorableAffix",
"org.elasticsearch.transport.ActionNotFoundTransportException",
"org.joda.time.field.ImpreciseDateTimeField$LinkedDurationField",
"org.elasticsearch.transport.RemoteTransportException",
"org.joda.time.ReadablePeriod",
"org.elasticsearch.Version",
"com.google.common.base.Converter$ReverseConverter",
"org.elasticsearch.cluster.routing.RoutingException",
"org.joda.time.chrono.GregorianChronology",
"org.elasticsearch.common.xcontent.ObjectParser",
"org.elasticsearch.common.bytes.BytesReference$MarkSupportingStreamInputWrapper",
"org.elasticsearch.index.engine.DocumentSourceMissingException",
"org.joda.time.format.DateTimeFormatterBuilder$PaddedNumber",
"org.elasticsearch.common.settings.NoClassSettingsException",
"com.google.common.base.Equivalence$Identity",
"org.elasticsearch.common.logging.DeprecationLogger",
"org.joda.time.base.AbstractPartial",
"org.elasticsearch.common.ParsingException",
"org.elasticsearch.common.xcontent.XContentType",
"org.joda.time.DateTimeUtils",
"org.joda.time.base.AbstractDuration",
"com.google.common.collect.Multiset",
"com.google.common.collect.ImmutableSetMultimap$EntrySet",
"org.joda.time.base.AbstractInterval",
"org.elasticsearch.common.xcontent.XContentParser$Token",
"com.google.common.collect.EmptyImmutableListMultimap",
"org.joda.time.field.DecoratedDurationField",
"com.vividsolutions.jts.geom.util.GeometryEditor$GeometryEditorOperation",
"org.elasticsearch.ElasticsearchTimeoutException",
"com.google.common.collect.ImmutableList",
"org.elasticsearch.transport.TcpTransport$HttpOnTransportException",
"com.google.common.collect.ReverseOrdering",
"org.elasticsearch.cluster.routing.UnassignedInfo$AllocationStatus",
"com.vividsolutions.jts.geom.GeometryComponentFilter",
"org.elasticsearch.repositories.RepositoryVerificationException",
"org.elasticsearch.common.unit.TimeValue",
"org.joda.time.TimeOfDay",
"com.google.common.collect.Maps$FilteredEntrySortedMap",
"org.postgresql.core.ConnectionFactory",
"org.joda.time.field.PreciseDurationField",
"org.elasticsearch.index.shard.IndexShardState",
"org.joda.time.format.DateTimeFormatterBuilder$NumberFormatter",
"org.elasticsearch.action.support.ToXContentToBytes",
"org.elasticsearch.common.xcontent.NamedXContentRegistry$Entry",
"com.vividsolutions.jts.util.AssertionFailedException",
"org.joda.time.DateTime",
"org.elasticsearch.action.ShardOperationFailedException",
"org.elasticsearch.action.UnavailableShardsException",
"org.elasticsearch.index.engine.FlushFailedEngineException",
"com.google.common.collect.Maps$EntryTransformer",
"org.elasticsearch.cluster.routing.RecoverySource$SnapshotRecoverySource",
"org.elasticsearch.common.xcontent.XContentParser$NumberType",
"com.google.common.collect.Ordering",
"org.elasticsearch.cluster.routing.RecoverySource$Type",
"org.joda.time.format.PeriodFormatterBuilder$Separator",
"org.joda.time.DurationFieldType$StandardDurationFieldType",
"org.elasticsearch.common.settings.Setting$3",
"org.elasticsearch.common.settings.Setting$2",
"com.google.common.collect.AllEqualOrdering",
"org.elasticsearch.index.snapshots.IndexShardSnapshotFailedException",
"org.elasticsearch.common.io.stream.StreamOutput",
"org.elasticsearch.common.unit.ByteSizeUnit",
"org.elasticsearch.discovery.MasterNotDiscoveredException",
"org.apache.lucene.index.IndexFormatTooNewException",
"org.joda.time.format.DateTimeFormatterBuilder$StringLiteral",
"org.elasticsearch.common.xcontent.ConstructingObjectParser$Target",
"org.elasticsearch.action.IndicesRequest",
"org.elasticsearch.indices.IndexClosedException",
"org.elasticsearch.common.xcontent.XContentBuilder",
"com.vividsolutions.jts.geom.PrecisionModel",
"org.joda.time.DateTimeUtils$MillisProvider",
"org.elasticsearch.transport.ConnectTransportException",
"org.elasticsearch.transport.ResponseHandlerFailureTransportException",
"org.elasticsearch.indices.IndexCreationException",
"org.joda.time.chrono.BasicWeekOfWeekyearDateTimeField",
"org.joda.time.DateTimeFieldType",
"org.elasticsearch.ElasticsearchGenerationException",
"org.joda.time.format.DateTimeFormatterBuilder$Fraction",
"org.elasticsearch.common.xcontent.AbstractObjectParser",
"org.elasticsearch.common.xcontent.XContentParser$Token$6",
"org.elasticsearch.common.xcontent.XContentParser$Token$7",
"org.joda.time.MutableDateTime$Property",
"org.elasticsearch.common.xcontent.XContentParser$Token$8",
"org.postgresql.core.PGStream",
"org.elasticsearch.search.SearchContextMissingException",
"org.elasticsearch.common.xcontent.XContentParser$Token$9",
"org.elasticsearch.common.joda.Joda",
"org.elasticsearch.common.xcontent.XContentParser$Token$2",
"org.elasticsearch.common.settings.AbstractScopedSettings$SettingUpdater",
"org.elasticsearch.common.xcontent.XContentParser$Token$3",
"org.elasticsearch.common.xcontent.XContentParser$Token$4",
"org.postgis.binary.ValueGetter",
"org.elasticsearch.common.xcontent.XContentParser$Token$5",
"com.google.common.collect.ImmutableMap$MapViewOfValuesAsSingletonSets$1",
"org.elasticsearch.common.xcontent.XContentParser$Token$1",
"org.postgresql.jdbc4.Jdbc4Array",
"org.postgis.binary.ValueSetter$NDR",
"org.joda.time.tz.DateTimeZoneBuilder$PrecalculatedZone",
"org.elasticsearch.common.io.stream.Writeable$Reader",
"com.google.common.collect.SortedMapDifference",
"org.postgresql.core.Encoding",
"org.postgresql.core.TypeInfo",
"com.google.common.collect.RegularImmutableSet",
"org.postgis.binary.ValueGetter$NDR",
"com.google.common.collect.LexicographicalOrdering",
"com.google.common.collect.ImmutableListMultimap",
"org.elasticsearch.indices.InvalidAliasNameException",
"org.elasticsearch.cluster.action.shard.ShardStateAction$NoLongerPrimaryShardException",
"org.elasticsearch.indices.InvalidIndexNameException",
"com.google.common.collect.ImmutableAsList",
"org.joda.time.tz.ZoneInfoProvider$1",
"com.vividsolutions.jts.geom.Lineal",
"com.google.common.collect.RegularImmutableAsList",
"org.elasticsearch.index.translog.TruncatedTranslogException",
"org.elasticsearch.index.shard.IndexShardRelocatedException",
"org.elasticsearch.common.io.stream.NamedWriteable",
"com.google.common.collect.SingletonImmutableSet",
"org.elasticsearch.cluster.routing.ShardRoutingState",
"com.vividsolutions.jts.geom.PrecisionModel$Type",
"com.google.common.collect.ImmutableSetMultimap$Builder",
"com.google.common.collect.ImmutableMapEntrySet",
"org.elasticsearch.indices.IndexTemplateAlreadyExistsException",
"com.vividsolutions.jts.geom.CoordinateSequenceFactory",
"org.elasticsearch.common.bytes.BytesArray",
"com.google.common.collect.ImmutableMultiset",
"org.elasticsearch.cluster.block.ClusterBlockException",
"org.postgresql.copy.CopyManager",
"com.google.common.collect.ImmutableMultimap$Keys",
"com.google.common.collect.Multisets$AbstractEntry",
"org.joda.time.YearMonthDay$Property",
"org.joda.time.field.UnsupportedDateTimeField",
"com.vividsolutions.jts.geom.LinearRing",
"org.joda.time.field.ScaledDurationField",
"org.joda.time.chrono.ISOYearOfEraDateTimeField",
"com.google.common.collect.ObjectArrays",
"org.apache.lucene.analysis.TokenStream",
"org.elasticsearch.action.NoSuchNodeException",
"org.apache.lucene.analysis.Analyzer",
"org.elasticsearch.cluster.routing.UnassignedInfo",
"org.postgresql.PGConnection",
"com.google.common.collect.ImmutableList$1",
"org.joda.time.tz.CachedDateTimeZone",
"org.elasticsearch.transport.SendRequestTransportException",
"com.google.common.collect.ImmutableMap$MapViewOfValuesAsSingletonSets",
"org.elasticsearch.common.io.stream.NotSerializableExceptionWrapper",
"com.google.common.collect.SortedIterable",
"org.postgresql.core.PGStream$1",
"org.joda.time.format.PeriodParser",
"com.vividsolutions.jts.geom.MultiLineString",
"com.google.common.collect.UnmodifiableIterator",
"com.google.common.collect.RegularImmutableBiMap$Inverse$InverseEntrySet$1",
"org.postgresql.jdbc2.TimestampUtils",
"com.vividsolutions.jts.geom.Polygon",
"org.elasticsearch.ElasticsearchException",
"org.postgresql.core.QueryExecutor",
"org.elasticsearch.action.PrimaryMissingActionException",
"org.elasticsearch.action.FailedNodeException",
"org.elasticsearch.common.settings.PropertyPlaceholder$PlaceholderResolver",
"org.elasticsearch.rest.action.admin.indices.AliasesNotFoundException",
"org.apache.lucene.index.CorruptIndexException",
"org.joda.time.chrono.BasicWeekyearDateTimeField",
"org.elasticsearch.action.RoutingMissingException",
"org.elasticsearch.common.io.stream.BytesStream",
"org.elasticsearch.index.snapshots.IndexShardRestoreFailedException",
"com.google.common.collect.SingletonImmutableList",
"org.elasticsearch.common.xcontent.NamedXContentRegistry",
"org.joda.time.format.DateTimeFormatterBuilder$MatchingParser",
"com.google.common.base.Converter",
"org.postgresql.PGNotification",
"com.vividsolutions.jts.io.ParseException",
"com.google.common.base.Function",
"org.elasticsearch.index.query.QueryShardException",
"org.elasticsearch.common.settings.Setting",
"com.google.common.collect.ImmutableMap",
"org.postgresql.jdbc2.AbstractJdbc2Clob",
"org.postgresql.jdbc2.AbstractJdbc2Array$PgArrayList",
"org.apache.lucene.util.BytesRef",
"org.elasticsearch.indices.recovery.DelayRecoveryException",
"com.vividsolutions.jts.io.WKTReader",
"org.elasticsearch.common.bytes.BytesReference",
"org.elasticsearch.snapshots.InvalidSnapshotNameException",
"com.google.common.collect.Multiset$Entry",
"org.joda.time.tz.Provider",
"org.elasticsearch.common.transport.TransportAddress",
"org.joda.time.chrono.AssembledChronology$Fields",
"com.google.common.collect.ExplicitOrdering",
"org.elasticsearch.repositories.RepositoryMissingException",
"org.joda.time.DurationFieldType",
"org.elasticsearch.common.io.stream.Writeable$Writer",
"org.joda.time.ReadWritableInstant",
"org.postgresql.jdbc2.AbstractJdbc2Connection",
"com.google.common.collect.ImmutableList$Builder",
"org.elasticsearch.cluster.routing.ShardRouting",
"org.elasticsearch.search.SearchShardTarget",
"com.google.common.collect.CompoundOrdering",
"org.elasticsearch.ResourceAlreadyExistsException",
"org.joda.time.chrono.AssembledChronology",
"com.google.common.collect.ImmutableMultiset$Builder",
"org.elasticsearch.search.query.QueryPhaseExecutionException",
"com.google.common.collect.SingletonImmutableBiMap",
"org.apache.lucene.index.IndexableFieldType",
"org.postgresql.core.v2.ConnectionFactoryImpl",
"com.google.common.collect.Ordering$IncomparableValueException",
"com.google.common.collect.ImmutableMultiset$1",
"org.joda.time.chrono.GJEraDateTimeField",
"com.vividsolutions.jts.geom.GeometryCollection",
"org.joda.time.chrono.BaseChronology",
"org.elasticsearch.client.Requests",
"org.elasticsearch.cluster.routing.ShardsIterator",
"org.elasticsearch.index.mapper.MapperParsingException",
"com.google.common.base.Equivalence",
"org.joda.time.format.PeriodFormat",
"org.joda.time.format.PeriodFormatterBuilder$Composite",
"org.joda.time.field.AbstractReadableInstantFieldProperty",
"org.postgresql.jdbc2.AbstractJdbc2BlobClob",
"org.joda.time.format.PeriodFormatterBuilder$PeriodFieldAffix",
"org.apache.lucene.index.IndexFormatTooOldException",
"com.google.common.collect.ReverseNaturalOrdering",
"com.google.common.collect.Maps",
"com.google.common.collect.SetMultimap",
"org.joda.time.UTCDateTimeZone",
"org.joda.time.LocalDate",
"com.google.common.collect.DescendingImmutableSortedSet",
"org.apache.lucene.util.BytesRefIterator",
"org.joda.time.chrono.BasicDayOfMonthDateTimeField",
"org.elasticsearch.common.breaker.CircuitBreakingException",
"org.elasticsearch.index.mapper.StrictDynamicMappingException",
"org.elasticsearch.common.bytes.PagedBytesReference",
"org.elasticsearch.cluster.routing.AllocationId",
"org.elasticsearch.indices.TypeMissingException",
"org.joda.time.field.BaseDurationField",
"com.vividsolutions.jts.geom.CoordinateSequenceComparator",
"org.elasticsearch.index.shard.IndexShardRecoveryException",
"org.elasticsearch.action.OriginalIndices",
"org.elasticsearch.cluster.routing.RecoverySource$StoreRecoverySource$2",
"org.postgresql.jdbc3.AbstractJdbc3Connection",
"org.elasticsearch.cluster.routing.RecoverySource$StoreRecoverySource$1",
"org.apache.lucene.store.AlreadyClosedException",
"org.elasticsearch.node.NodeClosedException",
"com.google.common.collect.ImmutableSet$Indexed",
"org.elasticsearch.index.shard.ShardNotFoundException",
"com.vividsolutions.jts.geom.Puntal",
"org.postgresql.core.BaseConnection",
"org.elasticsearch.action.support.broadcast.BroadcastShardOperationFailedException",
"org.postgresql.jdbc4.Jdbc4Clob",
"com.google.common.collect.ImmutableCollection$ArrayBasedBuilder",
"org.postgis.binary.ValueSetter",
"org.elasticsearch.script.ScriptException",
"com.vividsolutions.jts.algorithm.InteriorPointLine",
"com.google.common.base.Converter$IdentityConverter",
"com.google.common.collect.ImmutableMultimap$Values",
"org.joda.time.chrono.BasicChronology$HalfdayField",
"org.postgresql.jdbc3.AbstractJdbc3Clob",
"org.joda.time.chrono.BasicChronology$YearInfo",
"org.joda.time.LocalDate$Property",
"com.google.common.collect.ByFunctionOrdering",
"org.postgresql.core.PGBindException",
"org.elasticsearch.index.shard.TranslogRecoveryPerformer$BatchOperationException",
"org.elasticsearch.snapshots.SnapshotCreationException",
"org.elasticsearch.common.settings.Setting$Property",
"org.postgis.binary.ByteGetter$StringByteGetter",
"com.vividsolutions.jts.geom.impl.CoordinateArraySequenceFactory",
"com.google.common.collect.AbstractMapEntry",
"org.elasticsearch.cluster.routing.RecoverySource",
"com.google.common.collect.ImmutableMap$IteratorBasedImmutableMap",
"org.apache.logging.log4j.Logger",
"com.google.common.base.Predicate",
"org.elasticsearch.index.engine.DocumentMissingException",
"com.google.common.collect.ImmutableListMultimap$Builder",
"org.joda.time.format.DateTimePrinter",
"org.joda.time.base.BaseLocal",
"org.elasticsearch.search.SearchException",
"org.joda.time.field.DividedDateTimeField",
"org.joda.time.chrono.ZonedChronology",
"org.postgis.binary.ByteSetter$StringByteSetter",
"org.joda.time.format.DateTimeFormatterBuilder$TimeZoneOffset",
"org.postgresql.jdbc2.AbstractJdbc2Blob",
"org.postgresql.util.ServerErrorMessage",
"org.elasticsearch.common.xcontent.ObjectParser$Parser",
"org.apache.lucene.store.LockObtainFailedException",
"org.elasticsearch.indices.recovery.RecoveryFailedException",
"org.postgresql.jdbc3.AbstractJdbc3Blob",
"org.joda.time.format.PeriodFormatter",
"org.postgresql.util.PSQLException",
"org.postgis.binary.ByteGetter$BinaryByteGetter",
"com.vividsolutions.jts.geom.impl.CoordinateArraySequence",
"org.joda.time.Interval",
"org.elasticsearch.common.text.Text",
"com.google.common.collect.UnmodifiableListIterator",
"org.joda.time.tz.DateTimeZoneBuilder",
"org.elasticsearch.index.IndexShardAlreadyExistsException",
"org.postgresql.core.v3.ConnectionFactoryImpl",
"org.postgresql.largeobject.LargeObject",
"org.joda.time.format.DateTimeParserBucket",
"com.google.common.collect.ImmutableMultimap",
"org.elasticsearch.index.engine.VersionConflictEngineException",
"com.vividsolutions.jts.geom.impl.PackedCoordinateSequenceFactory",
"org.elasticsearch.index.engine.EngineException",
"com.google.common.collect.ImmutableSortedSet",
"com.google.common.collect.Maps$BiMapConverter",
"org.joda.time.ReadWritablePeriod",
"org.elasticsearch.cluster.routing.RecoverySource$PeerRecoverySource",
"org.elasticsearch.common.unit.RatioValue",
"com.google.common.base.Joiner$MapJoiner",
"org.postgresql.core.v3.ConnectionFactoryImpl$UnsupportedProtocolException",
"com.vividsolutions.jts.geom.impl.PackedCoordinateSequence$Float",
"org.elasticsearch.indices.IndexTemplateMissingException",
"org.joda.time.tz.FixedDateTimeZone",
"org.postgresql.copy.CopyOut",
"org.joda.time.format.PeriodPrinter",
"org.elasticsearch.common.xcontent.XContentParser",
"org.elasticsearch.common.settings.SecureSettings",
"org.elasticsearch.common.lucene.Lucene$EarlyTerminationException",
"com.fasterxml.jackson.core.util.ByteArrayBuilder",
"org.elasticsearch.indices.AliasFilterParsingException",
"org.postgresql.core.UTF8Encoding",
"com.google.common.base.Preconditions",
"org.joda.time.base.BaseDuration",
"org.joda.time.field.DecoratedDateTimeField",
"org.elasticsearch.common.collect.Tuple",
"org.postgresql.util.PSQLWarning",
"org.joda.time.YearMonthDay",
"org.postgresql.util.GT",
"org.joda.time.format.DateTimeParser",
"org.elasticsearch.snapshots.ConcurrentSnapshotExecutionException",
"org.joda.time.format.DateTimeFormatterBuilder$CharacterLiteral",
"com.vividsolutions.jts.geom.GeometryFilter",
"org.elasticsearch.common.xcontent.XContent",
"org.elasticsearch.index.engine.RecoveryEngineException",
"org.joda.time.LocalTime$Property",
"org.joda.time.field.OffsetDateTimeField",
"org.elasticsearch.common.util.concurrent.UncategorizedExecutionException",
"org.elasticsearch.action.support.IndicesOptions",
"org.elasticsearch.ElasticsearchStatusException",
"org.elasticsearch.index.engine.IndexFailedEngineException",
"org.joda.time.field.FieldUtils",
"org.elasticsearch.common.xcontent.XContentGenerator",
"org.elasticsearch.transport.NodeDisconnectedException",
"org.elasticsearch.index.AlreadyExpiredException",
"com.google.common.collect.BiMap",
"org.joda.time.format.ISODateTimeFormat",
"org.elasticsearch.index.Index$Builder",
"com.google.common.collect.ImmutableSet",
"com.google.common.collect.ImmutableMapEntry",
"com.google.common.collect.ImmutableSortedAsList",
"org.joda.time.base.AbstractPeriod",
"org.elasticsearch.common.xcontent.ToXContent",
"org.elasticsearch.client.transport.NoNodeAvailableException",
"org.joda.time.DateTimeUtils$SystemMillisProvider",
"org.joda.time.IllegalInstantException",
"org.joda.time.IllegalFieldValueException",
"org.joda.time.format.DateTimeFormatterBuilder$UnpaddedNumber",
"com.vividsolutions.jts.geom.DefaultCoordinateSequenceFactory",
"org.postgresql.jdbc4.AbstractJdbc4Blob",
"com.google.common.collect.ImmutableMultimap$EntryCollection",
"org.joda.time.chrono.ZonedChronology$ZonedDateTimeField",
"org.elasticsearch.discovery.Discovery$FailedToCommitClusterStateException",
"com.google.common.collect.Maps$IteratorBasedAbstractMap",
"org.elasticsearch.index.engine.IgnoreOnRecoveryEngineException",
"com.google.common.collect.Maps$FilteredEntryBiMap",
"com.vividsolutions.jts.geom.DefaultCoordinateSequence",
"com.google.common.collect.RegularImmutableBiMap$Inverse",
"com.google.common.collect.ImmutableMultimap$Builder",
"org.joda.time.chrono.BasicMonthOfYearDateTimeField",
"org.joda.time.base.BasePartial",
"org.postgresql.core.ParameterList",
"org.joda.time.base.BaseDateTime",
"org.elasticsearch.transport.BindTransportException",
"com.google.common.collect.AbstractMultimap",
"org.elasticsearch.index.shard.IndexShardRecoveringException",
"org.joda.time.LocalTime",
"org.elasticsearch.index.Index",
"org.joda.time.base.BasePeriod",
"com.vividsolutions.jts.geom.Point",
"org.elasticsearch.cluster.metadata.ProcessClusterEventTimeoutException",
"org.joda.time.tz.DateTimeZoneBuilder$DSTZone",
"org.elasticsearch.common.Strings",
"org.postgresql.util.PGobject",
"com.vividsolutions.jts.geom.impl.PackedCoordinateSequence",
"org.joda.time.TimeOfDay$Property",
"com.vividsolutions.jts.geom.impl.PackedCoordinateSequence$Double",
"org.postgresql.copy.CopyIn",
"org.joda.time.field.ImpreciseDateTimeField",
"org.apache.lucene.util.BytesRefIterator$1",
"org.elasticsearch.cluster.routing.RecoverySource$LocalShardsRecoverySource",
"org.elasticsearch.action.support.replication.ReplicationOperation$RetryOnPrimaryException",
"org.elasticsearch.cluster.routing.AllocationId$Builder",
"org.joda.time.ReadableDuration",
"org.joda.time.chrono.BasicGJChronology",
"org.elasticsearch.search.SearchContextException",
"org.joda.time.format.DateTimeFormatter",
"org.joda.time.DurationField",
"org.elasticsearch.search.builder.SearchSourceBuilderException",
"com.google.common.collect.ImmutableMap$Builder",
"org.postgresql.core.VisibleBufferedInputStream",
"org.apache.lucene.util.Version",
"com.google.common.base.Converter$FunctionBasedConverter",
"org.joda.time.format.DateTimeParserInternalParser",
"org.postgis.jts.JtsBinaryParser",
"org.joda.time.ReadWritableDateTime",
"org.joda.time.chrono.ZonedChronology$ZonedDurationField",
"org.elasticsearch.common.io.stream.StreamInput",
"org.elasticsearch.transport.NodeNotConnectedException",
"org.joda.time.Instant",
"com.google.common.collect.NaturalOrdering",
"de.komoot.photon.nominatim.DBUtils",
"org.joda.time.chrono.BasicDayOfYearDateTimeField",
"org.elasticsearch.common.xcontent.ToXContent$Params",
"org.postgresql.jdbc4.Jdbc4Blob",
"org.elasticsearch.index.shard.ShardId",
"org.elasticsearch.search.dfs.DfsPhaseExecutionException",
"com.google.common.collect.ImmutableList$SubList",
"com.google.common.collect.ListMultimap",
"com.google.common.base.FunctionalEquivalence",
"org.elasticsearch.cluster.routing.ShardIterator",
"org.postgresql.core.v3.ProtocolConnectionImpl",
"org.apache.lucene.util.SetOnce$AlreadySetException",
"org.postgresql.core.Logger",
"org.joda.time.format.ISODateTimeFormat$Constants",
"org.elasticsearch.action.search.ReduceSearchPhaseException",
"org.joda.time.chrono.GJYearOfEraDateTimeField",
"com.google.common.collect.RegularImmutableList",
"org.elasticsearch.common.io.stream.InputStreamStreamInput",
"org.elasticsearch.cluster.ClusterState",
"org.elasticsearch.transport.NotSerializableTransportException",
"org.elasticsearch.common.settings.Setting$AffixSetting",
"org.elasticsearch.index.IndexNotFoundException",
"org.joda.time.field.RemainderDateTimeField",
"org.joda.time.JodaTimePermission",
"org.elasticsearch.common.xcontent.NamedXContentRegistry$UnknownNamedObjectException",
"org.elasticsearch.ResourceNotFoundException",
"org.elasticsearch.common.settings.SecureString",
"org.elasticsearch.common.ParseField",
"com.vividsolutions.jts.geom.CoordinateSequenceFilter",
"org.joda.time.format.DateTimeFormatterBuilder$FixedNumber",
"com.google.common.collect.ImmutableMapKeySet",
"org.elasticsearch.index.shard.IndexShardStartedException",
"org.elasticsearch.common.xcontent.XContentType$4",
"org.joda.time.ReadableInterval",
"org.elasticsearch.common.settings.Setting$SimpleKey",
"org.joda.time.base.AbstractDateTime",
"org.elasticsearch.common.xcontent.XContentType$1",
"org.elasticsearch.common.xcontent.XContentType$3",
"org.elasticsearch.rest.RestStatus",
"org.elasticsearch.common.xcontent.XContentType$2",
"com.google.common.collect.ImmutableMultimap$1",
"org.joda.time.chrono.BasicChronology",
"com.google.common.collect.Maps$AbstractFilteredMap",
"com.vividsolutions.jts.geom.GeometryFactory",
"org.elasticsearch.common.xcontent.XContentLocation",
"org.joda.time.chrono.BasicYearDateTimeField",
"org.postgis.binary.ByteGetter",
"com.google.common.collect.ImmutableMultimap$2",
"org.elasticsearch.snapshots.SnapshotRestoreException",
"org.elasticsearch.cluster.routing.RecoverySource$StoreRecoverySource",
"org.joda.time.format.DateTimeFormatterBuilder",
"com.google.common.collect.ImmutableMapEntrySet$RegularEntrySet",
"com.vividsolutions.jts.geom.Polygonal",
"com.google.common.collect.ImmutableSet$Builder",
"org.joda.time.tz.CachedDateTimeZone$Info",
"com.google.common.collect.Maps$FilteredEntryMap",
"org.elasticsearch.transport.NodeShouldNotConnectException",
"org.postgresql.largeobject.BlobInputStream",
"org.joda.time.PeriodType",
"org.joda.time.field.MillisDurationField",
"org.joda.time.format.InternalPrinter",
"com.google.common.collect.UsingToStringOrdering",
"org.joda.time.LocalDateTime$Property",
"org.postgresql.largeobject.LargeObjectManager",
"com.vividsolutions.jts.geom.MultiPolygon",
"com.vividsolutions.jts.geom.Coordinate",
"org.elasticsearch.ElasticsearchWrapperException",
"org.apache.lucene.util.SetOnce",
"com.vividsolutions.jts.geom.Envelope",
"org.postgresql.core.Field",
"org.elasticsearch.common.settings.SettingsException",
"org.joda.time.field.PreciseDurationDateTimeField",
"org.postgresql.util.PSQLState",
"org.joda.time.MutablePeriod",
"org.joda.time.MutableDateTime",
"org.postgresql.jdbc4.AbstractJdbc4Connection",
"com.google.common.collect.MapDifference",
"org.postgresql.jdbc2.TimestampUtils$ParsedTimestamp",
"com.google.common.collect.RegularImmutableBiMap$Inverse$InverseEntrySet",
"org.joda.time.ReadableDateTime",
"com.vividsolutions.jts.geom.MultiPoint",
"org.elasticsearch.common.xcontent.ConstructingObjectParser",
"org.elasticsearch.gateway.GatewayException",
"org.joda.time.format.PeriodFormatterBuilder$PluralAffix",
"org.elasticsearch.index.shard.IndexShardNotRecoveringException",
"org.joda.time.DateMidnight",
"org.elasticsearch.http.HttpException",
"com.google.common.collect.Maps$FilteredEntryNavigableMap",
"org.postgresql.Driver",
"org.elasticsearch.cluster.node.DiscoveryNode$Role",
"org.postgis.binary.ByteSetter$BinaryByteSetter",
"org.elasticsearch.search.SearchParseException",
"org.apache.lucene.index.IndexableField",
"org.elasticsearch.cluster.IncompatibleClusterStateVersionException",
"org.elasticsearch.common.xcontent.ToXContent$1",
"com.google.common.collect.ImmutableMultiset$EntrySet",
"org.elasticsearch.action.TimestampParsingException",
"org.joda.time.chrono.GJMonthOfYearDateTimeField",
"com.google.common.collect.ImmutableList$ReverseImmutableList",
"com.vividsolutions.jts.geom.Geometry",
"org.postgresql.copy.CopyOperation",
"org.elasticsearch.common.unit.ByteSizeValue",
"com.google.common.collect.Maps$6",
"org.postgis.binary.ValueSetter$XDR",
"org.elasticsearch.indices.InvalidIndexTemplateException",
"org.elasticsearch.action.search.ShardSearchFailure",
"org.elasticsearch.index.engine.RefreshFailedEngineException",
"com.google.common.collect.ComparatorOrdering",
"com.google.common.collect.AbstractIndexedListIterator",
"org.joda.time.ReadableInstant",
"org.elasticsearch.env.ShardLockObtainFailedException",
"org.elasticsearch.index.shard.IllegalIndexShardStateException",
"org.elasticsearch.index.snapshots.IndexShardSnapshotException",
"org.postgresql.jdbc4.AbstractJdbc4Clob",
"org.elasticsearch.index.shard.IndexShardNotStartedException",
"org.postgresql.fastpath.FastpathArg",
"org.elasticsearch.action.search.SearchPhaseExecutionException",
"org.elasticsearch.transport.TransportSerializationException",
"org.elasticsearch.index.engine.EngineCreationFailureException",
"org.postgresql.core.ProtocolConnection",
"org.elasticsearch.common.xcontent.AbstractObjectParser$IOSupplier",
"org.elasticsearch.tasks.TaskCancelledException",
"org.postgis.jts.JtsBinaryWriter",
"org.joda.time.format.PeriodFormat$DynamicWordBased",
"com.google.common.collect.Maps$ViewCachingAbstractMap",
"org.joda.time.tz.NameProvider",
"com.vividsolutions.jts.geom.CoordinateSequence",
"com.google.common.collect.ImmutableMap$1",
"com.vividsolutions.jts.geom.util.GeometryMapper$MapOp",
"org.elasticsearch.index.translog.TranslogException",
"com.google.common.collect.ImmutableMapEntry$NonTerminalImmutableBiMapEntry",
"com.google.common.collect.Multimap",
"com.vividsolutions.jts.geom.LineString",
"com.google.common.collect.ImmutableBiMap",
"org.postgresql.jdbc2.AbstractJdbc2Array",
"com.vividsolutions.jts.geom.IntersectionMatrix",
"org.elasticsearch.common.xcontent.ObjectParser$ValueType",
"com.google.common.base.PairwiseEquivalence",
"org.elasticsearch.search.aggregations.InvalidAggregationPathException",
"org.joda.time.tz.ZoneInfoProvider",
"org.elasticsearch.common.xcontent.ObjectParser$FieldParser",
"org.joda.time.Period",
"org.elasticsearch.cluster.Diffable",
"org.elasticsearch.index.engine.EngineClosedException",
"org.joda.time.Chronology",
"org.elasticsearch.action.NoShardAvailableActionException",
"org.joda.time.format.DateTimeParserBucket$SavedField",
"org.joda.time.format.InternalParserDateTimeParser",
"org.joda.time.format.InternalParser",
"org.elasticsearch.cluster.routing.UnassignedInfo$Reason",
"org.joda.time.ReadablePartial",
"org.elasticsearch.action.support.replication.TransportReplicationAction$RetryOnReplicaException",
"org.postgresql.core.Query",
"org.postgresql.jdbc3g.AbstractJdbc3gConnection",
"org.elasticsearch.common.xcontent.ContextParser",
"org.elasticsearch.common.io.stream.Writeable",
"com.google.common.collect.RegularImmutableSortedSet",
"org.postgresql.jdbc4.Jdbc4Connection",
"org.elasticsearch.common.settings.Settings$Builder"
);
}
private static void resetClasses() {
org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(DBUtils_ESTest_scaffolding.class.getClassLoader());
org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses(
"de.komoot.photon.nominatim.DBUtils",
"com.google.common.base.Joiner",
"com.google.common.base.Preconditions",
"com.google.common.base.Joiner$1",
"com.google.common.collect.Collections2",
"org.postgresql.jdbc2.AbstractJdbc2Connection",
"org.postgresql.jdbc3.AbstractJdbc3Connection",
"org.postgresql.jdbc3g.AbstractJdbc3gConnection",
"org.postgresql.jdbc4.AbstractJdbc4Connection",
"org.postgresql.jdbc4.Jdbc4Connection",
"org.postgresql.core.Logger",
"org.postgresql.Driver",
"org.postgresql.core.v3.ConnectionFactoryImpl",
"org.postgresql.core.v2.ConnectionFactoryImpl",
"org.postgresql.core.ConnectionFactory",
"org.postgresql.core.PGStream",
"org.postgresql.util.PSQLException",
"org.postgresql.util.GT",
"org.postgresql.util.PSQLState",
"org.postgresql.jdbc2.AbstractJdbc2Array",
"org.postgresql.jdbc4.Jdbc4Array",
"com.google.common.base.Joiner$MapJoiner",
"com.google.common.collect.Maps",
"org.postgresql.util.PGobject",
"org.openstreetmap.osmosis.hstore.PGHStore",
"org.postgis.jts.JtsBinaryParser",
"org.postgis.jts.JtsBinaryWriter",
"com.vividsolutions.jts.geom.PrecisionModel$Type",
"com.vividsolutions.jts.geom.PrecisionModel",
"com.vividsolutions.jts.geom.impl.PackedCoordinateSequenceFactory",
"com.vividsolutions.jts.geom.GeometryFactory",
"com.vividsolutions.jts.io.WKTReader",
"org.postgis.jts.JtsGeometry",
"com.vividsolutions.jts.io.ParseException",
"com.vividsolutions.jts.geom.Geometry$1",
"com.vividsolutions.jts.geom.Geometry",
"com.vividsolutions.jts.geom.GeometryCollection",
"com.vividsolutions.jts.geom.MultiPoint",
"com.vividsolutions.jts.geom.impl.PackedCoordinateSequence",
"com.vividsolutions.jts.geom.impl.PackedCoordinateSequence$Double",
"org.openstreetmap.osmosis.hstore.PGHStore$Parser",
"org.postgresql.core.VisibleBufferedInputStream",
"org.postgresql.core.Encoding",
"org.postgresql.core.PGStream$1",
"com.vividsolutions.jts.geom.DefaultCoordinateSequenceFactory",
"com.vividsolutions.jts.geom.impl.CoordinateArraySequence",
"com.vividsolutions.jts.geom.LineString",
"com.vividsolutions.jts.geom.LinearRing",
"org.postgresql.jdbc2.AbstractJdbc2BlobClob",
"org.postgresql.jdbc2.AbstractJdbc2Blob",
"org.postgresql.jdbc3.AbstractJdbc3Blob",
"org.postgresql.jdbc4.AbstractJdbc4Blob",
"org.postgresql.jdbc4.Jdbc4Blob",
"com.vividsolutions.jts.geom.impl.CoordinateArraySequenceFactory",
"com.vividsolutions.jts.geom.impl.PackedCoordinateSequence$Float",
"com.vividsolutions.jts.geom.Point",
"com.vividsolutions.jts.util.Assert",
"com.fasterxml.jackson.core.util.ByteArrayBuilder",
"com.vividsolutions.jts.geom.DefaultCoordinateSequence",
"com.vividsolutions.jts.geom.Coordinate",
"com.vividsolutions.jts.geom.Polygon",
"org.postgresql.jdbc2.AbstractJdbc2Clob",
"org.postgresql.jdbc3.AbstractJdbc3Clob",
"org.postgresql.jdbc4.AbstractJdbc4Clob",
"org.postgresql.jdbc4.Jdbc4Clob",
"com.vividsolutions.jts.geom.Envelope",
"org.elasticsearch.common.xcontent.AbstractObjectParser",
"org.elasticsearch.common.xcontent.ConstructingObjectParser",
"com.vividsolutions.jts.geom.MultiLineString"
);
}
}
| 54.086085 | 183 | 0.749766 |
d49b0714908be3c0601ac9838f83c9369e24a624 | 162 | package com.devin12422.tweaks.item.weapon.onehanded.plancon;
public class PlanconItem {
public PlanconItem() {
// TODO Auto-generated constructor stub
}
}
| 16.2 | 60 | 0.759259 |
4c3e37bbf8e410ac0fabf7e883a18053bdda67f0 | 2,863 | /*
* Copyright (C) 2020 The zfoo Authors
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package com.zfoo.protocol.jprotobuf;
import com.baidu.bjf.remoting.protobuf.ProtobufProxy;
import com.zfoo.protocol.ProtocolManager;
import com.zfoo.protocol.generate.GenerateOperation;
import com.zfoo.protocol.packet.ProtobufObject;
import com.zfoo.protocol.serializer.CodeLanguage;
import com.zfoo.protocol.util.JsonUtils;
import org.junit.Ignore;
import org.junit.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @author jaysunxiao
* @version 3.0
*/
@Ignore
public class JProtobufTest {
private static final Map<Integer, String> mapWithInteger = new HashMap<>(Map.of(Integer.MIN_VALUE, "a", -99, "b", 0, "c", 99, "d", Integer.MAX_VALUE, "e"));
@Test
public void deserializerTest() throws IOException {
var simpleTypeCodec = ProtobufProxy.create(ObjectA.class);
var obj = new ObjectA();
obj.a = Integer.MAX_VALUE;
obj.m = mapWithInteger;
// 序列化
byte[] bytes = simpleTypeCodec.encode(obj);
// 反序列化
var newObj = simpleTypeCodec.decode(bytes);
// 反序列化到protobuf
var newProtobufObj = ProtobufObject.ObjectA.parseFrom(bytes);
System.out.println(JsonUtils.object2String(newObj));
}
@Test
public void serializerTest() throws IOException {
// 原生protobuf对象
var protobufObjectB = ProtobufObject.ObjectB.newBuilder().setFlag(false).build();
var protobufObjectA = ProtobufObject.ObjectA.newBuilder()
.setA(Integer.MAX_VALUE)
.putAllM(mapWithInteger)
.setObjectB(protobufObjectB)
.build();
byte[] bytes = protobufObjectA.toByteArray();
var simpleTypeCodec = ProtobufProxy.create(ObjectA.class);
var newObj = simpleTypeCodec.decode(bytes);
System.out.println(JsonUtils.object2String(newObj));
}
@Test
public void generateTest() throws IOException {
var op = GenerateOperation.NO_OPERATION;
op.getGenerateLanguages().add(CodeLanguage.Protobuf);
op.setFoldProtocol(true);
op.setProtocolParam("protobuf=protobufTest/protobuf.xml");
ProtocolManager.initProtocol(Set.of(ObjectA.class, ObjectB.class, ObjectC.class), op);
}
}
| 33.682353 | 160 | 0.698219 |
0c1451e114bcc11da222a67ce47046e9b72529bc | 677 | /*
Copyright © 2019 Pasqual K. | All rights reserved
*/
package systems.reformcloud.network.packets.in;
import systems.reformcloud.ReformCloudClient;
import systems.reformcloud.configurations.Configuration;
import systems.reformcloud.network.interfaces.NetworkInboundHandler;
import java.io.Serializable;
/**
* @author _Klaro | Pasqual K. / created on 06.02.2019
*/
public final class PacketInExecuteClientCommand implements Serializable, NetworkInboundHandler {
@Override
public void handle(Configuration configuration) {
ReformCloudClient.getInstance().getCommandManager()
.dispatchCommand(configuration.getStringValue("cmd"));
}
}
| 27.08 | 96 | 0.769572 |
69d08ab2e23a9dcff384e7310bdf232800884465 | 834 | package CodeChef.Practice;
import java.util.HashSet;
import java.util.Scanner;
public class StudyingAlphabet {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
HashSet<Character> jeffKnows = new HashSet<>();
for (int i = 0; i < s.length(); i++) {
jeffKnows.add(s.charAt(i));
}
int N = Integer.parseInt(scanner.nextLine());
outer : for (int i = 0; i < N; i++) {
String word = scanner.nextLine();
for (int i1 = 0; i1 < word.length(); i1++) {
if (!jeffKnows.contains(word.charAt(i1))) {
System.out.println("No");
continue outer;
}
}
System.out.println("Yes");
}
}
}
| 30.888889 | 59 | 0.51199 |
678dca9328d5e3d9ef6bd998f0ed97014506e71b | 21,945 | /*
* Copyright 2003 - 2017 The eFaps Team
*
* 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.efaps.ui.wicket;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.Session;
import org.apache.wicket.protocol.http.WebSession;
import org.apache.wicket.protocol.http.request.WebClientInfo;
import org.apache.wicket.protocol.http.servlet.ServletWebRequest;
import org.apache.wicket.protocol.ws.api.HttpSessionCopy;
import org.apache.wicket.request.IRequestParameters;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.util.string.StringValue;
import org.efaps.admin.access.user.AccessCache;
import org.efaps.admin.user.Person;
import org.efaps.admin.user.UserAttributesSet;
import org.efaps.api.background.IExecutionBridge;
import org.efaps.api.ui.ILoginProvider;
import org.efaps.db.Context;
import org.efaps.jaas.LoginHandler;
import org.efaps.ui.wicket.components.IRecent;
import org.efaps.ui.wicket.components.menu.LinkItem;
import org.efaps.ui.wicket.connectionregistry.RegistryManager;
import org.efaps.ui.wicket.models.EmbeddedLink;
import org.efaps.ui.wicket.models.objects.UIMenuItem;
import org.efaps.ui.wicket.pages.error.ErrorPage;
import org.efaps.ui.wicket.pages.info.GatherInfoPage;
import org.efaps.ui.wicket.request.EFapsMultipartRequest;
import org.efaps.ui.wicket.request.EFapsRequest;
import org.efaps.ui.wicket.store.InfinispanPageStore;
import org.efaps.ui.wicket.util.Configuration;
import org.efaps.ui.wicket.util.Configuration.ConfigAttribute;
import org.efaps.util.EFapsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A WebSession subclass that is used e.g. as a store for behaviors that last a
* Session and provides functionalities like open/close a Context and
* login/logout a User.
*
* @author The eFaps Team
*/
public class EFapsSession
extends WebSession
{
/**
* This variable is used as the Key to the UserName stored in the
* SessionAttributes.
*/
public static final String LOGIN_ATTRIBUTE_NAME = "org.efaps.ui.wicket.LoginAttributeName";
/**
* Needed for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* Logger for this class.
*/
private static final Logger LOG = LoggerFactory.getLogger(EFapsSession.class);
/** The execution bridges. */
private List<IExecutionBridge> executionBridges = Collections.synchronizedList(new ArrayList<IExecutionBridge>());
/**
* This instance variable holds the Name of the logged in user. It is also
* used to check if a user is logged in, by returning that a user is logged
* in, if this variable is not null.
*
* @see #isLogedIn()
* @see #checkin()
* @see #checkout()
*/
private String userName;
/**
* This instance map stores the Attributes which are valid for the whole
* session. It is passed on to the Context while opening it.
*
* @see #openContext()
*/
private final Map<String, Object> sessionAttributes = new HashMap<>();
/**
* File to be shown by the ShowFileCallBackBehavior.
*/
private File file;
/**
* Stack that contains the recent visited components.
*/
private final Stack<IRecent> recentStack = new Stack<>();
/**
* Links that are embeded in html, generated outside this wicket app.
*/
private final List<EmbeddedLink> embededlinks = new ArrayList<>();
/**
* Size of the Stack for the recent objects.
*/
private final int stackSize;
/**
* Standard Constructor from Wicket.
*
* @param _request Request
* @param _appKey application key
* @throws EFapsException
*/
public EFapsSession(final Request _request,
final String _appKey)
{
super(_request);
stackSize = Configuration.getAttributeAsInteger(ConfigAttribute.RECENTCACHESIZE);
}
/**
* Adds the execution bridge.
*
* @param _bridge the _bridge
*/
public synchronized void addExecutionBridge(final IExecutionBridge _bridge)
{
bind();
executionBridges.add(_bridge);
}
/**
* Prune finished tasks.
*/
public synchronized void pruneFinishedTasks()
{
final ArrayList<IExecutionBridge> nonFinishedBridges = new ArrayList<>();
for (final IExecutionBridge bridge: executionBridges) {
if (!bridge.isFinished()) {
nonFinishedBridges.add(bridge);
}
}
executionBridges = nonFinishedBridges;
}
/**
* Gets the tasks page.
*
* @param _start the _start
* @param _size the _size
* @return the tasks page
*/
public Iterator<IExecutionBridge> getJobsPage(final int _start,
final int _size)
{
final int min = Math.min(_size, executionBridges.size());
return new ArrayList<>(executionBridges.subList(_start, min)).iterator();
}
/**
* Gets the bridge for job.
*
* @param _jobName the _job name
* @param _prune the _prune
* @return the bridge4 job
*/
public IExecutionBridge getBridge4Job(final String _jobName,
final boolean _prune)
{
IExecutionBridge ret = null;
for (final IExecutionBridge bridge : executionBridges) {
if (bridge.getJobName().equals(_jobName)) {
ret = bridge;
if (_prune && ret.isFinished()) {
executionBridges.remove(ret);
}
break;
}
}
return ret;
}
/**
* Count jobs.
*
* @return the long
*/
public long countJobs()
{
return executionBridges.size();
}
/**
* @param _recent Recent Object to be pushed on the stack.
*/
public void addRecent(final IRecent _recent)
{
if (stackSize > 0) {
recentStack.push(_recent);
if (recentStack.size() > stackSize) {
recentStack.remove(0);
}
}
if (_recent instanceof LinkItem) {
final Object object = ((LinkItem) _recent).getDefaultModelObject();
if (object instanceof UIMenuItem) {
UsageRegistry.register(((UIMenuItem) object).getKey4UsageRegistry());
}
}
}
@Override
public WebClientInfo getClientInfo()
{
if (clientInfo == null) {
final RequestCycle requestCycle = RequestCycle.get();
clientInfo = new WebClientInfo(requestCycle);
}
return (WebClientInfo) clientInfo;
}
/**
* @return the most recent object from the stack, null if stack is empty
*/
public IRecent getRecent()
{
return recentStack.empty() ? null : recentStack.peek();
}
/**
* @return a list with IRecent in the order that a sequential
* pop on the stack would return
*/
public List<IRecent> getAllRecents()
{
@SuppressWarnings("unchecked")
final Stack<IRecent> clone = (Stack<IRecent>) recentStack.clone();
Collections.reverse(clone);
return clone;
}
/**
* Method to check if a user is checked in.
*
* @return true if a user is checked in, else false
* @see #userName
*/
public boolean isLogedIn()
{
boolean ret = false;
if (userName != null) {
ret = true;
} else if (!isSessionInvalidated()) {
ret = lazyLogin();
}
return ret;
}
/**
* Lazy login is used in copmination with a Single Sign On mechanism.
*
* @return true, if successful
*/
private boolean lazyLogin()
{
boolean ret = false;
final HttpServletRequest httpRequest = ((ServletWebRequest) RequestCycle.get().getRequest())
.getContainerRequest();
final HttpSession httpSession = httpRequest.getSession(false);
if (httpSession != null && !(httpSession instanceof HttpSessionCopy)) {
for (final ILoginProvider loginProvider : EFapsApplication.get().getLoginProviders()) {
userName = loginProvider.login(httpSession);
if (userName != null) {
break;
}
}
if (userName != null) {
openContext();
try {
setAttribute(EFapsSession.LOGIN_ATTRIBUTE_NAME, userName);
sessionAttributes.put(UserAttributesSet.CONTEXTMAPKEY, new UserAttributesSet(
userName));
} catch (final EFapsException e) {
EFapsSession.LOG.error("Problems with setting UserAttribues.", e);
}
RegistryManager.registerUserSession(userName, getId());
ret = true;
RequestCycle.get().setResponsePage(GatherInfoPage.class);
}
}
return ret;
}
/**
* Method to log a user with the Parameters from the Request in.
*
* @see #checkLogin(String, String)
*/
public final void login()
{
final IRequestParameters paras = RequestCycle.get().getRequest().getRequestParameters();
final StringValue name = paras.getParameterValue("name");
final StringValue pwd = paras.getParameterValue("password");
if (checkLogin(name.toString(), pwd.toString())) {
userName = name.toString();
// on login a valid Context for the User must be opened to ensure that the
// session attributes that depend on the user are set correctly before any
// further requests are made (e.g. setting the current company
openContext();
setAttribute(EFapsSession.LOGIN_ATTRIBUTE_NAME, userName);
RegistryManager.registerUserSession(userName, getId());
} else {
userName = null;
sessionAttributes.clear();
}
}
/**
* Logs a user out and stores the UserAttribues in the eFaps database.
*/
public final void logout()
{
if (sessionAttributes.containsKey(UserAttributesSet.CONTEXTMAPKEY)) {
try {
UsageRegistry.store();
((UserAttributesSet) sessionAttributes.get(UserAttributesSet.CONTEXTMAPKEY)).storeInDb();
AccessCache.clean4Person(Context.getThreadContext().getPersonId());
} catch (final EFapsException e) {
EFapsSession.LOG.error("Error on logout", e);
} finally {
sessionAttributes.clear();
removeAttribute(EFapsSession.LOGIN_ATTRIBUTE_NAME);
invalidate();
}
}
closeContext();
userName = null;
}
/**
* method to check the LoginInformation (Name and Password) against the
* eFapsDatabase. To check the Information a Context is opened an afterwards
* closed. It also puts a new Instance of UserAttributes into the instance
* map {@link #sessionAttributes}. The person returned must have at least one
* role asigned to be confirmed as value.
*
* @param _name Name of the User to be checked in
* @param _passwd Password of the User to be checked in
* @return true if LoginInformation was valid, else false
*/
private boolean checkLogin(final String _name,
final String _passwd)
{
boolean loginOk = false;
try {
if (Context.isTMActive()) {
Context.getThreadContext();
} else {
Context.begin();
}
boolean ok = false;
try {
// on a new login the cache for Person is reseted
Person.reset(_name);
final EFapsApplication app = (EFapsApplication) getApplication();
final LoginHandler loginHandler = new LoginHandler(app.getApplicationKey());
final Person person = loginHandler.checkLogin(_name, _passwd);
if (person != null && !person.getRoles().isEmpty()) {
loginOk = true;
sessionAttributes.put(UserAttributesSet.CONTEXTMAPKEY, new UserAttributesSet(_name));
}
ok = true;
} finally {
if (ok && Context.isTMActive()) {
Context.commit();
} else {
if (Context.isTMMarkedRollback()) {
EFapsSession.LOG.error("transaction is marked to roll back");
} else {
EFapsSession.LOG.error("transaction manager in undefined status");
}
Context.rollback();
}
}
} catch (final EFapsException e) {
EFapsSession.LOG.error("could not check name and password", e);
}
return loginOk;
}
/**
* Method that opens a new Context in eFaps, setting the User, the Locale,
* the Attributes of this Session {@link #sessionAttributes} and the
* RequestParameters for the Context.
*
* @see #attach()
*/
public void openContext()
{
if (isLogedIn()) {
try {
if (!Context.isTMActive()) {
final ServletWebRequest request = (ServletWebRequest) RequestCycle.get().getRequest();
if (request instanceof EFapsRequest || request instanceof EFapsMultipartRequest) {
final Map<String, String[]> parameters = new HashMap<>();
final IRequestParameters reqPara = request.getRequestParameters();
for (final String name : reqPara.getParameterNames()) {
final List<StringValue> values = reqPara.getParameterValues(name);
final String[] valArray;
if (values == null) {
valArray = ArrayUtils.EMPTY_STRING_ARRAY;
} else {
valArray = new String[values.size()];
int i = 0;
for (final StringValue value : values) {
valArray[i] = value.toString();
i++;
}
}
parameters.put(name, valArray);
}
if (Context.isThreadActive()) {
Context.getThreadContext().close();
}
Context.begin(userName, super.getLocale(), sessionAttributes, parameters, null,
Context.Inheritance.Inheritable);
// set the locale in the context and in the session
setLocale(Context.getThreadContext().getLocale());
setAttribute(UserAttributesSet.CONTEXTMAPKEY, Context.getThreadContext().getUserAttributes());
Context.getThreadContext().setPath(request.getContextPath());
}
}
} catch (final EFapsException e) {
EFapsSession.LOG.error("could not initialise the context", e);
throw new RestartResponseException(new ErrorPage(e));
}
}
}
/**
* Method that closes the opened Context {@link #openContext()}, by
* committing or rollback it.
*
* @see #detach()
*/
public void closeContext()
{
if (isLogedIn()) {
try {
if (!Context.isTMNoTransaction()) {
if (Context.isTMActive()) {
Context.commit();
} else {
Context.rollback();
}
}
} catch (final SecurityException e) {
throw new RestartResponseException(new ErrorPage(e));
} catch (final IllegalStateException e) {
throw new RestartResponseException(new ErrorPage(e));
} catch (final EFapsException e) {
throw new RestartResponseException(new ErrorPage(e));
}
}
}
/**
* Save the Context.
*/
public void saveContext()
{
closeContext();
openContext();
}
/**
* @param _file FIle to be used for the ShowFileCallBackBehavior
*/
public void setFile(final File _file)
{
file = _file;
}
/**
* Getter method for instance variable {@link #file}.
*
* @return value of instance variable {@link #file}
*/
public File getFile()
{
return file;
}
/**
* @param _embededLink link to add
*/
public void addEmbededLink(final EmbeddedLink _embededLink)
{
embededlinks.add(_embededLink);
}
/**
* Getter method for the instance variable {@link #linkElements}.
*
* @return value of instance variable {@link #linkElements}
*/
public List<EmbeddedLink> getEmbededLinks()
{
return embededlinks;
}
@Override
public void onInvalidate()
{
EFapsSession.LOG.trace("Session invalidated: {}", this);
RegistryManager.removeUserSession(getId());
InfinispanPageStore.removePages4Session(getId());
// invalidation came from other process
if (userName != null) {
userName = null;
}
super.onInvalidate();
final RequestCycle cycle = RequestCycle.get();
if (cycle != null) {
final HttpServletRequest httpRequest = ((ServletWebRequest) RequestCycle.get().getRequest())
.getContainerRequest();
try {
httpRequest.logout();
} catch (final ServletException e) {
EFapsSession.LOG.error("Catched erroror for logout", e);
}
invalidateNow();
}
}
@Override
public String toString()
{
return new ToStringBuilder(this).append("userName", userName)
.append("sessionId", getId()).build();
}
/**
* @return the current EFapsSession
*/
public static EFapsSession get()
{
return (EFapsSession) Session.get();
}
/**
* This Class is used to pass the FileItems along with its Parameters to the
* Context.
*/
public static class FileParameter implements Context.FileParameter
{
/**
* The FileItem of this FileParameter.
*/
private final FileItem fileItem;
/**
* The Name of the Parameter of the FileParameter.
*/
private final String parameterName;
/**
* Constructor setting the Name of the Parameter and the FileItem.
*
* @param _parameterName name of the parameter
* @param _fileItem file item
*/
public FileParameter(final String _parameterName, final FileItem _fileItem)
{
parameterName = _parameterName;
fileItem = _fileItem;
}
/**
* Not needed.
*/
@Override
public void close()
{
// not needed yet
}
/**
* Method to get the content type of the fileitem.
*
* @return content type
*/
@Override
public String getContentType()
{
return fileItem.getContentType();
}
/**
* Get the input stream of the fileitem.
*
* @return Inputstream
* @throws IOException on error
*/
@Override
public InputStream getInputStream() throws IOException
{
return fileItem.getInputStream();
}
/**
* Get the name of the file item.
*
* @return name of the file item
*/
@Override
public String getName()
{
return fileItem.getName();
}
/**
* Get the name of the parameter.
*
* @return name of the parameter
*/
@Override
public String getParameterName()
{
return parameterName;
}
/**
* Get the size of the file item.
*
* @return size in byte
*/
@Override
public long getSize()
{
return fileItem.getSize();
}
}
}
| 32.272059 | 118 | 0.575849 |
98b578baf9b66def752bcccaa735050a1a0c4f87 | 5,287 | package com.kuang.kuangshenesjd.service;
import com.alibaba.fastjson.JSON;
import com.kuang.kuangshenesjd.pojo.Content;
import com.kuang.kuangshenesjd.utils.HtmlParseUtil;
import org.apache.lucene.util.QueryBuilder;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.naming.directory.SearchResult;
import javax.swing.text.Highlighter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/*
* @description:业务编写
* @author: Felix_XHF
* @create:2021-11-23 20:18
*/
@Service
public class ContentService {
@Autowired
RestHighLevelClient restHighLevelClient;
//1.解析数据放入到es库中
public Boolean parseContent(String keywords) throws IOException {
ArrayList<Content> contents = new HtmlParseUtil().parseJD(keywords);
//把查询到的数据放入到es中
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("2m");
for (int i = 0; i < contents.size(); i++) {
bulkRequest.add(new IndexRequest("jd_goods")
.source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
}
BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
return !bulk.hasFailures();
}
//2.获取这些数据实现搜索功能
public List<Map<String,Object>> searchPage(String keyword, int pageNo, int pageSize) throws IOException {
if (pageNo <= 1){
pageNo = 1;
}
//条件搜索
SearchRequest searchRequest = new SearchRequest("jd_goods");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//分页
searchSourceBuilder.from(pageNo);
searchSourceBuilder.size(pageSize);
//精准匹配
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
searchSourceBuilder.query(termQueryBuilder);
searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//执行搜索
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//执行结果
ArrayList<Map<String,Object>> list = new ArrayList<>();
for (SearchHit documentFields : searchResponse.getHits().getHits()) {
list.add(documentFields.getSourceAsMap());
}
return list;
}
//高亮搜索
public List<Map<String,Object>> searchPageHighlightBuilder(String keyword, int pageNo, int pageSize) throws IOException {
if (pageNo <= 1){
pageNo = 1;
}
//条件搜索
SearchRequest searchRequest = new SearchRequest("jd_goods");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//分页
searchSourceBuilder.from(pageNo);
searchSourceBuilder.size(pageSize);
//精准匹配
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
searchSourceBuilder.query(termQueryBuilder);
searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//高亮
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("title");
//highlightBuilder.requireFieldMatch(false);//多个高亮显示
highlightBuilder.preTags("<span style='color:red'>");
highlightBuilder.postTags("</span>");
searchSourceBuilder.highlighter(highlightBuilder);
//执行搜索
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//执行结果
ArrayList<Map<String,Object>> list = new ArrayList<>();
for (SearchHit hit : searchResponse.getHits().getHits()) {
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
HighlightField title = highlightFields.get("title");
Map<String, Object> sourceAsMap = hit.getSourceAsMap(); //原来的结果
String n_title = "";
// 解析高亮的字段
if (title != null){
Text[] fragments = title.fragments();
for (Text text : fragments) {
n_title += text;
}
}
sourceAsMap.put("title",n_title);//高亮替换原来的title
list.add(sourceAsMap);
}
return list;
}
}
| 36.462069 | 125 | 0.69529 |
aa63ba9291731429d0c50731485db751a7ed46f3 | 5,903 | /*
* Copyright 2019 Baidu, 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.baidubce.services.cfc.model;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Contains the data returned by Baidu CFC service calls about aliases
*/
public class AliasConfigurationResponse extends CfcResponse {
/**
* The baidu resource name for alias
*/
@JsonProperty(value = "AliasBrn")
private String AliasBrn;
/**
* Compatible with AWS Lambda amazon resource name. Same as AliasBrn
*/
@JsonProperty(value = "AliasArn")
private String AliasArn;
/**
* The name of the function, consisting of a number, a letter, - or _. Length limited to 64 characters
*/
@JsonProperty(value = "FunctionName")
private String FunctionName;
/**
* The version of the function.$LATEST means the latest, otherwise it consists of numbers and length limited 1-32
* characters
*/
@JsonProperty(value = "FunctionVersion")
private String FunctionVersion;
/**
* The name of the alias
*/
@JsonProperty(value = "Name")
private String Name;
/**
* A short description of the alias. Length limited 0-256 characters.
*/
@JsonProperty(value = "Description")
private String Description;
/**
* User ID (consists of numbers, letters and _), length limited 128 characters
*/
@JsonProperty(value = "Uid")
private String Uid;
/**
* The alias latest update time. ISO-8601 format (YYYY-MM-DDThh:mm:ss.sTZD)
*/
@JsonProperty(value = "UpdatedAt")
private String UpdatedAt;
/**
* Represent the alias create time. ISO-8601 format (YYYY-MM-DDThh:mm:ss.sTZD)
*/
@JsonProperty(value = "CreatedAt")
private String CreatedAt;
/**
* Get the AliasBrn for alias
* @return The AliasBrn for alias
*/
@JsonProperty(value = "AliasBrn")
public String getAliasBrn() {
return this.AliasBrn;
}
/**
* Set the AliasBrn for alias
* @param aliasBrn The AliasBrn for alias
*/
public void setAliasBrn(String aliasBrn) {
this.AliasBrn = aliasBrn;
}
/**
* Get the AliasArn for alias
* @return The AliasArn for alias
*/
@JsonProperty(value = "AliasArn")
public String getAliasArn() {
return this.AliasArn;
}
/**
* Set the AliasArn for alias
* @param aliasArn The AliasArn for alias
*/
public void setAliasArn(String aliasArn) {
this.AliasArn = aliasArn;
}
/**
* Get the FunctionName for function
* @return The FunctionName for function
*/
@JsonProperty(value = "FunctionName")
public String getFunctionName() {
return this.FunctionName;
}
/**
* Set the FunctionName for function
* @param functionName The FunctionName for function
*/
public void setFunctionName(String functionName) {
this.FunctionName = functionName;
}
/**
* Get the FunctionVersion for function
* @return The FunctionVersion for function
*/
@JsonProperty(value = "FunctionVersion")
public String getFunctionVersion() {
return this.FunctionVersion;
}
/**
* Set the FunctionVersion for function
* @param functionVersion The FunctionVersion for function
*/
public void setFunctionVersion(String functionVersion) {
this.FunctionVersion = functionVersion;
}
/**
* Get the Name for alias
* @return The Name for alias
*/
@JsonProperty(value = "Name")
public String getName() {
return this.Name;
}
/**
* Set the Name for alias
* @param name The Name for alias
*/
public void setName(String name) {
this.Name = name;
}
/**
* Get the Description for alias
* @return The Description for alias
*/
@JsonProperty(value = "Description")
public String getDescription() {
return this.Description;
}
/**
* Set the Description for alias
* @param description The Description for alias
*/
public void setDescription(String description) {
this.Description = description;
}
/**
* Get the Uid for the function user
* @return The Uid for the function user
*/
@JsonProperty(value = "Uid")
public String getUid() {
return this.Uid;
}
/**
* Set the Uid for the function user
* @param uid The Uid for the function user
*/
public void setUid(String uid) {
this.Uid = uid;
}
/**
* Get the UpdatedAt for alias
* @return The UpdatedAt for alias
*/
@JsonProperty(value = "UpdatedAt")
public String getUpdatedAt() {
return this.UpdatedAt;
}
/**
* Set the UpdatedAt for alias
* @param updatedAt The UpdatedAt for alias
*/
public void setUpdatedAt(String updatedAt) {
this.UpdatedAt = updatedAt;
}
/**
* Get the CreatedAt for alias
* @return The CreatedAt for alias
*/
@JsonProperty(value = "CreatedAt")
public String getCreatedAt() {
return this.CreatedAt;
}
/**
* Set the CreatedAt for alias
* @param createdAt The CreatedAt for alias
*/
public void setCreatedAt(String createdAt) {
this.CreatedAt = createdAt;
}
}
| 25.777293 | 118 | 0.631204 |
2dec4043ec7d2bcb357fcf1aff9c89c9f8fecfd7 | 5,364 | /*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sandesha2.faulttests;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axiom.soap.impl.llom.soap11.SOAP11Factory;
import org.apache.axis2.addressing.AddressingConstants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.MessageContext;
import org.apache.sandesha2.RMMsgContext;
import org.apache.sandesha2.Sandesha2Constants;
import org.apache.sandesha2.SandeshaTestCase;
import org.apache.sandesha2.storage.beans.RMSBean;
import org.apache.sandesha2.util.RMMsgCreator;
import org.apache.sandesha2.util.SpecSpecificConstants;
import org.apache.sandesha2.wsrm.AcksTo;
import org.apache.sandesha2.wsrm.CreateSequence;
public class CreateSequenceRefusedFaultTest extends SandeshaTestCase {
private static final String server_repoPath = "target" + File.separator
+ "repos" + File.separator + "server";
private static final String server_axis2_xml = "target" + File.separator
+ "repos" + File.separator + "server" + File.separator
+ "server_axis2.xml";
private static ConfigurationContext serverConfigContext;
public CreateSequenceRefusedFaultTest() {
super("CreateSequenceProcessorTest");
}
public void setUp() throws Exception {
super.setUp();
serverConfigContext = startServer(server_repoPath, server_axis2_xml);
}
/**
* Sends a Create Sequence message to an RM Destination that will be refused.
*
* @throws Exception
*/
public void testCreateSequenceSOAPFault() throws Exception {
// Open a connection to the endpoint
HttpURLConnection connection =
FaultTestUtils.getHttpURLConnection("http://127.0.0.1:" + serverPort + "/axis2/services/RMSampleService",
"http://docs.oasis-open.org/ws-rx/wsrm/200702/CreateSequence");
OutputStream tmpOut2 = connection.getOutputStream();
byte ar[] = getMessageAsBytes();
// Send the message to the socket.
tmpOut2.write(ar);
tmpOut2.flush();
// Get the response message from the connection
String message = FaultTestUtils.retrieveResponseMessage(connection);
// Check that the fault message isn't null
assertNotNull(message);
// Check that the response contains the wsrm:CreateSequenceRefused tag
assertTrue(message.indexOf("CreateSequenceRefused") > -1);
// Disconnect at the end of the test
connection.disconnect();
}
/**
* Get a Create Sequence message as bytes
*
* This generates a CreateSequenceMessage that has a "bad" AcksTo value which
* will generate a Fault from the service.
* @return
*/
private byte[] getMessageAsBytes() throws Exception
{
String to = "http://127.0.0.1:" + serverPort + "/axis2/services/RMSampleService";
SOAPFactory factory = new SOAP11Factory();
SOAPEnvelope dummyEnvelope = factory.getDefaultEnvelope();
// Create a "new" application message
MessageContext messageContext = new MessageContext();
messageContext.setConfigurationContext(serverConfigContext);
messageContext.setAxisService(serverConfigContext.getAxisConfiguration().getService("RMSampleService"));
messageContext.setEnvelope(dummyEnvelope);
RMMsgContext applicationRMMsg = new RMMsgContext(messageContext);
// Create an RMSBean so the create sequence message can be created
RMSBean rmsBean = new RMSBean();
rmsBean.setRMVersion(Sandesha2Constants.SPEC_VERSIONS.v1_1);
rmsBean.setToEndpointReference(new EndpointReference(to));
rmsBean.setAcksToEndpointReference(new EndpointReference(AddressingConstants.Final.WSA_NONE_URI));
// Create a Create Sequence message
// generating a new create sequeuce message.
RMMsgContext createSeqRMMessage = RMMsgCreator.createCreateSeqMsg(rmsBean, applicationRMMsg);
messageContext = createSeqRMMessage.getMessageContext();
messageContext.setWSAAction(SpecSpecificConstants.getCreateSequenceAction(Sandesha2Constants.SPEC_VERSIONS.v1_1));
CreateSequence createSeqResPart = createSeqRMMessage.getCreateSequence();
createSeqResPart.setAcksTo(
new AcksTo(new EndpointReference(AddressingConstants.Final.WSA_NONE_URI),
SpecSpecificConstants.getRMNamespaceValue(rmsBean.getRMVersion()),
AddressingConstants.Final.WSA_NAMESPACE));
// Update the SOAP Envelope of the message
createSeqRMMessage.addSOAPEnvelope();
SOAPEnvelope envelope = createSeqRMMessage.getMessageContext().getEnvelope();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
envelope.serialize(outputStream);
return outputStream.toByteArray();
}
}
| 35.523179 | 116 | 0.771999 |
74ac08f90364b2a6eb26f4faad5609862725d8cd | 7,865 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* --------------------------------
* ComparableObjectSeriesTests.java
* --------------------------------
* (C) Copyright 2006-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 20-Oct-2006 : Version 1 (DG);
* 31-Oct-2007 : New hashCode() test (DG);
*
*/
package org.jfree.data.junit;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.data.ComparableObjectItem;
import org.jfree.data.ComparableObjectSeries;
/**
* Tests for the {@link ComparableObjectSeries} class.
*/
public class ComparableObjectSeriesTests extends TestCase {
static class MyComparableObjectSeries extends ComparableObjectSeries {
/**
* Creates a new instance.
*
* @param key the series key.
*/
public MyComparableObjectSeries(Comparable key) {
super(key);
}
/**
* Creates a new instance.
*
* @param key the series key.
* @param autoSort automatically sort by x-value?
* @param allowDuplicateXValues allow duplicate values?
*/
public MyComparableObjectSeries(Comparable key, boolean autoSort,
boolean allowDuplicateXValues) {
super(key, autoSort, allowDuplicateXValues);
}
public void add(Comparable x, Object y) {
super.add(x, y);
}
public ComparableObjectItem remove(Comparable x) {
return super.remove(x);
}
}
/**
* Returns the tests as a test suite.
*
* @return The test suite.
*/
public static Test suite() {
return new TestSuite(ComparableObjectSeriesTests.class);
}
/**
* Constructs a new set of tests.
*
* @param name the name of the tests.
*/
public ComparableObjectSeriesTests(String name) {
super(name);
}
/**
* Some checks for the constructor.
*/
public void testConstructor1() {
ComparableObjectSeries s1 = new ComparableObjectSeries("s1");
assertEquals("s1", s1.getKey());
assertNull(s1.getDescription());
assertTrue(s1.getAllowDuplicateXValues());
assertTrue(s1.getAutoSort());
assertEquals(0, s1.getItemCount());
assertEquals(Integer.MAX_VALUE, s1.getMaximumItemCount());
// try null key
boolean pass = false;
try {
/*s1 = */new ComparableObjectSeries(null);
}
catch (IllegalArgumentException e) {
pass = true;
}
assertTrue(pass);
}
/**
* Confirm that the equals method can distinguish all the required fields.
*/
public void testEquals() {
MyComparableObjectSeries s1 = new MyComparableObjectSeries("A");
MyComparableObjectSeries s2 = new MyComparableObjectSeries("A");
assertTrue(s1.equals(s2));
assertTrue(s2.equals(s1));
// key
s1 = new MyComparableObjectSeries("B");
assertFalse(s1.equals(s2));
s2 = new MyComparableObjectSeries("B");
assertTrue(s1.equals(s2));
// autoSort
s1 = new MyComparableObjectSeries("B", false, true);
assertFalse(s1.equals(s2));
s2 = new MyComparableObjectSeries("B", false, true);
assertTrue(s1.equals(s2));
// allowDuplicateXValues
s1 = new MyComparableObjectSeries("B", false, false);
assertFalse(s1.equals(s2));
s2 = new MyComparableObjectSeries("B", false, false);
assertTrue(s1.equals(s2));
// add a value
s1.add(new Integer(1), "ABC");
assertFalse(s1.equals(s2));
s2.add(new Integer(1), "ABC");
assertTrue(s1.equals(s2));
// add another value
s1.add(new Integer(0), "DEF");
assertFalse(s1.equals(s2));
s2.add(new Integer(0), "DEF");
assertTrue(s1.equals(s2));
// remove an item
s1.remove(new Integer(1));
assertFalse(s1.equals(s2));
s2.remove(new Integer(1));
assertTrue(s1.equals(s2));
}
/**
* Some checks for the clone() method.
*/
public void testCloning() {
MyComparableObjectSeries s1 = new MyComparableObjectSeries("A");
s1.add(new Integer(1), "ABC");
MyComparableObjectSeries s2 = null;
try {
s2 = (MyComparableObjectSeries) s1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(s1 != s2);
assertTrue(s1.getClass() == s2.getClass());
assertTrue(s1.equals(s2));
}
/**
* Serialize an instance, restore it, and check for equality.
*/
public void testSerialization() {
MyComparableObjectSeries s1 = new MyComparableObjectSeries("A");
s1.add(new Integer(1), "ABC");
MyComparableObjectSeries s2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(s1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
s2 = (MyComparableObjectSeries) in.readObject();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
assertEquals(s1, s2);
}
/**
* Some simple checks for the hashCode() method.
*/
public void testHashCode() {
MyComparableObjectSeries s1 = new MyComparableObjectSeries("Test");
MyComparableObjectSeries s2 = new MyComparableObjectSeries("Test");
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
s1.add("A", "1");
s2.add("A", "1");
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
s1.add("B", null);
s2.add("B", null);
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
s1.add("C", "3");
s2.add("C", "3");
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
s1.add("D", "4");
s2.add("D", "4");
assertEquals(s1, s2);
assertEquals(s1.hashCode(), s2.hashCode());
}
}
| 31.210317 | 79 | 0.59733 |
ef98b1f00c1b5727b74f73c5021c1dbe391aa9c4 | 5,782 | // Copyright 2017 Archos SA
//
// 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.archos.environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.Log;
import java.io.File;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public final class ArchosUtils {
private static final String TAG = "ArchosUtils";
private static Context globalContext;
@SuppressWarnings("unused")
public static void ArchosRKDeviceOnlyBarrier(final Activity activity) {
if (!Build.MANUFACTURER.equals("archos") ||
(!Build.MODEL.equals("ARCHOS 80XSK") &&
!Build.MODEL.equals("A70GT"))) {
AlertDialog alertDialog = new AlertDialog.Builder(activity).setTitle("Error")
.setMessage("This application in not authorized on this device.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
activity.finish();
}
}).create();
alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
activity.finish();
}
});
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setCancelable(false);
alertDialog.show();
}
}
public static boolean isNetworkConnected(Context context) {
// Check network status
boolean networkEnabled = false;
ConnectivityManager connectivity = (ConnectivityManager)(context.getSystemService(Context.CONNECTIVITY_SERVICE));
if (connectivity != null) {
NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
networkEnabled = true;
}
}
return networkEnabled;
}
public static boolean isLocalNetworkConnected(Context context) {
// Check network status
boolean networkEnabled = false;
ConnectivityManager connectivity = (ConnectivityManager)(context.getSystemService(Context.CONNECTIVITY_SERVICE));
if (connectivity != null) {
NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected() &&
(networkInfo.getType() == ConnectivityManager.TYPE_WIFI || networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET)) {
networkEnabled = true;
}
}
return networkEnabled;
}
public static boolean isArchosDevice(@SuppressWarnings("UnusedParameters") Context context) {
File file = new File("/system/framework/com.archos.frameworks.jar");
return (file.exists() && Build.MANUFACTURER.equalsIgnoreCase("archos"));
}
public static boolean isFreeVersion(Context context) {
return context.getPackageName().endsWith("free") && !isArchosDevice(context);
}
public static boolean isAmazonApk() {
return android.os.Build.MANUFACTURER.toLowerCase().equals("amazon");
}
public static String getIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) { // we get both ipv4 and ipv6, we want ipv4
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
Log.e(TAG,"getIpAddress", e);
}
return null;
}
public static String getNameWithoutExtension(String filenameWithExtension) {
int dotPos = filenameWithExtension.lastIndexOf('.');
if (dotPos >= 0 && dotPos < filenameWithExtension.length()) {
return filenameWithExtension.substring(0, dotPos);
} else {
return filenameWithExtension;
}
}
public static String getExtension(String filename) {
if (filename == null)
return null;
int dotPos = filename.lastIndexOf('.');
if (dotPos >= 0 && dotPos < filename.length()) {
return filename.substring(dotPos + 1).toLowerCase();
}
return null;
}
public static void setGlobalContext(Context globalContext) {
ArchosUtils.globalContext = globalContext;
}
public static Context getGlobalContext() {
return globalContext;
}
public static boolean shouldAnimate() {
return !(Build.MANUFACTURER.equalsIgnoreCase("samsung")&&Build.VERSION.SDK_INT==Build.VERSION_CODES.JELLY_BEAN_MR2); //do not animate fragments on samsung with 4.3
}
}
| 37.79085 | 171 | 0.667243 |
f4e1a660c42a0852750a2922e275ab7f396b9555 | 3,845 | package VoiceMenuTest.constraints;
/*Generated by MPS */
import jetbrains.mps.smodel.runtime.base.BaseConstraintsDescriptor;
import java.util.Map;
import org.jetbrains.mps.openapi.language.SReferenceLink;
import jetbrains.mps.smodel.runtime.ReferenceConstraintsDescriptor;
import jetbrains.mps.smodel.runtime.base.BaseReferenceConstraintsDescriptor;
import org.jetbrains.annotations.Nullable;
import jetbrains.mps.smodel.runtime.ReferenceScopeProvider;
import jetbrains.mps.smodel.runtime.base.BaseScopeProvider;
import org.jetbrains.mps.openapi.model.SNodeReference;
import jetbrains.mps.scope.Scope;
import jetbrains.mps.smodel.runtime.ReferenceConstraintsContext;
import java.util.List;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations;
import org.jetbrains.mps.openapi.language.SAbstractConcept;
import jetbrains.mps.scope.ListScope;
import java.util.HashMap;
import jetbrains.mps.smodel.SNodePointer;
import org.jetbrains.mps.openapi.language.SConcept;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
public class Assert_Constraints extends BaseConstraintsDescriptor {
public Assert_Constraints() {
super(CONCEPTS.Assert$Fi);
}
@Override
protected Map<SReferenceLink, ReferenceConstraintsDescriptor> getSpecifiedReferences() {
BaseReferenceConstraintsDescriptor d0 = new BaseReferenceConstraintsDescriptor(LINKS.expectedEvent$5c5c, this) {
@Override
public boolean hasOwnScopeProvider() {
return true;
}
@Nullable
@Override
public ReferenceScopeProvider getScopeProvider() {
return new BaseScopeProvider() {
@Override
public SNodeReference getSearchScopeValidatorNode() {
return breakingNode_g42j4u_a0a0a0a0a1a0a0a0c;
}
@Override
public Scope createScope(final ReferenceConstraintsContext _context) {
List<SNode> events = SNodeOperations.getNodeDescendants(SLinkOperations.getTarget(SNodeOperations.cast(SNodeOperations.getContainingRoot(_context.getContextNode()), CONCEPTS.VoiceMenuTestCase$U_), LINKS.workspaceToTest$OyBX), CONCEPTS.Event$Du, false, new SAbstractConcept[]{});
return ListScope.forNamedElements(events);
}
};
}
};
Map<SReferenceLink, ReferenceConstraintsDescriptor> references = new HashMap<SReferenceLink, ReferenceConstraintsDescriptor>();
references.put(d0.getReference(), d0);
return references;
}
private static final SNodePointer breakingNode_g42j4u_a0a0a0a0a1a0a0a0c = new SNodePointer("r:f13c684f-5a73-4f94-a84e-78c195b9a56b(VoiceMenuTest.constraints)", "8281000289632442912");
private static final class CONCEPTS {
/*package*/ static final SConcept Assert$Fi = MetaAdapterFactory.getConcept(0x25057fc953374f2eL, 0x9703a17097079193L, 0x72ec05e3887030a6L, "VoiceMenuTest.structure.Assert");
/*package*/ static final SConcept VoiceMenuTestCase$U_ = MetaAdapterFactory.getConcept(0x25057fc953374f2eL, 0x9703a17097079193L, 0x72ec05e3886dfc0cL, "VoiceMenuTest.structure.VoiceMenuTestCase");
/*package*/ static final SConcept Event$Du = MetaAdapterFactory.getConcept(0x4bc750d756884f52L, 0xb7d5b263a3393a24L, 0x5b6b060cf3fde30cL, "jetbrains.mps.samples.VoiceMenu.structure.Event");
}
private static final class LINKS {
/*package*/ static final SReferenceLink expectedEvent$5c5c = MetaAdapterFactory.getReferenceLink(0x25057fc953374f2eL, 0x9703a17097079193L, 0x72ec05e3887030a6L, 0x72ec05e38870a891L, "expectedEvent");
/*package*/ static final SReferenceLink workspaceToTest$OyBX = MetaAdapterFactory.getReferenceLink(0x25057fc953374f2eL, 0x9703a17097079193L, 0x72ec05e3886dfc0cL, 0x72ec05e388705231L, "workspaceToTest");
}
}
| 53.402778 | 290 | 0.79844 |
4ee502d0719d91d7890e2b05800cc79a98df752d | 887 | package com.linfaxin.transitionplayer.demo;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ShowDrawerLayoutDemo(View view) {
startActivity(new Intent(this, DrawerLayoutDemo.class));
}
public void ShowMaterialMenuDemo(View view) {
startActivity(new Intent(this, MaterialMenuDemo.class));
}
public void ShowChromeHomeDemo(View view) {
startActivity(new Intent(this, ChromeHomeDemo.class));
}
public void ShowXiaoMaIntroDemo(View view) {
startActivity(new Intent(this, XiaoMaIntroDemo.class));
}
}
| 26.878788 | 64 | 0.729425 |
ab9d6e64c521805b71f3b76d4c103d809ecbaf10 | 51 | package mytest;
public class DemoThread {
}
| 8.5 | 26 | 0.666667 |
447ab4f8da90cb020852a8c4c33068b98b4ab997 | 51 | /**
* バッチ起動クラスを提供する。
*/
package jp.dcworks.batch; | 12.75 | 25 | 0.666667 |
cf85fe08b0dd17bd8f6ce0957c1895d86940beee | 2,467 | /**
* 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.fusesource.hawtdb.internal.util;
import static org.fusesource.hawtdb.internal.util.Ranges.range;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import org.fusesource.hawtdb.internal.util.Ranges;
import org.fusesource.hawtdb.internal.util.Ranges.Range;
import org.junit.Test;
/**
*
* @author <a href="http://hiramchirino.com">Hiram Chirino</a>
*/
public class RangesTest {
@Test
public void test() {
Ranges ranges = new Ranges();
// Example of a simple range merges..
ranges.add(0, 5);
ranges.add(15, 5);
ranges.add(5,10);
assertEquals(ranges(range(0,20)), ranges.toArrayList());
// Remove which splits an existing range into 2.
ranges.remove(5,10);
assertEquals(ranges(range(0,5),range(15,20)), ranges.toArrayList());
// overlapping add...
ranges.add(4,12);
assertEquals(ranges(range(0,20)), ranges.toArrayList());
// Removes are idempotent
ranges.remove(5,10);
assertEquals(ranges(range(0,5),range(15,20)), ranges.toArrayList());
ranges.remove(5,10);
assertEquals(ranges(range(0,5),range(15,20)), ranges.toArrayList());
// Adds are idempotent
ranges.add(5,10);
assertEquals(ranges(range(0,20)), ranges.toArrayList());
ranges.add(5,10);
assertEquals(ranges(range(0,20)), ranges.toArrayList());
}
ArrayList<Range> ranges(Range... args) {
ArrayList<Range> rc = new ArrayList<Range>();
for (Range range : args) {
rc.add(range);
}
return rc;
}
}
| 32.893333 | 76 | 0.658695 |
b32104866ca30d7c0d8805d3ce4ffff8cfa56696 | 1,076 | package smithsonian.merlin.util;
import org.ini4j.Wini;
import java.io.File;
/**
* Created by albesmn on 8/24/2016.
*/
public class Options {
public static String currentLayout;
public static String shared_folder_path;
public static String museum;
public static void loadOptions() {
try {
Wini ini = new Wini(new File("res/options.ini"));
museum = ini.get("variables", "museum");
currentLayout = ini.get("variables", "layout_name");
shared_folder_path = ini.get("variables", "shared_folder_path");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void saveOptions() {
try {
Wini ini = new Wini(new File("res/options.ini"));
ini.put("variables", "museum", museum);
ini.put("variables", "layout_name", currentLayout);
ini.put("variables", "shared_folder_path", shared_folder_path);
ini.store();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| 27.589744 | 76 | 0.585502 |
48b4a55bb946ff65b67923f5b4ad5eb71741af55 | 1,828 | /*
* Copyright (C) 2011 The Best Company in the World
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/fmarslan/notifyman/blob/master/LICENSE
*
* 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.tarsolution.notifyman.core.filters;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import com.tarsolution.notifyman.common.exception.BusinessException;
import com.tarsolution.notifyman.common.response.ResponseData;
/**
*
* @author FMARSLAN
*
*/
@ControllerAdvice
public class ExceptionInterceptor extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body,
HttpHeaders headers, HttpStatus status, WebRequest request) {
if (ex instanceof BusinessException) {
return new ResponseData<>(HttpStatus.INTERNAL_SERVER_ERROR)
.setExceptionCode(((BusinessException) ex).getCode()).addMessage(ex.getMessage());
}
return new ResponseData<Object>(HttpStatus.INTERNAL_SERVER_ERROR).addMessage(ex.getMessage());
}
}
| 38.893617 | 98 | 0.786105 |
aa5934fadbdf86a05e0600f5427e172ab9234d1e | 686 | package com.frank.framework.validator;
import java.util.regex.Pattern;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.apache.commons.lang3.StringUtils;
import com.frank.framework.annotation.Phone;
/**
* 手机号码校验
* @author Frank
*
*/
public class PhoneValidator implements ConstraintValidator<Phone, String> {
private Pattern pattern = Pattern.compile("1(([38]\\d)|(5[^4&&\\d])|(4[579])|(7[0135678]))\\d{8}");
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return StringUtils.isNotBlank(value) ? pattern.matcher(value).matches() : true;
}
}
| 24.5 | 101 | 0.720117 |
e5b806646c0940e9e78543ca9c5ede4d848cf5c8 | 749 | package cn.jpush.android.a;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public final class i
{
private static Queue<Integer> a = new ConcurrentLinkedQueue();
public static int a()
{
if (a.size() > 0) {
return ((Integer)a.poll()).intValue();
}
return 0;
}
public static boolean a(int paramInt)
{
return a.offer(Integer.valueOf(paramInt));
}
public static int b()
{
return a.size();
}
public static boolean b(int paramInt)
{
return a.contains(Integer.valueOf(paramInt));
}
}
/* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/cn/jpush/android/a/i.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 19.710526 | 102 | 0.639519 |
caefc479cb7a48182e786bd85d309090ae070b6e | 2,684 | package blusunrize.discordstreamcompanion.config;
import blusunrize.discordstreamcompanion.util.Utils;
import javax.swing.*;
import java.awt.*;
/**
* @author BluSunrize
* @since 26.08.2017
*/
public class GuiConfig
{
private Config config;
private JFrame frame;
private JPanel window;
private JButton button_save;
private JButton button_exit;
private JPasswordField field_token;
private JCheckBox checkbox_token;
private JTextField field_frequency;
private JTextField field_color;
private JComboBox select_alignment;
private JCheckBox checkbox_avatars;
private JTextField field_bgcolor;
private JComboBox select_channelName;
public GuiConfig()
{
checkbox_token.addActionListener(e -> field_token.setEchoChar(checkbox_token.isSelected()?0: '•'));
button_exit.addActionListener(e -> {
Utils.closeJFrame(frame);
});
button_save.addActionListener(e -> {
this.saveConfig();
frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
Utils.closeJFrame(frame);
});
}
public GuiConfig setFrame(JFrame frame)
{
this.frame = frame;
return this;
}
public JPanel getWindow()
{
return window;
}
public GuiConfig setConfig(Config config)
{
this.config = config;
this.field_token.setText(this.config.getToken());
this.field_frequency.setText(""+this.config.getUpdateFrequency());
this.field_color.setText("#"+Integer.toHexString(this.config.getTextColor().getRGB()));
this.field_bgcolor.setText("#"+Integer.toHexString(this.config.getBgColor().getRGB()));
this.select_alignment.setSelectedIndex(this.config.getAlignment().ordinal());
this.select_channelName.setSelectedIndex(this.config.getShowChannelName().ordinal());
this.checkbox_avatars.setSelected(this.config.getShowAvatars());
return this;
}
private void saveConfig()
{
if(this.config!=null)
{
this.config.setToken(new String(field_token.getPassword()));
this.config.setUpdateFrequency(Utils.parseInteger(field_frequency.getText(), 500));
this.config.setTextColor(Utils.parseColor(field_color.getText(), Color.lightGray));
this.config.setBgColor(Utils.parseColor(field_bgcolor.getText(), Color.darkGray));
this.config.setAlignment(AlignmentStyle.values()[select_alignment.getSelectedIndex()]);
this.config.setShowChannelName(ChannelNameStyle.values()[select_channelName.getSelectedIndex()]);
this.config.setShowAvatars(checkbox_avatars.isSelected());
this.config.saveConfig();
if(!this.config.isLoaded())
this.config.setLoaded(true);
}
}
private void createUIComponents()
{
select_alignment = new JComboBox(AlignmentStyle.values());
select_channelName = new JComboBox(ChannelNameStyle.values());
}
}
| 28.252632 | 101 | 0.767511 |
986bbe9e0a1dedf8f6641792dfe4c7b112d21ca9 | 2,961 | package com.elementary.tasks.core.calendar;
import android.os.Environment;
import java.io.File;
/**
* Copyright 2016 Nazar Suhovich
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.
*/
public final class ImageCheck {
public static final String BASE_URL = "https://unsplash.it/1920/1080?image=";
private long[] photos = new long[]{
227,
226,
11,
25,
33,
10,
16,
17,
44,
71,
95,
132};
private static ImageCheck instance;
private ImageCheck() {
}
public static ImageCheck getInstance() {
if (instance == null) {
instance = new ImageCheck();
}
return instance;
}
public String getImage(int month, long id) {
String res = null;
File sdPath = Environment.getExternalStorageDirectory();
File sdPathDr = new File(sdPath.toString() + "/JustReminder/" + "image_cache");
if (!sdPathDr.exists()) {
sdPathDr.mkdirs();
}
File image = new File(sdPathDr, getImageName(month, id));
if (image.exists()) {
res = image.toString();
}
return res;
}
public boolean isImage(int month, long id) {
if (isSdPresent()) {
boolean res = false;
File sdPath = Environment.getExternalStorageDirectory();
File sdPathDr = new File(sdPath.toString() + "/JustReminder/" + "image_cache");
if (!sdPathDr.exists()) {
sdPathDr.mkdirs();
}
File image = new File(sdPathDr, getImageName(month, id));
if (image.exists()) {
res = true;
}
return res;
} else {
return false;
}
}
public String getImageUrl(int month, long id) {
if (id != -1) {
return BASE_URL + id;
} else {
return BASE_URL + photos[month];
}
}
public String getImageName(int month, long id) {
if (id != -1) {
return getFileName(id);
} else {
return getFileName(photos[month]);
}
}
private String getFileName(long id) {
return "photo_" + id + ".jpg";
}
public boolean isSdPresent() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
}
| 27.416667 | 91 | 0.559608 |
7811ceb915bb1d64fef0c61ff6450d791844a820 | 24,762 | /**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package com.heliosapm.streams.metrichub.tsdbplugin;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.heliosapm.streams.metrichub.MetricsMetaAPI;
import com.heliosapm.streams.metrichub.QueryContext;
import com.heliosapm.streams.metrichub.tsdbplugin.json.Netty3JSONRequest;
import com.heliosapm.streams.metrichub.tsdbplugin.json.Netty3JSONResponse;
import com.heliosapm.webrpc.annotations.JSONRequestHandler;
import com.heliosapm.webrpc.annotations.JSONRequestService;
import com.heliosapm.webrpc.jsonservice.ResponseType;
import net.opentsdb.meta.TSMeta;
import net.opentsdb.uid.UniqueId.UniqueIdType;
import net.opentsdb.utils.JSON;
import reactor.core.composable.Stream;
import reactor.function.Consumer;
/**
* <p>Title: JSONMetricsAPIService</p>
* <p>Description: JSON service to implement remoting for the Metric API over HTTP and WebSockets</p>
* @author Whitehead (nwhitehead AT heliosdev DOT org)
* <p><code>com.heliosapm.streams.metrichub.tsdbplugin.JSONMetricsAPIService</code></p>
*/
@JSONRequestService(name="meta", description="JSON service to implement remoting for the Metric API over HTTP and WebSockets")
public class JSONMetricsAPIService {
/** The Metric Meta API impl used to serve this JSON service */
protected final MetricsMetaAPI metricApi;
/** Instance logger */
protected final Logger log = LogManager.getLogger(getClass());
/** The ctx name for this class */
protected final String ctxName = getClass().getSimpleName();
/** The ctx name for the accept time */
protected final String ctxAcceptName = getClass().getSimpleName() + "Accepted";
/**
* Creates a new JSONMetricsAPIService
* @param metricApi The Metric Meta API impl used to serve this JSON service
*/
public JSONMetricsAPIService(final MetricsMetaAPI metricApi) {
this.metricApi = metricApi;
}
/**
* HTTP and WebSocket exposed interface to {@link MetricsMetaAPI#getMetricNames(net.opentsdb.meta.api.QueryContext, java.lang.String[])}
* @param request The JSON request
* @param q The query context
* @param tags The TSMeta tags to match the metric names for
* <p>Sample request:<pre>
{
"t": "req",
"rid": 1,
"svc": "meta",
"op": "metricswtags",
"q": {
"pageSize": 10
},
"tags": {
"host": "*",
"type": "combined"
}
}
* </pre></p>
*/
@JSONRequestHandler(name="metricswtags", description="Returns the MetricNames that match the passed tag pairs")
public void getMetricNamesWithTagsJSON(final Netty3JSONRequest request, final QueryContext q, final Map<String, String> tags) {
if(q==null) {
getMetricNamesWithTagsJSON(
request,
JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class).addCtx(ctxName, System.currentTimeMillis()),
getMap(request, "tags")
);
} else {
log.info("Processing JSONMetricNames. q: [{}], tags: {}", q, tags);
attachBatchHandlers(metricApi.getMetricNames(q, tags), q, request);
}
}
/**
* HTTP and WebSocket exposed interface to {@link MetricsMetaAPI#getMetricNames(net.opentsdb.meta.api.QueryContext, java.lang.String[])}
* @param request The JSON request
* @param q The query context
* @param tagKeys an array of tag keys to exclude
* <p>Sample request:<pre>
*
* </pre></p>
* FIXME: merge metric name functions
*/
@JSONRequestHandler(name="metricnames", description="Returns the MetricNames that match the passed tag keys")
public void getMetricNamesJSON(final Netty3JSONRequest request, final QueryContext q, final String...tagKeys) {
if(q==null) {
getMetricNamesJSON(
request,
JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class).addCtx(ctxName, System.currentTimeMillis()),
getStringArray(request, "keys")
);
} else {
log.info("Processing JSONMetricNames. q: [{}], keys: {}", q, Arrays.toString(tagKeys));
attachBatchHandlers(metricApi.getMetricNames(q.startExpiry(), tagKeys), q, request);
}
}
/**
* HTTP and WebSocket exposed interface to {@link MetricsMetaAPI#getTagKeys(QueryContext, String, String...)}
* @param request The JSON request
* @param q The query context
* @param metricName The optional TSMeta metric name to match
* @param tagKeys The tag keys to match
* <p>Sample request:<pre>
{
"t": "req",
"rid": 4,
"svc": "meta",
"op": "tagkeys",
"q": {
"nextIndex": null,
"pageSize": 100,
"maxSize": 2000,
"timeout": 500,
"continuous": false,
"format": "DEFAULT",
"exhausted": false,
"cummulative": 0,
"elapsed": -1,
"expired": false
},
"keys": [
"dc",
"host"
],
"m": "sys*"
}
* </pre></p>
*/
@JSONRequestHandler(name="tagkeys", description="Returns the Tag Key UIDs that match the passed metric name and tag keys")
public void getTagKeysJSON(final Netty3JSONRequest request, final QueryContext q, final String metricName, final String...tagKeys) {
if(q==null) {
getTagKeysJSON(
request,
JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class).addCtx(ctxName, System.currentTimeMillis()),
request.getRequest().get("m").textValue(),
getStringArray(request, "keys")
);
} else {
log.info("Processing JSONTagKeys. q: [{}], m: [{}], keys: {}", q, metricName, Arrays.toString(tagKeys));
attachBatchHandlers(metricApi.getTagKeys(q.startExpiry(), metricName, tagKeys), q, request);
}
}
/**
* HTTP and WebSocket exposed interface to {@link MetricsMetaAPI#getTagValues(QueryContext, String, Map, String)}
* @param request The JSON request
* @param q The query context
* @param metricName The optional TSMeta metric name to match
* @param tags The TSMeta tags to match
* @param tagKey The value of the tag key to get values for
* <p>Sample request:<pre>
{
"t": "req",
"rid": 12,
"svc": "meta",
"op": "tagvalues",
"q": {
"nextIndex": null,
"pageSize": 100,
"maxSize": 2000,
"timeout": 500,
"continuous": false,
"format": "DEFAULT",
"exhausted": false,
"cummulative": 0,
"elapsed": -1,
"expired": false
},
"tags": {
"host": "*Server*",
"cpu": "*"
},
"m": "sys.cpu",
"k": "type"
}
* </pre></p>
*/
@JSONRequestHandler(name="tagvalues", description="Returns the Tag Value UIDs that match the passed metric name and tag keys")
public void getTagValuesJSON(final Netty3JSONRequest request, final QueryContext q, final String metricName, final Map<String, String> tags, final String tagKey) {
if(q==null) {
getTagValuesJSON(
request,
JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class).addCtx(ctxName, System.currentTimeMillis()),
request.getRequest().get("m").textValue(),
getMap(request, "tags"),
request.getRequest().get("k").textValue()
);
} else {
log.info("Processing JSONTagValues. q: [{}], m: [{}], tags: {}", q, metricName, tags);
attachBatchHandlers(metricApi.getTagValues(q.startExpiry(), metricName, tags, tagKey), q, request);
}
}
/**
* HTTP and WebSocket exposed interface to {@link MetricsMetaAPI#getTagValues(QueryContext, String, Map, String)}
* @param request The JSON request
* @param q The query context
* @param expression The TSMeta fully qualified metric name pattern to match. An expression is basically an {@link javax.management.ObjectName} analog where
* the {@link javax.management.ObjectName#getDomain()} value is the metric name and the {@link javax.management.ObjectName#getKeyPropertyList()}
* map represents the tags. Supports <b><code>*</code></b> wildcards for all segments and <b><code>|</code></b> multipliers for tag keys.
* <p>Sample request:<pre>
{
"t": "req",
"rid": 13,
"svc": "meta",
"op": "tsMetaEval",
"q": {
"nextIndex": null,
"pageSize": 100,
"maxSize": 2000,
"timeout": 500,
"continuous": false,
"format": "DEFAULT",
"exhausted": false,
"cummulative": 0,
"elapsed": -1,
"expired": false
},
"x": "sys*:dc=dc*,host=WebServer1|WebServer5"
}
* </pre></p>
*/
@JSONRequestHandler(name="tsMetaEval", description="Returns the TSMetas that match the passed expression")
public void evaluateJSON(final Netty3JSONRequest request, final QueryContext q, final String expression) {
if(q==null) {
evaluateJSON(
request,
JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class).addCtx(ctxName, System.currentTimeMillis()),
request.getRequest().get("x").textValue()
);
} else {
log.debug("Processing JSONTSMetaExpression. \n\tQueryContext: [{}], \n\tExpression: [{}]", q, expression);
attachBatchHandlers(metricApi.evaluate(q, expression), q, request);
}
}
@JSONRequestHandler(name="overlap", description="Determines how may items are common between the two passed expressions")
public void overlap(final Netty3JSONRequest request, final QueryContext q, final String expressionOne, final String expressionTwo) {
if(q==null) {
overlap(
request,
JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class),
request.getRequest().get("x").textValue(),
request.getRequest().get("y").textValue()
);
} else {
final long result = metricApi.overlap(expressionOne, expressionTwo);
request.response(ResponseType.RESP).setContent(JSON.getMapper().createObjectNode().putPOJO("q", q).put("result", result)).send();
}
}
/**
* Attaches the consume and error handlers to the passed stream
* @param stream The stream to attach handlers to
* @param q The query context
* @param request The Netty3JSONRequest
*/
protected final <T> void attachBatchHandlers(Stream<T> stream, final QueryContext q, final Netty3JSONRequest request) {
stream.consume(new Consumer<T>(){
@Override
public void accept(T t) {
try {
final Netty3JSONResponse response;
if(q.shouldContinue()) {
response = request.response(ResponseType.MRESP);
} else {
response = request.response(ResponseType.XMRESP);
}
response.setOpCode("results");
JsonGenerator jgen = response.writeHeader(true);
jgen.setCodec(q.getMapper());
jgen.writeObjectField("results", t);
q.addCtx(ctxAcceptName, System.currentTimeMillis());
jgen.writeObjectField("q", q);
response.closeGenerator();
} catch (Exception ex) {
log.error("Failed to write result batch", ex);
throw new RuntimeException("Failed to write result batch", ex);
}
}
})
.when(Throwable.class, new Consumer<Throwable>(){
@Override
public void accept(Throwable t) {
q.setExhausted(true);
final Netty3JSONResponse response = request.response(ResponseType.ERR);
try {
response.resetChannelOutputStream();
response.setOpCode("error");
final JsonGenerator jgen = response.writeHeader(true);
String message = t.getMessage();
if(message==null || message.trim().isEmpty()) {
message = t.getClass().getSimpleName();
}
jgen.writeObjectField("error", message);
jgen.writeObjectField("q", q);
response.closeGenerator();
log.warn("Exception message dispatched");
} catch (Exception ex) {
throw new RuntimeException("Failed to write timeout response to JSON output streamer", ex);
}
}
});
// .timeout(q.getTimeout());
}
/**
* Attaches the D3 serialization consumee and error handlers to the passed stream
* @param stream The stream to attach handlers to
* @param q The query context
* @param request The Netty3JSONRequest
*/
protected final <T> void attachD3Handlers(Stream<T> stream, final QueryContext q, final Netty3JSONRequest request) {
stream.consume(new Consumer<T>(){
final LinkedHashSet<TSMeta> set = new LinkedHashSet<TSMeta>(q.getNextMaxLimit());
@SuppressWarnings("unchecked")
@Override
public void accept(T t) {
try {
set.addAll((Collection<TSMeta>) t);
final Netty3JSONResponse response;
if(q.shouldContinue()) {
response = request.response(ResponseType.MRESP);
} else {
response = request.response(ResponseType.XMRESP);
}
response.setOpCode("results");
JsonGenerator jgen = response.writeHeader(true);
jgen.setCodec(q.getMapper());
jgen.writeObjectField("results", set);
q.addCtx(ctxAcceptName, System.currentTimeMillis());
jgen.writeObjectField("q", q);
response.closeGenerator();
} catch (Exception ex) {
log.error("Failed to write result batch", ex);
throw new RuntimeException("Failed to write result batch", ex);
}
}
})
.when(Throwable.class, new Consumer<Throwable>(){
@Override
public void accept(Throwable t) {
q.setExhausted(true);
final Netty3JSONResponse response = request.response(ResponseType.ERR);
try {
response.resetChannelOutputStream();
response.setOpCode("error");
final JsonGenerator jgen = response.writeHeader(true);
String message = t.getMessage();
if(message==null || message.trim().isEmpty()) {
message = t.getClass().getSimpleName();
}
jgen.writeObjectField("error", message);
jgen.writeObjectField("q", q);
response.closeGenerator();
log.warn("Exception message dispatched");
} catch (Exception ex) {
throw new RuntimeException("Failed to write timeout response to JSON output streamer", ex);
}
}
});
// .timeout(q.getTimeout());
}
/**
* HTTP and WebSocket exposed interface to {@link MetricsMetaAPI#getTagValues(QueryContext, String, Map, String)}
* returning <a href="http://d3js.org"></a> friendly formatted JSON.
* @param request The JSON request
* @param q The query context
* @param expression The TSMeta fully qualified metric name pattern to match. An expression is basically an {@link javax.management.ObjectName} analog where
* the {@link javax.management.ObjectName#getDomain()} value is the metric name and the {@link javax.management.ObjectName#getKeyPropertyList()}
* map represents the tags. Supports <b><code>*</code></b> wildcards for all segments and <b><code>|</code></b> multipliers for tag keys.
* <p>Sample request:<pre>
{
"t": "req",
"rid": 14,
"svc": "meta",
"op": "tsMetaEval",
"q": {
"nextIndex": null,
"pageSize": 100,
"maxSize": 2000,
"timeout": 500,
"continuous": false,
"format": "D3",
"exhausted": false,
"cummulative": 0,
"elapsed": -1,
"expired": false
},
"x": "sys*:dc=dc*,host=WebServer1|WebServer5"
}
* </pre></p>
*/
@JSONRequestHandler(name="d3tsmeta", description="Returns the d3 json graph for the TSMetas that match the passed expression")
public void evaluateD3JSON(final Netty3JSONRequest request, final QueryContext q, final String expression) {
if(q==null) {
evaluateD3JSON(
request,
JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class),
request.getRequest().get("x").textValue()
);
} else {
attachD3Handlers(metricApi.evaluate(q, expression), q, request);
}
}
/**
* HTTP and WebSocket exposed interface to {@link MetricsMetaAPI#getTSMetas(net.opentsdb.meta.api.QueryContext, java.lang.String, java.util.Map)}
* @param request The JSON request
* @param q The query context
* @param metricName The TSMeta metric name
* @param tags The TSMeta metric tags
* <p>Sample request:<pre>
{
"t": "req",
"rid": 1,
"svc": "meta",
"op": "tsmetas",
"q": {
"nextIndex": null,
"pageSize": 100,
"maxSize": 2000,
"timeout": 500,
"continuous": false,
"format": "DEFAULT",
"exhausted": false,
"cummulative": 0,
"elapsed": -1,
"expired": false
},
"m" : "sys*",
"tags": {"dc" : "dc*", "host" : "WebServer1|WebServer5"}
}
* </pre></p>
*/
@JSONRequestHandler(name="tsmetas", description="Returns the MetricNames that match the passed tag pairs")
public void getTSMetasJSON(final Netty3JSONRequest request, final QueryContext q, final String metricName, final Map<String, String> tags) {
if(q==null) {
getTSMetasJSON(
request,
JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class).addCtx(ctxName, System.currentTimeMillis()),
request.getRequest().get("m").textValue(),
getMap(request, "tags")
);
} else {
// request.response().setOverrideObjectMapper(TSDBTypeSerializer.valueOf(q.getFormat()).getMapper());
// metricApi.getTSMetas(q, metricName, tags).consume(new ResultConsumer<List<TSMeta>>(request, q));
attachBatchHandlers(metricApi.getTSMetas(q, metricName, tags), q, request);
}
}
/**
* HTTP and WebSocket exposed interface to {@link MetricsMetaAPI#find(QueryContext, UniqueIdType, String)}
* @param request The JSON request
* @param q The query context
* @param type The UID type as enumerated in {@link UniqueIdType}
* @param name The UID name pattern to match. Supports <b><code>*</code></b> wildcards for all segments and <b><code>|</code></b> multipliers for tag keys.
* <p>Sample request:<pre>
{
"t": "req",
"rid": 5,
"svc": "meta",
"op": "finduid",
"q": {
"nextIndex": null,
"pageSize": 100,
"maxSize": 2000,
"timeout": 500,
"continuous": false,
"format": "DEFAULT",
"exhausted": false,
"cummulative": 0,
"elapsed": -1,
"expired": false
},
"name": "sys*",
"type": "METRIC"
}
* </pre></p>
*/
@JSONRequestHandler(name="finduid", description="Returns all UIDMetas of the specified type that match the passed name")
public void findJSON(final Netty3JSONRequest request, final QueryContext q, final UniqueIdType type, final String name) {
if(q==null) {
findJSON(
request,
JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class).addCtx(ctxName, System.currentTimeMillis()),
UniqueIdType.valueOf(request.getRequest().get("type").textValue().trim().toUpperCase()),
request.getRequest().get("name").textValue()
);
} else {
attachBatchHandlers(metricApi.find(q.startExpiry(), type, name), q, request);
}
}
// /**
// * @param request
// * @param q
// * @param expression
// * @param range
// */
// @JSONRequestHandler(name="annotations", description="Returns all Annotations associated to TSMetas defined in the expression")
// public void jsonGetAnnotations(final Netty3JSONRequest request, final QueryContext q, final String expression, final long... range) {
// if(q==null) {
// jsonGetAnnotations(
// request,
// JSON.parseToObject(request.getRequest().get("q").toString(), QueryContext.class).addCtx(ctxName, System.currentTimeMillis()),
// request.getRequest().has("x") ? request.getRequest().get("x").asText() : null,
// getLongArray(request, "r")
// );
// } else {
// request.response().setOverrideObjectMapper(TSDBTypeSerializer.valueOf(q.getFormat()).getMapper());
// final Deferred<Set<Annotation>> def;
// if(expression==null) {
// def = metricApi.getGlobalAnnotations(q, range);
// } else {
// def = metricApi.getAnnotations(q, expression, range);
// }
//// def.addCallback(new ResultCompleteCallback<Set<Annotation>>(request, q))
//// .addCallback(new Callback<Void, QueryContext>() {
//// @Override
//// public Void call(QueryContext ctx) throws Exception {
//// if(ctx.shouldContinue()) {
//// jsonGetAnnotations(request, ctx, expression, range);
//// }
//// return null;
//// }
//// });
// }
// }
/**
* Extracts the named string array from the Netty3JSONRequest
* @param request the Netty3JSONRequest to get the array from
* @param key the json name of the array
* @return the read string array
*/
public static String[] getStringArray(final Netty3JSONRequest request, final String key) {
final ArrayNode arrayNode = (ArrayNode)request.getRequest().get(key);
final String[] arr = new String[arrayNode.size()];
for(int i = 0; i < arrayNode.size(); i++) {
arr[i] = arrayNode.get(i).asText();
}
return arr;
}
/**
* Extracts the named long array from the Netty3JSONRequest
* @param request the Netty3JSONRequest to get the array from
* @param key the json name of the array
* @return the read long array
*/
public static long[] getLongArray(final Netty3JSONRequest request, final String key) {
final ArrayNode arrayNode = (ArrayNode)request.getRequest().get(key);
final long[] arr = new long[arrayNode.size()];
for(int i = 0; i < arrayNode.size(); i++) {
arr[i] = arrayNode.get(i).asLong();
}
return arr;
}
/**
* Extracts the named map from the Netty3JSONRequest
* @param request the Netty3JSONRequest to get the map from
* @param key the json name of the map
* @return the read map
*/
public static Map<String, String> getMap(final Netty3JSONRequest request, final String key) {
ObjectNode tagNode = (ObjectNode)request.getRequest().get(key);
final Map<String, String> map = new LinkedHashMap<String, String>();
Iterator<String> titer = tagNode.fieldNames();
while(titer.hasNext()) {
String k = titer.next();
map.put(k, tagNode.get(k).asText());
}
return map;
}
}
/*
protected final <T> void attachHandlers(Stream<T> stream, final QueryContext q, final Netty3JSONRequest request) {
stream.consume(new Consumer<T>(){
boolean firstRow = true;
Netty3JSONResponse response = request.response();
JsonGenerator jgen = null;
final AtomicLong msgId = new AtomicLong();
@Override
public synchronized void accept(T t) {
try {
if(t==null) {
if(firstRow) {
// empty results
jgen.writeObjectField("results", Collections.emptyList());
} else {
jgen.writeEndArray();
}
jgen.writeObjectField("q", q);
jgen.writeNumberField("msgid", msgId.incrementAndGet());
response = response.closeGenerator();
firstRow = true;
return;
}
if(firstRow) {
jgen = response.writeHeader(true);
response.setOpCode("results");
jgen.setCodec(q.getMapper());
jgen.writeFieldName("results");
jgen.writeStartArray();
firstRow = false;
}
jgen.writeObject(t);
} catch (Exception ex) {
log.error("Failed to write result instance. FR: {}, t: {}, jg: {}", firstRow, t, jgen, ex);
throw new RuntimeException("Failed to write result instance", ex);
}
}
})
.when(Throwable.class, new Consumer<Throwable>(){
@Override
public void accept(Throwable t) {
q.setExhausted(true);
final Netty3JSONResponse response = request.response();
try {
response.resetChannelOutputStream();
response.setOpCode("error");
@SuppressWarnings("resource")
final JsonGenerator jgen = response.writeHeader(true);
String message = t.getMessage();
if(message==null || message.trim().isEmpty()) {
message = t.getClass().getSimpleName();
}
jgen.writeObjectField("error", message);
jgen.writeObjectField("q", q);
response.closeGenerator();
log.warn("Exception message dispatched");
} catch (Exception ex) {
throw new RuntimeException("Failed to write timeout response to JSON output streamer", ex);
}
}
});
// .timeout(q.getTimeout());
}
*/ | 35.577586 | 164 | 0.668969 |
3c14c4e34eb036e50ec7e6c95072ed0836939a7c | 1,880 | package com.github.blutorange.translune.ic;
import java.io.IOException;
import javax.inject.Singleton;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.slf4j.Logger;
import com.github.blutorange.common.Suppliers;
import com.github.blutorange.common.ThrowingSupplier;
import com.github.blutorange.translune.db.EntityStore;
import com.github.blutorange.translune.db.IEntityManagerFactory;
import com.github.blutorange.translune.db.IEntityStore;
import com.github.blutorange.translune.db.ILunarDatabaseManager;
import com.github.blutorange.translune.db.LunarDatabaseManager;
import com.github.blutorange.translune.serial.IImportProcessing;
import dagger.Module;
import dagger.Provides;
@Module
public class DatabaseModule {
@Provides
@Singleton
static IEntityManagerFactory provideEntityManagerFactory(@Classed(DatabaseModule.class) final Logger logger) {
final ThrowingSupplier<EntityManagerFactory, IOException> supplier= Suppliers.memoize(() -> {
logger.info("creating entity manager factory");
final EntityManagerFactory emf;
try {
emf = Persistence.createEntityManagerFactory("hibernate");
}
catch (final Exception e) {
throw new IOException("failed to create entity manager factory", e);
}
logger.info("entity manager factory is " + emf.getClass().getCanonicalName());
return emf;
});
return () -> supplier.get();
}
@Provides
@Singleton
static IEntityStore provideEntityStore() {
return new EntityStore();
}
@Provides
@Singleton
static IImportProcessing provideImporProcessing() {
return ComponentFactory.getLunarComponent()._importProcessing();
}
@Provides
@Singleton
static ILunarDatabaseManager provideLunarDatabaseManager() {
final LunarDatabaseManager ldm = new LunarDatabaseManager();
ComponentFactory.getLunarComponent().inject(ldm);
return ldm;
}
}
| 29.84127 | 111 | 0.792553 |
d4ccbbb3e2c4d09107eed5cc6e54826b9a554688 | 6,752 | /*
* Copyright (c) 2017, WSO2 Inc. (http://wso2.com) All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.andes.kernel.slot;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.andes.kernel.MessagingEngine;
import org.wso2.andes.kernel.subscription.StorageQueue;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
/**
* Task executing the slot delete. It will poll on slots scheduled to delete and
* coordinate with slot coordinator in cluster to delete slots.
*/
public class SlotDeletingTask implements Runnable {
private static Log log = LogFactory.getLog(SlotDeletingTask.class);
/**
* Unique ID of the task
*/
private UUID id;
/**
* Condition running the task.
*/
private volatile boolean isLive = true;
/**
* Queue to keep slots to be removed. Reason to use a queue is
* if a slot could not be removed, it is definite later slots cannot be removed
* as well (because of safe-zone)
*/
private LinkedBlockingDeque<Slot> slotsToDelete;
/**
* Maximum number of slots to keep scheduled for deletion before
* raising a WARN
*/
private int maxNumberOfPendingSlots;
/**
* Specifically disable slot deleting task. At start up task
* is enabled by default. Once disabled cannot enable again.
*/
void stop() {
isLive = false;
}
/**
* Create an instance of SlotDeletingTask
*
* @param maxNumberOfPendingSlots max number of pending slots to be deleted (used to raise a WARN)
*/
public SlotDeletingTask(int maxNumberOfPendingSlots) {
this.id = UUID.randomUUID();
this.maxNumberOfPendingSlots = maxNumberOfPendingSlots;
this.slotsToDelete = new LinkedBlockingDeque<>();
}
@Override
public void run() {
while (isLive) {
try {
// Slot to attempt current deletion. This call will block if there is no slot
Slot slot = slotsToDelete.take();
if (log.isDebugEnabled()) {
log.debug("SlotDeletingTask id= " + id + " trying to delete slot " + slot.toString());
}
// Check DB for any remaining messages. (JIRA FIX: MB-1612)
// If there are any remaining messages wait till overlapped slot delivers the messages
if (MessagingEngine.getInstance().getMessageCountForQueueInRange(
slot.getStorageQueueName(), slot.getStartMessageId(), slot.getEndMessageId()) == 0) {
// Invoke coordinator to delete slot
boolean deleteSuccess = deleteSlotAtCoordinator(slot);
if (!deleteSuccess) {
// Delete attempt not success, therefore adding slot to the head of queue
slotsToDelete.addFirst(slot);
if (log.isDebugEnabled()) {
log.debug("SlotDeletingTask id= " + id + " could not agree with "
+ "coordinator to delete slot " + slot.toString());
}
//here try again after a second time delay (let coordinator update safe zone)
//TODO: is there other good way to fix this? We need to delete in the rate we read slots
TimeUnit.SECONDS.sleep(1);
} else {
StorageQueue storageQueue = slot.getStorageQueue();
storageQueue.deleteSlot(slot);
if (log.isDebugEnabled()) {
log.debug("SlotDeletingTask id= " + id + " deleted slot " + slot.toString());
}
}
} else {
if (log.isDebugEnabled()) {
log.debug("SlotDeletingTask id= " + id + " could not deleted slot "
+ slot.toString() + " as there are messages in range of slot");
}
slotsToDelete.put(slot); // Not deleted. Hence putting back to tail of queue
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("SlotDeletionTask was interrupted while trying to delete the slot.", e);
} catch (Throwable throwable) {
log.error("Unexpected error occurred while trying to delete the slot.", throwable);
}
}
log.info("SlotDeletingTask " + id + " has shutdown with " + slotsToDelete.size() + " slots to delete.");
}
/**
* Delete slot at coordinator and return delete status
*
* @param slot slot to be removed from cluster
* @return slot deletion status
*/
private boolean deleteSlotAtCoordinator(Slot slot) {
boolean deleteSuccess = false;
try {
deleteSuccess = MessagingEngine.getInstance().getSlotCoordinator().deleteSlot
(slot.getStorageQueueName(), slot);
} catch (ConnectionException e) {
log.error("Error while trying to delete the slot " + slot + " Thrift connection failed. " +
"Rescheduling delete.", e);
}
return deleteSuccess;
}
/**
* Schedule a slot for deletion. This will continuously try to delete the slot
* until slot manager informs that the slot is successfully removed
*
* @param slot slot to be removed from cluster
*/
public void scheduleToDelete(Slot slot) {
int currentNumberOfSlotsToDelete = slotsToDelete.size();
if (currentNumberOfSlotsToDelete > maxNumberOfPendingSlots) {
log.warn("Too many slots submitted to delete. Consider increasing <deleteTaskCount> "
+ "and <thriftClientPoolSize> parameters. Current submit value = "
+ currentNumberOfSlotsToDelete + " safe zone value = "
+ SlotMessageCounter.getInstance().getCurrentNodeSafeZoneId());
}
slotsToDelete.add(slot);
}
}
| 40.674699 | 112 | 0.601896 |
17ab5203c36d13599190d4a193d053e59c361a46 | 1,111 | package com.it.ymk.bubble.component.codetools.controller;
import org.durcframework.core.controller.CrudController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.it.ymk.bubble.component.codetools.entity.TemplateConfigEntity;
import com.it.ymk.bubble.component.codetools.service.TemplateConfigService;
@Controller
public class TemplateConfigController extends CrudController<TemplateConfigEntity, TemplateConfigService> {
@RequestMapping("/addTemplate.do")
public @ResponseBody
Object addTemplate(TemplateConfigEntity templateConfig) {
return this.save(templateConfig);
}
@RequestMapping("/updateTemplate.do")
public @ResponseBody
Object updateTemplate(TemplateConfigEntity templateConfig) {
return this.update(templateConfig);
}
@RequestMapping("/delTemplate.do")
public @ResponseBody
Object delTemplate(TemplateConfigEntity templateConfig) {
return this.delete(templateConfig);
}
}
| 34.71875 | 107 | 0.783078 |
c2faf1c0a311a1841ac38494bf10d474b7a802ad | 604 | package com.yourtion.leetcode.medium.c0024;
import com.yourtion.leetcode.utils.ListNode;
/**
* 24. 两两交换链表中的节点
*
* @author Yourtion
* @link https://leetcode-cn.com/problems/swap-nodes-in-pairs/
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
ListNode node = head;
while (node != null) {
if (node.next != null) {
int tmp = node.val;
node.val = node.next.val;
node.next.val = tmp;
node = node.next;
}
node = node.next;
}
return head;
}
}
| 23.230769 | 62 | 0.534768 |
f40eb774d154b53b76b86f7b5963584c1d94cae4 | 10,150 | package org.yarnandtail.andhow;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.*;
import org.yarnandtail.andhow.api.*;
import org.yarnandtail.andhow.export.SysPropExporter;
import org.yarnandtail.andhow.util.AndHowUtil;
import org.yarnandtail.andhow.internal.ConstructionProblem;
import org.yarnandtail.andhow.internal.NameAndProperty;
import org.yarnandtail.andhow.property.IntProp;
import org.yarnandtail.andhow.property.StrProp;
import org.yarnandtail.andhow.util.NameUtil;
/**
*
* @author ericeverman
*/
public class AndHow_AliasOutTest extends AndHowCoreTestBase {
//
//Alias names
static final String STR_PROP1_IN = "str.Prop.1.In";
static final String STR_PROP1_OUT_ALIAS = "strProp1Out";
static final String STR_PROP1_IN_AND_OUT_ALIAS = "StrProp1InAndOut";
static final String STR_PROP2_IN_ALIAS = "strProp2";
static final String STR_PROP2_OUT_ALIAS = "strProp2-out";
static final String INT_PROP1_ALIAS = "IntProp1";
static final String INT_PROP1_ALT_IN1_ALIAS = "Int.Prop.1-Alt-In!1";
//
//Property values
private static final String STR1 = "SOME_FIXED_VALUE_STRING_1";
private static final String STR2 = "SOME_FIXED_VALUE_STRING_2";
private static final Integer INT1 = 23572374;
private static final Integer INT2 = 9237347;
@GroupExport(
exporter=SysPropExporter.class,
exportByCanonicalName=Exporter.EXPORT_CANONICAL_NAME.ONLY_IF_NO_OUT_ALIAS,
exportByOutAliases=Exporter.EXPORT_OUT_ALIASES.ALWAYS
)
interface AliasGroup1 {
StrProp strProp1 = StrProp.builder().mustBeNonNull()
.aliasIn(STR_PROP1_IN).aliasOut(STR_PROP1_OUT_ALIAS).aliasInAndOut(STR_PROP1_IN_AND_OUT_ALIAS).build();
StrProp strProp2 = StrProp.builder()
.aliasIn(STR_PROP2_IN_ALIAS).build();
IntProp intProp1 = IntProp.builder()
.aliasIn(INT_PROP1_ALIAS).aliasInAndOut(INT_PROP1_ALIAS).aliasIn(INT_PROP1_ALT_IN1_ALIAS).build();
IntProp intProp2 = IntProp.builder().mustBeNonNull().defaultValue(INT2).build();
}
//Has dup alias for strProp1
interface AliasGroup4 {
StrProp strProp1 = StrProp.builder().mustBeNonNull().aliasOut(STR_PROP1_IN_AND_OUT_ALIAS).build();
}
interface AliasGroup5 {
StrProp strProp1 = StrProp.builder().aliasOut(STR_PROP1_OUT_ALIAS).build();
StrProp strProp2 = StrProp.builder().aliasOut(STR_PROP1_OUT_ALIAS).build(); //dup right here in the same group
}
interface AliasGroup6 {
StrProp strProp1 = StrProp.builder().aliasOut(STR_PROP1_OUT_ALIAS).build();
StrProp strProp2 = StrProp.builder().aliasOut(STR_PROP2_OUT_ALIAS).build();
}
interface AliasGroup7 {
StrProp strProp1 = StrProp.builder().aliasOut(STR_PROP1_OUT_ALIAS).build();
StrProp strProp2 = StrProp.builder().aliasOut(STR_PROP2_OUT_ALIAS).build();
}
@GroupExport(
exporter=SysPropExporter.class,
exportByCanonicalName=Exporter.EXPORT_CANONICAL_NAME.ONLY_IF_NO_OUT_ALIAS,
exportByOutAliases=Exporter.EXPORT_OUT_ALIASES.ALWAYS
)
interface AliasGroup2 {
StrProp strProp1 = StrProp.builder().mustBeNonNull().build();
StrProp strProp2 = StrProp.builder().build();
IntProp intProp1 = IntProp.builder().build();
IntProp intProp2 = IntProp.builder().mustBeNonNull().defaultValue(INT2).build();
}
@Test
public void testOutAliasForGroup1() {
AndHowConfiguration config = AndHowCoreTestConfig.instance()
.addCmdLineArg(STR_PROP1_IN, STR1)
.addCmdLineArg(STR_PROP2_IN_ALIAS, STR2)
.addCmdLineArg(INT_PROP1_ALIAS, INT1.toString())
.group(AliasGroup1.class);
AndHow.instance(config);
//This just tests the test...
assertEquals(STR1, AliasGroup1.strProp1.getValue());
assertEquals(STR2, AliasGroup1.strProp2.getValue());
assertEquals(INT1, AliasGroup1.intProp1.getValue());
assertEquals(INT2, AliasGroup1.intProp2.getValue()); //default should still come thru
//
//And now for something more interesting
//strProp1
assertEquals(STR1, System.getProperty(STR_PROP1_OUT_ALIAS));
assertEquals(STR1, System.getProperty(STR_PROP1_IN_AND_OUT_ALIAS));
assertNull(System.getProperty(STR_PROP1_IN));
assertNull(System.getProperty(AndHow.instance().getCanonicalName(AliasGroup1.strProp1)));
//strProp2
assertEquals(STR2, System.getProperty(AndHow.instance().getCanonicalName(AliasGroup1.strProp2)));
assertNull(System.getProperty(STR_PROP2_IN_ALIAS));
//intProp1
assertEquals(INT1.toString(), System.getProperty(INT_PROP1_ALIAS));
assertNull(System.getProperty(INT_PROP1_ALT_IN1_ALIAS));
assertNull(System.getProperty(AndHow.instance().getCanonicalName(AliasGroup1.intProp1)));
//intProp2
assertEquals(INT2.toString(), System.getProperty(AndHow.instance().getCanonicalName(AliasGroup1.intProp2)));
}
@Test
public void testOutAliasForGroup2() {
String grp2Name = AliasGroup2.class.getCanonicalName();
AndHowConfiguration config = AndHowCoreTestConfig.instance()
.addCmdLineArg(grp2Name + ".strProp1", STR1)
.addCmdLineArg(grp2Name + ".strProp2", STR2)
.addCmdLineArg(grp2Name + ".intProp1", INT1.toString())
.group(AliasGroup2.class);
AndHow.instance(config);
//
//No aliases - all canon names should be present
assertEquals(STR1, System.getProperty(AndHow.instance().getCanonicalName(AliasGroup2.strProp1)));
assertEquals(STR2, System.getProperty(AndHow.instance().getCanonicalName(AliasGroup2.strProp2)));
assertEquals(INT1.toString(), System.getProperty(AndHow.instance().getCanonicalName(AliasGroup2.intProp1)));
assertEquals(INT2.toString(), System.getProperty(AndHow.instance().getCanonicalName(AliasGroup2.intProp2)));
}
@Test
public void testOutAliasForGroup1and2() {
String grp2Name = AliasGroup2.class.getCanonicalName();
AndHowConfiguration config = AndHowCoreTestConfig.instance()
.group(AliasGroup1.class)
.group(AliasGroup2.class)
.addCmdLineArg(STR_PROP1_IN, STR1)
.addCmdLineArg(STR_PROP2_IN_ALIAS, STR2)
.addCmdLineArg(INT_PROP1_ALIAS, INT1.toString())
.addCmdLineArg(grp2Name + ".strProp1", STR1)
.addCmdLineArg(grp2Name + ".strProp2", STR2)
.addCmdLineArg(grp2Name + ".intProp1", INT1.toString());
AndHow.instance(config);
//
// Group 1
//strProp1
assertEquals(STR1, System.getProperty(STR_PROP1_OUT_ALIAS));
assertEquals(STR1, System.getProperty(STR_PROP1_IN_AND_OUT_ALIAS));
assertNull(System.getProperty(STR_PROP1_IN));
assertNull(System.getProperty(AndHow.instance().getCanonicalName(AliasGroup1.strProp1)));
//strProp2
assertEquals(STR2, System.getProperty(AndHow.instance().getCanonicalName(AliasGroup1.strProp2)));
assertNull(System.getProperty(STR_PROP2_IN_ALIAS));
//intProp1
assertEquals(INT1.toString(), System.getProperty(INT_PROP1_ALIAS));
assertNull(System.getProperty(INT_PROP1_ALT_IN1_ALIAS));
assertNull(System.getProperty(AndHow.instance().getCanonicalName(AliasGroup1.intProp1)));
//intProp2
assertEquals(INT2.toString(), System.getProperty(AndHow.instance().getCanonicalName(AliasGroup1.intProp2)));
//
//No aliases for group 2 - all canon names should be present
assertEquals(STR1, System.getProperty(AndHow.instance().getCanonicalName(AliasGroup2.strProp1)));
assertEquals(STR2, System.getProperty(AndHow.instance().getCanonicalName(AliasGroup2.strProp2)));
assertEquals(INT1.toString(), System.getProperty(AndHow.instance().getCanonicalName(AliasGroup2.intProp1)));
assertEquals(INT2.toString(), System.getProperty(AndHow.instance().getCanonicalName(AliasGroup2.intProp2)));
}
@Test
public void testSingleOutDuplicateOfGroup1InOutAlias() {
try {
AndHowConfiguration config = AndHowCoreTestConfig.instance()
.addCmdLineArg(STR_PROP1_IN, STR1) //minimal values set to ensure no missing value error
.addCmdLineArg(STR_PROP2_IN_ALIAS, STR2)
.addCmdLineArg(INT_PROP1_ALIAS, INT1.toString())
.group(AliasGroup1.class)
.group(AliasGroup4.class);
AndHow.instance(config);
fail("Should have thrown an exception");
} catch (AppFatalException e) {
List<ConstructionProblem> probs = e.getProblems().filter(ConstructionProblem.class);
assertEquals(1, probs.size());
assertTrue(probs.get(0) instanceof ConstructionProblem.NonUniqueNames);
ConstructionProblem.NonUniqueNames nun = (ConstructionProblem.NonUniqueNames)probs.get(0);
assertEquals(AliasGroup4.strProp1, nun.getBadPropertyCoord().getProperty());
assertEquals(AliasGroup4.class, nun.getBadPropertyCoord().getGroup());
assertEquals(STR_PROP1_IN_AND_OUT_ALIAS, nun.getConflictName());
}
}
@Test
public void testSingleOutDuplicateWithinASingleGroup() {
try {
AndHowConfiguration config = AndHowCoreTestConfig.instance()
.group(AliasGroup5.class);
AndHow.instance(config);
fail("Should have thrown an exception");
} catch (AppFatalException e) {
List<ConstructionProblem> probs = e.getProblems().filter(ConstructionProblem.class);
assertEquals(1, probs.size());
assertTrue(probs.get(0) instanceof ConstructionProblem.NonUniqueNames);
ConstructionProblem.NonUniqueNames nun = (ConstructionProblem.NonUniqueNames)probs.get(0);
assertEquals(AliasGroup5.strProp2, nun.getBadPropertyCoord().getProperty());
assertEquals(AliasGroup5.class, nun.getBadPropertyCoord().getGroup());
assertEquals(STR_PROP1_OUT_ALIAS, nun.getConflictName());
}
}
@Test
public void testTwoOutOutDuplicatesBetweenTwoGroups() {
try {
AndHowConfiguration config = AndHowCoreTestConfig.instance()
.group(AliasGroup6.class)
.group(AliasGroup7.class);
AndHow.instance(config);
fail("Should have thrown an exception");
} catch (AppFatalException e) {
List<ConstructionProblem> probs = e.getProblems().filter(ConstructionProblem.class);
assertEquals(2, probs.size());
assertTrue(probs.get(0) instanceof ConstructionProblem.NonUniqueNames);
ConstructionProblem.NonUniqueNames nun = (ConstructionProblem.NonUniqueNames)probs.get(0);
assertEquals(AliasGroup7.strProp1, nun.getBadPropertyCoord().getProperty());
assertEquals(AliasGroup7.class, nun.getBadPropertyCoord().getGroup());
assertEquals(STR_PROP1_OUT_ALIAS, nun.getConflictName());
}
}
}
| 36.642599 | 112 | 0.767783 |
f8d822f940228618969bd88abac88e90157c2d12 | 891 | package org.shapelogic.imageutil;
import ij.ImagePlus;
import ij.plugin.filter.PlugInFilter;
import ij.process.ImageProcessor;
/** Adapter from SLImageFilter to PlugInFilter.
*
* @author Sami Badawi
*
*/
public class PlugInFilterAdapter implements PlugInFilter {
protected ImageOperation _imageOperation;
public PlugInFilterAdapter(ImageOperation imageOperation){
_imageOperation = imageOperation;
}
@Override
public void run(ImageProcessor ip) {
_imageOperation.run();
}
/** Default is that if the input image is null show the about dialog. */
@Override
public int setup(String arg, ImagePlus imp) {
_imageOperation.setGuiWrapper(IJGui.INSTANCE);
if (imp == null)
return _imageOperation.setup(arg, null);
return _imageOperation.setup(arg, new IJImage(imp));
}
public ImageOperation getImageOperation() {
return _imageOperation;
}
}
| 23.447368 | 73 | 0.747475 |
e14ad0c73574b14b4dbccf50439f11523b8d4bc1 | 446 | package de.qaware.qav.test.generics;
import java.util.List;
/**
* @author QAware GmbH
*/
public class MyGenericsMethods {
public List<String> filterList(List<A> list) {
return null;
}
public List<String> f(List<List<B>> doubleList) {
return null;
}
public <V> V getX(List<V> list) {
return list.get(0);
}
public <U extends C> U getY(List<U> list) {
return list.get(0);
}
}
| 16.518519 | 53 | 0.585202 |
db8bd93c70bf272d4280ced53ed7b6f38527eaca | 2,149 | package it.sephiroth.android.library.floatingmenu;
/**
* Created by alessandro on 24/05/14.
*/
public class FloatingActionItem {
int id;
int resId;
int delay = 0;
int paddingTop = 0;
int paddingBottom = 0;
int paddingLeft = 0;
int paddingRight = 0;
int backgroundResId;
static public class Builder {
int id;
int resId = - 1;
int delay = 0;
int paddingTop = 0;
int paddingBottom = 0;
int paddingLeft = 0;
int paddingRight = 0;
int backgroundResId = 0;
/**
* @param id unique id to be used with the
* {@link it.sephiroth.android.library.floatingmenu.FloatingActionMenu.OnItemClickListener}
*/
public Builder(int id) {
this.id = id;
}
/**
* Assign a custom background resource
*/
public Builder withBackgroundResId(int resId) {
this.backgroundResId = resId;
return this;
}
/**
* Image drawable resource-id
* @param resId
* @return
*/
public Builder withResId(final int resId) {
this.resId = resId;
return this;
}
/**
* Show/Hide delay time
* @param delay
* @return
*/
public Builder withDelay(final int delay) {
this.delay = delay;
return this;
}
/**
* Image padding
* @param left
* @param top
* @param right
* @param bottom
* @return
*/
public Builder withPadding(int left, int top, int right, int bottom) {
this.paddingBottom = bottom;
this.paddingLeft = left;
this.paddingRight = right;
this.paddingTop = top;
return this;
}
/**
* Image padding, applied to all the padding directions
* @param padding
* @return
*/
public Builder withPadding(int padding) {
return withPadding(padding, padding, padding, padding);
}
public FloatingActionItem build() {
if (resId == - 1) throw new IllegalArgumentException("resId missing");
FloatingActionItem item = new FloatingActionItem();
item.id = id;
item.resId = resId;
item.delay = delay;
item.paddingBottom = paddingBottom;
item.paddingLeft = paddingLeft;
item.paddingRight = paddingRight;
item.paddingTop = paddingTop;
item.backgroundResId = backgroundResId;
return item;
}
}
}
| 21.068627 | 103 | 0.65705 |
30cdc1f7998e9928a8a50ade0b7ab6ea433a01c1 | 345 | package org.reasm.testhelpers;
import org.reasm.source.ParseError;
/**
* A dummy implementation of {@link ParseError}.
*
* @author Francis Gagné
*/
public final class DummyParseError extends ParseError {
/**
* Initializes a new DummyParseError.
*/
public DummyParseError() {
super("Dummy parse error");
}
}
| 17.25 | 55 | 0.663768 |
806cf3127e5722ae8985c7fe59475c72eb2578fc | 2,290 | /*
* 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.carbondata.processing.loading.parser.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.carbondata.processing.loading.complexobjects.ArrayObject;
import org.apache.commons.lang.ArrayUtils;
public class MapParserImpl extends ArrayParserImpl {
private String keyValueDelimiter;
public MapParserImpl(String delimiter, String nullFormat, String keyValueDelimiter) {
super(delimiter, nullFormat);
this.keyValueDelimiter = keyValueDelimiter;
}
//The Key for Map will always be a PRIMITIVE type so Set<Object> here will work fine
//The last occurance of the key, value pair will be added and all others will be overwritten
@Override
public ArrayObject parse(Object data) {
if (data != null) {
String value = data.toString();
if (!value.isEmpty() && !value.equals(nullFormat)) {
String[] split = pattern.split(value, -1);
if (ArrayUtils.isNotEmpty(split)) {
ArrayList<Object> array = new ArrayList<>();
Map<Object, String> map = new HashMap<>();
for (int i = 0; i < split.length; i++) {
Object currKey = split[i].split(keyValueDelimiter)[0];
map.put(currKey, split[i]);
}
for (Map.Entry<Object, String> entry : map.entrySet()) {
array.add(child.parse(entry.getValue()));
}
return new ArrayObject(array.toArray());
}
}
}
return null;
}
}
| 36.935484 | 94 | 0.69476 |
10185747d538de54181f663de6976d19de28d8b7 | 2,177 | /*
* This file is part of the L2JServer project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.l2jserver.gameserver.cache;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import org.l2jserver.Config;
import org.l2jserver.commons.concurrent.ThreadPool;
import org.l2jserver.gameserver.model.actor.instance.PlayerInstance;
/**
* @author -Nemesiss-
*/
public class WarehouseCacheManager
{
protected final Map<PlayerInstance, Long> _cachedWh;
protected final long _cacheTime;
private WarehouseCacheManager()
{
_cacheTime = Config.WAREHOUSE_CACHE_TIME * 60000; // 60*1000 = 60000
_cachedWh = new ConcurrentHashMap<>();
ThreadPool.scheduleAtFixedRate(new CacheScheduler(), 120000, 60000);
}
public void addCacheTask(PlayerInstance pc)
{
_cachedWh.put(pc, System.currentTimeMillis());
}
public void remCacheTask(PlayerInstance pc)
{
_cachedWh.remove(pc);
}
public class CacheScheduler implements Runnable
{
@Override
public void run()
{
final long cTime = System.currentTimeMillis();
for (Entry<PlayerInstance, Long> entry : _cachedWh.entrySet())
{
if ((cTime - entry.getValue()) > _cacheTime)
{
final PlayerInstance player = entry.getKey();
player.clearWarehouse();
_cachedWh.remove(player);
}
}
}
}
public static WarehouseCacheManager getInstance()
{
return SingletonHolder.INSTANCE;
}
private static class SingletonHolder
{
protected static final WarehouseCacheManager INSTANCE = new WarehouseCacheManager();
}
}
| 27.2125 | 86 | 0.740928 |
36c52c125b585b21863b47985aba82d3e9688f39 | 154 | import java.awt.Graphics;
public interface Drawable {
//einheitliche methode zum zeichnen eines objektes
public void drawObjects(Graphics g);
}
| 19.25 | 54 | 0.75974 |
476499ae45d9631052aee665c133c2a1ae5fac2b | 280 | package com.example.sproject.dao.sample;
import java.util.List;
import com.example.sproject.model.sample.Sample;
public interface SampleDao {
List<Sample> selectSample();
int insertSample(Sample sample);
void insertFinalTest(String name, String password, String message);
}
| 23.333333 | 68 | 0.792857 |
0fc3711cf5d9df2f530561f66470ec28ebb63c60 | 7,134 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.puntodeventa.global.printservice;
import com.puntodeventa.global.Entity.Venta;
import com.puntodeventa.global.Enum.PrintType;
import com.puntodeventa.global.Util.LogHelper;
import com.puntodeventa.global.report.viewer.ReportGenerator;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.PrintQuality;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.views.DocumentViewController;
import org.icepdf.ri.common.PrintHelper;
import org.icepdf.ri.common.SwingController;
import org.icepdf.ri.common.views.DocumentViewControllerImpl;
/**
*
* @author Nato
*/
public class POSPrintService {
private static final LogHelper objLog = new LogHelper("POSPrintService");
/*
* Imprime archivo en la impresora predeterminada del equipo
*/
public static void impresion() {
// tu archivo a imprimir
String file = "c:\\anadirUsuario.gif";
// definimos el tipo a imprimir
DocFlavor docFlavor = DocFlavor.INPUT_STREAM.GIF;
// establecemos algunos atributos de la impresora
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(MediaSizeName.ISO_A4);
aset.add(new Copies(1));
// mi impresora por default
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
Doc docPrint;
try {
docPrint = new SimpleDoc(new FileInputStream(file), docFlavor, null);
} catch (FileNotFoundException e) {
objLog.Log(e.getMessage());
return;
}
// inicio el proceso de impresion...
DocPrintJob printJob = service.createPrintJob();
try {
printJob.print(docPrint, aset);
} catch (PrintException e) {
objLog.Log(e.getMessage());
}
}
/*
* @Params type Indica el tipo de proceso que realiza: ventas, Corte para saber en qye directorio indicar
* @Params if_folio indicara el nombre del Reporte a generar en disco
*/
public static void printICEPdf(PrintType type, String id_folio) throws PDFSecurityException {
try {
String file = "";
if (type == PrintType.VENTA) {
file = "D:\\vPuntoVenta/ventas/" + id_folio + ".pdf";
//file = ParamHelper.getParam("tickets.path.location").toString().replace("_ticketNumber_", id_folio);
} else if (type == PrintType.CORTE) {
//file = ParamHelper.getParam("cashout.path.location").toString().replace("_folio_", id_folio);
file = "D:\\vPuntoVenta/Corte/" + id_folio + ".pdf";
}
Document pdf = new Document() {
};
pdf.setFile(file);
SwingController sc = new SwingController();
DocumentViewController vc = new DocumentViewControllerImpl(sc);
vc.setDocument(pdf);
// create a new print helper with a specified paper size and print
// quality
PrintHelper printHelper = new PrintHelper(vc, pdf.getPageTree(),
MediaSizeName.NA_LEGAL, PrintQuality.DRAFT);
// try and print pages 1 - 10, 1 copy, scale to fit paper.
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
//printHelper.setupPrintService(defaultService, 0, 9, 1, true);
printHelper.setupPrintService(defaultService, 0, 0, 1, true);
// print the document
printHelper.print();
} catch (PrintException ex) {
System.out.println("1: " + ex.getMessage());
} catch (org.icepdf.core.exceptions.PDFException ex) {
System.out.println("2: " + ex.getMessage());
} catch (PDFSecurityException ex) {
System.out.println("3: " + ex.getMessage());
} catch (IOException ex) {
System.out.println("4: " + ex.getMessage());
}
}
public static void printTicket(Venta venta) throws PDFSecurityException {
ReportGenerator repGenerator = new ReportGenerator();
byte[] pdfBuffer = null;
try {
pdfBuffer = repGenerator.generateTicketBuffer(venta);
Document pdf = new Document() {};
pdf.setByteArray(pdfBuffer, 0, pdfBuffer.length, null);
DocumentViewController vc = new DocumentViewControllerImpl(new SwingController());
vc.setDocument(pdf);
// create a new print helper with a specified paper size and print quality
PrintHelper printHelper = new PrintHelper(vc, pdf.getPageTree(), MediaSizeName.NA_LEGAL, PrintQuality.DRAFT);
//printHelper.setupPrintService(defaultService, 0, 9, 1, true);
printHelper.setupPrintService(PrintServiceLookup.lookupDefaultPrintService(), 0, 0, 1, true);
// print the document
printHelper.print();
} catch (PrintException ex) {
System.out.println("1: " + ex.getMessage());
} catch (org.icepdf.core.exceptions.PDFException ex) {
System.out.println("2: " + ex.getMessage());
} catch (PDFSecurityException ex) {
System.out.println("3: " + ex.getMessage());
} catch (IOException ex) {
System.out.println("4: " + ex.getMessage());
}
}
public static void printArrayPdf(byte[] pdfBuffer) throws PDFSecurityException {
try {
Document pdf = new Document() {};
pdf.setByteArray(pdfBuffer, 0, pdfBuffer.length, null);
DocumentViewController vc = new DocumentViewControllerImpl(new SwingController());
vc.setDocument(pdf);
// create a new print helper with a specified paper size and print quality
PrintHelper printHelper = new PrintHelper(vc, pdf.getPageTree(), MediaSizeName.NA_LEGAL, PrintQuality.DRAFT);
//printHelper.setupPrintService(defaultService, 0, 9, 1, true);
printHelper.setupPrintService(PrintServiceLookup.lookupDefaultPrintService(), 0, 0, 1, true);
// print the document
printHelper.print();
} catch (PrintException ex) {
System.out.println("1: " + ex.getMessage());
} catch (org.icepdf.core.exceptions.PDFException ex) {
System.out.println("2: " + ex.getMessage());
} catch (PDFSecurityException ex) {
System.out.println("3: " + ex.getMessage());
} catch (IOException ex) {
System.out.println("4: " + ex.getMessage());
}
}
}
| 39.633333 | 121 | 0.629521 |
c6c84e1b606e0999600e0022bcc8e00fa87aa438 | 1,047 | package com.c8y.ms.templates.agent.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.c8y.ms.templates.agent.service.MicroserviceConfigurationService;
@RestController
@RequestMapping("/api")
public class ConfigRESTController {
private MicroserviceConfigurationService microserviceConfigurationService;
public ConfigRESTController(MicroserviceConfigurationService microserviceConfigurationService) {
this.microserviceConfigurationService = microserviceConfigurationService;
}
@GetMapping(path = "/config/{key:.+}", produces = MediaType.APPLICATION_JSON_VALUE)
public String greeting(@PathVariable String key) {
return microserviceConfigurationService.getPropertyValue(key);
}
}
| 38.777778 | 100 | 0.82426 |
124943c3a3bd5a0d15a05de9615724b3c373e5a9 | 268 | package com.pispower.video.sdk.advertising.request;
public class AdvertisingGetRequest {
private String id;
public AdvertisingGetRequest(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
} | 15.764706 | 51 | 0.708955 |
c5185f38cf67b0d26ac0420acb87e4bbcd4e4f4b | 2,256 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.camera.data;
import android.media.MediaMetadataRetriever;
import com.android.camera.debug.Log;
public class VideoRotationMetadataLoader {
private static final Log.Tag TAG = new Log.Tag("VidRotDataLoader");
private static final String ROTATE_90 = "90";
private static final String ROTATE_270 = "270";
static boolean isRotated(FilmstripItem filmstripItem) {
final String rotation = filmstripItem.getMetadata().getVideoOrientation();
return ROTATE_90.equals(rotation) || ROTATE_270.equals(rotation);
}
static boolean loadRotationMetadata(final FilmstripItem data) {
final String path = data.getData().getFilePath();
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setDataSource(path);
data.getMetadata().setVideoOrientation(retriever.extractMetadata(
MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION));
String val = retriever.extractMetadata(
MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
data.getMetadata().setVideoWidth(Integer.parseInt(val));
val = retriever.extractMetadata(
MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
data.getMetadata().setVideoHeight(Integer.parseInt(val));
} catch (RuntimeException ex) {
// setDataSource() can cause RuntimeException beyond
// IllegalArgumentException. e.g: data contain *.avi file.
Log.e(TAG, "MediaMetdataRetriever.setDataSource() fail", ex);
}
return true;
}
}
| 38.237288 | 82 | 0.698582 |
9895d78579892a84653bc3bbc62a3ed45628b78f | 15,082 | /*
Copyright 2011-2013 Frederic Langlet
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 kanzi.util.sampling;
public class ICBIUpSampler implements UpSampler
{
private final int width;
private final int height;
private final int stride;
private final int offset;
public ICBIUpSampler(int width, int height)
{
this(width, height, width, 0);
}
public ICBIUpSampler(int width, int height, int stride, int offset)
{
if (height < 8)
throw new IllegalArgumentException("The height must be at least 8");
if (width < 8)
throw new IllegalArgumentException("The width must be at least 8");
if (offset < 0)
throw new IllegalArgumentException("The offset must be at least 0");
if (stride < width)
throw new IllegalArgumentException("The stride must be at least as big as the width");
if ((height & 7) != 0)
throw new IllegalArgumentException("The height must be a multiple of 8");
if ((width & 7) != 0)
throw new IllegalArgumentException("The width must be a multiple of 8");
this.height = height;
this.width = width;
this.stride = stride;
this.offset = offset;
}
@Override
// Supports in place resampling
public void superSampleVertical(int[] input, int[] output)
{
this.superSampleVertical(input, output, this.width, this.height, this.stride);
}
private void superSampleVertical(int[] input, int[] output, int sw, int sh, int st)
{
final int st2 = st + st;
final int dw = sw;
final int dh = sh * 2;
int iOffs = st * (sh - 1) + this.offset;
int oOffs = dw * (dh - 1);
// Rows h-1, h-2, h-3
System.arraycopy(input, iOffs, output, oOffs, sw);
oOffs -= dw;
System.arraycopy(input, iOffs, output, oOffs, sw);
oOffs -= dw;
iOffs -= st;
for (int i=0; i<sw; i++)
output[oOffs+i] = (input[iOffs+i] + input[iOffs+st+i]) >> 1;
oOffs -= dw;
for (int j=sh-3; j>0; j--)
{
// Copy
System.arraycopy(input, iOffs, output, oOffs, sw);
oOffs -= dw;
iOffs -= st;
// Interpolate
for (int i=0; i<sw; i++)
{
final int p0 = input[iOffs+i-st];
final int p1 = input[iOffs+i];
final int p2 = input[iOffs+i+st];
final int p3 = input[iOffs+i+st2];
//output[oOffs+i] = (int) (p1 + 0.5 * x*(p2 - p0 + x*(2.0*p0 - 5.0*p1 + 4.0*p2 - p3 + x*(3.0*(p1 - p2) + p3 - p0))));
final int val = (p1<<4) + (p2<<2) - (p1<<3) - (p1<<1) + (p2<<3) - (p3<<1) +
((p1<<1) + p1 - (p2<<1) - p2 + p3 - p0);
output[oOffs+i] = (val < 0) ? 0 : ((val >= 4087) ? 255 : (val+8)>>4);
}
oOffs -= dw;
}
// Rows 1, 2, 3
for (int i=0; i<sw; i++)
output[oOffs+i] = (input[iOffs+st+i] + input[iOffs+i]) >> 1;
oOffs -= dw;
System.arraycopy(input, iOffs, output, oOffs, sw);
oOffs -= dw;
System.arraycopy(input, iOffs, output, oOffs, sw);
}
@Override
// Supports in place resampling
public void superSampleHorizontal(int[] input, int[] output)
{
this.superSampleHorizontal(input, output, this.width, this.height, this.stride);
}
private void superSampleHorizontal(int[] input, int[] output, int sw, int sh, int st)
{
final int dw = sw * 2;
final int dh = sh;
int iOffs = st * (sh - 1) + this.offset;
int oOffs = dw * (dh - 1);
for (int j=sh-1; j>=0; j--)
{
// Columns w-1, w-2, w-3
int val = input[iOffs+sw-1];
output[oOffs+dw-1] = val;
output[oOffs+dw-2] = val;
output[oOffs+dw-3] = (val+input[iOffs+sw-2]) >> 1;
for (int i=sw-3; i>0; i--)
{
final int idx = oOffs + (i << 1);
final int p0 = input[iOffs+i-1];
final int p1 = input[iOffs+i];
final int p2 = input[iOffs+i+1];
final int p3 = input[iOffs+i+2];
// Copy
output[idx+2] = p2;
// Interpolate
//output[idx+1] = (int) (p1 + 0.5 * x*(p2 - p0 + x*(2.0*p0 - 5.0*p1 + 4.0*p2 - p3 + x*(3.0*(p1 - p2) + p3 - p0))));
val = (p1<<4) + (p2<<2) - (p1<<3) - (p1<<1) + (p2<<3) - (p3<<1) +
((p1<<1) + p1 - (p2<<1) - p2 + p3 - p0);
output[idx+1] = (val < 0) ? 0 : ((val >= 4087) ? 255 : (val+8)>>4);
}
// Columns 1, 2, 3
val = input[iOffs];
output[oOffs+2] = (val + input[iOffs+1]) >> 1;
output[oOffs+1] = val;
output[oOffs] = val;
iOffs -= st;
oOffs -= dw;
}
}
// p00 o p10 o p20 o p30 o
// o o o o o o o o
// p01 o p11 o p21 o p31 o
// o o o x o o o o
// p02 o p12 o p22 o p32 o
// o o o o o o o o
// p03 o p13 o p23 o p33 o
// o o o o o o o o
@Override
public void superSample(int[] input, int[] output)
{
// Positions (2x, 2y) and (2x+1, 2y+1)
this.superSampleStep1(input, output);
// Positions (2x+1, 2y) and (2x, 2y+1)
/// this.superSampleStep2(output, output);
}
private void superSampleStep1(int[] input, int[] output)
{
final int sw = this.width;
final int sh = this.height;
final int st = this.stride;
final int dw = sw + sw;
final int dw2 = dw + dw;
final int dh = sh + sh;
int iOffs = st * (sh - 3) + this.offset;
int oOffs = dw * (dh - 3);
// Last 3 rows, only horizontal interpolation
for (int i=sw-1; i>=0; i--)
{
final int valA = input[iOffs+i];
final int valB = (i == sw-1) ? valA : input[iOffs+i+1];
final int valAB = (valA + valB) >> 1;
int k = oOffs + (i << 1);
output[k] = valA;
output[k+1] = valAB;
k += dw;
output[k] = valA;
output[k+1] = valAB;
}
int last = input[iOffs+sw-1];
output[oOffs+dw-1] = last;
output[oOffs+dw-2] = last;
output[oOffs+dw-3] = (last+input[iOffs+sw-2]) >> 1;
//
//
// iOffs -= st;
// oOffs -= dw;
// Step 1
for (int j=sh-3; j>0; j--)
{
final int iOffs0 = iOffs - st;
final int iOffs1 = iOffs0 + st;
final int iOffs2 = iOffs1 + st;
final int iOffs3 = iOffs2 + st;
int p10 = input[iOffs0+sw-3];
int p20 = input[iOffs0+sw-2];
int p30 = input[iOffs0+sw-1];
int p11 = input[iOffs1+sw-3];
int p21 = input[iOffs1+sw-2];
int p31 = input[iOffs1+sw-1];
int p12 = input[iOffs2+sw-3];
int p22 = input[iOffs2+sw-2];
int p32 = input[iOffs2+sw-1];
int p13 = input[iOffs3+sw-3];
int p23 = input[iOffs3+sw-2];
int p33 = input[iOffs3+sw-1];
// Columns w-1, w-2, w-3, w-4
output[oOffs-dw+dw-1] = p30;
output[oOffs-dw+dw-2] = p30;
output[oOffs-dw+dw-3] = (p30+p20) >> 1;
output[oOffs-dw+dw-4] = p20;
output[oOffs+dw-1] = p31;
output[oOffs+dw-2] = p31;
output[oOffs+dw-3] = (p31+p21) >> 1;
output[oOffs+dw-4] = p21;
output[oOffs+dw+dw-1] = p32;
output[oOffs+dw+dw-2] = p32;
output[oOffs+dw+dw-3] = (p32+p22) >> 1;
output[oOffs+dw+dw-4] = p22;
output[oOffs+dw2+dw-1] = p33;
output[oOffs+dw2+dw-2] = p33;
output[oOffs+dw2+dw-3] = (p33+p23) >> 1;
output[oOffs+dw2+dw-4] = p23;
for (int i=sw-4; i>0; i--)
{
final int idx = oOffs + (i << 1);
final int p00 = input[iOffs0+i];
final int p01 = input[iOffs1+i];
final int p02 = input[iOffs2+i];
final int p03 = input[iOffs3+i];
final int valD1 = (p02 + p11 + p20) - 3*(p12 + p21) + (p13 + p22 + p31);
final int valD2 = (p10 + p21 + p32) - 3*(p11 + p22) + (p01 + p12 + p23);
final int valD = (valD1 > valD2) ? (p11 + p22) >> 1 : (p12 + p21) >> 1;
output[idx-dw+2] = p11;
// a
output[idx-dw+3] = p11 + (((p21<<2) - (p01<<2) + ((p01<<2) - (p11<<3) - (p11<<1) +
(p21<<3) - (p31<<1) + ((p11<<1) + p11 - (p21<<1) - p21 + p31 - p01)) + 8) >> 4);
//output[idx-dw+3] = (p11+p21)/2;
// b
output[idx+2] = p11 + (((p12<<2) - (p10<<2) + ((p10<<2) - (p11<<3) - (p11<<1) +
(p12<<3) - (p13<<1) + ((p11<<1) + p11 - (p12<<1) - p12 + p13 - p10)) + 8) >> 4);
//output[idx+2] =(p11+p12)/2;
// c
output[idx+3] = valD;
// Slide window
p30 = p20; p20 = p10; p10 = p00;
p31 = p21; p21 = p11; p11 = p01;
p32 = p22; p22 = p12; p12 = p02;
p33 = p23; p23 = p13; p13 = p03;
}
// Columns 1, 2, 3
// int val = input[iOffs];
// output[oOffs+st+2] = (val + input[iOffs+1]) >> 1;
// output[oOffs+st+1] = val;
// output[oOffs+st] = val;
// output[oOffs+2] = (val + input[iOffs+1]) >> 1;
// output[oOffs+1] = val;
// output[oOffs] = val;
iOffs -= st;
oOffs -= dw;
oOffs -= dw;
}
}
private void superSampleStep2(int[] input, int[] output)
{
final int sw = this.width;
final int sh = this.height;
final int st = this.stride;
final int dw = sw + sw;
final int dw2 = dw + dw;
final int dh = sh + sh;
int iOffs = st * (sh - 3) + this.offset;
int oOffs = dw * (dh - 3);
// Last 3 rows, only horizontal interpolation
for (int i=sw-1; i>=0; i--)
{
final int valA = input[iOffs+i];
final int valB = (i == sw-1) ? valA : input[iOffs+i+1];
final int valAB = (valA + valB) >> 1;
int k = oOffs + (i << 1);
output[k] = valA;
output[k+1] = valAB;
k += dw;
output[k] = valA;
output[k+1] = valAB;
}
int last = input[iOffs+sw-1];
output[oOffs+dw-1] = last;
output[oOffs+dw-2] = last;
output[oOffs+dw-3] = (last+input[iOffs+sw-2]) >> 1;
//
//
// iOffs -= st;
// oOffs -= dw;
// Step 1
for (int j=sh-3; j>0; j--)
{
final int iOffs0 = iOffs - st;
final int iOffs1 = iOffs0 + st;
final int iOffs2 = iOffs1 + st;
final int iOffs3 = iOffs2 + st;
int p10 = input[iOffs0+sw-3];
int p20 = input[iOffs0+sw-2];
int p30 = input[iOffs0+sw-1];
int p11 = input[iOffs1+sw-3];
int p21 = input[iOffs1+sw-2];
int p31 = input[iOffs1+sw-1];
int p12 = input[iOffs2+sw-3];
int p22 = input[iOffs2+sw-2];
int p32 = input[iOffs2+sw-1];
int p13 = input[iOffs3+sw-3];
int p23 = input[iOffs3+sw-2];
int p33 = input[iOffs3+sw-1];
// Columns w-1, w-2, w-3, w-4
output[oOffs-dw+dw-1] = p30;
output[oOffs-dw+dw-2] = p30;
output[oOffs-dw+dw-3] = (p30+p20) >> 1;
output[oOffs-dw+dw-4] = p20;
output[oOffs+dw-1] = p31;
output[oOffs+dw-2] = p31;
output[oOffs+dw-3] = (p31+p21) >> 1;
output[oOffs+dw-4] = p21;
output[oOffs+dw+dw-1] = p32;
output[oOffs+dw+dw-2] = p32;
output[oOffs+dw+dw-3] = (p32+p22) >> 1;
output[oOffs+dw+dw-4] = p22;
output[oOffs+dw2+dw-1] = p33;
output[oOffs+dw2+dw-2] = p33;
output[oOffs+dw2+dw-3] = (p33+p23) >> 1;
output[oOffs+dw2+dw-4] = p23;
for (int i=sw-4; i>0; i--)
{
final int idx = oOffs + (i << 1);
final int p00 = input[iOffs0+i];
final int p01 = input[iOffs1+i];
final int p02 = input[iOffs2+i];
final int p03 = input[iOffs3+i];
final int valD1 = (p02 + p11 + p20) - 3*(p12 + p21) + (p13 + p22 + p31);
final int valD2 = (p10 + p21 + p32) - 3*(p11 + p22) + (p01 + p12 + p23);
final int valD = (valD1 > valD2) ? (p11 + p22) >> 1 : (p12 + p21) >> 1;
output[idx-dw+2] = p11;
// a
output[idx-dw+3] = p11 + (((p21<<2) - (p01<<2) + ((p01<<2) - (p11<<3) - (p11<<1) +
(p21<<3) - (p31<<1) + ((p11<<1) + p11 - (p21<<1) - p21 + p31 - p01)) + 8) >> 4);
//output[idx-dw+3] = (p11+p21)/2;
// b
output[idx+2] = p11 + (((p12<<2) - (p10<<2) + ((p10<<2) - (p11<<3) - (p11<<1) +
(p12<<3) - (p13<<1) + ((p11<<1) + p11 - (p12<<1) - p12 + p13 - p10)) + 8) >> 4);
//output[idx+2] =(p11+p12)/2;
// c
output[idx+3] = valD;
// Slide window
p30 = p20; p20 = p10; p10 = p00;
p31 = p21; p21 = p11; p11 = p01;
p32 = p22; p22 = p12; p12 = p02;
p33 = p23; p23 = p13; p13 = p03;
}
// Columns 1, 2, 3
// int val = input[iOffs];
// output[oOffs+st+2] = (val + input[iOffs+1]) >> 1;
// output[oOffs+st+1] = val;
// output[oOffs+st] = val;
// output[oOffs+2] = (val + input[iOffs+1]) >> 1;
// output[oOffs+1] = val;
// output[oOffs] = val;
iOffs -= st;
oOffs -= dw;
oOffs -= dw;
}
}
@Override
public boolean supportsScalingFactor(int factor)
{
return (factor == 2);
}
} | 34.512586 | 129 | 0.449675 |
9e618d7b89eb6f2b1bd4b47c47c8908f56795fb2 | 7,003 | package com.example.asus.tastenews.news.adapter;
import android.content.Context;
import android.content.res.Resources;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.asus.tastenews.R;
import com.example.asus.tastenews.beans.NewsBean;
import com.example.asus.tastenews.utils.ImageLoaderUtils;
import com.example.asus.tastenews.utils.LogUtils;
import java.util.HashMap;
import java.util.List;
/**
* Created by SomeOneInTheWorld on 2016/5/26.
*/
public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private final String TAG = "NewsTestAdapter";
private static final int TYPE_ITEM = 0;
private static final int TYPE_FOOTER = 1;
private List<NewsBean> mData;
private HashMap<String,TypedValue> mThemes;
private boolean mShowFooter = true;
private Context mContext;
private int mode;
private OnItemClickListener mOnItemClickListener;
public interface OnItemClickListener{
void onItemClick(View view,int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.mOnItemClickListener = listener;
}
public NewsAdapter(Context context){
mContext = context;
}
public void setDatas(List<NewsBean>data){
mData = data;
notifyDataSetChanged();
}
public void setThemes(HashMap<String,TypedValue>themes){
LogUtils.d(TAG,"setThemes()");
// LogUtils.d(TAG,"themes is " + themes.get(MainActivity.THEME_BACKGROUND));
if(mThemes == null){
mThemes = themes;
notifyDataSetChanged();
return;
}
mThemes.clear();
mThemes.putAll(themes);
notifyDataSetChanged();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType){
LogUtils.d(TAG,"onCreateViewHolder()");
// mode = ((NewsApplication)(((Activity)mContext).getApplication())).getMode();
// final Context contextThemeWrapper = new ContextThemeWrapper(mContext,mode);
// LayoutInflater localInflater = LayoutInflater.from(mContext).cloneInContext(contextThemeWrapper);
if(viewType == TYPE_ITEM){
View v = LayoutInflater.from(mContext).inflate(R.layout.item_news,null);
ItemViewHolder ivh = new ItemViewHolder(v);
return ivh;
}else{
View v = LayoutInflater.from(mContext).inflate(R.layout.footer,null);
v.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
FooterViewHolder fvh = new FooterViewHolder(v);
return fvh;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder,int position){
LogUtils.d(TAG,"onBindViewHolder()");
if(holder instanceof ItemViewHolder){
NewsBean news = mData.get(position);
if(news == null){
return;
}
((ItemViewHolder)holder).mTitle.setText(news.getTitle());
((ItemViewHolder)holder).mDesc.setText(news.getDigest());
if(news.getImgsrc() == null){
((ItemViewHolder)holder).mNewsImg.setImageResource(R.mipmap.ic_image_white_24dp);
}else{
ImageLoaderUtils.display(mContext,((ItemViewHolder)holder).mNewsImg,news.getImgsrc());
}
if(mThemes == null || mThemes.size() == 0){
LogUtils.d(TAG,"theme is null is null is null is null");
return;
}
//换肤功能:
//这里不能直接使用resouceId去调用函数,而是要resources.getColor()再去调用函数,
//不然就会出现没法更换主题的情况
// Resources resources = mContext.getResources();
// ((ItemViewHolder)holder).mTitle.setTextColor(resources.getColor(mThemes.get(MainActivity.THEME_TEXT).resourceId));
// ((ItemViewHolder)holder).mDesc.setTextColor(resources.getColor(mThemes.get(MainActivity.THEME_TEXT_SECOND).resourceId));
// ((ItemViewHolder)holder).mCardView.setBackgroundResource(mThemes.get(MainActivity.THEME_BACKGROUND).resourceId);
}
}
@Override
public int getItemCount(){
LogUtils.d(TAG,"getItemCount()");
int begin = mShowFooter ? 1 : 0;
if(mData == null){
return begin;
}
return mData.size() + begin;
}
public NewsBean getItem(int position){
return mData == null ? null : mData.get(position);
}
public void isShowFooter(boolean showFooter){
mShowFooter = showFooter;
}
public boolean isShowFooter(){
return mShowFooter;
}
@Override
public int getItemViewType(int position){
LogUtils.d(TAG,"getItemViewType()");
if(!mShowFooter){
return TYPE_ITEM;
}
if(position + 1 == getItemCount()){
return TYPE_FOOTER;
}else{
return TYPE_ITEM;
}
}
public class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTitle;
public TextView mDesc;
public ImageView mNewsImg;
public CardView mCardView;
public ItemViewHolder(View v){
super(v);
mTitle = (TextView)v.findViewById(R.id.tvTitle);
mDesc = (TextView)v.findViewById(R.id.tvDesc);
mNewsImg = (ImageView)v.findViewById(R.id.ivNews);
mCardView = (CardView)v.findViewById(R.id.cardView);
// initItemLayout();
v.setOnClickListener(this);
}
private void initItemLayout() {
TypedValue backgroundColor = new TypedValue();
TypedValue textColor = new TypedValue();
TypedValue textPrimaryColor = new TypedValue();
Resources.Theme theme = mContext.getTheme();
theme.resolveAttribute(R.attr.colorBackground, backgroundColor, true);
theme.resolveAttribute(R.attr.colorText, textColor, true);
theme.resolveAttribute(R.attr.colorTextPrimary, textPrimaryColor, true);
mCardView.setBackgroundResource(backgroundColor.resourceId);
mTitle.setTextColor(mContext.getResources().getColor(textColor.resourceId));
mDesc.setTextColor(mContext.getResources().getColor(textPrimaryColor.resourceId));
}
@Override
public void onClick(View v){
if(mOnItemClickListener != null){
mOnItemClickListener.onItemClick(v,this.getPosition());
}
}
}
public class FooterViewHolder extends RecyclerView.ViewHolder {
public FooterViewHolder(View view){
super(view);
}
}
}
| 34.668317 | 134 | 0.646723 |
2b2e38b4890d514271f471058aa2c0eafacdfabf | 2,479 | /*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2003-2005 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.detect;
import org.apache.bcel.Const;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.StatelessDetector;
public class FindFloatMath extends BytecodeScanningDetector implements StatelessDetector {
private final BugReporter bugReporter;
public FindFloatMath(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
@Override
public void sawOpcode(int seen) {
switch (seen) {
case Const.FMUL:
case Const.FDIV:
if (getFullyQualifiedMethodName().indexOf("float") == -1 && getFullyQualifiedMethodName().indexOf("Float") == -1
&& getFullyQualifiedMethodName().indexOf("FLOAT") == -1) {
bugReporter.reportBug(new BugInstance(this, "FL_MATH_USING_FLOAT_PRECISION", LOW_PRIORITY)
.addClassAndMethod(this).addSourceLine(this));
}
break;
case Const.FCMPG:
case Const.FCMPL:
break;
case Const.FADD:
case Const.FSUB:
case Const.FREM:
if (getFullyQualifiedMethodName().indexOf("float") == -1 && getFullyQualifiedMethodName().indexOf("Float") == -1
&& getFullyQualifiedMethodName().indexOf("FLOAT") == -1) {
bugReporter.reportBug(new BugInstance(this, "FL_MATH_USING_FLOAT_PRECISION", NORMAL_PRIORITY).addClassAndMethod(
this).addSourceLine(this));
}
break;
default:
break;
}
}
}
| 38.734375 | 128 | 0.668415 |
91eed46dbc28a0cb600a38efbcc1c7cd195f63ac | 5,028 | /* Copyright (c) 2011 Peter Troshin
*
* JAva Bioinformatics Analysis Web Services (JABAWS) @version: 2.0
*
* This library is free software; you can redistribute it and/or modify it under the terms of the
* Apache License version 2 as published by the Apache Software Foundation
*
* 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 Apache
* License for more details.
*
* A copy of the license is in apache_license.txt. It is also available here:
* @see: http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Any republication or derived work distributed in source code form
* must include this copyright and license notice.
*/
package compbio.stat.servlet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;
import compbio.engine.conf.PropertyHelperManager;
import compbio.stat.collector.ExecutionStatCollector;
import compbio.stat.collector.StatDB;
import compbio.util.PropertyHelper;
import compbio.util.Util;
public class StatisticCollector implements ServletContextListener {
static PropertyHelper ph = PropertyHelperManager.getPropertyHelper();
private final Logger log = Logger.getLogger(StatisticCollector.class);
private ScheduledFuture<?> localcf;
private ScheduledFuture<?> clustercf;
private ScheduledExecutorService executor;
@Override
public void contextDestroyed(ServletContextEvent arg0) {
try {
if (localcf != null) {
localcf.cancel(true);
}
if (clustercf != null) {
clustercf.cancel(true);
}
executor.shutdown();
executor.awaitTermination(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.warn(e.getMessage(), e);
} finally {
StatDB.shutdownDBServer();
executor.shutdownNow();
}
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
String clusterWorkDir = getClusterJobDir();
int clusterMaxRuntime = getClusterJobTimeOut();
int localMaxRuntime = getLocalJobTimeOut();
String localWorkDir = compbio.engine.client.Util
.convertToAbsolute(getLocalJobDir());
log.info("Initializing statistics collector");
executor = Executors.newScheduledThreadPool(2);
if (collectClusterStats()) {
ExecutionStatCollector clusterCollector = new ExecutionStatCollector(
clusterWorkDir, clusterMaxRuntime);
clustercf = executor.scheduleAtFixedRate(clusterCollector, 60,
24 * 60, TimeUnit.MINUTES);
// clustercf = executor.scheduleAtFixedRate(clusterCollector, 15,
// 30,
// TimeUnit.SECONDS);
log.info("Collecting cluster statistics ");
} else {
log.info("Cluster statistics collector is disabled or not configured! ");
}
if (collectLocalStats()) {
ExecutionStatCollector localCollector = new ExecutionStatCollector(
localWorkDir, localMaxRuntime);
// localcf = executor.scheduleAtFixedRate(localCollector, 100, 60,
// TimeUnit.SECONDS);
localcf = executor.scheduleAtFixedRate(localCollector, 10, 24 * 60,
TimeUnit.MINUTES);
log.info("Collecting local statistics ");
} else {
log.info("Local statistics collector is disabled or not configured! ");
}
}
static String getClusterJobDir() {
return getStringProperty(ph.getProperty("cluster.tmp.directory"));
}
static int getClusterJobTimeOut() {
int maxRunTime = 24 * 7;
String clusterMaxRuntime = ph.getProperty("cluster.stat.maxruntime");
if (clusterMaxRuntime != null) {
clusterMaxRuntime = clusterMaxRuntime.trim();
maxRunTime = Integer.parseInt(clusterMaxRuntime);
}
return maxRunTime;
}
static int getLocalJobTimeOut() {
int maxRunTime = 24;
String localMaxRuntime = ph.getProperty("local.stat.maxruntime");
if (localMaxRuntime != null) {
localMaxRuntime = localMaxRuntime.trim();
maxRunTime = Integer.parseInt(localMaxRuntime);
}
return maxRunTime;
}
static String getLocalJobDir() {
return getStringProperty(ph.getProperty("local.tmp.directory"));
}
private static String getStringProperty(String propName) {
if (propName != null) {
propName = propName.trim();
}
return propName;
}
static boolean collectClusterStats() {
return getBooleanProperty(ph
.getProperty("cluster.stat.collector.enable"));
}
static boolean collectLocalStats() {
return getBooleanProperty(ph.getProperty("local.stat.collector.enable"));
}
private static boolean getBooleanProperty(String propValue) {
boolean enabled = false;
if (!Util.isEmpty(propValue)) {
propValue = propValue.trim();
enabled = Boolean.parseBoolean(propValue);
}
return enabled;
}
}
| 31.622642 | 102 | 0.725338 |
ee08a24cfdf8af0a1ae55251edf8f64acd5daede | 7,467 | package edu.kit.uneig.atisprint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import edu.kit.uneig.atisprint.login.LoginPromptActivity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SettingsActivity extends Activity {
private final int changeUser = 0;
private final int selectPrinter = 1;
private final int setDir = 2;
final CharSequence printers[] = new CharSequence[] {"pool-sw1", "pool-sw2", "pool-sw3", "pool-farb1"};
private SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
prefs = getApplicationContext().getSharedPreferences("AtisPrint", Context.MODE_PRIVATE);
initializeListView();
}
/**
* Initializes the ListView of this Activity. The ListView consists of an item and a subitem for each entry.
*/
private void initializeListView() {
//titles contains all the items in the ListView, subtitles are their subitems
final String[] titles = new String[] {"Change user", "Select printer", "Set directory"};
final String[] subtitles = new String[] {getUsername(), getPrinter(), getDirectory()};
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
for (int i = 0; i < titles.length; i++) {
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("title", titles[i]);
datum.put("subtitle", subtitles[i]);
data.add(datum);
}
SimpleAdapter mAdapter = new SimpleAdapter(this, data,
android.R.layout.simple_list_item_2,
new String[]{"title", "subtitle"},
new int[]{android.R.id.text1, android.R.id.text2});
ListView listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(new ListItemListener());
listView.setAdapter(mAdapter);
}
/**
* Returns the username that is saved in the Preferences of this application or
* "No user saved" if no user is saved
* @return the username that is saved in the Preferences of this application
*/
private String getUsername() {
return prefs.getString("username", "No User saved");
}
/**
* Returns the printer that is saved in the Preferences of this application or
* the first printer if no printer is saved
* @return the printer that is saved in the Preferences of this application.
*/
private String getPrinter() {
return prefs.getString("printer", printers[0].toString());
}
/**
* Sets the printer to the specified printer and updates the listView afterwards.
* The id corresponds to the index in the printers array.
* @param id the id of the printer
*/
private void setPrinter(int id) {
if (id < printers.length) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("printer", printers[id].toString()).apply();
initializeListView();
}
}
private String getDirectory() {
return prefs.getString("dir", "AtisPrint");
}
private void setDirectory(String dir) {
String regEx = "([a-zA-Z]/?)+([a-zA-Z]+)?/?";
if (dir.matches(regEx)) {
if (dir.charAt(dir.length()-1) != '/') {
dir = dir +"/";
}
SharedPreferences.Editor editor = prefs.edit();
editor.putString("dir", dir).apply();
initializeListView();
} else {
Toast.makeText(this, "The directory is invalid", Toast.LENGTH_LONG).show();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == changeUser) {
initializeListView();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.settings, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* This Listener is used for the ListItems inside the ListView.
*/
private class ListItemListener implements AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case changeUser:
Intent signIn = new Intent(getBaseContext(), LoginPromptActivity.class);
startActivityForResult(signIn, changeUser);
break;
case selectPrinter:
showPrinterSelection();
break;
case setDir:
showDirectoryInput();
break;
}
}
private void showDirectoryInput() {
AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
builder.setTitle("Set the directory");
final EditText input = new EditText(SettingsActivity.this);
input.setText(getDirectory());
builder.setView(input);
builder.setNegativeButton("Cancel", null);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
setDirectory(input.getText().toString());
}
});
builder.setNeutralButton("Reset to default", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
setDirectory("AtisPrint");
}
});
builder.show();
}
/**
* Shows a pop up window in which the user can select one printer which will then be saved to the Preference
* file of this application.
*/
private void showPrinterSelection() {
AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
builder.setTitle("Select a printer");
builder.setItems(printers, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
setPrinter(which);
}
});
builder.show();
}
}
}
| 35.727273 | 116 | 0.614973 |
763029870f38bb3ab72b4f583eab2c05d94919c8 | 26,907 | package com.eklanku.otuChat.ui.activities.payment.transaksi;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.eklanku.otuChat.R;
import com.eklanku.otuChat.ui.activities.main.PreferenceManager;
import com.eklanku.otuChat.ui.activities.payment.konfirmasitransaksi.TransKonfirmasiPrabayar;
import com.eklanku.otuChat.ui.activities.payment.models.DataAllProduct;
import com.eklanku.otuChat.ui.activities.payment.models.DataDetailPrefix;
import com.eklanku.otuChat.ui.activities.payment.models.DataPrefix;
import com.eklanku.otuChat.ui.activities.payment.models.DataProduct;
import com.eklanku.otuChat.ui.activities.payment.models.TransBeliResponse;
import com.eklanku.otuChat.ui.activities.payment.sqlite.database.DatabaseHelper;
import com.eklanku.otuChat.ui.activities.payment.sqlite.database.model.History;
import com.eklanku.otuChat.ui.activities.rest.ApiClientPayment;
import com.eklanku.otuChat.ui.activities.rest.ApiInterfacePayment;
import com.eklanku.otuChat.ui.adapters.payment.SpinnerAdapterNew;
import com.eklanku.otuChat.ui.views.ARTextView;
import com.eklanku.otuChat.utils.Utils;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class TransPulsa extends AppCompatActivity {
SharedPreferences prefs;
Spinner spnKartu, spnNominal;
EditText txtNo, etTransaksiKe;
TextInputLayout layoutNo;
Button btnBayar;
String load_id = "X";
Dialog loadingDialog;
ArrayAdapter<String> adapter;
ImageView imgopr;
TextView tvOpr;
ApiInterfacePayment apiInterfacePayment;
PreferenceManager preferenceManager;
String strUserID, strAccessToken, strAplUse = "OTU";
String code, point, price, name;
Context context;
TextView tvNomor, tvVoucher, tvProduct, tvTranske, tvKeterangan, tvBiaya, tvTotal;
ImageView imgKonfirmasi;
Button btnYes, btnNo;
Utils utilsAlert;
String titleAlert = "Pulsa";
ImageView imgOpr;
TextView txOpr;
RelativeLayout layOpr;
ARTextView txLayOpr;
ListView listPulsa;
ArrayList<String> id_paket;
LinearLayout layoutView;
ProgressBar progressBar;
TextView tvEmpty;
String nominalx, tujuanx;
private static long mLastClickTime = 0;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trans_pulsa2);
ButterKnife.bind(this);
utilsAlert = new Utils(TransPulsa.this);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras == null) {
nominalx = null;
tujuanx = null;
} else {
nominalx = extras.getString("nominal");
tujuanx = extras.getString("tujuan");
}
} else {
nominalx = (String) savedInstanceState.getSerializable("nominal");
tujuanx = (String) savedInstanceState.getSerializable("tujuan");
}
prefs = getSharedPreferences("app", Context.MODE_PRIVATE);
spnKartu = findViewById(R.id.spnTransPulsaKartu);
spnNominal = findViewById(R.id.spnTransPulsaNominal);
txtNo = findViewById(R.id.txtTransPulsaNo);
txtNo.setText(tujuanx);
etTransaksiKe = findViewById(R.id.txt_transaksi_ke);
btnBayar = findViewById(R.id.btnTransPulsaBayar);
layoutNo = findViewById(R.id.txtLayoutTransPulsaNo);
imgOpr = findViewById(R.id.imgOpr);
txOpr = findViewById(R.id.txOpr);
layOpr = findViewById(R.id.layNominal);
txLayOpr = findViewById(R.id.txLayOpr);
listPulsa = findViewById(R.id.listPulsa);
layoutView = findViewById(R.id.linear_pulsa);
progressBar = findViewById(R.id.progress_pulsa);
tvEmpty = findViewById(R.id.tv_empty);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
btnBayar.setEnabled(false);
btnBayar.setText(getString(R.string.beli));
tvOpr = findViewById(R.id.textopr);
imgopr = findViewById(R.id.imgopr);
etTransaksiKe.setText("1");
apiInterfacePayment = ApiClientPayment.getClient().create(ApiInterfacePayment.class);
preferenceManager = new PreferenceManager(this);
HashMap<String, String> user = preferenceManager.getUserDetailsPayment();
strUserID = user.get(PreferenceManager.KEY_USERID);
strAccessToken = user.get(PreferenceManager.KEY_ACCESS_TOKEN);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
initializeResources();
getPrefixPulsa();
txtNo.addTextChangedListener(new txtWatcher(txtNo));
}
private class txtWatcher implements TextWatcher {
private View view;
private txtWatcher(View view) {
this.view = view;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
cekPrefixNumber(s);
}
@Override
public void afterTextChanged(Editable s) {
validateIdPel();
//cekPrefixNumber(s);
}
}
private boolean validateIdPel() {
String id_pel = txtNo.getText().toString().trim();
txtNo.setError(null);
if (id_pel.isEmpty()) {
txtNo.setError("Kolom nomor tidak boleh kosong");
requestFocus(txtNo);
return false;
}
return true;
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private void cekTransaksi() {
loadingDialog = ProgressDialog.show(TransPulsa.this, "Harap Tunggu", "Cek Transaksi...");
loadingDialog.setCanceledOnTouchOutside(true);
Call<TransBeliResponse> transBeliCall = apiInterfacePayment.postTopup(strUserID, strAccessToken, strAplUse, txtNo.getText().toString().trim(), "", "", code);
transBeliCall.enqueue(new Callback<TransBeliResponse>() {
@Override
public void onResponse(Call<TransBeliResponse> call, Response<TransBeliResponse> response) {
loadingDialog.dismiss();
if (response.isSuccessful()) {
String status = response.body().getStatus();
String error = response.body().getRespMessage();
Log.d("OPPO-1", "onResponse: " + status);
if (status.equals("SUCCESS")) {
Intent inKonfirmasi = new Intent(getBaseContext(), TransKonfirmasiPrabayar.class);
inKonfirmasi.putExtra("productCode", "PULSA");//
inKonfirmasi.putExtra("billingReferenceID", response.body().getTransactionID());//
inKonfirmasi.putExtra("customerMSISDN", response.body().getMSISDN());//
inKonfirmasi.putExtra("respTime", response.body().getTransactionDate());//
inKonfirmasi.putExtra("billing", response.body().getNominal());//
inKonfirmasi.putExtra("adminBank", "0");
inKonfirmasi.putExtra("respMessage", response.body().getRespMessage());//
inKonfirmasi.putExtra("ep", point);
inKonfirmasi.putExtra("jenisvoucher", name);
inKonfirmasi.putExtra("oprPulsa", oprPulsa);
/*inKonfirmasi.putExtra("userID", response.body().getUserID());//
inKonfirmasi.putExtra("accessToken", strAccessToken);//
inKonfirmasi.putExtra("status", status);//
inKonfirmasi.putExtra("customerID", response.body().getMSISDN());//
inKonfirmasi.putExtra("customerName", "");
inKonfirmasi.putExtra("period", "");
inKonfirmasi.putExtra("policeNumber", "");
inKonfirmasi.putExtra("lastPaidPeriod", "");
inKonfirmasi.putExtra("tenor", "");
inKonfirmasi.putExtra("lastPaidDueDate", "");
inKonfirmasi.putExtra("usageUnit", "TOPUP");
inKonfirmasi.putExtra("penalty", "");
inKonfirmasi.putExtra("payment", response.body().getNominal());//
inKonfirmasi.putExtra("minPayment", "");
inKonfirmasi.putExtra("minPayment", "");
inKonfirmasi.putExtra("additionalMessage", response.body().getAdditionalMessage());
inKonfirmasi.putExtra("sellPrice", "");
inKonfirmasi.putExtra("profit", "");*/
startActivity(inKonfirmasi);
// finish();
} else {
utilsAlert.globalDialog(TransPulsa.this, titleAlert, error);
}
} else {
utilsAlert.globalDialog(TransPulsa.this, titleAlert, getResources().getString(R.string.error_api));
}
}
@Override
public void onFailure(Call<TransBeliResponse> call, Throwable t) {
loadingDialog.dismiss();
utilsAlert.globalDialog(TransPulsa.this, titleAlert, getResources().getString(R.string.error_api));
Log.d("API_TRANSBELI", t.getMessage());
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.payment_transaction_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_transaction_confirmation:
Toast.makeText(this, "Konfirmasi pembayaran", Toast.LENGTH_SHORT).show();
return true;
case android.R.id.home:
finish();
return true;
case R.id.action_transaction_evidence:
Toast.makeText(this, "Kirim bukti pembayaran", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
String oprPulsa = "";
String tempOprPulsa = "";
boolean statOprPulsa = false;
boolean otherOpr = true;
private void initializeResources() {
listPulsa = findViewById(R.id.listPulsa);
listPulsa.setOnItemClickListener((parent, view, position, id) -> {
if (!validateIdPel()) {
return;
}
code = code_product.get(position);
point = point_ep.get(position);
price = b.get(position);
name = code_name.get(position);
dialogWarning(code, name, name, price);
});
}
public void dialogWarning(String kodepaket, String name, String keterangan, String total) {
final Dialog dialog = new Dialog(TransPulsa.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.activity_alert_dialog);
dialog.setCancelable(false);
dialog.setTitle("Peringatan Transaksi!!!");
btnYes = dialog.findViewById(R.id.btn_yes);
btnNo = dialog.findViewById(R.id.btn_no);
tvNomor = dialog.findViewById(R.id.txt_nomor);
tvVoucher = dialog.findViewById(R.id.txt_voucher);
tvProduct = dialog.findViewById(R.id.txt_product);
tvTranske = dialog.findViewById(R.id.txt_transke);
tvKeterangan = dialog.findViewById(R.id.txt_keterangan);
tvBiaya = dialog.findViewById(R.id.txt_biaya);
tvTotal = dialog.findViewById(R.id.txt_total);
imgKonfirmasi = dialog.findViewById(R.id.img_konfirmasi);
tvProduct.setText(name);
tvTranske.setText(etTransaksiKe.getText().toString());
tvNomor.setText(txtNo.getText().toString().trim());
tvVoucher.setText(kodepaket);
tvNomor.setText(txtNo.getText().toString().trim());
tvVoucher.setText(formatRupiah(Double.parseDouble(price)));
tvKeterangan.setText(name);
tvBiaya.setText("Rp0");
tvTotal.setText(formatRupiah(Double.parseDouble(price)));
int id = TransPulsa.this.getResources().getIdentifier("mipmap/" + oprPulsa.toLowerCase(), null, TransPulsa.this.getPackageName());
imgKonfirmasi.setImageResource(id);
btnYes.setText(getString(R.string.lanjutkan));
btnYes.setOnClickListener(view -> {
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
return;
}
mLastClickTime = SystemClock.elapsedRealtime();
cekTransaksi();
dialog.dismiss();
});
btnNo.setOnClickListener(view -> dialog.dismiss());
dialog.show();
Window window = dialog.getWindow();
assert window != null;
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
return;
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
public String formatRupiah(double nominal) {
String parseRp = "";
Locale localeID = new Locale("in", "ID");
NumberFormat formatRupiah = NumberFormat.getCurrencyInstance(localeID);
parseRp = formatRupiah.format(nominal);
return parseRp;
}
/*====================================================new service api=====================================*/
ArrayList<String> listProvider;
ArrayList<String> listPrefix;
public void getPrefixPulsa() {
showProgress(true);
Call<DataPrefix> dataPrefix = apiInterfacePayment.getPrefixPulsa(strUserID, strAccessToken, strAplUse);
Log.d("OPPO-1", "getPrefixPulsa: " + strUserID + ", " + strAccessToken + ", " + strAplUse);
dataPrefix.enqueue(new Callback<DataPrefix>() {
@Override
public void onResponse(Call<DataPrefix> call, Response<DataPrefix> response) {
if (response.isSuccessful()) {
String status = response.body().getStatus();
Log.d("OPPO-1", "status: " + status);
String respMessage = response.body().getRespMessage();
listProvider = new ArrayList<>();
listPrefix = new ArrayList<>();
listProvider.clear();
listPrefix.clear();
if (status.equalsIgnoreCase("SUCCESS")) {
List<DataDetailPrefix> data = response.body().getData();
for (int i = 0; i < data.size(); i++) {
listProvider.add(data.get(i).getProvider());
listPrefix.add(data.get(i).getPrefix());
}
getProductPulsa();
} else {
showProgress(false);
utilsAlert.globalDialog(TransPulsa.this, titleAlert, respMessage);
}
} else {
showProgress(false);
utilsAlert.globalDialog(TransPulsa.this, titleAlert, "1. " + getResources().getString(R.string.error_api));
}
}
@Override
public void onFailure(Call<DataPrefix> call, Throwable t) {
showProgress(false);
utilsAlert.globalDialog(TransPulsa.this, titleAlert, "2. " + getResources().getString(R.string.error_api));
}
});
}
ArrayList<String> code_product;
ArrayList<String> code_name;
ArrayList<String> point_ep;
ArrayList<String> a, b, c, d;
public void cekPrefixNumber(CharSequence s) {
//Toast.makeText(context, "cek prefix " + s, Toast.LENGTH_SHORT).show();
SpinnerAdapterNew adapter = null;
a = new ArrayList<>();
b = new ArrayList<>();
c = new ArrayList<>();
d = new ArrayList<>();
code_product = new ArrayList<>();
code_name = new ArrayList<>();
point_ep = new ArrayList<>();
listPulsa.setAdapter(null);
try {
String nomorHp;
if (s.length() >= 6) {
a.clear();
b.clear();
c.clear();
d.clear();
listPulsa.setAdapter(null);
String nomorHP1 = s.toString().substring(0, 2);
String valNomorHp /*, valNomorHP2 = ""*/;
if (nomorHP1.startsWith("+6")) {
valNomorHp = nomorHP1.replace("+6", "0");
nomorHp = valNomorHp + s.toString().substring(3, 6);
} else if (nomorHP1.startsWith("62")) {
valNomorHp = nomorHP1.replace("62", "0");
nomorHp = valNomorHp + s.toString().substring(2, 5);
} else {
nomorHp = s.toString().substring(0, 4);
}
for (int i = 0; i < listPrefix.size(); i++) {
Log.d("AYIK", "list->" + nomorHp + ", " + listPrefix.get(i));
if (nomorHp.equals(listPrefix.get(i))) {
oprPulsa = listProvider.get(i);
txOpr.setText(oprPulsa);
statOprPulsa = true;
otherOpr = false;
int id = TransPulsa.this.getResources().getIdentifier("mipmap/" + oprPulsa.toLowerCase(), null, TransPulsa.this.getPackageName());
imgOpr.setImageResource(id);
break;
} else {
a.clear();
b.clear();
c.clear();
d.clear();
point_ep.clear();
code_product.clear();
code_name.clear();
layOpr.setVisibility(View.GONE);
txLayOpr.setVisibility(View.GONE);
statOprPulsa = false;
tempOprPulsa = "";
btnBayar.setEnabled(true);
oprPulsa = "";
listPulsa.setAdapter(null);
imgOpr.setImageResource(0);
}
}
for (int j = 0; j < listProviderProduct.size(); j++) {
if (listProviderProduct.get(j).equalsIgnoreCase(oprPulsa)) {
a.add(listName.get(j));
b.add(listPrice.get(j));
c.add(listEP.get(j));
d.add(listProviderProduct.get(j));
code_product.add(listCode.get(j));
code_name.add(listName.get(j));
point_ep.add(listEP.get(j));
}
}
Log.d("AYIK", "list->" + a.size());
if (a.size() >= 1 /*&& nomorHp.equals(oprPulsa)*/) {
tvEmpty.setVisibility(View.GONE);
listPulsa.setVisibility(View.VISIBLE);
} else {
tvEmpty.setVisibility(View.VISIBLE);
//listPulsa.setVisibility(View.VISIBLE);
}
adapter = new SpinnerAdapterNew(getApplicationContext(), a, b, c, d, oprPulsa);
listPulsa.setAdapter(adapter);
adapter.notifyDataSetChanged();
if (!oprPulsa.equalsIgnoreCase(tempOprPulsa) && statOprPulsa) {
//loadProduct(strUserID, strAccessToken, strAplUse, oprPulsa);
tempOprPulsa = oprPulsa;
statOprPulsa = false;
btnBayar.setEnabled(true);
layOpr.setVisibility(View.GONE);
txLayOpr.setVisibility(View.GONE);
otherOpr = true;
}
if (otherOpr && oprPulsa.equalsIgnoreCase("")) {
Log.d("OPPO-1", "cekPrefix: ");
//loadProvider(strUserID, strAccessToken, strAplUse, strProductType);
otherOpr = false;
}
} else /*if (s.length() < 4)*/ {
//listPulsa.setAdapter(adapter);
listPulsa.setAdapter(null);
a.clear();
b.clear();
c.clear();
d.clear();
statOprPulsa = false;
otherOpr = true;
tempOprPulsa = "";
txOpr.setText("");
imgOpr.setImageResource(0);
layOpr.setVisibility(View.GONE);
txLayOpr.setVisibility(View.GONE);
btnBayar.setEnabled(false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
ArrayList<String> listCode;
ArrayList<String> listPrice;
ArrayList<String> listName;
ArrayList<String> listEP;
ArrayList<String> listisActive;
ArrayList<String> listType;
ArrayList<String> listProviderProduct;
public void getProductPulsa() {
Call<DataAllProduct> dataPulsa = apiInterfacePayment.getProduct_pulsa(strUserID, strAccessToken, strAplUse);
dataPulsa.enqueue(new Callback<DataAllProduct>() {
@Override
public void onResponse(Call<DataAllProduct> call, Response<DataAllProduct> response) {
showProgress(false);
if (response.isSuccessful()) {
listCode = new ArrayList<>();
listPrice = new ArrayList<>();
listName = new ArrayList<>();
listEP = new ArrayList<>();
listisActive = new ArrayList<>();
listType = new ArrayList<>();
listProviderProduct = new ArrayList<>();
listCode.clear();
listPrice.clear();
listName.clear();
listEP.clear();
listisActive.clear();
listType.clear();
listProviderProduct.clear();
String status = response.body().getStatus();
String respMessage = response.body().getRespMessage();
if (status.equalsIgnoreCase("SUCCESS")) {
List<DataProduct> data = response.body().getData();
for (int i = 0; i < data.size(); i++) {
listCode.add(data.get(i).getCode());
listPrice.add(data.get(i).getPrice());
listName.add(data.get(i).getName());
listEP.add(data.get(i).getEp());
listisActive.add(data.get(i).getIsActive());
listType.add(data.get(i).getType());
listProviderProduct.add(data.get(i).getProvider());
}
if (!TextUtils.isEmpty(tujuanx)) {
cekPrefixNumber(tujuanx);
}
} else {
utilsAlert.globalDialog(TransPulsa.this, titleAlert, respMessage);
}
} else {
utilsAlert.globalDialog(TransPulsa.this, titleAlert, "1. " + getResources().getString(R.string.error_api));
}
}
@Override
public void onFailure(Call<DataAllProduct> call, Throwable t) {
showProgress(false);
utilsAlert.globalDialog(TransPulsa.this, titleAlert, "2. " + getResources().getString(R.string.error_api));
}
});
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
layoutView.setVisibility(show ? View.GONE : View.VISIBLE);
layoutView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
layoutView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
progressBar.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
layoutView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
}
| 39.862222 | 165 | 0.573382 |
9d2b6a38a1632ff9862b1a325b7d533b3789dcd8 | 844 | package com.fos.fosmvp.ui.login.contract;
import com.fos.fosmvp.base.BaseModel;
import com.fos.fosmvp.base.BasePresenter;
import com.fos.fosmvp.base.BaseResponse;
import com.fos.fosmvp.base.BaseView;
import com.fos.fosmvp.entity.login.UserEntity;
import java.util.Map;
import rx.Observable;
public interface LoginContract {
interface Model extends BaseModel {
//请求用户登录信息
Observable<BaseResponse<UserEntity>> getLoginData(Map map);
}
interface View extends BaseView {
//登录成功返回
void returnLoginSucceed(UserEntity userEntity);
//登录失败返回
void returnLoginFail(BaseResponse baseResponse, boolean isVisitError);
}
abstract class Presenter extends BasePresenter<View, Model> {
//发起用户登录请求
public abstract void getLoginRequest(String tel,String password);
}
}
| 26.375 | 78 | 0.726303 |
4c325014c84040151ca3f130187e1ba642babdea | 1,380 | package org.spongycastle.crypto.tls;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class HeartbeatExtension
{
protected short mode;
public HeartbeatExtension(short mode)
{
if (!HeartbeatMode.isValid(mode))
{
throw new IllegalArgumentException("'mode' is not a valid HeartbeatMode value");
}
this.mode = mode;
}
public short getMode()
{
return mode;
}
/**
* Encode this {@link HeartbeatExtension} to an {@link OutputStream}.
*
* @param output
* the {@link OutputStream} to encode to.
* @throws IOException
*/
public void encode(OutputStream output) throws IOException
{
TlsUtils.writeUint8(mode, output);
}
/**
* Parse a {@link HeartbeatExtension} from an {@link InputStream}.
*
* @param input
* the {@link InputStream} to parse from.
* @return a {@link HeartbeatExtension} object.
* @throws IOException
*/
public static HeartbeatExtension parse(InputStream input) throws IOException
{
short mode = TlsUtils.readUint8(input);
if (!HeartbeatMode.isValid(mode))
{
throw new TlsFatalAlert(AlertDescription.illegal_parameter);
}
return new HeartbeatExtension(mode);
}
}
| 24.210526 | 92 | 0.615942 |
c3b14b5d392f64b45a52f8d91c6c427d7ea2e2b6 | 1,969 | package com.logginghub.logging.api.patterns;
import com.logginghub.utils.sof.SerialisableObject;
import com.logginghub.utils.sof.SofException;
import com.logginghub.utils.sof.SofReader;
import com.logginghub.utils.sof.SofWriter;
public class InstanceDetails implements SerialisableObject {
private String hostname;
private String hostIP;
private String instanceName;
private int pid;
private int localPort;
@Override public void read(SofReader reader) throws SofException {
hostname = reader.readString(0);
hostIP = reader.readString(1);
instanceName = reader.readString(2);
pid = reader.readInt(3);
localPort = reader.readInt(4);
}
@Override public void write(SofWriter writer) throws SofException {
writer.write(0, hostname);
writer.write(1, hostIP);
writer.write(2, instanceName);
writer.write(3, pid);
writer.write(4, localPort);
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getHostIP() {
return hostIP;
}
public void setHostIP(String hostIP) {
this.hostIP = hostIP;
}
public String getInstanceName() {
return instanceName;
}
public void setInstanceName(String instanceName) {
this.instanceName = instanceName;
}
@Override public String toString() {
return "InstanceDetails [hostname=" + hostname + ", hostIP=" + hostIP + ", instanceName=" + instanceName + ", pid=" + pid + "]";
}
public void setPid(int pid) {
this.pid = pid;
}
public int getPid() {
return pid;
}
public void setLocalPort(int localPort) {
this.localPort = localPort;
}
public int getLocalPort() {
return localPort;
}
}
| 25.907895 | 137 | 0.616557 |
fd90ec27f8f41aab07eca69cd93b7098059ce550 | 4,133 | /**
* Copyright (c) 2010 Perforce Software. All rights reserved.
*/
package com.perforce.team.ui.charts.diff;
import org.eclipse.osgi.util.NLS;
/**
* @author Kevin Sawicki (ksawicki@perforce.com)
*/
public class Messages extends NLS {
private static final String BUNDLE_NAME = "com.perforce.team.ui.charts.diff.messages"; //$NON-NLS-1$
/**
* ChangelistChart_Added
*/
public static String ChangelistChart_Added;
/**
* ChangelistChart_Changed
*/
public static String ChangelistChart_Changed;
/**
* ChangelistChart_Deleted
*/
public static String ChangelistChart_Deleted;
/**
* ChangelistChart_LineDifferencesPerFile
*/
public static String ChangelistChart_LineDifferencesPerFile;
/**
* ChangelistChartPage_BuildingDiffChart
*/
public static String ChangelistChartPage_BuildingDiffChart;
/**
* ChangelistChartPage_DiffChart
*/
public static String ChangelistChartPage_DiffChart;
/**
* ChangelistChartPage_EmptyDescription
*/
public static String ChangelistChartPage_EmptyDescription;
/**
* ChangelistChartPage_LimitedSectionDescription
*/
public static String ChangelistChartPage_LimitedSectionDescription;
/**
* ChangelistChartPage_LoadingDiffs
*/
public static String ChangelistChartPage_LoadingDiffs;
/**
* ChangelistChartPage_SectionDescription
*/
public static String ChangelistChartPage_SectionDescription;
/**
* Diff2AuthorChartPage_ChartTitle
*/
public static String Diff2AuthorChartPage_ChartTitle;
/**
* Diff2AuthorChartPage_ContentDescription
*/
public static String Diff2AuthorChartPage_ContentDescription;
/**
* Diff2AuthorChartPage_UniqueDescription
*/
public static String Diff2AuthorChartPage_UniqueDescription;
/**
* Diff2ChartPage_ContentTitle
*/
public static String Diff2ChartPage_ContentTitle;
/**
* Diff2ChartPage_Differing
*/
public static String Diff2ChartPage_Differing;
/**
* Diff2ChartPage_DiffTypeChartDescription
*/
public static String Diff2ChartPage_DiffTypeChartDescription;
/**
* Diff2ChartPage_DiffTypeChartTitle
*/
public static String Diff2ChartPage_DiffTypeChartTitle;
/**
* Diff2ChartPage_Identical
*/
public static String Diff2ChartPage_Identical;
/**
* Diff2ChartPage_NoProject
*/
public static String Diff2ChartPage_NoProject;
/**
* Diff2ChartPage_Unique
*/
public static String Diff2ChartPage_Unique;
/**
* Diff2ChartPage_UniqueTitle
*/
public static String Diff2ChartPage_UniqueTitle;
/**
* Diff2ChartPage_Unknown
*/
public static String Diff2ChartPage_Unknown;
/**
* Diff2ContentTypeChartPage_ChartTitle
*/
public static String Diff2ContentTypeChartPage_ChartTitle;
/**
* Diff2ContentTypeChartPage_ContentDescription
*/
public static String Diff2ContentTypeChartPage_ContentDescription;
/**
* Diff2ContentTypeChartPage_ExtensionFile
*/
public static String Diff2ContentTypeChartPage_ExtensionFile;
/**
* Diff2ContentTypeChartPage_FileType
*/
public static String Diff2ContentTypeChartPage_FileType;
/**
* Diff2ContentTypeChartPage_UniqueDescription
*/
public static String Diff2ContentTypeChartPage_UniqueDescription;
/**
* Diff2OverviewChartPage_ChartTitle
*/
public static String Diff2OverviewChartPage_ChartTitle;
/**
* Diff2ProjectChartPage_ChartTitle
*/
public static String Diff2ProjectChartPage_ChartTitle;
/**
* Diff2ProjectChartPage_ContentDescription
*/
public static String Diff2ProjectChartPage_ContentDescription;
/**
* Diff2ProjectChartPage_UniqueDescription
*/
public static String Diff2ProjectChartPage_UniqueDescription;
static {
// initialize resource bundle
NLS.initializeMessages(BUNDLE_NAME, Messages.class);
}
private Messages() {
}
}
| 23.219101 | 104 | 0.706267 |
eb41b667e7cacd7641687dcd02e363895731af51 | 757 |
// Demonstration of both constructor
// and ordinary method overloading.
import java.util.*;
class Tree {
int height;
Tree() {
prt("Planting a seedling");
height = 0;
}
Tree(int i) {
prt("Creating new Tree that is "
+ i + " feet tall");
height = i;
}
void info() {
prt("Tree is " + height
+ " feet tall");
}
void info(String s) {
prt(s + ": Tree is "
+ height + " feet tall");
}
static void prt(String s) {
System.out.println(s);
}
}
public class Overloading {
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
Tree t = new Tree(i);
t.info();
t.info("overloaded method");
}
// Overloaded constructor:
new Tree();
}
} ///:~ | 18.925 | 42 | 0.536328 |
1466bc459b68c02d2726f546256199f9b929f3ff | 13,453 | package org.embulk.jruby;
import com.google.inject.Injector;
import com.google.inject.ProvisionException;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.embulk.config.ModelManager;
import org.embulk.spi.BufferAllocator;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
public final class JRubyInitializer {
private JRubyInitializer(
final Injector injector,
final Logger logger,
final String gemHome,
final boolean useDefaultEmbulkGemHome,
final List<String> jrubyLoadPath,
final List<String> jrubyClasspath,
final List<String> jrubyOptions,
final String jrubyBundlerPluginSourceDirectory) {
this.injector = injector;
this.logger = logger;
this.gemHome = gemHome;
this.useDefaultEmbulkGemHome = useDefaultEmbulkGemHome;
this.jrubyLoadPath = jrubyLoadPath;
this.jrubyClasspath = jrubyClasspath;
this.jrubyOptions = jrubyOptions;
this.jrubyBundlerPluginSourceDirectory = jrubyBundlerPluginSourceDirectory;
}
public static JRubyInitializer of(
final Injector injector,
final Logger logger,
final String gemHome,
final boolean useDefaultEmbulkGemHome,
final List jrubyLoadPathNonGeneric,
final List jrubyClasspathNonGeneric,
final List jrubyOptionsNonGeneric,
final String jrubyBundlerPluginSourceDirectory) {
final ArrayList<String> jrubyLoadPathBuilt = new ArrayList<String>();
if (jrubyLoadPathNonGeneric != null) {
for (final Object oneJRubyLoadPath : jrubyLoadPathNonGeneric) {
if (oneJRubyLoadPath instanceof String) {
jrubyLoadPathBuilt.add((String) oneJRubyLoadPath);
} else {
logger.warn("System config \"jruby_load_path\" contains non-String.");
jrubyLoadPathBuilt.add(oneJRubyLoadPath.toString());
}
}
}
final ArrayList<String> jrubyClasspathBuilt = new ArrayList<String>();
if (jrubyClasspathNonGeneric != null) {
for (final Object oneJRubyClasspath : jrubyClasspathNonGeneric) {
if (oneJRubyClasspath instanceof String) {
jrubyClasspathBuilt.add((String) oneJRubyClasspath);
} else {
logger.warn("System config \"jruby_classpath\" contains non-String.");
jrubyClasspathBuilt.add(oneJRubyClasspath.toString());
}
}
}
final ArrayList<String> jrubyOptionsBuilt = new ArrayList<String>();
if (jrubyOptionsNonGeneric != null) {
for (final Object oneJRubyOption : jrubyOptionsNonGeneric) {
if (oneJRubyOption instanceof String) {
jrubyOptionsBuilt.add((String) oneJRubyOption);
} else {
logger.warn("System config \"jruby_command_line_options\" contains non-String.");
jrubyOptionsBuilt.add(oneJRubyOption.toString());
}
}
}
return new JRubyInitializer(
injector,
logger,
gemHome,
useDefaultEmbulkGemHome,
Collections.unmodifiableList(jrubyLoadPathBuilt),
Collections.unmodifiableList(jrubyClasspathBuilt),
Collections.unmodifiableList(jrubyOptionsBuilt),
jrubyBundlerPluginSourceDirectory);
}
public void initialize(final ScriptingContainerDelegate jruby) {
// JRuby runtime options are processed at first.
for (final String jrubyOption : this.jrubyOptions) {
try {
jruby.processJRubyOption(jrubyOption);
} catch (ScriptingContainerDelegate.UnrecognizedJRubyOptionException ex) {
this.logger.error("The \"-R\" option(s) are not recognized in Embulk: -R" + jrubyOption
+ ". Please add your requests at: https://github.com/embulk/embulk/issues/707",
ex);
throw new RuntimeException(ex);
} catch (ScriptingContainerDelegate.NotWorkingJRubyOptionException ex) {
this.logger.warn("The \"-R\" option(s) do not work in Embulk: -R" + jrubyOption + ".", ex);
}
}
// Gem paths and Bundler are configured earlier.
this.setGemVariables(jruby);
this.setBundlerPluginSourceDirectory(jruby, this.jrubyBundlerPluginSourceDirectory);
// $LOAD_PATH and $CLASSPATH are configured after Gem paths and Bundler.
for (final String oneJRubyLoadPath : this.jrubyLoadPath) {
// ruby script directory (use unshift to make it highest priority)
jruby.put("__internal_load_path__", oneJRubyLoadPath);
// TODO: Check if $LOAD_PATH already contains it.
jruby.runScriptlet("$LOAD_PATH.unshift File.expand_path(__internal_load_path__)");
jruby.remove("__internal_load_path__");
}
for (final String oneJRubyClasspath : this.jrubyClasspath) {
jruby.put("__internal_classpath__", oneJRubyClasspath);
// $CLASSPATH object doesn't have concat method
// TODO: Check if $CLASSPATH already contains it.
jruby.runScriptlet("$CLASSPATH << __internal_classpath__");
jruby.remove("__internal_classpath__");
}
// Embulk's base Ruby code is loaded at last.
jruby.runScriptlet("require 'embulk/logger'");
jruby.runScriptlet("require 'embulk/java/bootstrap'");
final Object injected = jruby.runScriptlet("Embulk::Java::Injected");
jruby.callMethod(injected, "const_set", "Injector", injector);
jruby.callMethod(injected, "const_set", "ModelManager", injector.getInstance(ModelManager.class));
jruby.callMethod(injected, "const_set", "BufferAllocator", injector.getInstance(BufferAllocator.class));
jruby.callMethod(jruby.runScriptlet("Embulk"), "logger=", jruby.callMethod(
jruby.runScriptlet("Embulk::Logger"),
"new",
injector.getInstance(ILoggerFactory.class).getLogger("ruby")));
}
// TODO: Remove these probing methods, and test through mocked ScriptingContainerDelegate.
String probeGemHomeForTesting() {
return this.gemHome;
}
boolean probeUseDefaultEmbulkGemHomeForTesting() {
return this.useDefaultEmbulkGemHome;
}
List<String> probeJRubyLoadPathForTesting() {
return this.jrubyLoadPath;
}
List<String> probeJRubyClasspathForTesting() {
return this.jrubyClasspath;
}
List<String> probeJRubyOptionsForTesting() {
return this.jrubyOptions;
}
String probeJRubyBundlerPluginSourceDirectoryForTesting() {
return this.jrubyBundlerPluginSourceDirectory;
}
private void setGemVariables(final ScriptingContainerDelegate jruby) {
final boolean hasBundleGemfile = jruby.isBundleGemfileDefined();
if (hasBundleGemfile) {
this.logger.warn("BUNDLE_GEMFILE has already been set: \"" + jruby.getBundleGemfile() + "\"");
}
if (this.jrubyBundlerPluginSourceDirectory != null) {
final String gemfilePath = this.buildGemfilePath(this.jrubyBundlerPluginSourceDirectory);
if (hasBundleGemfile) {
this.logger.warn("BUNDLE_GEMFILE is being overwritten: \"" + gemfilePath + "\"");
} else {
this.logger.info("BUNDLE_GEMFILE is being set: \"" + gemfilePath + "\"");
}
jruby.setBundleGemfile(gemfilePath);
this.logger.info("Gem's home and path are being cleared.");
jruby.clearGemPaths();
this.logger.debug("Gem.paths.home = \"" + jruby.getGemHome() + "\"");
this.logger.debug("Gem.paths.path = " + jruby.getGemPathInString() + "");
} else {
if (hasBundleGemfile) {
this.logger.warn("BUNDLE_GEMFILE is being unset.");
jruby.unsetBundleGemfile();
}
if (this.gemHome != null) {
// The system config "gem_home" is always prioritized.
//
// Overwrites GEM_HOME and GEM_PATH. GEM_PATH becomes same with GEM_HOME. Therefore
// with this code, there're no ways to set extra GEM_PATHs in addition to GEM_HOME.
// Here doesn't modify ENV['GEM_HOME'] so that a JVM process can create multiple
// JRubyScriptingModule instances. However, because Gem loads ENV['GEM_HOME'] when
// Gem.clear_paths is called, applications may use unexpected GEM_HOME if clear_path
// is used.
this.logger.info("Gem's home and path are set by system config \"gem_home\": \"" + this.gemHome + "\"");
jruby.setGemPaths(this.gemHome);
this.logger.debug("Gem.paths.home = \"" + jruby.getGemHome() + "\"");
this.logger.debug("Gem.paths.path = " + jruby.getGemPathInString() + "");
} else if (this.useDefaultEmbulkGemHome) {
// NOTE: Same done in "gem", "exec", and "irb" subcommands.
// Remember to update |org.embulk.cli.EmbulkRun| as well when these environment variables are change
final String defaultGemHome = this.buildDefaultGemPath();
this.logger.info("Gem's home and path are set by default: \"" + defaultGemHome + "\"");
jruby.setGemPaths(defaultGemHome);
this.logger.debug("Gem.paths.home = \"" + jruby.getGemHome() + "\"");
this.logger.debug("Gem.paths.path = " + jruby.getGemPathInString() + "");
} else {
this.logger.info("Gem's home and path are not managed.");
this.logger.info("Gem.paths.home = \"" + jruby.getGemHome() + "\"");
this.logger.info("Gem.paths.path = " + jruby.getGemPathInString() + "");
}
}
}
private void setBundlerPluginSourceDirectory(final ScriptingContainerDelegate jruby, final String directory) {
if (directory != null) {
jruby.runScriptlet("require 'bundler'");
// TODO: Remove the monkey patch once the issue is fixed on Bundler or JRuby side.
// @see <a href="https://github.com/bundler/bundler/issues/4565">Bundler::SharedHelpers.clean_load_path does cleanup the default load_path on jruby - Issue #4565 - bundler/bundler</a>
final String monkeyPatchOnSharedHelpersCleanLoadPath =
"begin\n"
+ " require 'bundler/shared_helpers'\n"
+ " module Bundler\n"
+ " module DisableCleanLoadPath\n"
+ " def clean_load_path\n"
+ " # Do nothing.\n"
+ " end\n"
+ " end\n"
+ " module SharedHelpers\n"
+ " def included(bundler)\n"
+ " bundler.send :include, DisableCleanLoadPath\n"
+ " end\n"
+ " end\n"
+ " end\n"
+ "rescue LoadError\n"
+ " # Ignore LoadError.\n"
+ "end\n";
jruby.runScriptlet(monkeyPatchOnSharedHelpersCleanLoadPath);
jruby.runScriptlet("require 'bundler/setup'");
}
}
private String buildDefaultGemPath() throws ProvisionException {
return this.buildEmbulkHome().resolve("lib").resolve("gems").toString();
}
private String buildGemfilePath(final String bundleDirectoryString) throws ProvisionException {
final Path bundleDirectory;
try {
bundleDirectory = Paths.get(bundleDirectoryString);
} catch (InvalidPathException ex) {
throw new ProvisionException("Bundle directory is invalid: \"" + bundleDirectoryString + "\"", ex);
}
return bundleDirectory.toAbsolutePath().resolve("Gemfile").toString();
}
private Path buildEmbulkHome() throws ProvisionException {
final String userHomeProperty = System.getProperty("user.home");
if (userHomeProperty == null) {
throw new ProvisionException("User home directory is not set in Java properties.");
}
final Path userHome;
try {
userHome = Paths.get(userHomeProperty);
} catch (InvalidPathException ex) {
throw new ProvisionException("User home directory is invalid: \"" + userHomeProperty + "\"", ex);
}
return userHome.toAbsolutePath().resolve(".embulk");
}
private final Injector injector;
private final Logger logger;
private final String gemHome;
private final boolean useDefaultEmbulkGemHome;
private final List<String> jrubyLoadPath;
private final List<String> jrubyClasspath;
private final List<String> jrubyOptions;
private final String jrubyBundlerPluginSourceDirectory;
}
| 46.389655 | 195 | 0.610347 |
6c93cc68f4cf923b8821bb172630c2afdfebe097 | 2,727 | package com.jg.wx.admin.web;
import com.alibaba.fastjson.JSONObject;
import com.jg.wx.core.util.RegexUtil;
import com.jg.wx.core.util.ResponseUtil;
import com.jg.wx.domain.DtsFeedback;
import com.jg.wx.domain.DtsUser;
import com.jg.wx.service.DtsFeedbackService;
import com.jg.wx.service.DtsUserService;
import com.jg.wx.admin.annotation.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 意见反馈服务
*
* @author CHENBO
* @since 1.0.0
* @QQ 623659388
*/
@RestController
@RequestMapping("/wx/feedback")
@Validated
public class WxFeedbackController {
private static final Logger logger = LoggerFactory.getLogger(WxFeedbackController.class);
@Autowired
private DtsFeedbackService feedbackService;
@Autowired
private DtsUserService userService;
private Object validate(DtsFeedback feedback) {
String content = feedback.getContent();
if (StringUtils.isEmpty(content)) {
return ResponseUtil.badArgument();
}
String type = feedback.getFeedType();
if (StringUtils.isEmpty(type)) {
return ResponseUtil.badArgument();
}
Boolean hasPicture = feedback.getHasPicture();
if (hasPicture == null || !hasPicture) {
feedback.setPicUrls(new String[0]);
}
// 测试手机号码是否正确
String mobile = feedback.getMobile();
if (StringUtils.isEmpty(mobile)) {
return ResponseUtil.badArgument();
}
if (!RegexUtil.isMobileExact(mobile)) {
return ResponseUtil.badArgument();
}
return null;
}
/**
* 添加意见反馈
*
* @param userId
* 用户ID
* @param feedback
* 意见反馈
* @return 操作结果
*/
@PostMapping("submit")
public Object submit(@LoginUser Integer userId, @RequestBody DtsFeedback feedback) {
logger.info("【请求开始】添加意见反馈,请求参数,userId:{},size:{}", userId, JSONObject.toJSONString(feedback));
if (userId == null) {
logger.error("添加意见反馈失败:用户未登录!!!");
return ResponseUtil.unlogin();
}
Object error = validate(feedback);
if (error != null) {
return error;
}
DtsUser user = userService.findById(userId);
String username = user.getUsername();
feedback.setId(null);
feedback.setUserId(userId);
feedback.setUsername(username);
// 状态默认是0,1表示状态已发生变化
feedback.setStatus(1);
feedbackService.add(feedback);
logger.info("【请求结束】添加意见反馈,响应结果:{}", JSONObject.toJSONString(feedback));
return ResponseUtil.ok();
}
}
| 26.735294 | 96 | 0.740007 |
613eb98e1856bad810aa314f446613295615e9c4 | 3,243 | package org.ovirt.engine.ui.common;
import com.google.gwt.i18n.client.Constants;
public interface CommonApplicationConstants extends Constants {
@DefaultStringValue("Oops!")
String errorPopupCaption();
@DefaultStringValue("Close")
String closeButtonLabel();
@DefaultStringValue("[N/A]")
String unAvailablePropertyLabel();
// Widgets
@DefaultStringValue("Next >>")
String actionTableNextPageButtonLabel();
@DefaultStringValue("<< Prev")
String actionTablePrevPageButtonLabel();
// Table columns
@DefaultStringValue("Disk Activate/Deactivate while VM is running, is supported only for Clusters of version 3.1 and above")
String diskHotPlugNotSupported();
@DefaultStringValue("Disks Allocation:")
String disksAllocation();
@DefaultStringValue("Disk ")
String diskNamePrefix();
@DefaultStringValue("Single Destination Storage")
String singleDestinationStorage();
// Model-bound widgets
@DefaultStringValue("Boot Options:")
String runOncePopupBootOptionsLabel();
@DefaultStringValue("Display Protocol:")
String runOncePopupDisplayProtocolLabel();
@DefaultStringValue("Custom Properties")
String runOncePopupCustomPropertiesLabel();
@DefaultStringValue("Vnc")
String runOncePopupDisplayConsoleVncLabel();
@DefaultStringValue("Spice")
String runOncePopupDisplayConsoleSpiceLabel();
@DefaultStringValue("Run Stateless")
String runOncePopupRunAsStatelessLabel();
@DefaultStringValue("Start in Pause Mode")
String runOncePopupRunAndPauseLabel();
@DefaultStringValue("Linux Boot Options:")
String runOncePopupLinuxBootOptionsLabel();
@DefaultStringValue("kernel path")
String runOncePopupKernelPathLabel();
@DefaultStringValue("initrd path")
String runOncePopupInitrdPathLabel();
@DefaultStringValue("kernel params")
String runOncePopupKernelParamsLabel();
@DefaultStringValue("Attach Floppy")
String runOncePopupAttachFloppyLabel();
@DefaultStringValue("Attach CD")
String runOncePopupAttachIsoLabel();
@DefaultStringValue("Windows Sysprep:")
String runOncePopupWindowsSysprepLabel();
@DefaultStringValue("Domain")
String runOncePopupSysPrepDomainNameLabel();
@DefaultStringValue("Alternate Credentials")
String runOnceUseAlternateCredentialsLabel();
@DefaultStringValue("User Name")
String runOncePopupSysPrepUserNameLabel();
@DefaultStringValue("Password")
String runOncePopupSysPrepPasswordLabel();
@DefaultStringValue("Boot Sequence:")
String runOncePopupBootSequenceLabel();
@DefaultStringValue("Name")
String makeTemplatePopupNameLabel();
@DefaultStringValue("Description")
String makeTemplatePopupDescriptionLabel();
@DefaultStringValue("Host Cluster")
String makeTemplateClusterLabel();
@DefaultStringValue("Quota")
String makeTemplateQuotaLabel();
@DefaultStringValue("Storage Domain")
String makeTemplateStorageDomainLabel();
@DefaultStringValue("Make Private")
String makeTemplateIsTemplatePrivateEditorLabel();
@DefaultStringValue("Description")
String virtualMachineSnapshotCreatePopupDescriptionLabel();
}
| 27.252101 | 128 | 0.748381 |
9961140272fdaa4c8015d67191035d0d4c2e87c5 | 15,543 | package com.github.ddth.queue.impl.universal;
import java.sql.Connection;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import com.github.ddth.commons.utils.MapUtils;
import com.github.ddth.dao.jdbc.IJdbcHelper;
import com.github.ddth.dao.jdbc.utils.BuildNamedParamsSqlResult;
import com.github.ddth.dao.jdbc.utils.DefaultNamedParamsFilters;
import com.github.ddth.dao.jdbc.utils.DefaultNamedParamsSqlBuilders;
import com.github.ddth.dao.jdbc.utils.ParamRawExpression;
import com.github.ddth.dao.utils.DaoException;
import com.github.ddth.queue.IQueueMessage;
import com.github.ddth.queue.internal.utils.QueueUtils;
/**
* Same as {@link BaseUniversalJdbcQueue}, but using a "less-locking" algorithm,
* requires only one single db table for both queue and ephemeral storage.
*
* <p>
* Queue db table schema:
* </p>
* <ul>
* <li>{@code queue_id}: {@code <ID>}, see {@link IQueueMessage#getId()}, {@link #COL_QUEUE_ID}</li>
* <li>{@code ephemeral_id}: {@code bigint, not null, default value = 0}, see {@link #COL_EPHEMERAL_ID}</li>
* <li>{@code msg_org_timestamp}: {@code datetime}, see {@link IQueueMessage#getTimestamp()}, {@link #COL_ORG_TIMESTAMP}</li>
* <li>{@code msg_timestamp}: {@code datetime}, see {@link IQueueMessage#getQueueTimestamp()}, {@link #COL_TIMESTAMP}</li>
* <li>{@code msg_num_requeues}: {@code int}, see {@link IQueueMessage#getNumRequeues()}, {@link #COL_NUM_REQUEUES}</li>
* <li>{@code msg_content}: {@code blob}, message's content, see {@link #COL_CONTENT}</li>
* </ul>
*
* @param <T>
* @author Thanh Nguyen <btnguyen2k@gmail.com>
* @since 1.0.0
*/
public abstract class BaseLessLockingUniversalJdbcQueue<T extends BaseUniversalQueueMessage<ID>, ID>
extends BaseUniversalJdbcQueue<T, ID> {
/**
* Table's column name to store queue-id
*/
public final static String COL_QUEUE_ID = "queue_id";
/**
* Table's column name to store ephemeral id
*/
public final static String COL_EPHEMERAL_ID = "ephemeral_id";
/**
* Table's column name to store message's original timestamp
*/
public final static String COL_ORG_TIMESTAMP = "msg_org_timestamp";
/**
* Table's column name to store message's timestamp
*/
public final static String COL_TIMESTAMP = "msg_timestamp";
/**
* Table's column name to store message's number of requeues
*/
public final static String COL_NUM_REQUEUES = "msg_num_requeues";
/**
* Table's column name to store message's content
*/
public final static String COL_CONTENT = "msg_content";
/**
* {@inheritDoc}
*/
@Override
public String getTableNameEphemeral() {
return getTableName();
}
/*----------------------------------------------------------------------*/
private final static String FIELD_COUNT = "num_entries";
private String SQL_COUNT = "SELECT COUNT(*) AS " + FIELD_COUNT + " FROM {0} WHERE " + COL_EPHEMERAL_ID + "=0";
private String SQL_COUNT_EPHEMERAL =
"SELECT COUNT(*) AS " + FIELD_COUNT + " FROM {0} WHERE " + COL_EPHEMERAL_ID + "!=0";
private BuildNamedParamsSqlResult NPSQL_GET_ORPHAN_MSGS;
private BuildNamedParamsSqlResult NPSQL_DELETE_MSG;
private BuildNamedParamsSqlResult NPSQL_PUT_NEW_TO_QUEUE, NPSQL_REPUT_TO_QUEUE;
private BuildNamedParamsSqlResult NPSQL_REQUEUE, NPSQL_REQUEUE_SILENT;
private BuildNamedParamsSqlResult NPSQL_GET_FIRST_AVAILABLE_MSG, NPSQL_ASSIGN_EPHEMERAL_ID;
/**
* {@inheritDoc}
*/
@Override
public BaseLessLockingUniversalJdbcQueue<T, ID> init() throws Exception {
/* count number of queue messages */
SQL_COUNT = MessageFormat.format(SQL_COUNT, getTableName());
/* count number of ephemeral messages */
SQL_COUNT_EPHEMERAL = MessageFormat.format(SQL_COUNT_EPHEMERAL, getTableNameEphemeral());
String[] COLUMNS_SELECT = { COL_QUEUE_ID + " AS " + UniversalIdStrQueueMessage.FIELD_QUEUE_ID,
COL_ORG_TIMESTAMP + " AS " + UniversalIdStrQueueMessage.FIELD_TIMESTAMP,
COL_TIMESTAMP + " AS " + UniversalIdStrQueueMessage.FIELD_QUEUE_TIMESTAMP,
COL_NUM_REQUEUES + " AS " + UniversalIdStrQueueMessage.FIELD_NUM_REQUEUES,
COL_CONTENT + " AS " + UniversalIdStrQueueMessage.FIELD_DATA };
/* read orphan messages from ephemeral storage */
NPSQL_GET_ORPHAN_MSGS = new DefaultNamedParamsSqlBuilders.SelectBuilder().withColumns(COLUMNS_SELECT)
.withFilterWhere(new DefaultNamedParamsFilters.FilterAnd().addFilter(
new DefaultNamedParamsFilters.FilterFieldValue(COL_EPHEMERAL_ID, "!=",
new ParamRawExpression("0")))
.addFilter(new DefaultNamedParamsFilters.FilterFieldValue(COL_TIMESTAMP, "<", "dummy")))
.withTableNames(getTableNameEphemeral()).build();
/* remove a message from storage completely */
NPSQL_DELETE_MSG = new DefaultNamedParamsSqlBuilders.DeleteBuilder(getTableName(),
new DefaultNamedParamsFilters.FilterFieldValue(COL_QUEUE_ID, "=", "dummy")).build();
/* put a new message (message without pre-set queue id) to queue, assuming column COL_QUEUE_ID is auto-number. */
NPSQL_PUT_NEW_TO_QUEUE = new DefaultNamedParamsSqlBuilders.InsertBuilder(getTableName(),
MapUtils.createMap(COL_EPHEMERAL_ID, "dummy", COL_ORG_TIMESTAMP, "dummy", COL_TIMESTAMP, "dummy",
COL_NUM_REQUEUES, "dummy", COL_CONTENT, "dummy")).build();
/* put a message with pre-set queue id to queue */
NPSQL_REPUT_TO_QUEUE = new DefaultNamedParamsSqlBuilders.InsertBuilder(getTableName(),
MapUtils.createMap(COL_QUEUE_ID, "dummy", COL_EPHEMERAL_ID, "dummy", COL_ORG_TIMESTAMP, "dummy",
COL_TIMESTAMP, "dummy", COL_NUM_REQUEUES, "dummy", COL_CONTENT, "dummy")).build();
/* requeue a message: move from ephemeral storage to queue storage by resetting value of COL_EPHEMERAL_ID */
NPSQL_REQUEUE = new DefaultNamedParamsSqlBuilders.UpdateBuilder(getTableName()).withValues(
MapUtils.createMap(COL_EPHEMERAL_ID, new ParamRawExpression("0"), COL_NUM_REQUEUES,
new ParamRawExpression(COL_NUM_REQUEUES + "+1"), COL_TIMESTAMP, "dummy")).withFilter(
new DefaultNamedParamsFilters.FilterAnd()
.addFilter(new DefaultNamedParamsFilters.FilterFieldValue(COL_QUEUE_ID, "=", "dummy"))
.addFilter(new DefaultNamedParamsFilters.FilterFieldValue(COL_EPHEMERAL_ID, "!=",
new ParamRawExpression("0")))).build();
/* requeue a message silently: move from ephemeral storage to queue storage by resetting value of COL_EPHEMERAL_ID */
NPSQL_REQUEUE_SILENT = new DefaultNamedParamsSqlBuilders.UpdateBuilder(getTableName())
.withValues(MapUtils.createMap(COL_EPHEMERAL_ID, new ParamRawExpression("0"))).withFilter(
new DefaultNamedParamsFilters.FilterAnd()
.addFilter(new DefaultNamedParamsFilters.FilterFieldValue(COL_QUEUE_ID, "=", "dummy"))
.addFilter(new DefaultNamedParamsFilters.FilterFieldValue(COL_EPHEMERAL_ID, "!=",
new ParamRawExpression("0")))).build();
/* get first available queue message */
NPSQL_GET_FIRST_AVAILABLE_MSG = new DefaultNamedParamsSqlBuilders.SelectBuilder().withColumns(COLUMNS_SELECT)
.withFilterWhere(new DefaultNamedParamsFilters.FilterFieldValue(COL_EPHEMERAL_ID, "=",
new ParamRawExpression("0"))).withLimit(1)
.withSorting(isFifo() ? MapUtils.createMap(COL_ORG_TIMESTAMP, Boolean.FALSE) : null)
.withTableNames(getTableName()).build();
/* assign ephemeral-id to message */
NPSQL_ASSIGN_EPHEMERAL_ID = new DefaultNamedParamsSqlBuilders.UpdateBuilder(getTableName())
.withValues(MapUtils.createMap(COL_EPHEMERAL_ID, "dummy")).withFilter(
new DefaultNamedParamsFilters.FilterAnd()
.addFilter(new DefaultNamedParamsFilters.FilterFieldValue(COL_QUEUE_ID, "=", "dummy"))
.addFilter(new DefaultNamedParamsFilters.FilterFieldValue(COL_EPHEMERAL_ID, "=",
new ParamRawExpression("0")))).build();
super.init();
return this;
}
/**
* {@inheritDoc}
*/
@Override
protected int queueSize(Connection conn) {
return doSize(conn, SQL_COUNT, FIELD_COUNT);
}
/**
* {@inheritDoc}
*/
@Override
protected int ephemeralSize(Connection conn) {
return doSize(conn, SQL_COUNT_EPHEMERAL, FIELD_COUNT);
}
/*----------------------------------------------------------------------*/
/**
* {@inheritDoc}
*/
@Override
protected T peekFromQueueStorage(Connection conn) {
// UNUSED
return null;
}
/**
* {@inheritDoc}
*/
@Override
protected T readFromEphemeralStorage(Connection conn, ID id) {
// UNUSED
return null;
}
/**
* {@inheritDoc}
*/
@Override
protected boolean putToEphemeralStorage(Connection conn, IQueueMessage<ID, byte[]> _msg) {
// UNUSED
return true;
}
/**
* {@inheritDoc}
*/
@Override
protected boolean removeFromQueueStorage(Connection conn, IQueueMessage<ID, byte[]> msg) {
// UNUSED
return true;
}
/**
* {@inheritDoc}
*/
@Override
protected boolean removeFromEphemeralStorage(Connection conn, IQueueMessage<ID, byte[]> msg) {
// UNUSED
return true;
}
/**
* {@inheritDoc}
*/
@Override
protected Collection<T> getOrphanMessagesFromEphemeralStorage(Connection conn, long thresholdTimestampMs) {
Date threshold = new Date(System.currentTimeMillis() - thresholdTimestampMs);
Map<String, Object> params = MapUtils.createMap(COL_TIMESTAMP, threshold);
return selectMessages(conn, NPSQL_GET_ORPHAN_MSGS.clause, params);
}
/**
* {@inheritDoc}
*/
@Override
protected boolean putToQueueStorage(Connection conn, IQueueMessage<ID, byte[]> msg) {
ID qid = msg.getId();
boolean isEmptyId = qid == null;
if (!isEmptyId) {
if (qid instanceof String) {
isEmptyId = StringUtils.isBlank(qid.toString());
}
if (qid instanceof Number) {
isEmptyId = ((Number) qid).longValue() == 0;
}
}
int numRows;
if (isEmptyId) {
Map<String, Object> params = MapUtils
.createMap(COL_EPHEMERAL_ID, 0, COL_ORG_TIMESTAMP, msg.getTimestamp(), COL_TIMESTAMP,
msg.getQueueTimestamp(), COL_NUM_REQUEUES, msg.getNumRequeues(), COL_CONTENT,
msg.getData());
numRows = getJdbcHelper().execute(conn, NPSQL_PUT_NEW_TO_QUEUE.clause, params);
} else {
Map<String, Object> params = MapUtils
.createMap(COL_QUEUE_ID, qid, COL_EPHEMERAL_ID, 0, COL_ORG_TIMESTAMP, msg.getTimestamp(),
COL_TIMESTAMP, msg.getQueueTimestamp(), COL_NUM_REQUEUES, msg.getNumRequeues(), COL_CONTENT,
msg.getData());
numRows = getJdbcHelper().execute(conn, NPSQL_REPUT_TO_QUEUE.clause, params);
}
return numRows > 0;
}
/*----------------------------------------------------------------------*/
/**
* {@inheritDoc}
*
* <p>Implementation: remove message completely from storage.</p>
*/
@Override
protected void _finishWithRetries(Connection conn, IQueueMessage<ID, byte[]> msg, int numRetries, int maxRetries) {
Map<String, Object> params = MapUtils.createMap(COL_QUEUE_ID, msg.getId());
executeWithRetries(numRetries, maxRetries, false, conn, NPSQL_DELETE_MSG.clause, params);
}
/** There is no overridden implementation of {@link #_queueWithRetries(Connection, IQueueMessage, int, int)} as it has been covered by {@link #putToQueueStorage(Connection, IQueueMessage)} */
/**
* {@inheritDoc}
*
* <p>Implementation:</p>
* <ul>
* <li>Reset value of {@link #COL_EPHEMERAL_ID} to {@code 0}.</li>
* <li>Update value of {@link #COL_NUM_REQUEUES} and {@link #COL_TIMESTAMP}.</li>
* </ul>
*/
@Override
protected boolean _requeueWithRetries(Connection conn, IQueueMessage<ID, byte[]> msg, int numRetries,
int maxRetries) {
Map<String, Object> params = MapUtils.createMap(COL_QUEUE_ID, msg.getId(), COL_TIMESTAMP, new Date());
int numRows = executeWithRetries(numRetries, maxRetries, false, conn, NPSQL_REQUEUE.clause, params);
return numRows > 0;
}
/**
* {@inheritDoc}
*
* <p>Implementation:</p>
* <ul>
* <li>Reset value of {@link #COL_EPHEMERAL_ID} to {@code 0}.</li>
* <li>Update value of {@link #COL_NUM_REQUEUES} and {@link #COL_TIMESTAMP}.</li>
* </ul>
*/
@Override
protected boolean _requeueSilentWithRetries(Connection conn, IQueueMessage<ID, byte[]> msg, int numRetries,
int maxRetries) {
Map<String, Object> params = MapUtils.createMap(COL_QUEUE_ID, msg.getId());
int numRows = executeWithRetries(numRetries, maxRetries, false, conn, NPSQL_REQUEUE_SILENT.clause, params);
return numRows > 0;
}
/**
* {@inheritDoc}
*
* <p>Implementation:</p>
* <ul>
* <li>Get the first available queue message.</li>
* <li>Generate a unique-id and assign to the message's {@link #COL_EPHEMERAL_ID}.</li>
* <li>Return the message object.</li>
* </ul>
*/
@Override
protected T _takeWithRetries(Connection conn, int numRetries, int maxRetries) {
IJdbcHelper jdbcHelper = getJdbcHelper();
return executeWithRetries(numRetries, maxRetries, () -> {
try {
jdbcHelper.startTransaction(conn);
conn.setTransactionIsolation(getTransactionIsolationLevel());
Map<String, Object> dbRow = jdbcHelper.executeSelectOne(conn, NPSQL_GET_FIRST_AVAILABLE_MSG.clause);
T msg = dbRow != null ? createMessge(dbRow) : null;
if (msg != null) {
long ephemeralId = QueueUtils.IDGEN.generateId64();
Map<String, Object> params = MapUtils
.createMap(COL_EPHEMERAL_ID, ephemeralId, COL_QUEUE_ID, msg.getId());
int numRows = jdbcHelper.execute(conn, NPSQL_ASSIGN_EPHEMERAL_ID.clause, params);
msg = numRows > 0 ? msg : null;
}
if (msg == null) {
jdbcHelper.rollbackTransaction(conn);
} else {
jdbcHelper.commitTransaction(conn);
}
return msg;
} catch (Exception e) {
jdbcHelper.rollbackTransaction(conn);
throw e instanceof DaoException ? (DaoException) e : new DaoException(e);
}
});
}
}
| 43.295265 | 195 | 0.629158 |
47347cfcb2e3a1bb050743d9f1a3b3629864f233 | 615 | package com.yeungeek.basicjava.data.list;
import java.util.LinkedList;
import java.util.List;
public class LinkedListTest {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
println(list);
System.out.println(list.removeLast());
println(list);
list.add(6);
println(list);
}
private static void println(List<Integer> list) {
for (Integer i : list) {
System.out.println(i);
}
}
}
| 22.777778 | 54 | 0.565854 |
5e69e2bc9d552ef9dd774e46dc4e453311f3fdc4 | 1,901 | package com.example.asus.androiddrinkshopserver.Utils;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import com.example.asus.androiddrinkshopserver.Interface.UploadCallBack;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;
public class ProgressRequestBody extends RequestBody {
//this class help us to upload an image to server
private File file;
private static final int DEFAULT_BUFFER_SIZE = 4096;
private UploadCallBack listener;
public ProgressRequestBody(File file, UploadCallBack listener) {
this.file = file;
this.listener = listener;
}
@Override
public long contentLength() throws IOException {
return file.length();
}
@Nullable
@Override
public MediaType contentType() {
return MediaType.parse("image/*");
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
long fileLength = file.length();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
FileInputStream in = new FileInputStream(file);
long uploaded = 0;
try {
int read;
Handler handler = new Handler(Looper.getMainLooper());
while ((read = in.read(buffer)) != -1){
handler.post(new ProgressUpdate(uploaded , fileLength));
uploaded += read;
sink.write(buffer , 0 , read);
}
}
finally {
in.close();
}
}
private class ProgressUpdate implements Runnable {
private long uploaded , fileLength;
public ProgressUpdate(long uploaded, long fileLength) {
this.fileLength = fileLength;
this.uploaded = uploaded;
}
@Override
public void run() {
listener.onProgressUpdate((int)(100*uploaded/fileLength));
}
}
} | 23.182927 | 72 | 0.678064 |
7ac6f9ea7ee21973b9e7582305217601221f72fb | 1,354 | package top.jasonkayzk.ezshare.system.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import top.jasonkayzk.ezshare.common.entity.QueryRequest;
import top.jasonkayzk.ezshare.common.exception.CacheException;
import top.jasonkayzk.ezshare.system.entity.Role;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* @author Jasonkay
*/
public interface IRoleService extends IService<Role> {
/**
* 分页查询角色
*
* @param role 其他查询参数
*
* @param request 分页参数
*
* @return 角色列表
*/
IPage<Role> findRoles(Role role, QueryRequest request);
/**
* 根据username
*
* @param username 查询角色信息
*
* @return 用户角色列表
*/
List<Role> findUserRole(String username);
/**
* 根据角色名称查询角色信息
*
* @param roleName 角色名称
*
* @return 角色信息
*/
Role findByName(String roleName);
/**
* 增加角色
*
* @param role 角色
*/
void createRole(Role role);
/**
* 根据Id删除角色
*
* @param roleIds 角色Id
*/
void deleteRoles(String[] roleIds) throws CacheException, JsonProcessingException;
/**
* 更新角色信息
*
* @param role 角色
*/
void updateRole(Role role) throws CacheException, JsonProcessingException;
}
| 19.911765 | 86 | 0.636632 |
beb1042b5b51e7b403ff6aff73d0865f02ab7271 | 223 | package cn.chenzw.excel.magic.core.support.converter;
/**
* 字段值转换器
* @param <A>
* @param <T>
*/
public interface AbstractExcelColumnConverter<A, T> {
void initialize(A annotation);
T convert(String value);
}
| 15.928571 | 53 | 0.681614 |
6cf36daee096fc85cc397e87390b42baeab72172 | 1,602 | package org.jruby.ir.instructions.defined;
import org.jruby.ir.IRVisitor;
import org.jruby.ir.Operation;
import org.jruby.ir.instructions.FixedArityInstr;
import org.jruby.ir.instructions.Instr;
import org.jruby.ir.operands.Operand;
import org.jruby.ir.persistence.IRReaderDecoder;
import org.jruby.ir.persistence.IRWriterEncoder;
import org.jruby.ir.transformations.inlining.CloneInfo;
import org.jruby.parser.StaticScope;
import org.jruby.runtime.DynamicScope;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
public class RestoreErrorInfoInstr extends Instr implements FixedArityInstr {
public RestoreErrorInfoInstr(Operand arg) {
super(Operation.RESTORE_ERROR_INFO, new Operand[] { arg });
}
public Operand getArg() {
return operands[0];
}
@Override
public Instr clone(CloneInfo ii) {
return new RestoreErrorInfoInstr(getArg().cloneForInlining(ii));
}
@Override
public void encode(IRWriterEncoder e) {
super.encode(e);
e.encode(getArg());
}
public static RestoreErrorInfoInstr decode(IRReaderDecoder d) {
return new RestoreErrorInfoInstr(d.decodeOperand());
}
@Override
public Object interpret(ThreadContext context, StaticScope currScope, DynamicScope currDynScope, IRubyObject self, Object[] temp) {
context.setErrorInfo((IRubyObject) getArg().retrieve(context, self, currScope, currDynScope, temp));
return null;
}
@Override
public void visit(IRVisitor visitor) {
visitor.RestoreErrorInfoInstr(this);
}
}
| 30.807692 | 135 | 0.735955 |
8cdf4537329cce1cc96efe2cd696e430d1e7cd4e | 6,085 | /* This file is part of VoltDB.
* Copyright (C) 2008-2020 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS 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.voltdb.regressionsuites;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.voltdb.BackendTarget;
import org.voltdb.compiler.VoltProjectBuilder;
import org.voltdb.compiler.VoltProjectBuilder.RoleInfo;
import org.voltdb.compiler.VoltProjectBuilder.UserInfo;
import org.voltdb.compiler.deploymentfile.ServerExportEnum;
import org.voltdb.export.ExportDataProcessor;
import org.voltdb.export.ExportTestClient;
import org.voltdb.export.ExportTestVerifier;
import org.voltdb.export.TestExportBaseSocketExport;
import org.voltdb.utils.VoltFile;
import com.google_voltpatches.common.collect.ImmutableMap;
public class TestExportWithMisconfiguredExportClient extends RegressionSuite {
private static LocalCluster m_config;
public static final RoleInfo GROUPS[] = new RoleInfo[] {
new RoleInfo("export", false, false, false, false, false, false),
new RoleInfo("proc", true, false, true, true, false, false),
new RoleInfo("admin", true, false, true, true, false, false)
};
public static final UserInfo[] USERS = new UserInfo[] {
new UserInfo("export", "export", new String[]{"export"}),
new UserInfo("default", "password", new String[]{"proc"}),
new UserInfo("admin", "admin", new String[]{"proc", "admin"})
};
/*
* Test suite boilerplate
*/
public TestExportWithMisconfiguredExportClient(final String s) {
super(s);
}
@Override
public void setUp() throws Exception
{
m_username = "default";
m_password = "password";
VoltFile.recursivelyDelete(new File("/tmp/" + System.getProperty("user.name")));
File f = new File("/tmp/" + System.getProperty("user.name"));
f.mkdirs();
ExportTestVerifier.m_paused = false;
}
@Override
public void tearDown() throws Exception {
super.tearDown();
ExportTestClient.clear();
}
//
// Only notify the verifier of the first set of rows. Expect that the rows after will be truncated
// when the snapshot is restored
// @throws Exception
//
public void testFailureOnMissingNonce() throws Exception {
if (isValgrind()) {
return;
}
System.out.println("testFailureOnMissingNonce");
m_config.startUp();
PipeToFile pf = m_config.m_pipes.get(0);
Thread.currentThread().sleep(10000);
BufferedReader bi = new BufferedReader(new FileReader(new File(pf.m_filename)));
String line;
boolean failed = true;
final CharSequence cs = "doing what I am being told";
while ((line = bi.readLine()) != null) {
if (line.contains(cs)) {
failed = false;
break;
}
}
assertFalse(failed);
}
static public junit.framework.Test suite() throws Exception
{
final MultiConfigSuiteBuilder builder =
new MultiConfigSuiteBuilder(TestExportWithMisconfiguredExportClient.class);
System.setProperty(ExportDataProcessor.EXPORT_TO_TYPE, "org.voltdb.export.ExportTestClient");
String dexportClientClassName = System.getProperty("exportclass", "");
System.out.println("Test System override export class is: " + dexportClientClassName);
Map<String, String> additionalEnv = new HashMap<String, String>();
additionalEnv.put(ExportDataProcessor.EXPORT_TO_TYPE, "org.voltdb.export.ExportTestClient");
VoltProjectBuilder project = new VoltProjectBuilder();
project.setUseDDLSchema(true);
project.setSecurityEnabled(true, true);
project.addRoles(GROUPS);
project.addUsers(USERS);
project.addSchema(TestExportBaseSocketExport.class.getResource("export-nonulls-ddl-with-target.sql"));
Properties props = new Properties();
// omit nonce
props.putAll(ImmutableMap.<String, String>of(
"type", "csv",
"batched", "false",
"with-schema", "true",
"complain", "true",
"outdir", "/tmp/" + System.getProperty("user.name")));
project.addExport(true /* enabled */, ServerExportEnum.CUSTOM, props);
project.addPartitionInfo("S_NO_NULLS", "PKEY");
project.addProcedures(TestExportBaseSocketExport.NONULLS_PROCEDURES);
/*
* compile the catalog all tests start with
*/
m_config = new LocalCluster("export-ddl-cluster-rep.jar", 8, 1, 0,
BackendTarget.NATIVE_EE_JNI, LocalCluster.FailureState.ALL_RUNNING, true, additionalEnv);
m_config.setExpectedToCrash(true);
m_config.setHasLocalServer(false);
boolean compile = m_config.compile(project);
assertTrue(compile);
builder.addServerConfig(m_config);
return builder;
}
}
| 38.03125 | 110 | 0.679704 |
021be15676d3e95abbb90d5ebd54d464c87f9af9 | 2,494 | package rocks.cleanstone.storage.engine.rocksdb;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.rocksdb.*;
import rocks.cleanstone.data.KeyValueDataRepository;
import javax.annotation.Nullable;
import java.nio.file.Path;
/**
* LevelDB data source which supports key-value based IO
*/
@Slf4j
public class RocksDBDataSource implements KeyValueDataRepository<ByteBuf, ByteBuf>, AutoCloseable {
static {
RocksDB.loadLibrary();
}
private final Path path;
private final RocksDB database;
public RocksDBDataSource(Path path, Options options) throws RocksDBException {
this.path = path;
if (options == null) {
options = new Options();
}
options.setCreateIfMissing(true);
log.info("Opening Database: " + path.toFile().getPath());
database = RocksDB.open(options, path.toFile().getPath());
}
public RocksDBDataSource(Path path) throws RocksDBException {
this(path, null);
}
@Override
public void close() {
try {
database.closeE();
} catch (RocksDBException e) {
log.error("Error occurred while closing LevelDB '" + path.getFileName() + "'", e);
}
}
@SneakyThrows
@Nullable
@Override
public ByteBuf get(ByteBuf key) {
byte[] keyBytes = new byte[key.readableBytes()];
key.readBytes(keyBytes);
byte[] value = database.get(keyBytes);
return value != null ? Unpooled.wrappedBuffer(value) : null;
}
@SneakyThrows
@Override
public void set(ByteBuf key, ByteBuf value) {
byte[] keyBytes = new byte[key.readableBytes()];
key.readBytes(keyBytes);
if (value == null) {
database.delete(keyBytes);
return;
}
byte[] valueBytes = new byte[value.readableBytes()];
value.readBytes(valueBytes);
database.put(keyBytes, valueBytes);
}
@SneakyThrows
@Override
public void drop() {
WriteOptions options = new WriteOptions();
WriteBatch batch = new WriteBatch();
RocksIterator iterator = database.newIterator();
iterator.seekToFirst();
for (iterator.seekToFirst(); iterator.isValid(); iterator.next()) {
batch.delete(iterator.key());
}
database.write(options, batch);
log.info("dropped rocksdb at {}", path);
}
}
| 28.022472 | 99 | 0.630313 |
a3dbc2bd79a3c1ae6dc76aa30e95965bceb01ef1 | 27,772 | /*
* Copyright 2019 EIS Ltd and/or one of its affiliates.
*
* 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 kraken.el.ast.builder;
import kraken.el.Kel;
import kraken.el.Kel.TemplateContext;
import kraken.el.Kel.TemplateTextContext;
import kraken.el.KelBaseVisitor;
import kraken.el.ast.*;
import kraken.el.ast.InlineMap.KeyValuePair;
import kraken.el.ast.token.Token;
import kraken.el.scope.Scope;
import kraken.el.scope.ScopeType;
import kraken.el.scope.SymbolTable;
import kraken.el.scope.symbol.FunctionParameter;
import kraken.el.scope.symbol.FunctionSymbol;
import kraken.el.scope.symbol.VariableSymbol;
import kraken.el.scope.type.ArrayType;
import kraken.el.scope.type.GenericType;
import kraken.el.scope.type.Type;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.misc.Interval;
import org.antlr.v4.runtime.tree.TerminalNode;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
/**
* Traverses over Kraken Expression Language Parse Tree which is parsed by ANTLR4 from grammar
*
* @author mulevicius
*/
public class AstGeneratingVisitor extends KelBaseVisitor<Expression> {
private Map<String, Function> functions = new HashMap<>();
private Collection<Reference> references = new ArrayList<>();
private Deque<Scope> currentScope = new ArrayDeque<>();
public AstGeneratingVisitor(Scope scope) {
this.currentScope.add(scope);
}
// Precedence
@Override
public Expression visitPrecedence(Kel.PrecedenceContext ctx) {
return visit(ctx.value());
}
@Override
public Expression visitPrecedencePredicate(Kel.PrecedencePredicateContext ctx) {
return visit(ctx.valuePredicate());
}
@Override
public Expression visitPrecedenceValue(Kel.PrecedenceValueContext ctx) {
return visit(ctx.indexValue());
}
@Override
public Expression visitReferencePrecedence(Kel.ReferencePrecedenceContext ctx) {
return visit(ctx.reference());
}
@Override
public Expression visitCast(Kel.CastContext ctx) {
Reference reference = (Reference) visit(ctx.reference());
Scope scope = scope();
TypeLiteral typeLiteral = new TypeLiteral(ctx.type().getText(), scope, token(ctx));
return new Cast(typeLiteral, reference, scope, token(ctx));
}
@Override
public Expression visitTypeComparison(Kel.TypeComparisonContext ctx) {
Expression left = visit(ctx.value());
Identifier typeIdentifier = (Identifier) visit(ctx.identifier());
Scope scope = scope();
TypeLiteral type = new TypeLiteral(typeIdentifier.getIdentifier(), scope, token(ctx));
if(ctx.OP_INSTANCEOF() != null) {
return new InstanceOf(left, type, scope(), token(ctx));
}
if(ctx.OP_TYPEOF() != null) {
return new TypeOf(left, type, scope(), token(ctx));
}
throw new IllegalStateException("Unexpected state when parsing expression");
}
@Override
public Expression visitTypeComparisonPredicate(Kel.TypeComparisonPredicateContext ctx) {
Expression left = visit(ctx.value());
Identifier typeIdentifier = (Identifier) visit(ctx.identifier());
Scope scope = scope();
TypeLiteral type = new TypeLiteral(typeIdentifier.getIdentifier(), scope, token(ctx));
if(ctx.OP_INSTANCEOF() != null) {
return new InstanceOf(left, type, scope(), token(ctx));
}
if(ctx.OP_TYPEOF() != null) {
return new TypeOf(left, type, scope(), token(ctx));
}
throw new IllegalStateException("Unexpected state when parsing expression");
}
// RegExp
@Override
public Expression visitMatchesRegExp(Kel.MatchesRegExpContext ctx) {
Expression left = visit(ctx.value());
String regexp = Literals.stripQuotes(ctx.STRING().getText());
return new MatchesRegExp(left, regexp, scope(), token(ctx));
}
@Override
public Expression visitMatchesRegExpPredicate(Kel.MatchesRegExpPredicateContext ctx) {
Expression left = visit(ctx.value());
String regexp = Literals.stripQuotes(ctx.STRING().getText());
return new MatchesRegExp(left, regexp, scope(), token(ctx));
}
// Multiplication Division Modulus
private Expression resolveMultiplicationOrDivision(
Kel.ValueContext leftCtx,
Kel.ValueContext rightCtx,
TerminalNode division,
TerminalNode multiplication,
TerminalNode modulus,
Token token
) {
Expression left = visit(leftCtx);
Expression right = visit(rightCtx);
if (division != null) {
return new Division(left, right, scope(), token);
}
if (multiplication != null) {
return new Multiplication(left, right, scope(), token);
}
if (modulus != null) {
return new Modulus(left, right, scope(), token);
}
throw new IllegalStateException("Unexpected state when parsing expression");
}
@Override
public Expression visitMultiplicationOrDivisionValue(Kel.MultiplicationOrDivisionValueContext ctx) {
return resolveMultiplicationOrDivision(
ctx.value(0),
ctx.value(1),
ctx.OP_DIV(),
ctx.OP_MULT(),
ctx.OP_MOD(),
token(ctx)
);
}
@Override
public Expression visitMultiplicationOrDivision(Kel.MultiplicationOrDivisionContext ctx) {
return resolveMultiplicationOrDivision(
ctx.value(0),
ctx.value(1),
ctx.OP_DIV(),
ctx.OP_MULT(),
ctx.OP_MOD(),
token(ctx)
);
}
// Subtraction Addition
private Expression resolveSubtractionOrAddition(
Kel.ValueContext leftCtx,
Kel.ValueContext rightCtx,
TerminalNode subtraction,
TerminalNode addition,
Token token
) {
Expression left = visit(leftCtx);
Expression right = visit(rightCtx);
if (subtraction != null) {
return new Subtraction(left, right, scope(), token);
}
if (addition != null) {
return new Addition(left, right, scope(), token);
}
throw new IllegalStateException("Unexpected state when parsing expression");
}
@Override
public Expression visitSubtractionOrAddition(Kel.SubtractionOrAdditionContext ctx) {
return resolveSubtractionOrAddition(
ctx.value(0),
ctx.value(1),
ctx.OP_MINUS(),
ctx.OP_ADD(),
token(ctx)
);
}
@Override
public Expression visitSubtractionOrAdditionValue(Kel.SubtractionOrAdditionValueContext ctx) {
return resolveSubtractionOrAddition(
ctx.value(0),
ctx.value(1),
ctx.OP_MINUS(),
ctx.OP_ADD(),
token(ctx)
);
}
private ReferenceValue resolveReferenceValueValue(Kel.ReferenceContext ctx, TerminalNode thiz) {
Reference reference = (Reference) visit(ctx);
references.add(reference);
return new ReferenceValue(thiz != null, reference, scope(), reference.getEvaluationType(), token(ctx));
}
@Override
public Expression visitReferenceValueValue(Kel.ReferenceValueValueContext ctx) {
return resolveReferenceValueValue(ctx.reference(), ctx.THIS());
}
@Override
public Expression visitReferenceValue(Kel.ReferenceValueContext ctx) {
return resolveReferenceValueValue(ctx.reference(), ctx.THIS());
}
// This
@Override
public Expression visitThisValue(Kel.ThisValueContext ctx) {
return new This(scope(), token(ctx));
}
@Override
public Expression visitThis(Kel.ThisContext ctx) {
return new This(scope(), token(ctx));
}
// Negation
@Override
public Expression visitNegationPredicate(Kel.NegationPredicateContext ctx) {
return new Negation(visit(ctx.value()), scope(), token(ctx));
}
@Override
public Expression visitNegation(Kel.NegationContext ctx) {
return new Negation(visit(ctx.value()), scope(), token(ctx));
}
// Numerical Comparison
private Expression resolveNumericalComparisonPredicate(
Kel.ValueContext leftCtx,
Kel.ValueContext rightCtx,
TerminalNode less,
TerminalNode lessEq,
TerminalNode more,
TerminalNode moreEq,
Token token
) {
Expression left = visit(leftCtx);
Expression right = visit(rightCtx);
if (less != null) {
return new LessThan(left, right, scope(), token);
}
if (lessEq != null) {
return new LessThanOrEquals(left, right, scope(), token);
}
if (more != null) {
return new MoreThan(left, right, scope(), token);
}
if (moreEq != null) {
return new MoreThanOrEquals(left, right, scope(), token);
}
throw new IllegalStateException("Unexpected state when parsing expression");
}
@Override
public Expression visitNumericalComparisonPredicate(Kel.NumericalComparisonPredicateContext ctx) {
return resolveNumericalComparisonPredicate(
ctx.value(0),
ctx.value(1),
ctx.OP_LESS(),
ctx.OP_LESS_EQUALS(),
ctx.OP_MORE(),
ctx.OP_MORE_EQUALS(),
token(ctx)
);
}
@Override
public Expression visitNumericalComparison(Kel.NumericalComparisonContext ctx) {
return resolveNumericalComparisonPredicate(
ctx.value(0),
ctx.value(1),
ctx.OP_LESS(),
ctx.OP_LESS_EQUALS(),
ctx.OP_MORE(),
ctx.OP_MORE_EQUALS(),
token(ctx)
);
}
// Equality comparison
private Expression resolveEqualityComparisonPredicate(
Kel.ValueContext leftCtx,
Kel.ValueContext rightCtx,
TerminalNode equals,
TerminalNode notEquals,
Token token
) {
Expression left = visit(leftCtx);
Expression right = visit(rightCtx);
if (equals != null) {
return new Equals(left, right, scope(), token);
}
if (notEquals != null) {
return new NotEquals(left, right, scope(), token);
}
throw new IllegalStateException("Unexpected state when parsing expression");
}
@Override
public Expression visitEqualityComparisonPredicate(Kel.EqualityComparisonPredicateContext ctx) {
return resolveEqualityComparisonPredicate(
ctx.value(0),
ctx.value(1),
ctx.OP_EQUALS(),
ctx.OP_NOT_EQUALS(),
token(ctx)
);
}
@Override
public Expression visitEqualityComparison(Kel.EqualityComparisonContext ctx) {
return resolveEqualityComparisonPredicate(
ctx.value(0),
ctx.value(1),
ctx.OP_EQUALS(),
ctx.OP_NOT_EQUALS(),
token(ctx)
);
}
// Conjunction
@Override
public Expression visitConjunctionPredicate(Kel.ConjunctionPredicateContext ctx) {
Expression left = visit(ctx.value(0));
Expression right = visit(ctx.value(1));
return new And(left, right, scope(), token(ctx));
}
@Override
public Expression visitConjunction(Kel.ConjunctionContext ctx) {
Expression left = visit(ctx.value(0));
Expression right = visit(ctx.value(1));
return new And(left, right, scope(), token(ctx));
}
// Disjunction
@Override
public Expression visitDisjunctionPredicate(Kel.DisjunctionPredicateContext ctx) {
Expression left = visit(ctx.value(0));
Expression right = visit(ctx.value(1));
return new Or(left, right, scope(), token(ctx));
}
@Override
public Expression visitDisjunction(Kel.DisjunctionContext ctx) {
Expression left = visit(ctx.value(0));
Expression right = visit(ctx.value(1));
return new Or(left, right, scope(), token(ctx));
}
@Override
public Expression visitAccessByIndex(Kel.AccessByIndexContext ctx) {
Reference collection = (Reference) visit(ctx.collection);
Deque<Scope> pathScopes = unwrapParentScopeOfPath();
Expression index = visit(ctx.indices().indexValue());
wrapPathScopes(pathScopes);
return new AccessByIndex(collection, index, scope(), token(ctx));
}
private void wrapPathScopes(Deque<Scope> pathScopes) {
for(Scope pathScope : pathScopes) {
currentScope.push(pathScope);
}
}
private Deque<Scope> unwrapParentScopeOfPath() {
Deque<Scope> pathScopes = new LinkedList<>();
while(currentScope.peek().getScopeType().equals(ScopeType.PATH)) {
pathScopes.addFirst(currentScope.pop());
}
return pathScopes;
}
@Override
public Expression visitExpression(Kel.ExpressionContext ctx) {
if (ctx.value() == null) {
return new Null(scope(), token(ctx));
}
return visit(ctx.value());
}
@Override
public Expression visitNegative(Kel.NegativeContext ctx) {
return unwrapNegatedNumberLiteralIfNeeded(visit(ctx.value()), token(ctx));
}
@Override
public Expression visitNegativeValue(Kel.NegativeValueContext ctx) {
return unwrapNegatedNumberLiteralIfNeeded(visit(ctx.value()), token(ctx));
}
private Expression unwrapNegatedNumberLiteralIfNeeded(Expression negatedExpression, Token token) {
if(negatedExpression instanceof NumberLiteral) {
BigDecimal positiveDecimal = ((NumberLiteral) negatedExpression).getValue();
return new NumberLiteral(positiveDecimal.negate(), scope(), token);
}
return new Negative(negatedExpression, scope(), token);
}
@Override
public Expression visitExponent(Kel.ExponentContext ctx) {
Expression left = visit(ctx.value(0));
Expression right = visit(ctx.value(1));
return new Exponent(left, right, scope(), token(ctx));
}
@Override
public Expression visitExponentValue(Kel.ExponentValueContext ctx) {
Expression left = visit(ctx.value(0));
Expression right = visit(ctx.value(1));
return new Exponent(left, right, scope(), token(ctx));
}
@Override
public Expression visitIn(Kel.InContext ctx) {
Expression left = visit(ctx.value(0));
Expression right = visit(ctx.value(1));
return new In(left, right, scope(), token(ctx));
}
@Override
public Expression visitInPredicate(Kel.InPredicateContext ctx) {
Expression left = visit(ctx.value(0));
Expression right = visit(ctx.value(1));
return new In(left, right, scope(), token(ctx));
}
@Override
public Expression visitPath(Kel.PathContext ctx) {
Reference object = (Reference) visit(ctx.object);
Type evaluationType = object.getEvaluationType();
if(object.getEvaluationType() instanceof ArrayType) {
evaluationType = ((ArrayType) object.getEvaluationType()).getElementType();
}
currentScope.push(new Scope(ScopeType.PATH, null, evaluationType));
Reference property = (Reference) visit(ctx.property);
currentScope.pop();
return new Path(object, property, scope(), token(ctx));
}
@Override
public Expression visitFilter(Kel.FilterContext ctx) {
Reference collection = (Reference) visit(ctx.filterCollection);
Expression predicate = null;
if(ctx.predicate() != null) {
currentScope.push(new Scope(ScopeType.FILTER, scope(), unwrapTypeForIteration(collection.getEvaluationType())));
predicate = ctx.predicate().valuePredicate() != null
? visit(ctx.predicate().valuePredicate())
: visit(ctx.predicate().value());
currentScope.pop();
}
return new CollectionFilter(collection, predicate, scope(), token(ctx));
}
@Override
public Expression visitIfValue(Kel.IfValueContext ctx) {
Expression condition = visit(ctx.condition);
Expression then = visit(ctx.thenExpression);
Expression ifElse = ctx.elseExpression != null ? visit(ctx.elseExpression) : null;
return new If(condition, then, ifElse, scope(), token(ctx));
}
@Override
public Expression visitForEach(Kel.ForEachContext ctx) {
Expression collection = visit(ctx.collection);
String var = ctx.var.getText();
Type forScopeType = buildTypeForIterationContext(collection, var);
currentScope.push(new Scope(ScopeType.FOR_RETURN_EXPRESSION, scope(), forScopeType));
Expression returnExpression = visit(ctx.returnExpression);
currentScope.pop();
return new ForEach(var, collection, returnExpression, scope(), token(ctx));
}
@Override
public Expression visitForEvery(Kel.ForEveryContext ctx) {
return buildForEvery(ctx.var, ctx.collection, ctx.returnExpression, token(ctx));
}
@Override
public Expression visitForEveryPredicate(Kel.ForEveryPredicateContext ctx) {
return buildForEvery(ctx.var, ctx.collection, ctx.returnExpression, token(ctx));
}
@Override
public Expression visitForSome(Kel.ForSomeContext ctx) {
return buildForSome(ctx.var, ctx.collection, ctx.returnExpression, token(ctx));
}
@Override
public Expression visitForSomePredicate(Kel.ForSomePredicateContext ctx) {
return buildForSome(ctx.var, ctx.collection, ctx.returnExpression, token(ctx));
}
private Expression buildForSome(Kel.IdentifierContext varCtx,
Kel.ValueContext collectionCtx,
Kel.ValueContext returnExpressionCtx,
Token token) {
Expression collection = visit(collectionCtx);
String var = varCtx.getText();
Type forScopeType = buildTypeForIterationContext(collection, var);
currentScope.push(new Scope(ScopeType.FOR_RETURN_EXPRESSION, scope(), forScopeType));
Expression returnExpression = visit(returnExpressionCtx);
currentScope.pop();
return new ForSome(var, collection, returnExpression, scope(), token);
}
private Expression buildForEvery(Kel.IdentifierContext varCtx,
Kel.ValueContext collectionCtx,
Kel.ValueContext returnExpressionCtx,
Token token) {
Expression collection = visit(collectionCtx);
String var = varCtx.getText();
Type forScopeType = buildTypeForIterationContext(collection, var);
currentScope.push(new Scope(ScopeType.FOR_RETURN_EXPRESSION, scope(), forScopeType));
Expression returnExpression = visit(returnExpressionCtx);
currentScope.pop();
return new ForEvery(var, collection, returnExpression, scope(), token);
}
private Type buildTypeForIterationContext(Expression collection, String varName) {
return new Type("for_" + varName + "_" + UUID.randomUUID().toString(),
new SymbolTable(Collections.emptyList(),
Map.of(varName,
new VariableSymbol(varName,
unwrapTypeForIteration(collection.getEvaluationType())
)
)
)
);
}
@Override
public Expression visitInlineArray(Kel.InlineArrayContext ctx) {
List<Expression> items = ctx.valueList() == null
? Collections.emptyList()
: ctx.valueList().value().stream()
.map(valueContext -> visit(valueContext))
.collect(Collectors.toList());
return new InlineArray(items, scope(), token(ctx));
}
@Override
public Expression visitInlineMap(Kel.InlineMapContext ctx) {
List<KeyValuePair> keyValuePairs = ctx.keyValuePairs().keyValuePair().stream()
.map(this::toKeyValuePair)
.collect(Collectors.toList());
return new InlineMap(keyValuePairs, scope(), token(ctx));
}
private KeyValuePair toKeyValuePair(Kel.KeyValuePairContext ctx) {
return new KeyValuePair(Literals.stripQuotes(ctx.key.getText()), visit(ctx.value()));
}
@Override
public Expression visitIdentifierReference(Kel.IdentifierReferenceContext ctx) {
return visit(ctx.identifier());
}
@Override
public Expression visitIdentifier(Kel.IdentifierContext ctx) {
return new Identifier(ctx.getText(), scope(), token(ctx));
}
@Override
public Expression visitBoolean(Kel.BooleanContext ctx) {
return new BooleanLiteral(Literals.getBoolean(ctx.BOOL().getText()), scope(), token(ctx));
}
@Override
public Expression visitDecimal(Kel.DecimalContext ctx) {
try {
return new NumberLiteral(Literals.getDecimal(ctx.decimalLiteral().getText()), scope(), token(ctx));
} catch (ArithmeticException e) {
throw new IllegalStateException(
"Cannot parse decimal literal without loss of precision, " +
"because decimal literal exceeds 64bit Decimal prevision: " + ctx.decimalLiteral().getText()
);
}
}
@Override
public Expression visitString(Kel.StringContext ctx) {
return new StringLiteral(Literals.stripQuotes(ctx.STRING().getText()), scope(), token(ctx));
}
@Override
public Expression visitNull(Kel.NullContext ctx) {
return new Null(scope(), token(ctx));
}
@Override
public Expression visitDateTime(Kel.DateTimeContext ctx) {
LocalDateTime dateTime = Literals.getDateTime(ctx.TIME_TOKEN().getText());
return new DateTimeLiteral(dateTime, scope(), token(ctx));
}
@Override
public Expression visitDate(Kel.DateContext ctx) {
LocalDate date = Literals.getDate(ctx.DATE_TOKEN().getText());
return new DateLiteral(date, scope(), token(ctx));
}
@Override
public Expression visitFunction(Kel.FunctionContext ctx) {
String functionName = ctx.functionCall().functionName.getText();
List<Expression> parameters = ctx.functionCall().arguments != null
? parseArguments(ctx.functionCall().arguments)
: Collections.emptyList();
Scope scope = scope();
FunctionSymbol functionSymbol = resolveFunctionOrThrow(scope, functionName, parameters.size());
Type evaluationType = functionSymbol.getType();
Type scalarReturnType = unwrapScalarType(functionSymbol.getType());
if(scalarReturnType instanceof GenericType) {
FunctionParameter parameter = functionSymbol.findGenericParameter((GenericType)scalarReturnType);
Type type = parameters.get(parameter.getParameterIndex()).getEvaluationType();
evaluationType = calculateGenericEvaluationType(functionSymbol.getType(), unwrapScalarType(type));
}
Function function = new Function(functionName, parameters, scope, evaluationType, token(ctx));
functions.put(function.getFunctionName(), function);
return function;
}
private Type calculateGenericEvaluationType(Type functionEvaluationType, Type genericType) {
if(functionEvaluationType instanceof ArrayType) {
Type subtype = ((ArrayType) functionEvaluationType).getElementType();
return ArrayType.of(calculateGenericEvaluationType(subtype, genericType));
}
if(functionEvaluationType instanceof GenericType) {
return genericType;
}
return functionEvaluationType;
}
@Override
public Expression visitTemplate(TemplateContext ctx) {
List<Expression> templateExpressions = new ArrayList<>();
List<String> templateParts = new ArrayList<>();
StringBuilder currentTemplatePart = new StringBuilder();
for(TemplateTextContext t : ctx.templateText()) {
if(t.TEMPLATE_TEXT() != null) {
String text = escapeTemplate(t.TEMPLATE_TEXT().getText());
currentTemplatePart.append(text);
} else if(t.templateExpression().value() != null) {
templateParts.add(currentTemplatePart.toString());
currentTemplatePart = new StringBuilder();
Expression templateExpression = visit(t.templateExpression().value());
templateExpressions.add(templateExpression);
}
}
templateParts.add(currentTemplatePart.toString());
return new Template(templateParts, templateExpressions, scope(), token(ctx));
}
private String escapeTemplate(String templatePart) {
return templatePart.replace("\\`", "`")
.replace("\\$", "$")
.replace("\\\\", "\\");
}
private Token token(ParserRuleContext ctx) {
int startIndex = ctx.getStart() != null ? ctx.getStart().getStartIndex() : 0;
int endIndex = ctx.getStop() != null ? ctx.getStop().getStopIndex() : 0;
String text = ctx.getStart().getInputStream().getText(new Interval(startIndex, endIndex));
return new Token(startIndex, endIndex, text);
}
private FunctionSymbol resolveFunctionOrThrow(Scope scope, String functionName, int paramCount) {
return scope.resolveFunctionSymbol(functionName, paramCount)
.orElseThrow(() -> new IllegalStateException(
functionName + " function with " + paramCount + " parameter(s) does not exist in system"
));
}
private Scope scope() {
return currentScope.peek();
}
private Type unwrapScalarType(Type type) {
if(type instanceof ArrayType) {
return unwrapScalarType(((ArrayType) type).getElementType());
}
return type;
}
private Type unwrapTypeForIteration(Type type) {
if(type instanceof ArrayType) {
return ((ArrayType) type).getElementType();
}
if(type.equals(Type.ANY)) {
return Type.ANY;
}
return Type.UNKNOWN;
}
private List<Expression> parseArguments(Kel.ValueListContext arguments) {
return arguments.value()
.stream()
.map(valueContext -> visit(valueContext))
.collect(Collectors.toList());
}
public Map<String, Function> getFunctions() {
return functions;
}
public Collection<Reference> getReferences() {
return references;
}
}
| 36.020752 | 124 | 0.635712 |
1fe839e5ef5e7562d2be36d5178597ccf7a35910 | 7,866 | package com.ssafy.nnd.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ssafy.nnd.dto.Letter;
import com.ssafy.nnd.dto.Member;
import com.ssafy.nnd.dto.TeamBoard;
import com.ssafy.nnd.dto.TeamRegist;
import com.ssafy.nnd.repository.LetterRepository;
import com.ssafy.nnd.repository.MemberRepository;
import com.ssafy.nnd.repository.TeamBoardRepository;
import com.ssafy.nnd.repository.TeamRegistRepository;
@CrossOrigin
@Controller
public class LetterController {
@Autowired
LetterRepository letterRepository;
@Autowired
MemberRepository memberRepository;
@Autowired
TeamBoardRepository teamBoardRepository;
@Autowired
TeamRegistRepository teamregistRepository;
@GetMapping("/letter/member/teamlist/{memberidx}") // 현재 꼬시기 버트을 누르는 member의 idx
public @ResponseBody List<Map<String, Object>> getAllTeamList(@PathVariable Long memberidx) {
List<Object> teamList = teamregistRepository.findTeamByIdx(memberidx);
List<Map<String, Object>> datalist = new ArrayList<Map<String, Object>>();
for (int i = 0; i < teamList.size(); i++) {
Map<String, Object> map = new HashMap<String, Object>();
Object[] temp = (Object[]) teamList.get(i);
map.put("teamboardNo", temp[0]);
map.put("teamName", temp[1]);
datalist.add(map);
}
return datalist;
}
// R
// 모든 메시지
@GetMapping("/letter/list/all")
public @ResponseBody List<Letter> getAllLetter() {
return letterRepository.findAll();
}
@GetMapping("/letter/list/{letterno}")
public @ResponseBody Optional<Letter> getAllLetter(@PathVariable Long letterno) {
return letterRepository.findById(letterno);
}
// 보내는 사람 기준으로 검색
@GetMapping("/letter/list/send/{idx}")
public @ResponseBody List<Map<String, Object>> getLetterBySend(@PathVariable Long idx) {
List<Object> letter = letterRepository.findBySendIdx(idx);
List<Map<String, Object>> datalist = new ArrayList<Map<String, Object>>();
for (int i = 0; i < letter.size(); i++) {
Map<String, Object> map = new HashMap<String, Object>();
Object[] temp = (Object[]) letter.get(i);
map.put("name", temp[1]);
map.put("profile", temp[3]);
map.put("letterNo", temp[8]);
map.put("sendIdx", temp[9]);
map.put("receiveIdx", temp[10]);
map.put("content", temp[11]);
map.put("createDate", temp[12]);
map.put("read", temp[13]);
map.put("letterType", temp[14]);
map.put("teamboardNo", temp[15]);
datalist.add(map);
}
return datalist;
}
// 받는 사람 기준으로 검색
@GetMapping("/letter/list/receive/{idx}")
public @ResponseBody List<Map<String, Object>> getLetterByReceive(@PathVariable Long idx) {
List<Object> letter = letterRepository.findByReceiveIdx(idx);
List<Map<String, Object>> datalist = new ArrayList<Map<String, Object>>();
for (int i = 0; i < letter.size(); i++) {
Map<String, Object> map = new HashMap<String, Object>();
Object[] temp = (Object[]) letter.get(i);
map.put("name", temp[1]);
map.put("profile", temp[3]);
map.put("letterNo", temp[8]);
map.put("sendIdx", temp[9]);
map.put("receiveIdx", temp[10]);
map.put("content", temp[11]);
map.put("createDate", temp[12]);
map.put("read", temp[13]);
map.put("letterType", temp[14]);
map.put("teamboardNo", temp[15]);
datalist.add(map);
}
return datalist;
}
// C
@PutMapping("/letter/create/{type}")
public @ResponseBody String createLetter(@PathVariable String type, @RequestBody Letter letter) {
System.out.println(letter.toString());
try {
if (type.equals("tboard")) {
letter.setLetterType("tboard");
} else if (type.equals("mboard")) {
letter.setLetterType("mboard");
}
letterRepository.save(letter);
return "success";
} catch (Exception e) {
return "error";
}
}
@PostMapping("/letter/update/{letterno}")
public @ResponseBody Letter updateLetter(@PathVariable Long letterno) {
Optional<Letter> letter = letterRepository.findById(letterno);
letter.get().setRead(1);
letterRepository.save(letter.get());
return letter.get();
}
// D
@DeleteMapping("/letter/delete/{id}")
public @ResponseBody String deleteLetter(@PathVariable String id) {
int postID = Integer.parseInt(id);
try {
letterRepository.deleteById((long) postID);
return "success";
} catch (Exception e) {
return "error";
}
}
// 팀장이 개인 신청사항을 수락할 경우
@PostMapping("letter/teamaccept/{sendidx}/{teamboardno}")
public @ResponseBody String teamAccept(@PathVariable Long sendidx, @PathVariable Long teamboardno) {
Optional<TeamBoard> team = teamBoardRepository.findById(teamboardno);
Optional<Member> member = memberRepository.findById(sendidx);
boolean check = true;
int curgroupsize = team.get().getMemCnt();
int groupsize = team.get().getGroupSize();
String message = "success";
if (curgroupsize >= groupsize) {
check = false;
return message = "already full";
}
if (teamregistRepository.findByTeamboardNoAndMemberIdx(teamboardno, sendidx).isPresent()) {
check = false;
}
if (check) {
TeamRegist memberRegist = new TeamRegist();
memberRegist.setTeamboardNo(team.get().getTeamboardNo());
memberRegist.setMemberIdx(member.get().getIdx());
memberRegist.setMemberEmail(member.get().getEmail());
teamregistRepository.save(memberRegist);
team.get().setMemCnt(++curgroupsize);
teamBoardRepository.save(team.get());
return message;
} else {
message = "already joined";
return message;
}
}
// 개인이 팀장의 스카웃을 수락할 경우
@PostMapping("letter/memberaccept/{teamboardno}/{receiveidx}")
public @ResponseBody String memberAccept(@PathVariable Long teamboardno, @PathVariable Long receiveidx) {
Optional<TeamBoard> team = teamBoardRepository.findById(teamboardno);
Optional<Member> member = memberRepository.findById(receiveidx);
boolean check = true;
int curgroupsize = team.get().getMemCnt();
int groupsize = team.get().getGroupSize();
String message = "success";
if (curgroupsize >= groupsize) {
check = false;
return message = "already full";
}
if (teamregistRepository.findByTeamboardNoAndMemberIdx(teamboardno, receiveidx).isPresent()) {
check = false;
}
if (check) {
TeamRegist memberRegist = new TeamRegist();
memberRegist.setTeamboardNo(team.get().getTeamboardNo());
memberRegist.setMemberIdx(member.get().getIdx());
memberRegist.setMemberEmail(member.get().getEmail());
teamregistRepository.save(memberRegist);
team.get().setMemCnt(++curgroupsize);
teamBoardRepository.save(team.get());
return message;
} else {
message = "already joined";
return message;
}
}
@GetMapping("letter/check/overlap/{memberidx}/{receiveidx}/{type}/{teamboardno}")
public @ResponseBody String checkOverlap(@PathVariable Long memberidx, @PathVariable Long receiveidx,
@PathVariable String type, @PathVariable Long teamboardno) {
try {
Optional<Letter> letter = letterRepository.findByVariableCol(memberidx, receiveidx, type, teamboardno);
Optional<TeamRegist> teamregist = teamregistRepository.findByTeamboardNoAndMemberIdx(teamboardno,
memberidx);
if(!letter.isPresent()&&!teamregist.isPresent()) {
return "success";
}else {
return "overlap letter";
}
} catch (Exception e) {
return "error";
}
}
}
| 31.717742 | 106 | 0.719553 |
9fffb9a0c4eb568fb0cda027e99c22041d740339 | 305 | package tech.aistar.day02.homework.entity;
import lombok.Data;
import java.util.List;
/**
* @Description: java类作用描述:
* @Author: tyg
* @CreateDate: 2019/05/05
* @Version: 1.0
*/
@Data
public class Customer {
private Integer cid;
private String cname;
private List<Order> orderList;
}
| 14.52381 | 42 | 0.685246 |
ffbaadcffa974d119b8e68c23246f09065d0eeb8 | 3,520 | package it.linksmt.cts2.plugin.sti.db.commands.search;
import it.linksmt.cts2.plugin.sti.db.hibernate.HibernateCommand;
import it.linksmt.cts2.plugin.sti.service.exception.StiAuthorizationException;
import it.linksmt.cts2.plugin.sti.service.exception.StiHibernateException;
import java.util.List;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
public class GetListValueFromParameterAndCodeSystemAndVersion extends HibernateCommand {
// SELECT distinct val.parametervalue
// FROM code_system c
// INNER JOIN code_system_version v ON c.id = v.codesystemid
// INNER JOIN code_system_version_entity_membership m ON v.versionid = m.codesystemversionid
// INNER JOIN code_system_entity_version ev ON m.codesystementityid = ev.codesystementityid
// INNER JOIN code_system_concept cpt ON ev.versionid = cpt.codesystementityversionid
// LEFT JOIN code_system_concept_translation tr ON tr.codesystementityversionid = cpt.codesystementityversionid
// INNER JOIN metadata_parameter p on c.id = p.codesystemid
// INNER JOIN code_system_metadata_value val on p.id = val.metadataparameterid and cpt.codesystementityversionid = val.codesystementityversionid
// WHERE c.name='ICPC2'
// AND v.name = 'ICPC__7.0'
// AND p.paramname = 'INCLUSION'
// ORDER BY val.parametervalue;
String SQL_QUERY_SELECT_FULL = " SELECT distinct val.parametervalue "
+ " FROM code_system c "
+ " INNER JOIN code_system_version v ON c.id = v.codesystemid "
+ " INNER JOIN code_system_version_entity_membership m ON v.versionid = m.codesystemversionid "
+ " INNER JOIN code_system_entity_version ev ON m.codesystementityid = ev.codesystementityid "
+ " INNER JOIN code_system_concept cpt ON ev.versionid = cpt.codesystementityversionid "
+ " LEFT JOIN code_system_concept_translation tr ON tr.codesystementityversionid = cpt.codesystementityversionid "
+ " INNER JOIN metadata_parameter p on c.id = p.codesystemid "
+ " INNER JOIN code_system_metadata_value val on p.id = val.metadataparameterid and cpt.codesystementityversionid = val.codesystementityversionid "
+ " WHERE c.name=:NAME "
+ " AND v.name = :VERSION "
+ " AND p.paramname = :PARAMNAME "
+ " AND (cpt.languagecd is null or LOWER(cpt.languagecd) = LOWER(:LANG)) "
+ " ORDER BY val.parametervalue; ";
private String name;
private String version;
private String paramName;
private String lang;
public GetListValueFromParameterAndCodeSystemAndVersion(String name,String version,String paramName,String lang) {
this.name = name;
this.version = version;
this.paramName = paramName;
this.lang = lang;
}
@Override
public void checkPermission(final Session session) throws StiAuthorizationException, StiHibernateException {
if (userInfo == null) {
throw new StiAuthorizationException("Occorre effettuare il login per utilizzare il servizio.");
}
}
@SuppressWarnings("unchecked")
@Override
public List<String> execute(final Session session) throws StiAuthorizationException, StiHibernateException {
if (name==null || version==null || paramName==null || lang == null) {
return null;
}
SQLQuery querySelect = session.createSQLQuery(SQL_QUERY_SELECT_FULL);
querySelect.setString("NAME",name);
querySelect.setString("VERSION",version);
querySelect.setString("PARAMNAME",paramName);
querySelect.setString("LANG",lang);
List<String> resList = querySelect.list();
return resList;
}
}
| 40.45977 | 150 | 0.752841 |
2418c09866625c4f73e8f65f2864294ac89235ce | 15,408 | /*******************************************************************************
* Copyright (c) 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Zend Technologies
*******************************************************************************/
package org.eclipse.php.internal.debug.ui.launching;
import java.io.File;
import org.eclipse.core.filesystem.URIUtil;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.debug.core.*;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.debug.ui.ILaunchShortcut2;
import org.eclipse.dltk.core.IMethod;
import org.eclipse.dltk.core.IModelElement;
import org.eclipse.dltk.core.ISourceModule;
import org.eclipse.dltk.core.IType;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.php.debug.core.debugger.parameters.IDebugParametersKeys;
import org.eclipse.php.internal.core.documentModel.provisional.contenttype.ContentTypeIdForPHP;
import org.eclipse.php.internal.debug.core.IPHPDebugConstants;
import org.eclipse.php.internal.debug.core.PHPDebugPlugin;
import org.eclipse.php.internal.debug.core.debugger.AbstractDebuggerConfiguration;
import org.eclipse.php.internal.debug.core.preferences.*;
import org.eclipse.php.internal.debug.ui.Logger;
import org.eclipse.php.internal.debug.ui.PHPDebugUIMessages;
import org.eclipse.php.internal.debug.ui.PHPDebugUIPlugin;
import org.eclipse.php.internal.ui.editor.input.NonExistingPHPFileEditorInput;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IStorageEditorInput;
import org.eclipse.ui.IURIEditorInput;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.editors.text.TextFileDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditor;
public class PHPExeLaunchShortcut implements ILaunchShortcut2 {
/**
* PHPExeLaunchShortcut constructor.
*/
public PHPExeLaunchShortcut() {
super();
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.debug.ui.ILaunchShortcut#launch(org.eclipse.jface.viewers
* .ISelection, java.lang.String)
*/
public void launch(ISelection selection, String mode) {
if (selection instanceof IStructuredSelection) {
searchAndLaunch(((IStructuredSelection) selection).toArray(), mode,
getPHPExeLaunchConfigType());
}
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.debug.ui.ILaunchShortcut#launch(org.eclipse.ui.IEditorPart,
* java.lang.String)
*/
public void launch(IEditorPart editor, String mode) {
IEditorInput input = editor.getEditorInput();
IFile file = (IFile) input.getAdapter(IFile.class);
if (file == null) {
IPath path = null;
try {
if (input instanceof IStorageEditorInput) {
IStorageEditorInput editorInput = (IStorageEditorInput) input;
IStorage storage = editorInput.getStorage();
path = storage.getFullPath();
} else if (input instanceof IURIEditorInput) {
path = URIUtil.toPath(((IURIEditorInput) input).getURI());
} else if (input instanceof NonExistingPHPFileEditorInput) {
// handle untitled document debugging
// first save the file to the disk and after that set the
// document as dirty
if (editor instanceof ITextEditor) {
ITextEditor textEditor = (ITextEditor) editor;
final TextFileDocumentProvider documentProvider = (TextFileDocumentProvider) textEditor
.getDocumentProvider();
final IDocument document = documentProvider
.getDocument(input);
documentProvider.saveDocument(null, input, document,
true);
// set document dirty
document.replace(0, 0, ""); //$NON-NLS-1$
}
path = ((NonExistingPHPFileEditorInput) input)
.getPath(input);// Untitled
// dummy
// path
}
if (path != null) {
File systemFile = new File(path.toOSString());
if (systemFile.exists()) {
searchAndLaunch(new Object[] { systemFile }, mode,
getPHPExeLaunchConfigType());
}
}
} catch (Exception e) {
Logger.logException(e);
}
} else {
searchAndLaunch(new Object[] { file }, mode,
getPHPExeLaunchConfigType());
}
}
protected ILaunchConfigurationType getPHPExeLaunchConfigType() {
ILaunchManager lm = DebugPlugin.getDefault().getLaunchManager();
return lm
.getLaunchConfigurationType(IPHPDebugConstants.PHPEXELaunchType);
}
public static void searchAndLaunch(Object[] search, String mode,
ILaunchConfigurationType configType) {
int entries = search == null ? 0 : search.length;
for (int i = 0; i < entries; i++) {
try {
String phpPathString = null;
String phpFileLocation = null;
IProject project = null;
Object obj = search[i];
IResource res = null;
if (obj instanceof IModelElement) {
IModelElement elem = (IModelElement) obj;
if (elem instanceof ISourceModule) {
res = ((ISourceModule) elem).getCorrespondingResource();
} else if (elem instanceof IType) {
res = ((IType) elem).getUnderlyingResource();
} else if (elem instanceof IMethod) {
res = ((IMethod) elem).getUnderlyingResource();
}
if (res instanceof IFile) {
obj = (IFile) res;
}
}
if (obj instanceof IFile) {
IFile file = (IFile) obj;
res = file;
project = file.getProject();
IContentType contentType = Platform.getContentTypeManager()
.getContentType(
ContentTypeIdForPHP.ContentTypeID_PHP);
if (contentType.isAssociatedWith(file.getName())) {
if (new File(file.getFullPath().toOSString()).exists()) {
phpPathString = file.getFullPath().toOSString();
} else {
phpPathString = file.getFullPath().toString();
}
IPath location = file.getLocation();
// check for non null values - EFS issues
if (location != null) {
phpFileLocation = location.toOSString();
} else {
phpFileLocation = file.getFullPath().toString();
}
}
} else if (obj instanceof File) {
File systemFile = (File) obj;
phpPathString = systemFile.getAbsolutePath();
phpFileLocation = phpPathString;
}
if (phpPathString == null) {
// Could not find target to launch
throw new CoreException(new Status(IStatus.ERROR,
PHPDebugUIPlugin.ID, IStatus.OK,
PHPDebugUIMessages.launch_failure_no_target, null));
}
PHPexeItem defaultEXE = getDefaultPHPExe(project);
String phpExeName = (defaultEXE != null) ? defaultEXE
.getExecutable().getAbsolutePath().toString() : null;
if (phpExeName == null) {
MessageDialog.openError(PHPDebugUIPlugin
.getActiveWorkbenchShell(),
PHPDebugUIMessages.launch_noexe_msg_title,
PHPDebugUIMessages.launch_noexe_msg_text);
PreferencesUtil
.createPreferenceDialogOn(
PHPDebugUIPlugin.getActiveWorkbenchShell(),
"org.eclipse.php.debug.ui.preferencesphps.PHPsPreferencePage", //$NON-NLS-1$
null, null).open();
return;
}
// Launch the app
ILaunchConfiguration config = findLaunchConfiguration(project,
phpPathString, phpFileLocation, defaultEXE, mode,
configType, res);
if (config != null) {
DebugUITools.launch(config, mode);
} else {
// Could not find launch configuration
throw new CoreException(new Status(IStatus.ERROR,
PHPDebugUIPlugin.ID, IStatus.OK,
PHPDebugUIMessages.launch_failure_no_config, null));
}
} catch (CoreException ce) {
final IStatus stat = ce.getStatus();
Display.getDefault().asyncExec(new Runnable() {
public void run() {
ErrorDialog
.openError(
PHPDebugUIPlugin
.getActiveWorkbenchShell(),
PHPDebugUIMessages.launch_failure_msg_title,
PHPDebugUIMessages.launch_failure_exec_msg_text,
stat);
}
});
}
}
}
// Returns the default php executable name for the current project.
// In case the project does not have any special settings, return the
// workspace default.
private static PHPexeItem getDefaultPHPExe(IProject project) {
PHPexeItem defaultItem = PHPDebugPlugin.getPHPexeItem(project);
if (defaultItem != null) {
return defaultItem;
}
return PHPDebugPlugin.getWorkspaceDefaultExe();
}
// Creates a preferences scope for the given project.
// This scope will be used to search for preferences values.
private static IScopeContext[] createPreferenceScopes(IProject project) {
if (project != null) {
return new IScopeContext[] { new ProjectScope(project),
new InstanceScope(), new DefaultScope() };
}
return new IScopeContext[] { new InstanceScope(), new DefaultScope() };
}
/**
* Locate a configuration to relaunch for the given type. If one cannot be
* found, create one.
*
* @param res
*
* @return a re-useable config or <code>null</code> if none
*/
protected static ILaunchConfiguration findLaunchConfiguration(
IProject phpProject, String phpPathString,
String phpFileFullLocation, PHPexeItem defaultEXE, String mode,
ILaunchConfigurationType configType, IResource res) {
ILaunchConfiguration config = null;
try {
ILaunchConfiguration[] configs = DebugPlugin.getDefault()
.getLaunchManager().getLaunchConfigurations(configType);
int numConfigs = configs == null ? 0 : configs.length;
for (int i = 0; i < numConfigs; i++) {
String fileName = configs[i].getAttribute(
IPHPDebugConstants.ATTR_FILE, (String) null);
String exeName = configs[i].getAttribute(
IPHPDebugConstants.ATTR_EXECUTABLE_LOCATION,
(String) null);
String iniPath = configs[i].getAttribute(
IPHPDebugConstants.ATTR_INI_LOCATION, (String) null);
PHPexeItem item = PHPexes.getInstance().getItemForFile(exeName,
iniPath);
if (phpPathString.equals(fileName)/* && defaultEXE.equals(item) */) {
config = configs[i];
break;
}
}
if (config == null) {
config = createConfiguration(phpProject, phpPathString,
phpFileFullLocation, defaultEXE, configType, res);
}
} catch (CoreException ce) {
ce.printStackTrace();
}
return config;
}
/**
* Create & return a new configuration
*
* @param res
*/
protected static ILaunchConfiguration createConfiguration(
IProject phpProject, String phpPathString,
String phpFileFullLocation, PHPexeItem defaultEXE,
ILaunchConfigurationType configType, IResource res)
throws CoreException {
ILaunchConfiguration config = null;
ILaunchConfigurationWorkingCopy wc = configType.newInstance(null,
getNewConfigurationName(phpPathString));
// Set the delegate class according to selected executable.
wc.setAttribute(PHPDebugCorePreferenceNames.PHP_DEBUGGER_ID, defaultEXE
.getDebuggerID());
AbstractDebuggerConfiguration debuggerConfiguration = PHPDebuggersRegistry
.getDebuggerConfiguration(defaultEXE.getDebuggerID());
wc.setAttribute(
PHPDebugCorePreferenceNames.CONFIGURATION_DELEGATE_CLASS,
debuggerConfiguration.getScriptLaunchDelegateClass());
wc.setAttribute(IPHPDebugConstants.ATTR_FILE, phpPathString);
wc.setAttribute(IPHPDebugConstants.ATTR_FILE_FULL_PATH,
phpFileFullLocation);
wc.setAttribute(IPHPDebugConstants.ATTR_EXECUTABLE_LOCATION, defaultEXE
.getExecutable().getAbsolutePath().toString());
String iniPath = defaultEXE.getINILocation() != null ? defaultEXE
.getINILocation().toString() : null;
wc.setAttribute(IPHPDebugConstants.ATTR_INI_LOCATION, iniPath);
wc.setAttribute(IPHPDebugConstants.RUN_WITH_DEBUG_INFO, PHPDebugPlugin
.getDebugInfoOption());
wc.setAttribute(IDebugParametersKeys.FIRST_LINE_BREAKPOINT,
PHPProjectPreferences.getStopAtFirstLine(phpProject));
if (res != null) {
wc.setMappedResources(new IResource[] { res });
}
config = wc.doSave();
return config;
}
/**
* Returns a name for a newly created launch configuration according to the
* given file name. In case the name generation fails, return the
* "New_configuration" string.
*
* @param fileName
* The original file name that this shortcut shoul execute.
* @return The new configuration name, or "New_configuration" in case it
* fails for some reason.
*/
protected static String getNewConfigurationName(String fileName) {
String configurationName = PHPDebugUIMessages.PHPExeLaunchShortcut_0;
try {
IPath path = Path.fromOSString(fileName);
NonExistingPHPFileEditorInput editorInput = NonExistingPHPFileEditorInput
.findEditorInput(path);
if (editorInput != null) {
path = new Path(editorInput.getName());
}
String fileExtention = path.getFileExtension();
String lastSegment = path.lastSegment();
if (lastSegment != null) {
if (fileExtention != null) {
lastSegment = lastSegment.replaceFirst("." + fileExtention, //$NON-NLS-1$
""); //$NON-NLS-1$
}
configurationName = lastSegment;
}
} catch (Exception e) {
Logger.log(Logger.WARNING_DEBUG,
"Could not generate configuration name for " + fileName //$NON-NLS-1$
+ ".\nThe default name will be used.", e); //$NON-NLS-1$
}
return DebugPlugin.getDefault().getLaunchManager()
.generateUniqueLaunchConfigurationNameFrom(configurationName);
}
public ILaunchConfiguration[] getLaunchConfigurations(ISelection selection) {
return null;
}
public ILaunchConfiguration[] getLaunchConfigurations(IEditorPart editorpart) {
return null;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.debug.ui.ILaunchShortcut2#getLaunchableResource(org.eclipse
* .ui.IEditorPart)
*/
public IResource getLaunchableResource(IEditorPart editorpart) {
return getLaunchableResource(editorpart.getEditorInput());
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.debug.ui.ILaunchShortcut2#getLaunchableResource(org.eclipse
* .jface.viewers.ISelection)
*/
public IResource getLaunchableResource(ISelection selection) {
if (selection instanceof IStructuredSelection) {
IStructuredSelection ss = (IStructuredSelection) selection;
if (ss.size() == 1) {
Object element = ss.getFirstElement();
if (element instanceof IAdaptable) {
return getLaunchableResource((IAdaptable) element);
}
}
}
return null;
}
/**
* Returns the resource containing the Java element associated with the
* given adaptable, or <code>null</code>.
*
* @param adaptable
* adaptable object
* @return containing resource or <code>null</code>
*/
private IResource getLaunchableResource(IAdaptable adaptable) {
IModelElement je = (IModelElement) adaptable
.getAdapter(IModelElement.class);
if (je != null) {
return je.getResource();
}
return null;
}
}
| 34.392857 | 95 | 0.711319 |
d18db8238d9fe404ed46a9abd1274c8fb38cd2f3 | 2,634 | package speedith.core.reasoning.rules.transformers.copTrans;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeMap;
import java.util.TreeSet;
import speedith.core.lang.CompoundSpiderDiagram;
import speedith.core.lang.IdTransformer;
import speedith.core.lang.PrimarySpiderDiagram;
import speedith.core.lang.Region;
import speedith.core.lang.SpiderDiagram;
import speedith.core.lang.SpiderDiagrams;
import speedith.core.lang.TransformationException;
import speedith.core.lang.Zone;
import speedith.core.lang.cop.Arrow;
import speedith.core.lang.cop.COPDiagram;
import speedith.core.lang.cop.Cardinality;
import speedith.core.lang.cop.CompleteCOPDiagram;
import speedith.core.lang.cop.LUCarCOPDiagram;
import speedith.core.lang.cop.SpiderComparator;
import speedith.core.reasoning.ApplyStyle;
import speedith.core.reasoning.args.SpiderArg;
public class RemoveSpidersTransformer extends IdTransformer {
private final List<SpiderArg> spiderArgs;
private final ApplyStyle applyStyle;
public RemoveSpidersTransformer(List<SpiderArg> args, ApplyStyle applyStyle) {
this.spiderArgs = args;
this.applyStyle = applyStyle;
}
@Override
public SpiderDiagram transform(PrimarySpiderDiagram psd,
int diagramIndex,
ArrayList<CompoundSpiderDiagram> parents,
ArrayList<Integer> childIndices) {
if(spiderArgs.isEmpty()){
return psd;
}
if(!(psd instanceof COPDiagram)){
throw new TransformationException("The rule is not applicaple to this diagram.");
}
if (diagramIndex == spiderArgs.get(0).getSubDiagramIndex()){
for (String spider : getSpidersTarget()){
Region spiderHabitat = psd.getSpiderHabitat(spider);
for(Zone zone : spiderHabitat.sortedZones()){
if(psd.getShadedZones().contains(zone)){
throw new IllegalArgumentException("The habitat of the spider cannot contain any shaded zones.");
}
}
}
COPDiagram cop = (COPDiagram) psd;
String[] spidersArray = getSpidersTarget().toArray(new String[getSpidersTarget().size()]);
return cop.deleteSpider(spidersArray);
}
return null;
}
private List<String> getSpidersTarget() {
ArrayList<String> spiders = new ArrayList<>();
for (SpiderArg spiderArg : spiderArgs) {
spiders.add(spiderArg.getSpider());
}
return spiders;
}
}
| 31.73494 | 112 | 0.676538 |
1f16314b42a358c7569c17ecccf1a2c1ffd5d850 | 889 | package models.hmcore.setting;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import models.BaseModel;
@Entity
@Table(name="system_setting")
@org.hibernate.annotations.Table(comment="系统设置", appliesTo = "system_setting")
public class SystemSetting extends BaseModel{
@Column(name="setting_key", columnDefinition="varchar(255) comment '系统设置的Key'")
public String settingKey;
@Column(name="setting_value", columnDefinition="varchar(255) comment '系统设置的值'")
public String settingValue;
public SystemSetting() {
super();
}
public SystemSetting(String settingKey) {
super();
this.settingKey = settingKey;
}
public SystemSetting(String settingKey, String settingValue) {
super();
this.settingKey = settingKey;
this.settingValue = settingValue;
}
@Override
public String toString() {
return settingKey;
}
}
| 21.682927 | 80 | 0.75703 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.