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
|
---|---|---|---|---|---|
c4f94911c7d4516acc2cce0f1ca1661acdb90938
| 1,900 |
/*
* 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 org.femass.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
*
* @author enzoappi
*/
public class Livro {
private Integer id;
private String nome;
private List<Autor> autores = new ArrayList();
private String editora;
private Boolean emprestado = false;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public List<Autor> getAutores() {
return autores;
}
public void adicionarAutor(Autor autor) {
if(this.autores == null) {
this.autores = new ArrayList();
}
this.autores.add(autor);
}
public void removerAutor(Autor autor) {
this.autores.remove(autor);
}
public String getEditora() {
return editora;
}
public void setEditora(String editora) {
this.editora = editora;
}
@Override
public String toString() {
return nome;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Livro other = (Livro) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
public Boolean getEmprestado() {
return emprestado;
}
public void setEmprestado(Boolean emprestado) {
this.emprestado = emprestado;
}
}
| 20.430108 | 79 | 0.572105 |
3a1373b549589890acf43555a9e01b08f32b562d
| 2,014 |
package com.mohadian;
import java.util.Stack;
public class RemoveAdjacentDuplicatesString {
public String removeDuplicatesUsingStack(String s) {
StringBuffer res = new StringBuffer();
Stack<Character> stack = new Stack();
for (int i = 0; i < s.length(); i++) {
Character ch = s.charAt(i);
if (!stack.isEmpty() && stack.peek() == ch) {
stack.pop();
} else {
stack.push(ch);
}
}
while (!stack.isEmpty()) {
res.append(stack.pop());
}
return res.reverse().toString();
}
public String removeDuplicates(String s) {
boolean couldRemove = true;
while (couldRemove) {
if (s.length() > 0) {
couldRemove = false;
StringBuffer sb = new StringBuffer();
char current = s.charAt(0);
int count = 1;
for (int i = 1; i < s.length(); i++) {
char next = s.charAt(i);
if (current == next) {
count++;
couldRemove = true;
} else {
if (count % 2 == 1) {
sb.append(current);
}
count = 1;
current = next;
}
}
if (count % 2 == 1 && current == s.charAt(s.length() - 1)) {
sb.append(current);
}
s = sb.toString();
sb = new StringBuffer();
} else {
couldRemove = false;
}
}
return s;
}
public static void main(String[] args) {
RemoveAdjacentDuplicatesString cls = new RemoveAdjacentDuplicatesString();
System.out.println(cls.removeDuplicates("aababaab"));
System.out.println(cls.removeDuplicatesUsingStack("aababaab"));
}
}
| 30.515152 | 82 | 0.437934 |
2bf7dac7474f7fd09b69ceaacf7be2b48935afa4
| 894 |
/*
* Copyright 2019 LinkedIn Corp. 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.
*/
package com.github.ambry.utils;
import com.codahale.metrics.Clock;
import java.util.concurrent.TimeUnit;
public class MockClock extends Clock {
private long tick = 0;
@Override
public long getTick() {
return tick;
}
public void tick(int seconds) {
// Meter's TICK_INTERVAL = TimeUnit.SECONDS.toNanos(5)
tick += TimeUnit.SECONDS.toNanos(seconds) + 1;
}
}
| 26.294118 | 75 | 0.720358 |
06312a94e9e495ff772f71535fb33e076922139a
| 391 |
package edu.harvard.iq.dataverse.api.dto;
/**
*
* @author mderuijter
*/
public class LicenseDTO {
String name;
String uri;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
}
| 14.481481 | 41 | 0.56266 |
7b8fdf02e1e94192cac3c9957f57df29be696297
| 1,184 |
package top.sstime.server;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
/**
* @author chenwei
* @date 2019年6月19日
* @descriptions 未使用netty的阻塞网络编程
*/
public class PlainOioServer {
public static void server(int port) throws IOException {
final ServerSocket socket = new ServerSocket(port);
try {
for(;;) {
final Socket clientSocket = socket.accept();
System.out.println(
"Accepted connection from " + clientSocket);
new Thread(new Runnable() {
@Override
public void run() {
OutputStream out = null;
try {
out = clientSocket.getOutputStream();
out.write("Hi!\r\n".getBytes(Charset.forName("UTF-8")));
out.flush();
// 关闭连接
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (Exception ex) {
//
}
}
}
}).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
server(9999);
}
}
| 21.527273 | 63 | 0.615709 |
e9df8122d10553b28389bd6bcf05e95a9513690b
| 4,409 |
package com.ibm.sbt.opensocial.domino.oauth;
import java.util.Map;
import java.util.logging.Level;
import org.apache.shindig.common.crypto.BlobCrypter;
import org.apache.shindig.common.crypto.BlobCrypterException;
import org.apache.shindig.gadgets.oauth2.OAuth2CallbackState;
import com.google.common.base.Objects;
import com.google.common.collect.Maps;
import com.ibm.sbt.opensocial.domino.internal.OpenSocialPlugin;
/**
* An OAuth 2.0 callback state object that includes the container.
*
*/
public class DominoOAuth2CallbackState extends OAuth2CallbackState {
private static final long serialVersionUID = -2681620021214587536L;
private static final String GADGET_URI_KEY = "g";
private static final String CONTAINER_KEY = "c";
private static final String SERVICE_NAME = "sn";
private static final String USER = "u";
private static final String SCOPE = "sc";
private static final String CLASS = OAuth2CallbackState.class.getName();
private transient BlobCrypter crypter;
private Map<String, String> state;
/**
* Creates a new DominoOAuth2CallbackState object.
*/
public DominoOAuth2CallbackState() {
this.state = Maps.newHashMapWithExpectedSize(5);
this.crypter = null;
}
/**
* Creates a new DominoOAuth2CallbackState object.
* @param crypter The crypter to use to encrypt and decrypt the callback state.
*/
public DominoOAuth2CallbackState(final BlobCrypter crypter) {
this();
this.crypter = crypter;
}
/**
* Creates a new DominoOAuth2CallbackState object.
* @param crypter The crypter to use to encrypt and decrypt the callback state.
* @param stateBlob The encrypted state blob to instantiate the callback object with.
*/
public DominoOAuth2CallbackState(final BlobCrypter crypter, final String stateBlob) {
final String method = "constructor";
this.crypter = crypter;
Map<String, String> state = null;
if (stateBlob != null && crypter != null) {
try {
state = crypter.unwrap(stateBlob);
if (state == null) {
state = Maps.newHashMap();
}
this.state = state;
} catch (final BlobCrypterException e) {
// Too old, or corrupt. Ignore it.
state = null;
OpenSocialPlugin.getLogger().logp(Level.WARNING, CLASS, method, "Error decrypting state.", e);
}
}
if (state == null) {
this.state = Maps.newHashMapWithExpectedSize(5);
}
}
@Override
public String getEncryptedState() throws BlobCrypterException {
String ret = null;
if (this.crypter != null) {
ret = this.crypter.wrap(this.state);
}
return ret;
}
@Override
public String getGadgetUri() {
return this.state.get(GADGET_URI_KEY);
}
@Override
public void setGadgetUri(String gadgetUri) {
this.state.put(GADGET_URI_KEY, gadgetUri);
}
@Override
public String getServiceName() {
return this.state.get(SERVICE_NAME);
}
@Override
public void setServiceName(String serviceName) {
this.state.put(SERVICE_NAME, serviceName);
}
@Override
public String getUser() {
return this.state.get(USER);
}
@Override
public void setUser(String user) {
this.state.put(USER, user);
}
@Override
public String getScope() {
return this.state.get(SCOPE);
}
@Override
public void setScope(String scope) {
this.state.put(SCOPE, scope);
}
/**
* Gets the container.
* @return The container.
*/
public String getContainer() {
return this.state.get(CONTAINER_KEY);
}
/**
* Sets the container.
* @param container The container.
*/
public void setContainer(String container) {
this.state.put(CONTAINER_KEY, container);
}
@Override
public boolean equals(Object o) {
boolean result = false;
if(o instanceof OAuth2CallbackState) {
DominoOAuth2CallbackState state = (DominoOAuth2CallbackState)o;
result = getContainer() != null ? getContainer().equals(state.getContainer()) : getContainer() == state.getContainer();
result &= getGadgetUri() != null ? getGadgetUri().equals(state.getGadgetUri()) : getGadgetUri() == state.getGadgetUri();
result &= getScope() != null ? getScope().equals(state.getScope()) : getScope() == state.getScope();
result &= getServiceName() != null ? getServiceName().equals(state.getServiceName()) : getServiceName() == state.getServiceName();
result &= getUser() != null ? getUser().equals(state.getUser()) : getUser() == state.getUser();
}
return result;
}
@Override
public int hashCode() {
return Objects.hashCode(state);
}
}
| 27.216049 | 133 | 0.718303 |
bc51846d37dc2fbc416c70987d8738eb48ac3db1
| 1,246 |
/*
* Copyright 2020 Wuyi Chen.
*
* 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.ftgo.orderservice.api.controller.model;
/**
* The response for creating an order API.
*
* @author Wuyi Chen
* @date 05/13/2020
* @version 1.0
* @since 1.0
*/
public class CreateOrderResponse {
private long orderId;
private CreateOrderResponse() {}
public CreateOrderResponse(long orderId) {
this.orderId = orderId;
}
public long getOrderId() {
return orderId;
}
public CreateOrderResponse setOrderId(long orderId) {
this.orderId = orderId;
return this;
}
public static CreateOrderResponse newBuilder() {
return new CreateOrderResponse();
}
public CreateOrderResponse build() {
return this;
}
}
| 23.961538 | 75 | 0.721509 |
94d1d5a97968c8fa54f674891996d0e0f68c0164
| 3,521 |
/*
* Copyright (c) 2002-2012 Alibaba Group Holding Limited.
* 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.alibaba.citrus.service.resource.support.context;
import com.alibaba.citrus.service.resource.support.ResourceLoadingSupport;
import com.alibaba.citrus.springext.support.context.AbstractXmlApplicationContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
/**
* 从resource loading service中装载配置文件<code>ApplicationContext</code>实现。
*
* @author Michael Zhou
* @see AbstractXmlApplicationContext
*/
public class ResourceLoadingXmlApplicationContext extends AbstractXmlApplicationContext {
private Resource configResource;
/** 从一个现成的<code>Resource</code>中创建spring容器,并初始化。 */
public ResourceLoadingXmlApplicationContext(Resource resource) throws BeansException {
this(resource, null);
}
/** 从一个现成的<code>Resource</code>中创建spring容器,并初始化。 */
public ResourceLoadingXmlApplicationContext(Resource resource, ApplicationContext parentContext)
throws BeansException {
this(resource, parentContext, true);
}
/** 从一个现成的<code>Resource</code>中创建spring容器,并初始化。 */
public ResourceLoadingXmlApplicationContext(Resource resource, ApplicationContext parentContext, boolean refresh)
throws BeansException {
super(parentContext);
this.configResource = resource;
setResourceLoadingExtender(new ResourceLoadingSupport(this));
if (refresh) {
refresh();
}
}
/**
* 从一组配置文件名中,创建spring容器,并初始化。
* <p>
* 假如<code>parentContext</code>中定义了<code>ResourceLoadingService</code>,那么
* <code>configLocations</code>以及所有的imports将从中装载。
* </p>
*/
public ResourceLoadingXmlApplicationContext(String[] configLocations, ApplicationContext parentContext) {
this(configLocations, parentContext, true);
}
/**
* 从一组配置文件名中,创建spring容器,并初始化。
* <p>
* 假如<code>parentContext</code>中定义了<code>ResourceLoadingService</code>,那么
* <code>configLocations</code>以及所有的imports将从中装载。
* </p>
*/
public ResourceLoadingXmlApplicationContext(String[] configLocations, ApplicationContext parentContext,
boolean refresh) {
super(parentContext);
setConfigLocations(configLocations);
setResourceLoadingExtender(new ResourceLoadingSupport(this));
if (refresh) {
refresh();
}
}
public void setConfigResource(Resource configResource) {
this.configResource = configResource;
}
@Override
protected Resource[] getConfigResources() {
if (configResource == null) {
return null;
} else {
return new Resource[] { configResource };
}
}
}
| 35.21 | 118 | 0.680488 |
6475c33343a69425518598f720191f362073eba7
| 1,812 |
/* (c) British Telecommunications plc, 2010, All Rights Reserved */
package com.bt.pi.ops.website;
import java.util.Collection;
import javax.ws.rs.Path;
import javax.ws.rs.ext.Provider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import com.sun.jersey.api.core.DefaultResourceConfig;
public class SpringResourceConfig extends DefaultResourceConfig implements ApplicationContextAware {
private static final Log LOG = LogFactory.getLog(SpringResourceConfig.class);
private final String[] packages;
private ApplicationContext applicationContext;
public SpringResourceConfig(String... thePackages) {
super();
packages = thePackages;
applicationContext = null;
}
@Override
public void setApplicationContext(ApplicationContext theApplicationContext) {
applicationContext = theApplicationContext;
loadObjects();
}
private void loadObjects() {
loadObjects(applicationContext.getBeansWithAnnotation(Provider.class).values());
loadObjects(applicationContext.getBeansWithAnnotation(Path.class).values());
}
private void loadObjects(Collection<Object> beans) {
for (Object object : beans) {
if (isBeanInPackages(object)) {
LOG.info("Adding jersey singleton " + object.getClass().getName());
getSingletons().add(object);
}
}
}
private boolean isBeanInPackages(Object object) {
String name = object.getClass().getName();
for (String pckage : packages) {
if (name.startsWith(pckage))
return true;
}
return false;
}
}
| 32.357143 | 100 | 0.695916 |
d856257cb1143cb1d6693c10660106dcaf64a56b
| 2,496 |
/**
* Copyright (C) 2014-2018 LinkedIn Corp. (pinot-core@linkedin.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.linkedin.thirdeye.anomaly.detection;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.linkedin.thirdeye.api.DimensionMap;
import com.linkedin.thirdeye.api.MetricTimeSeries;
import com.linkedin.thirdeye.datalayer.dto.MergedAnomalyResultDTO;
import com.linkedin.thirdeye.detector.metric.transfer.ScalingFactor;
import java.util.Collections;
import java.util.List;
import java.util.Map;
public class AnomalyDetectionInputContext {
private Map<DimensionMap, MetricTimeSeries> dimensionMapMetricTimeSeriesMap = Collections.emptyMap();
private MetricTimeSeries globalMetric;
private ListMultimap<DimensionMap, MergedAnomalyResultDTO> knownMergedAnomalies = ArrayListMultimap.create();;
private List<ScalingFactor> scalingFactors = Collections.emptyList();
public Map<DimensionMap, MetricTimeSeries> getDimensionMapMetricTimeSeriesMap() {
return dimensionMapMetricTimeSeriesMap;
}
public void setDimensionMapMetricTimeSeriesMap(
Map<DimensionMap, MetricTimeSeries> dimensionMapMetricTimeSeriesMap) {
this.dimensionMapMetricTimeSeriesMap = dimensionMapMetricTimeSeriesMap;
}
public ListMultimap<DimensionMap, MergedAnomalyResultDTO> getKnownMergedAnomalies() {
return knownMergedAnomalies;
}
public void setKnownMergedAnomalies(ListMultimap<DimensionMap, MergedAnomalyResultDTO> knownMergedAnomalies) {
this.knownMergedAnomalies = knownMergedAnomalies;
}
public List<ScalingFactor> getScalingFactors() {
return scalingFactors;
}
public void setScalingFactors(List<ScalingFactor> scalingFactors) {
this.scalingFactors = scalingFactors;
}
public MetricTimeSeries getGlobalMetric() {
return globalMetric;
}
public void setGlobalMetric(MetricTimeSeries globalMetric) {
this.globalMetric = globalMetric;
}
}
| 36.173913 | 112 | 0.794071 |
e80327f606c5924870cc71f7fbd819abacd160e1
| 8,708 |
package org.talend.dataprofiler.core.migration.impl;
import java.util.Date;
import org.talend.cwm.helper.TaggedValueHelper;
import org.talend.dataprofiler.core.migration.AbstractWorksapceUpdateTask;
import org.talend.dataprofiler.core.migration.helper.IndicatorDefinitionFileHelper;
import org.talend.dataquality.indicators.definition.IndicatorDefinition;
import org.talend.dq.indicators.definitions.DefinitionHandler;
import orgomg.cwm.objectmodel.core.TaggedValue;
public class UpdateDescriptionOfAllTextIndicatorsTask extends AbstractWorksapceUpdateTask {
// indicator uuids
private final String AVERAGE_LENGTH_WITH_BLANK_AND_NULL_UUID = "__TbUIJSOEd-TE5ti6XNR2Q"; //$NON-NLS-1$
private final String AVERAGE_LENGTH_WITH_BLANK_UUID = "__gPoIJSOEd-TE5ti6XNR2Q"; //$NON-NLS-1$
private final String AVERAGE_LENGTH_WITH_NULL_UUID = "__vI_wJSOEd-TE5ti6XNR2Q"; //$NON-NLS-1$
private final String AVERAGE_LENGTH_UUID = "_ccIR4BF2Ed2PKb6nEJEvhw"; //$NON-NLS-1$
private final String MAXIMAL_LENGTH_WITH_BLANK_AND_NULL_UUID = "_-hzp8JSOEd-TE5ti6XNR2Q"; //$NON-NLS-1$
private final String MAXIMAL_LENGTH_WITH_BLANK_UUID = "_-xmZcJSOEd-TE5ti6XNR2Q"; //$NON-NLS-1$
private final String MAXIMAL_LENGTH_WITH_NULL_UUID = "_-_UFUJSOEd-TE5ti6XNR2Q"; //$NON-NLS-1$
private final String MAXIMAL_LENGTH_UUID = "_ccHq1RF2Ed2PKb6nEJEvhw"; //$NON-NLS-1$
private final String MINIMAL_LENGTH_WITH_BLANK_AND_NULL_UUID = "_9HDjMJSOEd-TE5ti6XNR2Q"; //$NON-NLS-1$
private final String MINIMAL_LENGTH_WITH_BLANK_UUID = "_G4EzQZU9Ed-Y15ulK_jijQ"; //$NON-NLS-1$
private final String MINIMAL_LENGTH_WITH_NULL_UUID = "_a4KsoI1qEd-xwI2imLgHRA"; //$NON-NLS-1$
private final String MINIMAL_LENGTH_UUID = "_ccHq1BF2Ed2PKb6nEJEvhw"; //$NON-NLS-1$
@Override
public Date getOrder() {
return createDate(2019, 7, 3);
}
@Override
public MigrationTaskType getMigrationTaskType() {
return MigrationTaskType.FILE;
}
@Override
protected boolean doExecute() throws Exception {
boolean result = true;
DefinitionHandler definitionHandler = DefinitionHandler.getInstance();
// AVERAGE_LENGTH_WITH_BLANK_AND_NULL
IndicatorDefinition definition = definitionHandler.getDefinitionById(AVERAGE_LENGTH_WITH_BLANK_AND_NULL_UUID);
if (definition != null) {
updateIndicator(definition, "evaluates the average length of the textual record",
"computes the average length of the field. ");
result = result && IndicatorDefinitionFileHelper.save(definition);
}
// AVERAGE_LENGTH_WITH_BLANK
definition = definitionHandler.getDefinitionById(AVERAGE_LENGTH_WITH_BLANK_UUID);
if (definition != null) {
updateIndicator(definition, "evaluates the average length of the textual record of non-null values",
"computes the average length of the field. Does not take into account the null values when computing the average length.");
result = result && IndicatorDefinitionFileHelper.save(definition);
}
// AVERAGE_LENGTH_WITH_NULL
definition = definitionHandler.getDefinitionById(AVERAGE_LENGTH_WITH_NULL_UUID);
if (definition != null) {
updateIndicator(definition, "evaluates the average length of the textual record of non-blank values",
"computes the average length of the field. Does not take into account the blank values when computing the average length.");
result = result && IndicatorDefinitionFileHelper.save(definition);
}
// AVERAGE_LENGTH
definition = definitionHandler.getDefinitionById(AVERAGE_LENGTH_UUID);
if (definition != null) {
updateIndicator(definition, "evaluates the average length of the textual record of non-null and non-blank values",
"computes the average length of the field. Does not take into account the null and blank values when computing the average length.");
result = result && IndicatorDefinitionFileHelper.save(definition);
}
// MAXIMAL_LENGTH_WITH_BLANK_AND_NULL
definition = definitionHandler.getDefinitionById(MAXIMAL_LENGTH_WITH_BLANK_AND_NULL_UUID);
if (definition != null) {
updateIndicator(definition, "evaluates the length of the longest textual record",
"computes the maximal length of a text field.");
result = result && IndicatorDefinitionFileHelper.save(definition);
}
// MAXIMAL_LENGTH_WITH_BLANK
definition = definitionHandler.getDefinitionById(MAXIMAL_LENGTH_WITH_BLANK_UUID);
if (definition != null) {
updateIndicator(definition, "evaluates the length of the longest textual record of non-null values",
"computes the maximal length of a text field. Does not take into account the null values when computing the maximal length.");
result = result && IndicatorDefinitionFileHelper.save(definition);
}
// MAXIMAL_LENGTH_WITH_NULL
definition = definitionHandler.getDefinitionById(MAXIMAL_LENGTH_WITH_NULL_UUID);
if (definition != null) {
updateIndicator(definition, "evaluates the length of the longest textual record of non-blank values",
"computes the maximal length of a text field. Does not take into account the blank values when computing the maximal length.");
result = result && IndicatorDefinitionFileHelper.save(definition);
}
// MAXIMAL_LENGTH
definition = definitionHandler.getDefinitionById(MAXIMAL_LENGTH_UUID);
if (definition != null) {
updateIndicator(definition, "evaluates the length of the longest textual record of non-null and non-blank values",
"computes the maximal length of a text field. Does not take into account the null and blank values when computing the maximal length.");
result = result && IndicatorDefinitionFileHelper.save(definition);
}
// MINIMAL_LENGTH_WITH_BLANK_AND_NULL
definition = definitionHandler.getDefinitionById(MINIMAL_LENGTH_WITH_BLANK_AND_NULL_UUID);
if (definition != null) {
updateIndicator(definition, "evaluates the length of the smallest textual record",
"computes the minimal length of a text field.");
result = result && IndicatorDefinitionFileHelper.save(definition);
}
// MINIMAL_LENGTH_WITH_BLANK
definition = definitionHandler.getDefinitionById(MINIMAL_LENGTH_WITH_BLANK_UUID);
if (definition != null) {
updateIndicator(definition, "evaluates the length of the smallest textual record of non-null values",
"computes the minimal length of a text field. Does not take into account the null values when computing the minimal length.");
result = result && IndicatorDefinitionFileHelper.save(definition);
}
// MINIMAL_LENGTH_WITH_NULL
definition = definitionHandler.getDefinitionById(MINIMAL_LENGTH_WITH_NULL_UUID);
if (definition != null) {
updateIndicator(definition, "evaluates the length of the smallest textual record of non-blank values",
"computes the minimal length of a text field. Does not take into account the blank values when computing the minimal length.");
result = result && IndicatorDefinitionFileHelper.save(definition);
}
// MINIMAL_LENGTH
definition = definitionHandler.getDefinitionById(MINIMAL_LENGTH_UUID);
if (definition != null) {
updateIndicator(definition, "evaluates the length of the smallest textual record of non-null and non-blank values",
"computes the minimal length of a text field. Does not take into account the null and blank values when computing the minimal length.");
result = result && IndicatorDefinitionFileHelper.save(definition);
}
DefinitionHandler.getInstance().reloadIndicatorsDefinitions();
return result;
}
private void updateIndicator(IndicatorDefinition definition, String purpose, String description) {
TaggedValue taggedValue = TaggedValueHelper.getTaggedValue(TaggedValueHelper.DESCRIPTION, definition.getTaggedValue());
if (taggedValue != null) {
taggedValue.setValue(description);
}
taggedValue = TaggedValueHelper.getTaggedValue(TaggedValueHelper.PURPOSE, definition.getTaggedValue());
if (taggedValue != null) {
taggedValue.setValue(purpose);
}
}
}
| 51.526627 | 156 | 0.708544 |
f2fff2378aa4a608c9ceafd7d52b3258aa70a379
| 502 |
class Solution {
public boolean isPerfectSquare(int num) {
if (num < 2)
return true;
int L = 2;
int R = num;
long square;
int mid;
while (L <= R) {
mid = (L + R) / 2;
square = (long) mid * mid;
if ((int) square == num)
return true;
else if (square > num) {
R = mid - 1;
} else
L = mid + 1;
}
return false;
}
}
| 22.818182 | 45 | 0.366534 |
8b2084a11c9f7ef0fe7c7740ca168066866adbdf
| 555 |
package com.gEmbedded.api.device.gpio.pin;
import com.gEmbedded.api.device.gpio.listener.EventListener;
import java.util.Optional;
public interface PWMPin {
PWMPin getInstanceIfExist(PinNumber pinNumber);
PinType getPinType();
PWMType getPWMType();
PinNumber getPinNumber();
PinFunction getPinFunction();
PullUpDownStatus getPullUpDownStatus();
EventDetectStatus getEventDetectStatus();
Optional<EventListener> getEventListener();
void pulse(final int periodMicroSecond, final int dutyCycleMicroSecond);
}
| 19.821429 | 76 | 0.762162 |
e348493b466bab2fe73e3fb69c189990fb73f0cd
| 3,406 |
/*
* @(#)DependencyFigure.java
*
* Copyright (c) 1996-2010 by the original authors of JHotDraw and all its
* contributors. All rights reserved.
*
* You may not use, copy or modify this file, except in compliance with the
* license agreement you entered into with the copyright holders. For details
* see accompanying license terms.
*/
package org.jhotdraw.samples.pert.figures;
import org.jhotdraw.draw.connector.Connector;
import org.jhotdraw.draw.decoration.ArrowTip;
import java.awt.*;
import static org.jhotdraw.draw.AttributeKeys.*;
import org.jhotdraw.draw.*;
/**
* DependencyFigure.
*
* @author Werner Randelshofer.
* @version $Id: DependencyFigure.java 718 2010-11-21 17:49:53Z rawcoder $
*/
public class DependencyFigure extends LineConnectionFigure {
/** Creates a new instance. */
public DependencyFigure() {
set(STROKE_COLOR, new Color(0x000099));
set(STROKE_WIDTH, 1d);
set(END_DECORATION, new ArrowTip());
setAttributeEnabled(END_DECORATION, false);
setAttributeEnabled(START_DECORATION, false);
setAttributeEnabled(STROKE_DASHES, false);
setAttributeEnabled(FONT_ITALIC, false);
setAttributeEnabled(FONT_UNDERLINE, false);
}
/**
* Checks if two figures can be connected. Implement this method
* to constrain the allowed connections between figures.
*/
@Override
public boolean canConnect(Connector start, Connector end) {
if ((start.getOwner() instanceof TaskFigure)
&& (end.getOwner() instanceof TaskFigure)) {
TaskFigure sf = (TaskFigure) start.getOwner();
TaskFigure ef = (TaskFigure) end.getOwner();
// Disallow multiple connections to same dependent
if (ef.getPredecessors().contains(sf)) {
return false;
}
// Disallow cyclic connections
return !sf.isDependentOf(ef);
}
return false;
}
@Override
public boolean canConnect(Connector start) {
return (start.getOwner() instanceof TaskFigure);
}
/**
* Handles the disconnection of a connection.
* Override this method to handle this event.
*/
@Override
protected void handleDisconnect(Connector start, Connector end) {
TaskFigure sf = (TaskFigure) start.getOwner();
TaskFigure ef = (TaskFigure) end.getOwner();
sf.removeDependency(this);
ef.removeDependency(this);
}
/**
* Handles the connection of a connection.
* Override this method to handle this event.
*/
@Override
protected void handleConnect(Connector start, Connector end) {
TaskFigure sf = (TaskFigure) start.getOwner();
TaskFigure ef = (TaskFigure) end.getOwner();
sf.addDependency(this);
ef.addDependency(this);
}
@Override
public DependencyFigure clone() {
DependencyFigure that = (DependencyFigure) super.clone();
return that;
}
@Override
public int getLayer() {
return 1;
}
@Override
public void removeNotify(Drawing d) {
if (getStartFigure() != null) {
((TaskFigure) getStartFigure()).removeDependency(this);
}
if (getEndFigure() != null) {
((TaskFigure) getEndFigure()).removeDependency(this);
}
super.removeNotify(d);
}
}
| 28.864407 | 77 | 0.643277 |
68f7fa229581dbcb506ff655904c8c3fb1df868c
| 615 |
package ru.job4j.storage;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class UserStorageTest {
private UserStorage stoge = new UserStorage();
@Test
public void whenTryToUseStorageThenUseItWell() {
assertThat(stoge.add(new User(1, 100)), is(true));
assertThat(stoge.add(new User(2, 200)), is(true));
assertThat(stoge.transfer(1, 2, 50), is(true));
assertThat(stoge.getUsers().get(0).getAmount(), is(50));
assertThat(stoge.getUsers().get(1).getAmount(), is(250));
}
}
| 29.285714 | 66 | 0.652033 |
a6058d366142ee7bfd3f6f0e8ddc184fa6b501dd
| 2,534 |
/* Copyright (c) 2013 OpenPlans. All rights reserved.
* This code is licensed under the GNU GPL 2.0 license, available at the root
* application directory.
*/
package org.geogit.rest.repository;
import static org.geogit.rest.repository.RESTUtils.getGeogit;
import java.io.IOException;
import java.io.InputStream;
import org.geogit.api.GeoGIT;
import org.geogit.remote.BinaryPackedObjects;
import org.geogit.remote.BinaryPackedObjects.IngestResults;
import org.restlet.data.Request;
import org.restlet.data.Status;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Stopwatch;
import com.google.common.io.Closeables;
import com.google.common.io.CountingInputStream;
/**
*
*/
public class SendObjectResource extends Resource {
private static final Logger LOGGER = LoggerFactory.getLogger(SendObjectResource.class);
@Override
public boolean allowPost() {
return true;
}
@Override
public void post(Representation entity) {
InputStream input = null;
Request request = getRequest();
try {
LOGGER.info("Receiving objects from {}", request.getClientInfo().getAddress());
Representation representation = request.getEntity();
input = representation.getStream();
final GeoGIT ggit = getGeogit(request).get();
final BinaryPackedObjects unpacker = new BinaryPackedObjects(ggit.getRepository()
.objectDatabase());
CountingInputStream countingStream = new CountingInputStream(input);
Stopwatch sw = Stopwatch.createStarted();
IngestResults ingestResults = unpacker.ingest(countingStream);
sw.stop();
LOGGER.info(String
.format("SendObjectResource: Processed %,d objects.\nInserted: %,d.\nExisting: %,d.\nTime to process: %s.\nStream size: %,d bytes.\n",
ingestResults.total(), ingestResults.getInserted(),
ingestResults.getExisting(), sw, countingStream.getCount()));
} catch (IOException e) {
LOGGER.warn("Error processing incoming objects from {}", request.getClientInfo()
.getAddress(), e);
throw new RestletException(e.getMessage(), Status.SERVER_ERROR_INTERNAL, e);
} finally {
if (input != null)
Closeables.closeQuietly(input);
}
}
}
| 34.712329 | 154 | 0.669298 |
ee57cae50fce108040f2b85e624095fdc1a52bfb
| 2,257 |
/*
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.ar.core.codelab.cloudanchor.helpers;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
/** Helper class for managing on-device storage of cloud anchor IDs. */
public class StorageManager {
private static final String SHARED_PREFS_NAME = "cloud_anchor_codelab_short_codes";
private static final String NEXT_SHORT_CODE = "next_short_code";
private static final String KEY_PREFIX = "anchor;";
private static final int INITIAL_SHORT_CODE = 1;
/** Gets a new short code that can be used to store the anchor ID. */
public int nextShortCode(Activity activity) {
SharedPreferences sharedPrefs =
activity.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
int shortCode = sharedPrefs.getInt(NEXT_SHORT_CODE, INITIAL_SHORT_CODE);
sharedPrefs.edit().putInt(NEXT_SHORT_CODE, shortCode + 1).apply();
return shortCode;
}
/** Stores the cloud anchor ID in the activity's SharedPrefernces. */
public void storeUsingShortCode(Activity activity, int shortCode, String cloudAnchorId) {
SharedPreferences sharedPrefs = activity.getPreferences(Context.MODE_PRIVATE);
sharedPrefs.edit().putString(KEY_PREFIX + shortCode, cloudAnchorId).apply();
}
/**
* Retrieves the cloud anchor ID using a short code. Returns an empty string if a cloud anchor ID
* was not stored for this short code.
*/
public String getCloudAnchorId(Activity activity, int shortCode) {
SharedPreferences sharedPrefs = activity.getPreferences(Context.MODE_PRIVATE);
return sharedPrefs.getString(KEY_PREFIX + shortCode, "");
}
}
| 41.796296 | 99 | 0.758972 |
f0cec376a6e5bbd749ab90c5d8cdc1f1929d6997
| 27,961 |
package com.dtrules.compiler.excel.util;
import java.awt.font.FontRenderContext;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.io.FileOutputStream;
import java.text.AttributedString;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import com.dtrules.admin.IRulesAdminService;
import com.dtrules.admin.RulesAdminService;
import com.dtrules.decisiontables.RDecisionTable;
import com.dtrules.entity.IREntity;
import com.dtrules.entity.REntityEntry;
import com.dtrules.infrastructure.RulesException;
import com.dtrules.interpreter.RName;
import com.dtrules.session.EntityFactory;
import com.dtrules.session.IRSession;
import com.dtrules.session.RuleSet;
import com.dtrules.session.RulesDirectory;
public class Rules2Excel {
boolean balanced = false;
int maxCol = 16;
IRulesAdminService admin;
RulesDirectory rd;
RuleSet rs;
IRSession session;
String tablefilename;
Workbook wb;
int sheetCnt = 0; // The index of the "about to be created" sheet.
CellStyle cs_default;
CellStyle cs_title;
CellStyle cs_header;
CellStyle cs_num_header;
CellStyle cs_field;
CellStyle cs_comment;
CellStyle cs_formal;
CellStyle cs_table;
CellStyle cs_type;
CellStyle cs_number;
public Rules2Excel(boolean balanced){
this.balanced = balanced;
}
void newWb() {
wb = new HSSFWorkbook();
sheetCnt = 0;
cs_default = wb.createCellStyle();
cs_title = wb.createCellStyle();
cs_header = wb.createCellStyle();
cs_num_header = wb.createCellStyle();
cs_field = wb.createCellStyle();
cs_comment = wb.createCellStyle();
cs_formal = wb.createCellStyle();
cs_table = wb.createCellStyle();
cs_type = wb.createCellStyle();
cs_number = wb.createCellStyle();
Font title_font = wb.createFont();
title_font.setFontHeightInPoints((short)12);
title_font.setColor(HSSFColor.DARK_BLUE.index);
Font header_font = wb.createFont();
header_font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
header_font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
Font table_font = wb.createFont();
table_font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
defaultcellstyle(cs_default);
defaultcellstyle(cs_title);
defaultcellstyle(cs_header);
defaultcellstyle(cs_num_header);
defaultcellstyle(cs_field);
defaultcellstyle(cs_comment);
defaultcellstyle(cs_formal);
defaultcellstyle(cs_table);
defaultcellstyle(cs_type);
defaultcellstyle(cs_number);
// Fonts
cs_title.setFont(title_font);
cs_header.setFont(header_font);
cs_table.setFont(table_font);
// Background
cs_title.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
cs_header.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
cs_header.setFillPattern(CellStyle.SOLID_FOREGROUND);
cs_num_header.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
cs_num_header.setFillPattern(CellStyle.SOLID_FOREGROUND);
cs_num_header.setAlignment(CellStyle.ALIGN_CENTER);
cs_num_header.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
cs_formal.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
cs_comment.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
cs_type.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
cs_type.setFillPattern(CellStyle.SOLID_FOREGROUND);
cs_number.setAlignment(CellStyle.ALIGN_CENTER);
cs_number.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
cs_table.setAlignment(CellStyle.ALIGN_CENTER);
cs_table.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
}
private void defaultcellstyle(CellStyle cs){
cs.setBorderBottom(CellStyle.BORDER_THIN);
cs.setBottomBorderColor(IndexedColors.BLACK.getIndex());
cs.setBorderTop(CellStyle.BORDER_THIN);
cs.setTopBorderColor(IndexedColors.BLACK.getIndex());
cs.setBorderLeft(CellStyle.BORDER_THIN);
cs.setLeftBorderColor(IndexedColors.BLACK.getIndex());
cs.setBorderRight(CellStyle.BORDER_THIN);
cs.setRightBorderColor(IndexedColors.BLACK.getIndex());
cs.setWrapText(true);
cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
cs.setAlignment(CellStyle.ALIGN_LEFT);
}
private Sheet newDecisionTableSheet(){
Sheet s = wb.createSheet(); // Create the sheet for this decision table
s.setColumnWidth(0,800); // Numbers for Contexts, Actions, Conditions, etc.
s.setColumnWidth(1,12000); // Numbers for Contexts, Actions, Conditions, etc.
s.setColumnWidth(2,12000); // Numbers for Contexts, Actions, Conditions, etc.
for(int i = 0; i < maxCol; i++){
s.setColumnWidth(i+3, 700);
}
Cell c;
Row r = s.createRow(0);
r.setHeightInPoints(20);
for(int i = 0; i <= maxCol+2; i++){
c = r.createCell(i);
c.setCellValue("");
c.setCellStyle(cs_default);
}
return s;
}
Row nextRow(Sheet s, int cRow, int columnCnt){
Row r = s.createRow(cRow);
r.setHeight((short)-1);
for(int i = 0; i <= columnCnt; i++){
Cell c = r.createCell(i);
if(i==0){
c.setCellStyle(cs_number);
}else if(i>=3){
c.setCellStyle(cs_table);
}else{
c.setCellStyle(cs_default);
}
}
return r;
}
void setCell (Row r, Cell c, String text, int width){
if(text == null) text = "";
c.setCellValue(text);
// Create Font object with Font attribute (e.g. Font family, Font size, etc)
// for calculation
if(text.length()>0){
java.awt.Font currFont = new java.awt.Font("Arial", java.awt.Font.PLAIN, 10);
AttributedString attrStr = new AttributedString(text);
attrStr.addAttribute(TextAttribute.FONT, currFont);
// Use LineBreakMeasurer to count number of lines needed for the text
FontRenderContext frc = new FontRenderContext(null, true, true);
LineBreakMeasurer measurer = new LineBreakMeasurer(attrStr.getIterator(),
frc);
int nextPos = 0;
int lineCnt = 0;
while (measurer.getPosition() < text.length()) {
nextPos = measurer.nextOffset(width/43); // mergedCellWidth is the max width of each line
lineCnt++;
measurer.setPosition(nextPos);
}
if(255*lineCnt > r.getHeight()){
r.setHeight((short)(255 * lineCnt));
}
}
}
/**
* Write out one Decision Table into one Sheet.
* @param dt
*/
private void writeDT(RDecisionTable dt){
if(balanced){
maxCol = dt.getActionTableBalanced(session).length>0 ? dt.getActionTableBalanced(session)[0].length : 0;
if(maxCol <16) maxCol = 16;
}else{
maxCol = 16;
}
Sheet s = newDecisionTableSheet(); // Create the sheet for this decision table
int cRow = 0; // Our current row.
cRow = writeName(dt, s, cRow);
cRow = writeType(dt, s, cRow);
cRow = writeFields(dt, s, cRow);
cRow = writeContexts(dt, s, cRow);
cRow = writeInitialActions(dt, s, cRow);
cRow = writeConditions(dt, s, cRow);
cRow = writeActions(dt, s, cRow);
cRow = writePolicyStatements(dt, s, cRow);
}
int writeName(RDecisionTable dt, Sheet s, int cRow){
// Name
String name = dt.getName().stringValue(); // Get the name of the Decision Table
name = name.replaceAll("_", " ");
String sname = name;
if(sname.length()>30){
sname = sname.substring(0,30)+sheetCnt;
}
boolean tryAgain = true;
int cnt = 0;
String n = sname;
while(tryAgain){
try{
wb.setSheetName(sheetCnt, sname); // Set the sheet name, and increment the count.
tryAgain = false;
}catch(IllegalArgumentException e){
sname = ++cnt + n;
}
}
sheetCnt++;
Row r = s.getRow(cRow); // Get the first row.
Cell c = r.createCell(0);
s.addMergedRegion(new CellRangeAddress(cRow,cRow,0,maxCol+2));
setCell(r, c, "Name: "+name,
s.getColumnWidth(1)+
s.getColumnWidth(2)+
s.getColumnWidth(3)*maxCol);
c.setCellStyle(cs_title);
return cRow+1;
}
int writeType(RDecisionTable dt, Sheet s, int cRow){
// Type
Row r = nextRow(s, cRow, maxCol+2); // Create a new row
Cell c = r.createCell(0);
s.addMergedRegion(new CellRangeAddress(cRow,cRow,0,maxCol+2));
setCell(r, c, "Type: "+dt.getType(),
s.getColumnWidth(1)+
s.getColumnWidth(2)+
s.getColumnWidth(3)*maxCol);
c.setCellStyle(cs_type);
return cRow+1;
}
int writeFields(RDecisionTable dt, Sheet s, int cRow){
// Get the fields, sort them so they always come out in the same order
Map<RName,String> fields = dt.fields;
RName [] fieldnames = new RName[0];
fieldnames = fields.keySet().toArray(fieldnames);
for(int i=0; i < fieldnames.length-1; i++){
for(int j=0; j < fieldnames.length-i-1;j++){
try {
if(fieldnames[j].compare(fieldnames[j+1])>0){
RName hld = fieldnames[j];
fieldnames[j] = fieldnames[j+1];
fieldnames[j+1] = hld;
}
} catch (RulesException e) { } // Nothing to do on an error to compare...
}
}
for(RName field : fieldnames){
if(field.stringValue().equalsIgnoreCase("type")) continue;
Row r = nextRow(s, cRow, maxCol+2); // Create a new row
Cell c = r.createCell(0);
s.addMergedRegion(new CellRangeAddress(cRow,cRow,0,maxCol+2));
setCell(r, c, field.stringValue()+": "+fields.get(field),
s.getColumnWidth(1)+
s.getColumnWidth(2)+
s.getColumnWidth(3)*maxCol);
c.setCellStyle(cs_field);
cRow++;
}
// Add a blank row
Row r = nextRow(s, cRow, maxCol+2); // Create a new row
Cell c = r.createCell(0);
c.setCellStyle(cs_field);
s.addMergedRegion(new CellRangeAddress(cRow,cRow,0,maxCol+2));
return cRow+1;
}
int writeContexts(RDecisionTable dt, Sheet s, int cRow){
//CONTEXTS:
{
Row r = nextRow(s, cRow, maxCol+2); // Create a new row
Cell c = r.createCell(0);
s.addMergedRegion(new CellRangeAddress(cRow,cRow,0,maxCol+2));
c.setCellValue("Contexts:");
c.setCellStyle(cs_header);
cRow++;
String contexts [] = dt.getContexts();
String ccontexts [] = dt.getContextsComment();
for(int cnt = 1; cnt <= contexts.length; cnt++){
r = nextRow(s, cRow, maxCol+2); // Create a new row
c = r.createCell(0);
c.setCellValue(cnt);
c.setCellStyle(cs_number);
c = r.createCell(1);
c.setCellStyle(cs_comment);
setCell(r,c, ccontexts[cnt-1],s.getColumnWidth(1));
c = r.createCell(2);
s.addMergedRegion(new CellRangeAddress(cRow,cRow,2,maxCol+2));
c.setCellStyle(cs_formal);
setCell(r,c, contexts[cnt-1], s.getColumnWidth(2)+s.getColumnWidth(3)*maxCol);
cRow++;
}
r = nextRow(s, cRow, maxCol+2); // Create a new row
s.addMergedRegion(new CellRangeAddress(cRow,cRow,2,maxCol+2));
}
return cRow+1;
}
int writeInitialActions(RDecisionTable dt, Sheet s, int cRow){
Row r = nextRow(s, cRow, maxCol+2); // Create a new row
Cell c = r.createCell(0);
s.addMergedRegion(new CellRangeAddress(cRow,cRow,0,1));
s.addMergedRegion(new CellRangeAddress(cRow,cRow,2,maxCol+2));
c.setCellValue("Initial Actions:");
c.setCellStyle(cs_header);
c = r.createCell(2);
c.setCellValue("Initial Actions");
c.setCellStyle(cs_header);
cRow++;
String iactions [] = dt.getInitialActions();
String ciactions [] = dt.getInitialActionsComment();
for(int cnt=1; cnt<=iactions.length; cnt++){
r = nextRow(s, cRow, maxCol+2); // Create a new row
c = r.createCell(0);
c.setCellValue(cnt);
c.setCellStyle(cs_number);
c = r.createCell(1);
c.setCellStyle(cs_comment);
setCell(r,c,ciactions[cnt-1],s.getColumnWidth(1));
c = r.createCell(2);
s.addMergedRegion(new CellRangeAddress(cRow,cRow,2,maxCol+2));
c.setCellStyle(cs_formal);
setCell(r,c,iactions[cnt-1],s.getColumnWidth(2)+s.getColumnWidth(3)*maxCol);
c.setCellValue(iactions[cnt-1]);
cRow++;
}
r = nextRow(s, cRow, maxCol+2); // Create a new row
s.addMergedRegion(new CellRangeAddress(cRow,cRow,2,maxCol+2));
return cRow+1;
}
int writeConditions(RDecisionTable dt, Sheet s, int cRow){
Row r = nextRow(s, cRow, maxCol+2); // Create a new row
Cell c = r.createCell(0);
s.addMergedRegion(new CellRangeAddress(cRow,cRow,0,1));
c.setCellValue("Conditions:");
c.setCellStyle(cs_header);
for(int i = 3; i <= maxCol+2; i++){
c = r.createCell(i);
c.setCellValue(i-2);
c.setCellStyle(cs_num_header);
}
c = r.createCell(2);
c.setCellValue("Conditions");
c.setCellStyle(cs_header);
cRow++;
int startRow = cRow;
String conditions [] = dt.getConditions();
String cConditions [] = dt.getConditionsComment();
for(int cnt=1; cnt <= conditions.length; cnt++){
r = nextRow(s, cRow, maxCol+2); // Create a new row
c = r.createCell(0);
c.setCellValue(cnt);
c.setCellStyle(cs_number);
c = r.createCell(1);
c.setCellStyle(cs_comment);
setCell(r, c, cConditions[cnt-1], s.getColumnWidth(1));
c = r.createCell(2);
c.setCellStyle(cs_formal);
setCell(r, c, conditions[cnt-1], s.getColumnWidth(2));
cRow++;
}
r = nextRow(s, cRow, maxCol+2); // Create a new row
String conditionTable[][] = balanced ? dt.getConditionTableBalanced(session) : dt.getConditiontable();
for(int i = 0; i < conditionTable.length; i++){
Row cr = s.getRow(startRow+i);
for(int j = 0; j < conditionTable[i].length; j++){
String v = "";
if(conditionTable[i][j] != null && !conditionTable[i][j].equals("-")){
v = conditionTable[i][j];
}
Cell cell = cr.createCell(3+j);
cell.setCellValue(v);
cell.setCellStyle(cs_table);
}
}
return cRow+1;
}
int writeActions(RDecisionTable dt, Sheet s, int cRow){
Row r = nextRow(s, cRow, maxCol+2); // Create a new row
Cell c = r.createCell(0);
s.addMergedRegion(new CellRangeAddress(cRow,cRow,0,1));
c.setCellValue("Actions:");
c.setCellStyle(cs_header);
for(int i = 3; i <= maxCol+2; i++){
c = r.createCell(i);
c.setCellValue(i-2);
c.setCellStyle(cs_num_header);
}
c = r.createCell(2);
c.setCellValue("Actions");
c.setCellStyle(cs_header);
cRow++;
int startRow = cRow;
String actions [] = dt.getActions();
String cActions [] = dt.getActionsComment();
for(int cnt=1; cnt <= actions.length; cnt++){
r = nextRow(s, cRow, maxCol+2); // Create a new row
c = r.createCell(0);
c.setCellValue(cnt);
c.setCellStyle(cs_number);
c = r.createCell(1);
c.setCellStyle(cs_comment);
setCell(r, c, cActions[cnt-1], s.getColumnWidth(1));
c = r.createCell(2);
c.setCellStyle(cs_formal);
setCell(r, c, actions[cnt-1], s.getColumnWidth(2));
cRow++;
}
r = nextRow(s, cRow, maxCol+2); // Create a new row
String actionTable[][] = balanced ? dt.getActionTableBalanced(session) : dt.getActiontable();
for(int i = 0; i < actionTable.length; i++){
Row cr = s.getRow(startRow+i);
for(int j = 0; j < actionTable[i].length; j++){
String v = "";
if(actionTable[i][j] != null && !actionTable[i][j].equals("-")){
v = actionTable[i][j];
}
Cell cell = cr.createCell(3+j);
cell.setCellValue(v);
cell.setCellStyle(cs_table);
}
}
return cRow+1;
}
int writePolicyStatements(RDecisionTable dt, Sheet s, int cRow){
Row r = nextRow(s, cRow, maxCol+2); // Create a new row
Cell c = r.createCell(0);
s.addMergedRegion(new CellRangeAddress(cRow,cRow,0,maxCol+2));
c.setCellValue("Policy Statements:");
c.setCellStyle(cs_header);
for(int i = 3; i <= maxCol+2; i++){
c = r.createCell(i);
c.setCellValue(i-2);
c.setCellStyle(cs_num_header);
}
cRow++;
String policystatements [] =
balanced? dt.getPolicyStatementsBalanced(session) : dt.getPolicystatements();
for(int cnt=1; cnt < policystatements.length; cnt++){
r = nextRow(s, cRow, maxCol+2); // Create a new row
s.addMergedRegion(new CellRangeAddress(cRow,cRow,1,maxCol+2));
c = r.createCell(0);
c.setCellValue(cnt);
c.setCellStyle(cs_number);
c = r.createCell(1);
c.setCellStyle(cs_formal);
setCell(r, c, policystatements[cnt],
s.getColumnWidth(1)+
s.getColumnWidth(2)+
s.getColumnWidth(3)*maxCol);
cRow++;
}
r = nextRow(s, cRow, maxCol+2); // Create a new row
s.addMergedRegion(new CellRangeAddress(cRow,cRow,1,maxCol+2));
c = r.createCell(0);
c.setCellStyle(cs_number);
c = r.createCell(1);
c.setCellStyle(cs_formal);
return cRow+1;
}
/**
* We by fields specified. The first field is the primary key, followed by the secondary, etc.
* @param dts
* @param field
* @param ascending
*/
private void sort(ArrayList<RDecisionTable> dts, String fields[], boolean ascending){
if(fields == null) return;
for(int i = fields.length-1; i >=0 ; i--){
sort(dts,fields[i],ascending);
}
}
private void sort(ArrayList<RDecisionTable> dts, String field, boolean ascending){
for(int i=0; i < dts.size()-1; i++){
for(int j=0; j < dts.size()-1; j++){
RDecisionTable a = dts.get(j);
RDecisionTable b = dts.get(j+1);
String af = a.getField(field);
String bf = b.getField(field);
if(af != null && bf != null && af.compareTo(bf) < 0 ^ ascending){
dts.set(j+1,a);
dts.set(j, b);
}
}
}
}
@SuppressWarnings("unchecked")
public void writeDecisionTables(String excelName, String fields[], boolean ascending, int limit){
try{
List<?> decisiontables = admin.getDecisionTables(rs.getName());
ArrayList<RDecisionTable> dts = new ArrayList<RDecisionTable>();
for(String dt : (List<String>)decisiontables){
RDecisionTable rdt = session.getEntityFactory().findTable(dt);
dts.add(rdt);
}
sort(dts,fields,ascending);
int index = 0;
int filecnt = 1;
while(index < dts.size()){
newWb();
for(int i = 0; i < limit && index < dts.size();i++,index++){
writeDT(dts.get(index));
}
String filename = excelName+"_"+filecnt++ +"_.xls";
FileOutputStream excelfile = new FileOutputStream(filename);
wb.write(excelfile);
excelfile.close();
}
for(String dt : (List<String>)decisiontables){
RDecisionTable rdt = session.getEntityFactory().findTable(dt);
writeDT(rdt);
}
}catch(Exception e){
System.err.println("\n"+e.toString());
}
}
private Sheet newEDDSheet(){
Sheet s = wb.createSheet(); // Create the sheet for this decision table
s.setColumnWidth(0,4000); // Entity
s.setColumnWidth(1,4000); // Attribute
s.setColumnWidth(2,2000); // Type
s.setColumnWidth(3,3000); // SubType
s.setColumnWidth(4,6000); // Default Value
s.setColumnWidth(5,3000); // Input
s.setColumnWidth(6,3000); // Access
s.setColumnWidth(7,16000); // Comment
Cell c;
Row r = s.createRow(0);
r.setHeightInPoints(20);
r.createCell(0).setCellValue("Entity");
r.createCell(1).setCellValue("Attribute");
r.createCell(2).setCellValue("Type");
r.createCell(3).setCellValue("SubType");
r.createCell(4).setCellValue("Default Value");
r.createCell(5).setCellValue("Input");
r.createCell(6).setCellValue("Access");
r.createCell(7).setCellValue("Comment");
cs_title.setAlignment(CellStyle.ALIGN_CENTER);
cs_title.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
for(int i=0; i<8; i++){
r.getCell(i).setCellStyle(cs_title);
}
return s;
}
int writeEntity(Sheet s, int rowC, RName entity ){
IREntity e = session.getEntityFactory().findRefEntity(entity);
ArrayList<RName> attributes = EntityFactory.sorted(e.getAttributeIterator(),true);
for(RName a : attributes){
Row row = nextRow(s, rowC, 8);
REntityEntry entry = e.getEntry(a);
row.getCell(0).setCellValue(e.getName().stringValue()); // Name
row.getCell(1).setCellValue(a.stringValue()); // Attribute
row.getCell(2).setCellValue(entry.type.toString()); // Type
row.getCell(3).setCellValue(entry.subtype); // SubType
row.getCell(4).setCellValue(entry.defaulttxt); // Default
row.getCell(5).setCellValue(entry.input); // Input
row.getCell(6).setCellValue( (entry.readable? "r":"") + // Access
(entry.writable ? "w":"") );
setCell(row, row.getCell(7), entry.comment, 16000); // Add the comment. Wrap it.
rowC++;
}
return rowC;
}
void writeEDD(String excelName){
try{
Sheet s = newEDDSheet();
EntityFactory ef = session.getEntityFactory();
ArrayList<RName> list = EntityFactory.sorted(ef.getEntityRNameIterator(),true);
int rowC = 1;
for(RName entity : list){
rowC = writeEntity(s, rowC, entity );
nextRow(s, rowC, 8);
rowC++;
}
FileOutputStream excelfile = new FileOutputStream(excelName);
wb.write(excelfile);
excelfile.close();
}catch(Exception e){
System.err.println("\n"+e.toString());
}
}
public void writeExcel(
IRulesAdminService admin,
RuleSet ruleset,
String excelName,
String fields[],
boolean ascending,
int limit ){
try{
this.admin = admin;
rd = admin.getRulesDirectory();
rs = ruleset;
session = rs.newSession();
writeDecisionTables(ruleset.getWorkingdirectory()+excelName,fields,ascending, limit);
writeEDD(ruleset.getWorkingdirectory()+excelName+"_edd.xls");
}catch(Exception e){
System.err.println("\n"+e.toString());
}
}
}
| 36.598168 | 116 | 0.521834 |
8e2ab36d5f410bef68a5aa534b36994137a4c001
| 705 |
package io.pivotal.beach.tokyo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class DatabaseRestaurantRepository implements RestaurantRepository {
private final JdbcTemplate jdbcTemplate;
@Autowired
public DatabaseRestaurantRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<Restaurant> selectAll() {
return jdbcTemplate.query("select * from restaurant", (rs, rowNum) -> {
return new Restaurant(rs.getInt("id"), rs.getString("name"));
});
}
}
| 29.375 | 79 | 0.739007 |
5ef720ac9f8aafd02abfb05a81931f37777c39bb
| 4,889 |
package com.company;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class fileConverter {
//constructor method, calls method depending on what type of file we want to convert to
public void fileConvert(String file, String datatype) throws FileNotFoundException {
if (datatype.equals("-c")) {
convertCSV(file);
}
if (datatype.equals("-j")) {
convertJSON(file);
}
if (datatype.equals("-x")) {
convertXML(file);
}
}
//converts file to XML, very similar to JSON
private void convertXML(String inputFile) throws FileNotFoundException {
//Create Scanner object to parse file, StringBuilder to properly format. Create new array of strings with all tags.
Scanner fileScnr = new Scanner(new File(inputFile));
StringBuilder frmtedFile = new StringBuilder();
String[] tagArray = fileScnr.nextLine().split("\\t");
//Format the text file to JSON.
frmtedFile.append("<players>" + "\n");
while (fileScnr.hasNextLine()) {
String [] currLine = fileScnr.nextLine().split("\\t");
//i want to go to bed, im sorry for my sins
frmtedFile.append("\t<player>\n");
for (int i = 0; i < tagArray.length; i++){
tagArray[i] = tagArray[i].replaceAll(" ","");
tagArray[i] = tagArray[i].replaceAll("/", "");
tagArray[i] = tagArray[i].replaceAll("\\(", "");
tagArray[i] = tagArray[i].replaceAll("\\)", "");
tagArray[i] = tagArray[i].replaceAll("1", "");
tagArray[i] = tagArray[i].replaceAll("2", "");
tagArray[i] = tagArray[i].replaceAll("3", "");
tagArray[i] = tagArray[i].replaceAll("4", "");
tagArray[i] = tagArray[i].replaceAll("5", "");
tagArray[i] = tagArray[i].replaceAll("6", "");
tagArray[i] = tagArray[i].replaceAll("7", "");
tagArray[i] = tagArray[i].replaceAll("8", "");
tagArray[i] = tagArray[i].replaceAll("9", "");
tagArray[i] = tagArray[i].replaceAll("0", "");
frmtedFile.append("\t\t" + '<' + tagArray[i] + '>' + currLine[i].replaceAll(" ",""));
frmtedFile.append("</" + tagArray[i] + ">\n");
}
frmtedFile.append("\t</player>\n");
}
frmtedFile.append("\n</players>");
//Write out to new file, close stream.
PrintWriter out = new PrintWriter("C:\\Users\\row3b\\IdeaProjects\\HW #2 CMPE 131\\src\\outputXML.xml");
out.print(frmtedFile);
out.close();
}
private void convertJSON(String inputFile) throws FileNotFoundException {
//Create Scanner object to parse file, StringBuilder to properly format. Create new array of strings with all tags.
Scanner fileScnr = new Scanner(new File(inputFile));
StringBuilder frmtedFile = new StringBuilder();
String[] tagArray = fileScnr.nextLine().split("\\t");
//Format the text file to JSON.
frmtedFile.append("[" + "\n");
while (fileScnr.hasNextLine()) {
String [] currLine = fileScnr.nextLine().split("\\t");
frmtedFile.append("\t{\n");
for (int i = 0; i < tagArray.length; i++){
frmtedFile.append("\t\t" + '"' + tagArray[i]+'"' + ":" + '"' + currLine[i] + '"');
if (i < tagArray.length-1){
frmtedFile.append(",");
}
frmtedFile.append("\n");
}
frmtedFile.append("\t},\n");
}
frmtedFile.delete(frmtedFile.length()-2,frmtedFile.length());
frmtedFile.append("\n]");
//Write out to new file, close stream.
PrintWriter out = new PrintWriter("C:\\Users\\row3b\\IdeaProjects\\HW #2 CMPE 131\\src\\outputJSON.json");
out.print(frmtedFile);
out.close();
}
public void convertCSV(String inputFile) throws FileNotFoundException {
Scanner fileScnr = new Scanner(new File(inputFile));
StringBuilder frmtedFile = new StringBuilder();
//Format the text file to CSV.
while (fileScnr.hasNextLine()) {
String currLine = fileScnr.nextLine();
currLine = (currLine.replaceAll("\\t", ","));
frmtedFile.append(currLine);
frmtedFile.append("\n");
}
//Write out to new file, close stream.
PrintWriter out = new PrintWriter("C:\\Users\\row3b\\IdeaProjects\\HW #2 CMPE 131\\src\\outputCSV.csv");
out.print(frmtedFile);
out.close();
}
}
| 39.112 | 125 | 0.54142 |
d65f26322780c508c0f7d2c72e43d988d27d09cd
| 2,382 |
package cn.enjoy.zk;
import org.I0Itec.zkclient.IZkDataListener;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class ZookeeperDistrbuteLock2 extends ZookeeperAbstractLock {
private CountDownLatch countDownLatch = null;
private String beforePath;//当前请求的节点前一个节点
private String currentPath;//当前请求的节点
public ZookeeperDistrbuteLock2() {
if (!this.zkClient.exists(PATH2)) {
this.zkClient.createPersistent(PATH2);
}
}
@Override
public boolean tryLock() {
//如果currentPath为空则为第一次尝试加锁,第一次加锁赋值currentPath
if (currentPath == null || currentPath.length() <= 0) {
//创建一个临时顺序节点
currentPath = this.zkClient.createEphemeralSequential(PATH2 + '/', "lock");
}
//获取所有临时节点并排序,临时节点名称为自增长的字符串如:0000000400
List<String> childrens = this.zkClient.getChildren(PATH2);
Collections.sort(childrens);
if (currentPath.equals(PATH2 + '/' + childrens.get(0))) {//如果当前节点在所有节点中排名第一则获取锁成功
return true;
} else {//如果当前节点在所有节点中排名中不是排名第一,则获取前面的节点名称,并赋值给beforePath
//获取当前节点的索引值
int wz = Collections.binarySearch(childrens,
currentPath.substring(7));
beforePath = PATH2 + '/' + childrens.get(wz - 1);
}
return false;
}
@Override
public void waitLock() {
IZkDataListener listener = new IZkDataListener() {
public void handleDataDeleted(String dataPath) throws Exception {
if (countDownLatch != null) {
countDownLatch.countDown();
}
}
public void handleDataChange(String dataPath, Object data) throws Exception {
}
};
//给排在前面的的节点增加数据删除的watcher,本质是启动另外一个线程去监听前置节点
this.zkClient.subscribeDataChanges(beforePath, listener);
if (this.zkClient.exists(beforePath)) {
countDownLatch = new CountDownLatch(1);
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.zkClient.unsubscribeDataChanges(beforePath, listener);
}
public void unLock() {
//删除当前临时节点
zkClient.delete(currentPath);
zkClient.close();
}
}
| 29.04878 | 89 | 0.611671 |
e35ac398c4e93d2f21e6e15a365c04de12d3d67f
| 5,347 |
package com.cognition.android.mailboxapp.models;
import com.google.api.services.gmail.model.MessagePart;
import com.raizlabs.android.dbflow.annotation.ColumnIgnore;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import com.raizlabs.android.dbflow.structure.BaseModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import java.util.Map;
@Table(database = AppDatabase.class, allFields = true)
public class Message extends BaseModel {
@PrimaryKey(autoincrement = true)
private int id;
private int message_id;
private String labelsJson;
private String snippet;
private String mimetype;
private String headersJson;
private String parentPartJson;
private String partsJson;
private String from;
private String subject;
private String summary;
private long timestamp;
private int color;
@ColumnIgnore
private List<String> labels;
@ColumnIgnore
private Map<String, String> headers;
@ColumnIgnore
private MessagePart parentPart;
@ColumnIgnore
private List<MessagePart> parts;
public Message() {
}
public Message(List<String> labels, String snippet, String mimetype, Map<String, String> headers, List<MessagePart> parts, long timestamp, int color, MessagePart parentPart, String summary) throws JSONException {
this.labels = labels;
this.snippet = snippet;
this.mimetype = mimetype;
this.headers = headers;
this.parts = parts;
this.timestamp = timestamp;
this.parentPart = parentPart;
this.summary = summary;
this.from = this.headers.get("From");
this.subject = this.headers.get("Subject");
this.color = color;
if (this.labels != null) {
JSONArray labelsArr = new JSONArray();
for (String label : this.labels)
labelsArr.put(label);
this.labelsJson = labelsArr.toString();
}
if (this.headers != null) {
JSONObject headersObj = new JSONObject();
for (Map.Entry<String, String> header : this.headers.entrySet())
headersObj.put(header.getKey(), header.getValue());
this.headersJson = headersObj.toString();
}
if (this.parts != null) {
JSONArray partsArr = new JSONArray();
for (MessagePart messagePart : this.parts)
partsArr.put(messagePart.toString());
this.partsJson = partsArr.toString();
}
if (this.parentPart != null)
this.parentPartJson = parentPart.toString();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getMessage_id() {
return message_id;
}
public void setMessage_id(int message_id) {
this.message_id = message_id;
}
public List<String> getLabels() {
return labels;
}
public void setLabels(List<String> labels) {
this.labels = labels;
}
public String getSnippet() {
return snippet;
}
public void setSnippet(String snippet) {
this.snippet = snippet;
}
public String getMimetype() {
return mimetype;
}
public void setMimetype(String mimetype) {
this.mimetype = mimetype;
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public List<MessagePart> getParts() {
return parts;
}
public void setParts(List<MessagePart> parts) {
this.parts = parts;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public int getColor() {
return color;
}
public void setColor(int color) {
this.color = color;
}
public String getLabelsJson() {
return labelsJson;
}
public void setLabelsJson(String labelsJson) {
this.labelsJson = labelsJson;
}
public String getHeadersJson() {
return headersJson;
}
public void setHeadersJson(String headersJson) {
this.headersJson = headersJson;
}
public String getPartsJson() {
return partsJson;
}
public void setPartsJson(String partsJson) {
this.partsJson = partsJson;
}
public MessagePart getParentPart() {
return parentPart;
}
public void setParentPart(MessagePart parentPart) {
this.parentPart = parentPart;
}
public String getParentPartJson() {
return parentPartJson;
}
public void setParentPartJson(String parentPartJson) {
this.parentPartJson = parentPartJson;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
}
| 24.415525 | 216 | 0.628951 |
de9fa48c8a3aeb3994b7568a65dfd7fbf12d5215
| 2,480 |
package com.github.q115.goalie_android;
/*
* Copyright 2017 Qi Li
*
* 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.
*/
public class Constants {
public static final String URL = BuildConfig.DEBUG ? "http://104.197.166.11:8080" : "http://goalie.es";
public static final String KEY = BuildConfig.DEBUG ? "xxx" : "xxxx";
public static final String CUSTOM_KEY = BuildConfig.DEBUG ? "CUSTOM_KEY" : "CUSTOM_KEY_PROD";
public static final String PREFERENCE_FILE_NAME = "PREFERENCE_FILE_NAME";
public static final String FAILED_TO_CONNECT = "Connection failure, please ensure internet connection is active.";
public static final String FAILED_TO_SEND = "Failed to reach server, please try again.";
public static final String FAILED = "Failed";
public static final int MAX_USERNAME_LENGTH = 30;
//profile image sizes
public static final int IMAGE_JPG_QUALITY = 99;
public static final int PROFILE_ROW_SIZE = 75; // dp
public static final int PROFILE_IMAGE_WIDTH = 600; // px
public static final int PROFILE_IMAGE_HEIGHT = 600;
public static final float ROUNDED_PROFILE = 10f; // the bigger the value the more square the image
public static final float CIRCLE_PROFILE = 2f; // 2 = circle, the bigger the value the more square the image
public static final int ASYNC_CONNECTION_NORMAL_TIMEOUT = 9 * 1000; // 9 seconds
public static final int ASYNC_CONNECTION_EXTENDED_TIMEOUT = 16 * 1000; // 16 seconds
public static final int RESULT_PROFILE_IMAGE_SELECTED = 10;
public static final int RESULT_PROFILE_IMAGE_TAKEN = 11;
public static final int RESULT_PROFILE_UPDATE = 12;
public static final int RESULT_GOAL_SET = 30;
public static final int RESULT_MY_GOAL_DIALOG = 40;
public static final int REQUEST_PERMISSIONS_CAMERA_STORAGE = 100;
public static final int REQUEST_PERMISSIONS_CONTACT = 102;
// notification
public static final int ID_NOTIFICATION_BROADCAST = 607;
}
| 46.792453 | 118 | 0.746774 |
20f256401c9500a215701dca2556ce60363f3f6c
| 18,581 |
/*
* Copyright 2018 Key Bridge.
*
* 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.broadbandforum.tr143.internetgatewaydevice.wandevice;
import java.util.ArrayList;
import java.util.Collection;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.broadbandforum.annotation.CWMPObject;
import org.broadbandforum.annotation.CWMPParameter;
import org.broadbandforum.tr143.internetgatewaydevice.wandevice.wancommoninterfaceconfig.Connection;
/**
* This object models WAN interface properties common across all connection instances.
*
* @since TR143 v1.0
*/
@CWMPObject(name = "InternetGatewayDevice.WANDevice.{i}.WANCommonInterfaceConfig.")
@XmlRootElement(name = "InternetGatewayDevice.WANDevice.WANCommonInterfaceConfig")
@XmlType(name = "InternetGatewayDevice.WANDevice.WANCommonInterfaceConfig")
@XmlAccessorType(XmlAccessType.FIELD)
public class WANCommonInterfaceConfig {
/**
* Used to enable or disable access to and from the Internet across all connection instances.
*
* @since 1.0
*/
@XmlElement(name = "EnabledForInternet")
@CWMPParameter(access = "readWrite")
public Boolean enabledForInternet;
/**
* Specifies the WAN access (modem) type.
*
* @since 1.0
*/
@XmlElement(name = "WANAccessType")
public String wanAccessType;
/**
* Specifies the maximum upstream theoretical bit rate for the WAN device in bits per second. This describes the maximum possible rate given the type of interface assuming the best-case operating environment, regardless of the current operating rate.
For example, if the physical interface is 100BaseT, this value would be 100000000, regardless of the current operating rate.
*
* @since 1.0
*/
@XmlElement(name = "Layer1UpstreamMaxBitRate")
public Long layer1UpstreamMaxBitRate;
/**
* Specifies the maximum downstream theoretical bit rate for the WAN device in bits per second. This describes the maximum possible rate given the type of interface assuming the best-case operating environment, regardless of the current operating rate.
For example, if the physical interface is 100BaseT, this value would be 100000000, regardless of the current operating rate.
*
* @since 1.0
*/
@XmlElement(name = "Layer1DownstreamMaxBitRate")
public Long layer1DownstreamMaxBitRate;
/**
* Indicates the state of the physical connection (link) from WANDevice to a connected entity.
*
* @since 1.0
*/
@XmlElement(name = "PhysicalLinkStatus")
public String physicalLinkStatus;
/**
* Name of the Service Provider providing link connectivity on the WAN.
*
* @since 1.0
*/
@XmlElement(name = "WANAccessProvider")
@Size(max = 256)
public String wanAccessProvider;
/**
* The cumulative counter for total number of bytes sent upstream across all connection service instances on the WAN device.
*
* @since 1.0
*/
@XmlElement(name = "TotalBytesSent")
@CWMPParameter(activeNotify = "canDeny")
public Long totalBytesSent;
/**
* The cumulative counter for total number of bytes received downstream across all connection service instances on the WAN device.
*
* @since 1.0
*/
@XmlElement(name = "TotalBytesReceived")
@CWMPParameter(activeNotify = "canDeny")
public Long totalBytesReceived;
/**
* The cumulative counter for total number of packets (IP or PPP) sent upstream across all connection service instances on the WAN device.
*
* @since 1.0
*/
@XmlElement(name = "TotalPacketsSent")
@CWMPParameter(activeNotify = "canDeny")
public Long totalPacketsSent;
/**
* The cumulative counter for total number of packets (IP or PPP) received downstream across all connection service instances on the WAN device.
*
* @since 1.0
*/
@XmlElement(name = "TotalPacketsReceived")
@CWMPParameter(activeNotify = "canDeny")
public Long totalPacketsReceived;
/**
* Indicates the maximum number of active connections the CPE can simultaneously support.
*
* @since 1.0
*/
@XmlElement(name = "MaximumActiveConnections")
@CWMPParameter(activeNotify = "canDeny")
public Long maximumActiveConnections;
/**
* Number of WAN connection service instances currently active on this WAN interface.
*
* @since 1.0
*/
@XmlElement(name = "NumberOfActiveConnections")
public Long numberOfActiveConnections;
/**
* Active connection table.
*/
@XmlElementWrapper(name = "Connections")
@XmlElement(name = "Connection")
public Collection<Connection> connections;
public WANCommonInterfaceConfig() {
}
//<editor-fold defaultstate="collapsed" desc="Getter and Setter">
/**
* Get the used to enable or disable access to and from the Internet across all connection instances.
*
* @since 1.0
* @return the value
*/
public Boolean isEnabledForInternet() {
return enabledForInternet;
}
/**
* Set the used to enable or disable access to and from the Internet across all connection instances.
*
* @since 1.0
* @param enabledForInternet the input value
*/
public void setEnabledForInternet(Boolean enabledForInternet) {
this.enabledForInternet = enabledForInternet;
}
/**
* Set the used to enable or disable access to and from the Internet across all connection instances.
*
* @since 1.0
* @param enabledForInternet the input value
* @return this instance
*/
public WANCommonInterfaceConfig withEnabledForInternet(Boolean enabledForInternet) {
this.enabledForInternet = enabledForInternet;
return this;
}
/**
* Get the specifies the WAN access (modem) type.
*
* @since 1.0
* @return the value
*/
public String getWanAccessType() {
return wanAccessType;
}
/**
* Set the specifies the WAN access (modem) type.
*
* @since 1.0
* @param wanAccessType the input value
*/
public void setWanAccessType(String wanAccessType) {
this.wanAccessType = wanAccessType;
}
/**
* Set the specifies the WAN access (modem) type.
*
* @since 1.0
* @param wanAccessType the input value
* @return this instance
*/
public WANCommonInterfaceConfig withWanAccessType(String wanAccessType) {
this.wanAccessType = wanAccessType;
return this;
}
/**
* Get the specifies the maximum upstream theoretical bit rate for the WAN device in bits per second. This describes the maximum possible rate given the type of interface assuming the best-case operating environment, regardless of the current operating rate.
For example, if the physical interface is 100BaseT, this value would be 100000000, regardless of the current operating rate.
*
* @since 1.0
* @return the value
*/
public Long getLayer1UpstreamMaxBitRate() {
return layer1UpstreamMaxBitRate;
}
/**
* Set the specifies the maximum upstream theoretical bit rate for the WAN device in bits per second. This describes the maximum possible rate given the type of interface assuming the best-case operating environment, regardless of the current operating rate.
For example, if the physical interface is 100BaseT, this value would be 100000000, regardless of the current operating rate.
*
* @since 1.0
* @param layer1UpstreamMaxBitRate the input value
*/
public void setLayer1UpstreamMaxBitRate(Long layer1UpstreamMaxBitRate) {
this.layer1UpstreamMaxBitRate = layer1UpstreamMaxBitRate;
}
/**
* Set the specifies the maximum upstream theoretical bit rate for the WAN device in bits per second. This describes the maximum possible rate given the type of interface assuming the best-case operating environment, regardless of the current operating rate.
For example, if the physical interface is 100BaseT, this value would be 100000000, regardless of the current operating rate.
*
* @since 1.0
* @param layer1UpstreamMaxBitRate the input value
* @return this instance
*/
public WANCommonInterfaceConfig withLayer1UpstreamMaxBitRate(Long layer1UpstreamMaxBitRate) {
this.layer1UpstreamMaxBitRate = layer1UpstreamMaxBitRate;
return this;
}
/**
* Get the specifies the maximum downstream theoretical bit rate for the WAN device in bits per second. This describes the maximum possible rate given the type of interface assuming the best-case operating environment, regardless of the current operating rate.
For example, if the physical interface is 100BaseT, this value would be 100000000, regardless of the current operating rate.
*
* @since 1.0
* @return the value
*/
public Long getLayer1DownstreamMaxBitRate() {
return layer1DownstreamMaxBitRate;
}
/**
* Set the specifies the maximum downstream theoretical bit rate for the WAN device in bits per second. This describes the maximum possible rate given the type of interface assuming the best-case operating environment, regardless of the current operating rate.
For example, if the physical interface is 100BaseT, this value would be 100000000, regardless of the current operating rate.
*
* @since 1.0
* @param layer1DownstreamMaxBitRate the input value
*/
public void setLayer1DownstreamMaxBitRate(Long layer1DownstreamMaxBitRate) {
this.layer1DownstreamMaxBitRate = layer1DownstreamMaxBitRate;
}
/**
* Set the specifies the maximum downstream theoretical bit rate for the WAN device in bits per second. This describes the maximum possible rate given the type of interface assuming the best-case operating environment, regardless of the current operating rate.
For example, if the physical interface is 100BaseT, this value would be 100000000, regardless of the current operating rate.
*
* @since 1.0
* @param layer1DownstreamMaxBitRate the input value
* @return this instance
*/
public WANCommonInterfaceConfig withLayer1DownstreamMaxBitRate(Long layer1DownstreamMaxBitRate) {
this.layer1DownstreamMaxBitRate = layer1DownstreamMaxBitRate;
return this;
}
/**
* Get the indicates the state of the physical connection (link) from WANDevice to a connected entity.
*
* @since 1.0
* @return the value
*/
public String getPhysicalLinkStatus() {
return physicalLinkStatus;
}
/**
* Set the indicates the state of the physical connection (link) from WANDevice to a connected entity.
*
* @since 1.0
* @param physicalLinkStatus the input value
*/
public void setPhysicalLinkStatus(String physicalLinkStatus) {
this.physicalLinkStatus = physicalLinkStatus;
}
/**
* Set the indicates the state of the physical connection (link) from WANDevice to a connected entity.
*
* @since 1.0
* @param physicalLinkStatus the input value
* @return this instance
*/
public WANCommonInterfaceConfig withPhysicalLinkStatus(String physicalLinkStatus) {
this.physicalLinkStatus = physicalLinkStatus;
return this;
}
/**
* Get the name of the Service Provider providing link connectivity on the WAN.
*
* @since 1.0
* @return the value
*/
public String getWanAccessProvider() {
return wanAccessProvider;
}
/**
* Set the name of the Service Provider providing link connectivity on the WAN.
*
* @since 1.0
* @param wanAccessProvider the input value
*/
public void setWanAccessProvider(String wanAccessProvider) {
this.wanAccessProvider = wanAccessProvider;
}
/**
* Set the name of the Service Provider providing link connectivity on the WAN.
*
* @since 1.0
* @param wanAccessProvider the input value
* @return this instance
*/
public WANCommonInterfaceConfig withWanAccessProvider(String wanAccessProvider) {
this.wanAccessProvider = wanAccessProvider;
return this;
}
/**
* Get the cumulative counter for total number of bytes sent upstream across all connection service instances on the WAN device.
*
* @since 1.0
* @return the value
*/
public Long getTotalBytesSent() {
return totalBytesSent;
}
/**
* Set the cumulative counter for total number of bytes sent upstream across all connection service instances on the WAN device.
*
* @since 1.0
* @param totalBytesSent the input value
*/
public void setTotalBytesSent(Long totalBytesSent) {
this.totalBytesSent = totalBytesSent;
}
/**
* Set the cumulative counter for total number of bytes sent upstream across all connection service instances on the WAN device.
*
* @since 1.0
* @param totalBytesSent the input value
* @return this instance
*/
public WANCommonInterfaceConfig withTotalBytesSent(Long totalBytesSent) {
this.totalBytesSent = totalBytesSent;
return this;
}
/**
* Get the cumulative counter for total number of bytes received downstream across all connection service instances on the WAN device.
*
* @since 1.0
* @return the value
*/
public Long getTotalBytesReceived() {
return totalBytesReceived;
}
/**
* Set the cumulative counter for total number of bytes received downstream across all connection service instances on the WAN device.
*
* @since 1.0
* @param totalBytesReceived the input value
*/
public void setTotalBytesReceived(Long totalBytesReceived) {
this.totalBytesReceived = totalBytesReceived;
}
/**
* Set the cumulative counter for total number of bytes received downstream across all connection service instances on the WAN device.
*
* @since 1.0
* @param totalBytesReceived the input value
* @return this instance
*/
public WANCommonInterfaceConfig withTotalBytesReceived(Long totalBytesReceived) {
this.totalBytesReceived = totalBytesReceived;
return this;
}
/**
* Get the cumulative counter for total number of packets (IP or PPP) sent upstream across all connection service instances on the WAN device.
*
* @since 1.0
* @return the value
*/
public Long getTotalPacketsSent() {
return totalPacketsSent;
}
/**
* Set the cumulative counter for total number of packets (IP or PPP) sent upstream across all connection service instances on the WAN device.
*
* @since 1.0
* @param totalPacketsSent the input value
*/
public void setTotalPacketsSent(Long totalPacketsSent) {
this.totalPacketsSent = totalPacketsSent;
}
/**
* Set the cumulative counter for total number of packets (IP or PPP) sent upstream across all connection service instances on the WAN device.
*
* @since 1.0
* @param totalPacketsSent the input value
* @return this instance
*/
public WANCommonInterfaceConfig withTotalPacketsSent(Long totalPacketsSent) {
this.totalPacketsSent = totalPacketsSent;
return this;
}
/**
* Get the cumulative counter for total number of packets (IP or PPP) received downstream across all connection service instances on the WAN device.
*
* @since 1.0
* @return the value
*/
public Long getTotalPacketsReceived() {
return totalPacketsReceived;
}
/**
* Set the cumulative counter for total number of packets (IP or PPP) received downstream across all connection service instances on the WAN device.
*
* @since 1.0
* @param totalPacketsReceived the input value
*/
public void setTotalPacketsReceived(Long totalPacketsReceived) {
this.totalPacketsReceived = totalPacketsReceived;
}
/**
* Set the cumulative counter for total number of packets (IP or PPP) received downstream across all connection service instances on the WAN device.
*
* @since 1.0
* @param totalPacketsReceived the input value
* @return this instance
*/
public WANCommonInterfaceConfig withTotalPacketsReceived(Long totalPacketsReceived) {
this.totalPacketsReceived = totalPacketsReceived;
return this;
}
/**
* Get the indicates the maximum number of active connections the CPE can simultaneously support.
*
* @since 1.0
* @return the value
*/
public Long getMaximumActiveConnections() {
return maximumActiveConnections;
}
/**
* Set the indicates the maximum number of active connections the CPE can simultaneously support.
*
* @since 1.0
* @param maximumActiveConnections the input value
*/
public void setMaximumActiveConnections(Long maximumActiveConnections) {
this.maximumActiveConnections = maximumActiveConnections;
}
/**
* Set the indicates the maximum number of active connections the CPE can simultaneously support.
*
* @since 1.0
* @param maximumActiveConnections the input value
* @return this instance
*/
public WANCommonInterfaceConfig withMaximumActiveConnections(Long maximumActiveConnections) {
this.maximumActiveConnections = maximumActiveConnections;
return this;
}
/**
* Get the number of WAN connection service instances currently active on this WAN interface.
*
* @since 1.0
* @return the value
*/
public Long getNumberOfActiveConnections() {
return numberOfActiveConnections;
}
/**
* Set the number of WAN connection service instances currently active on this WAN interface.
*
* @since 1.0
* @param numberOfActiveConnections the input value
*/
public void setNumberOfActiveConnections(Long numberOfActiveConnections) {
this.numberOfActiveConnections = numberOfActiveConnections;
}
/**
* Set the number of WAN connection service instances currently active on this WAN interface.
*
* @since 1.0
* @param numberOfActiveConnections the input value
* @return this instance
*/
public WANCommonInterfaceConfig withNumberOfActiveConnections(Long numberOfActiveConnections) {
this.numberOfActiveConnections = numberOfActiveConnections;
return this;
}
/**
* Get active connection table.
*
* @return the value
*/
public Collection<Connection> getConnections() {
if (this.connections == null){ this.connections=new ArrayList<>();}
return connections;
}
/**
* Set active connection table.
*
* @param connections the input value
*/
public void setConnections(Collection<Connection> connections) {
this.connections = connections;
}
/**
* Set active connection table.
*
* @param connection the input value
* @return this instance
*/
public WANCommonInterfaceConfig withConnection(Connection connection) {
getConnections().add(connection);
return this;
}
//</editor-fold>
}
| 32.258681 | 262 | 0.752973 |
93799d49c1b001bf54eaf799026fb34651b5192e
| 7,247 |
/*
* 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.syncope.wa.starter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import javax.ws.rs.core.HttpHeaders;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.ContextConfiguration;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
"cas.authn.accept.users=mrossi::password",
"cas.sso.allow-missing-service-parameter=true"
})
@ContextConfiguration(initializers = ZookeeperTestingServer.class)
public class SyncopeWATest {
@LocalServerPort
private int port;
private String getLoginURL() {
return "http://localhost:" + port + "/syncope-wa/login";
}
@Test
public void loginLogout() throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpClientContext context = HttpClientContext.create();
context.setCookieStore(new BasicCookieStore());
// 1. first GET to fetch execution
HttpGet get = new HttpGet(getLoginURL());
get.addHeader(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, "en-US,en;q=0.5"));
CloseableHttpResponse response = httpclient.execute(get, context);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
String responseBody = EntityUtils.toString(response.getEntity());
int begin = responseBody.indexOf("name=\"execution\" value=\"");
assertNotEquals(-1, begin);
int end = responseBody.indexOf("\"/><input type=\"hidden\" name=\"_eventId\"");
assertNotEquals(-1, end);
String execution = responseBody.substring(begin + 24, end);
assertNotNull(execution);
// 2. then POST to authenticate
List<NameValuePair> form = new ArrayList<>();
form.add(new BasicNameValuePair("_eventId", "submit"));
form.add(new BasicNameValuePair("execution", execution));
form.add(new BasicNameValuePair("username", "mrossi"));
form.add(new BasicNameValuePair("password", "password"));
form.add(new BasicNameValuePair("geolocation", ""));
HttpPost post = new HttpPost(getLoginURL());
post.addHeader(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, "en-US,en;q=0.5"));
post.setEntity(new UrlEncodedFormEntity(form, Consts.UTF_8));
response = httpclient.execute(post, context);
// 3. check authentication results
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
Header[] cookie = response.getHeaders("Set-Cookie");
assertNotNull(cookie);
assertTrue(cookie.length > 0);
assertEquals(1, Stream.of(cookie).filter(item -> item.getValue().startsWith("TGC")).count());
String body = EntityUtils.toString(response.getEntity());
assertTrue(body.contains("Log In Successful"));
assertTrue(body.contains("have successfully logged into the Central Authentication Service"));
// 4. logout
HttpGet logout = new HttpGet(getLoginURL().replace("login", "logout"));
logout.addHeader(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, "en-US,en;q=0.5"));
response = httpclient.execute(logout, context);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
body = EntityUtils.toString(response.getEntity());
assertTrue(body.contains("Logout successful"));
assertTrue(body.contains("have successfully logged out of the Central Authentication Service"));
}
@Test
public void loginError() throws IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpClientContext context = HttpClientContext.create();
context.setCookieStore(new BasicCookieStore());
// 1. first GET to fetch execution
HttpGet get = new HttpGet(getLoginURL());
get.addHeader(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, "en-US,en;q=0.5"));
CloseableHttpResponse response = httpclient.execute(get, context);
assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
String responseBody = EntityUtils.toString(response.getEntity());
int begin = responseBody.indexOf("name=\"execution\" value=\"");
assertNotEquals(-1, begin);
int end = responseBody.indexOf("\"/><input type=\"hidden\" name=\"_eventId\"");
assertNotEquals(-1, end);
String execution = responseBody.substring(begin + 24, end);
assertNotNull(execution);
// 2. then POST to authenticate
List<NameValuePair> form = new ArrayList<>();
form.add(new BasicNameValuePair("_eventId", "submit"));
form.add(new BasicNameValuePair("execution", execution));
form.add(new BasicNameValuePair("username", "mrossi"));
form.add(new BasicNameValuePair("password", "WRONG"));
form.add(new BasicNameValuePair("geolocation", ""));
HttpPost post = new HttpPost(getLoginURL());
post.addHeader(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, "en-US,en;q=0.5"));
post.setEntity(new UrlEncodedFormEntity(form, Consts.UTF_8));
response = httpclient.execute(post, context);
// 3. check authentication results
assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
}
}
| 45.29375 | 104 | 0.716986 |
8e2c05907c6e51f96679d2b57a90f86dc1eb6153
| 4,522 |
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package red.zyc.desensitization.util;
import red.zyc.desensitization.exception.DesensitizationException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author zyc
*/
public final class ReflectionUtil {
private ReflectionUtil() {
}
/**
* 获取目标对象以及所有父类定义的 {@link Field}。
* <p><strong>注意:不要缓存域对象,否则在多线程运行环境下会有线程安全问题。</strong></p>
*
* @param targetClass 目标对象的{@link Class}
* @return 目标对象以及所有父类定义的 {@link Field}
*/
public static List<Field> listAllFields(Class<?> targetClass) {
return Optional.ofNullable(targetClass)
.filter(clazz -> clazz != Object.class)
.map(clazz -> {
List<Field> fields = Stream.of(clazz.getDeclaredFields()).collect(Collectors.toList());
fields.addAll(listAllFields(clazz.getSuperclass()));
return fields;
}).orElseGet(ArrayList::new);
}
/**
* 从指定的{@code class}中获取带有指定参数的构造器
*
* @param clazz 指定的{@code class}
* @param parameterTypes 构造器的参数
* @param <T> 构造器代表的对象类型
* @return 带有指定参数的构造器
*/
public static <T> Constructor<T> getDeclaredConstructor(Class<T> clazz, Class<?>... parameterTypes) {
try {
Constructor<T> declaredConstructor = clazz.getDeclaredConstructor(parameterTypes);
if (!declaredConstructor.isAccessible()) {
declaredConstructor.setAccessible(true);
}
return declaredConstructor;
} catch (NoSuchMethodException e) {
return null;
}
}
/**
* 类型转换方法用来获取指定类型对象的{@link Class},因为{@link Object#getClass()}方法返回的
* {@link Class}的泛型是通配符类型
*
* @param value 对象值
* @param <T> 对象类型
* @return 指定类型对象的 {@link Class}
*/
@SuppressWarnings("unchecked")
public static <T> Class<T> getClass(T value) {
return (Class<T>) value.getClass();
}
/**
* 获取目标{@link Class}代表的类或接口中声明的方法
*
* @param clazz 目标{@link Class}
* @param name 方法名
* @param parameterTypes 方法参数类型
* @return 目标{@code Class}代表的类或接口中声明的方法
*/
public static Method getDeclaredMethod(Class<?> clazz, String name, Class<?>... parameterTypes) {
try {
return clazz.getDeclaredMethod(name, parameterTypes);
} catch (NoSuchMethodException e) {
throw new DesensitizationException(String.format("获取%s的方法%s失败。", clazz, name), e);
}
}
/**
* 获取目标对象中某个{@link Field}的值
*
* @param target 目标对象
* @param field 目标对象的{@link Field}
* @return {@link Field}的值
*/
public static Object getFieldValue(Object target, Field field) {
try {
if (field.isAccessible()) {
return field.get(target);
}
field.setAccessible(true);
return field.get(target);
} catch (Exception e) {
throw new DesensitizationException(String.format("获取%s的域%s失败。", target.getClass(), field.getName()), e);
}
}
/**
* 设置目标对象某个域的值
*
* @param target 目标对象
* @param field 目标对象的{@link Field}
* @param newValue 将要设置的新值
*/
public static void setFieldValue(Object target, Field field, Object newValue) {
try {
if (field.isAccessible()) {
field.set(target, newValue);
return;
}
field.setAccessible(true);
field.set(target, newValue);
} catch (Exception e) {
throw new DesensitizationException(String.format("给%s的域%s赋值失败。", target.getClass(), field.getName()), e);
}
}
}
| 31.622378 | 117 | 0.606369 |
801cf2e3c81b6e7e0d4200be13d02e83b72dc158
| 146 |
package com.ycb.mobliesafe.bean;
/**
* Created by where on 2016/4/10.
*/
public class Virus {
public String md5;
public String desc;
}
| 14.6 | 33 | 0.664384 |
6a9546edb25560cf8c17075465f674d8881da527
| 2,422 |
/*
* 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.gbif.registry.cli.util;
import org.gbif.registry.cli.common.DbConfiguration;
import org.gbif.utils.file.FileUtils;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
public final class RegistryCliUtils {
private RegistryCliUtils() {}
/** Prepare JDBC Connection. */
public static Connection prepareConnection(DbConfiguration dbConfiguration) throws Exception {
return prepareConnection(
dbConfiguration.serverName,
dbConfiguration.databaseName,
dbConfiguration.user,
dbConfiguration.password);
}
/** Prepare JDBC Connection. */
public static Connection prepareConnection(
String host, String databaseName, String user, String password) throws Exception {
return DriverManager.getConnection(
String.format("jdbc:postgresql://%s/%s", host, databaseName), user, password);
}
/** Read data from file and put it into String. */
public static String getFileData(String filename) throws Exception {
//noinspection ConstantConditions
byte[] bytes =
Files.readAllBytes(
Paths.get(ClassLoader.getSystemClassLoader().getResource(filename).getFile()));
return new String(bytes);
}
/** Load yaml config into Configuration class. */
public static <T> T loadConfig(String configFile, Class<T> type) {
try {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
InputStream is = FileUtils.classpathStream(configFile);
T cfg = mapper.readValue(is, type);
System.out.println(cfg);
return cfg;
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
| 33.638889 | 96 | 0.727911 |
a0c6693c8fbb88030ae7f16df1ac4f514cea4b35
| 1,021 |
package com.findjob.findjobgradle.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
@EqualsAndHashCode(of = "id")
@Getter
@Setter
@Table(name = "JOB_DETAILS")
public class JobDetails {
@Id
@Column(name = "ID")
private Long id;
@Column(name = "CREATED")
private LocalDateTime created;
@Column(name = "END_DATED")
private LocalDateTime endDated;
@Column(name = "DESCRIPTION")
private String description;
@Column(name = "EMAIL")
private String email;
@JsonIgnore
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private Job job;
public JobDetails() {
}
public JobDetails(LocalDateTime created, LocalDateTime endDated, String description,String email) {
this.created = created;
this.endDated = endDated;
this.description = description;
this.email=email;
}
}
| 20.836735 | 103 | 0.6905 |
745747f44a4e3d93da8e550c7ca5209e63371437
| 6,219 |
/*
* 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.sierra.test.logic;
import co.edu.uniandes.csw.sierra.ejb.MedioDePagoLogic;
import co.edu.uniandes.csw.sierra.entities.ClienteEntity;
import co.edu.uniandes.csw.sierra.entities.MedioDePagoEntity;
import co.edu.uniandes.csw.sierra.exceptions.BusinessLogicException;
import co.edu.uniandes.csw.sierra.persistence.MedioDePagoPersistence;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import uk.co.jemos.podam.api.PodamFactory;
import uk.co.jemos.podam.api.PodamFactoryImpl;
/**
*
* @author de.gutierrez
*/
@RunWith(Arquillian.class)
public class MedioDePagoLogicTest {
private PodamFactory factory = new PodamFactoryImpl();
@Inject
private MedioDePagoLogic medioDePago;
@PersistenceContext
private EntityManager em;
@Inject
private UserTransaction utx;
private List<MedioDePagoEntity> data = new ArrayList<MedioDePagoEntity>();
/**
* @return Devuelve el jar que Arquillian va a desplegar en el Glassfish
* embebido. El jar contiene las clases de Guia, el descriptor de la base de
* datos y el archivo beans.xml para resolver la inyección de dependencias.
*/
@Deployment
public static JavaArchive createDeploment(){
return ShrinkWrap.create(JavaArchive.class)
.addPackage(MedioDePagoEntity.class.getPackage())
.addPackage(MedioDePagoLogic.class.getPackage())
.addPackage(MedioDePagoPersistence.class.getPackage())
.addAsManifestResource("META-INF/persistence.xml", "persistence.xml")
.addAsManifestResource("META-INF/beans.xml", "beans.xml");
}
/**
* Constructor por defecto.
*/
public MedioDePagoLogicTest(){
}
/**
* Configuración inicial de la prueba.
*/
@Before
public void setUp(){
try {
utx.begin();
clearData();
insertData();
utx.commit();
} catch (Exception e) {
e.printStackTrace();
try {
utx.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
/**
* Limpia las tablas que están implicadas en la prueba.
*/
private void clearData(){
em.createQuery("delete from MedioDePagoEntity").executeUpdate();
}
/**
* Inserta los datos iniciales para el correcto funcionamiento de las
* pruebas.
*/
private void insertData() {
for(int i=0;i<3;i++)
{
MedioDePagoEntity entity = factory.manufacturePojo(MedioDePagoEntity.class);
em.persist(entity);
data.add(entity);
}
}
/**
* Prueba para crear un MedioDePago.
* @throws BusinessLogicException Si ya existe un cliente.
*/
@Test
public void createMedioDePagoTest () throws BusinessLogicException{
MedioDePagoEntity newEntity = factory.manufacturePojo(MedioDePagoEntity.class);
MedioDePagoEntity result = medioDePago.createMedioDePago(newEntity);
Assert.assertNotNull(result);
MedioDePagoEntity entity = em.find(MedioDePagoEntity.class,result.getId());
Assert.assertEquals(newEntity.getId(), entity.getId());
Assert.assertEquals(newEntity.getTipo(), entity.getTipo());
Assert.assertEquals(newEntity.getNumeroReferencia(), entity.getNumeroReferencia());
}
/**
* Prueba para consultar la lista de MedioDePago.
*/
@Test
public void geMediosDePagoTest(){
List<MedioDePagoEntity> list = medioDePago.getMediosDePago();
Assert.assertEquals(data.size(), list.size());
for(MedioDePagoEntity entity : list){
boolean found = false;
for(MedioDePagoEntity storeEntity : data){
if(entity.getId().equals(storeEntity.getId())){
found = true;
}
}
Assert.assertTrue(found);
}
}
/**
* Prueba consultar un MedioDePago.
*/
@Test
public void getMedioDePagoTest(){
MedioDePagoEntity entity = data.get(0);
MedioDePagoEntity result = medioDePago.getMedioDePago(entity.getId());
Assert.assertNotNull(result);
Assert.assertEquals(entity.getId(), result.getId());
Assert.assertEquals(entity.getTipo(), result.getTipo());
Assert.assertEquals(entity.getNumeroReferencia(), result.getNumeroReferencia());
}
/**
* Prueba para actualizar un MedioDePago.
**/
@Test
public void updateMedioDePagoTest() throws BusinessLogicException {
MedioDePagoEntity entity = data.get(0);
MedioDePagoEntity pojoEntity = factory.manufacturePojo(MedioDePagoEntity.class);
pojoEntity.setId(entity.getId());
medioDePago.updateMedioDePago(pojoEntity.getId(), pojoEntity);
MedioDePagoEntity resp = em.find(MedioDePagoEntity.class, entity.getId());
Assert.assertEquals(pojoEntity.getId(), resp.getId());
Assert.assertEquals(pojoEntity.getTipo(), resp.getTipo());
Assert.assertEquals(pojoEntity.getNumeroReferencia(), resp.getNumeroReferencia());
}
/**
* Prueba para eliminar un MedioDePago.
*/
@Test
public void deleteMedioDePagoTest(){
MedioDePagoEntity entity = data.get(0);
medioDePago.deleteMedioDePago(entity.getId());
MedioDePagoEntity deleted = em.find(MedioDePagoEntity.class, entity.getId());
Assert.assertNull(deleted);
}
}
| 34.938202 | 91 | 0.664737 |
d8776aef7af8fa4b4839550740186f2f7aed0351
| 887 |
package com.showka.service.query.u08;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.showka.common.PersistenceTestCase;
import com.showka.entity.JNyukinFBFurikomi;
public class NyukinFBFurikomiQueryImplTest extends PersistenceTestCase {
@Autowired
private NyukinFBFurikomiQueryImpl service;
/** 入金FB振込データ. */
private Object[] DATA01 = { "r-001", "r-20170820-001", "r-001^20170820-001" };
/**
* FB振込IDで入金FB関係TableのRecordを取得できる.
*/
@Test
public void test_findByFbFurikomiId_01() throws Exception {
// database
super.deleteAndInsert(J_NYUKIN_FB_FURIKOMI, J_NYUKIN_FB_FURIKOMI_COLUMN, DATA01);
// input
String fbFurikomiId = "r-20170820-001";
// do
JNyukinFBFurikomi actual = service.findByFbFurikomiId(fbFurikomiId);
// check
assertEquals("r-001", actual.getNyukinId());
}
}
| 27.71875 | 84 | 0.740699 |
9fb65c077983b6ad0d8dd99494c554f070d34cbf
| 9,857 |
package dao;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Alert;
import model.Movie;
import model.Session;
import util.ConnectionFactory;
import util.Utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import static util.Utils.mostrarAlerta;
public class SessionDAO implements DAO<Session> {
public Session readOne(int idSession) throws SQLException {
Connection conn = ConnectionFactory.createConnection();
try {
String sql = "select * from session where id = ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setInt(1, idSession);
ResultSet res = prep.executeQuery();
while (res.next()) {
MovieDAO movieDAO = new MovieDAO();
Movie movieName = MovieDAO.getById(res.getInt("movie"));
Session session = new Session(res.getInt("id"),
res.getInt("theater"),
res.getString("starts_at"),
res.getString("ends_at"),
res.getString("date"),
res.getBoolean("promotional"),
movieName.getName(),
res.getString("seat_map"),
res.getInt("ticket"),
movieName);
conn.close();
return session;
}
} catch (SQLException e) {
conn.close();
e.printStackTrace();
}
return null;
}
public ObservableList<Session> readAll() throws SQLException {
ObservableList<Session> list = FXCollections.observableArrayList();
Connection conn = ConnectionFactory.createConnection();
try {
String sql = "select * from session";
PreparedStatement prep = conn.prepareStatement(sql);
ResultSet res = prep.executeQuery();
while (res.next()) {
MovieDAO movieDAO = new MovieDAO();
Movie movieName = MovieDAO.getById(res.getInt("movie"));
Session session = new Session(res.getInt("id"),
res.getInt("theater"),
res.getString("starts_at"),
res.getString("ends_at"),
res.getString("date"),
res.getBoolean("promotional"),
movieName.getName(),
res.getString("seat_map"),
res.getInt("ticket"),
movieName);
list.add(session);
}
return list;
} catch (SQLException e) {
conn.close();
e.printStackTrace();
}
return null;
}
public ObservableList<Session> readAll(int idTheater) throws SQLException {
ObservableList<Session> list = FXCollections.observableArrayList();
Connection conn = ConnectionFactory.createConnection();
try {
String sql = "select * from session where theater = ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setInt(1, idTheater);
ResultSet res = prep.executeQuery();
while (res.next()) {
MovieDAO movieDAO = new MovieDAO();
Movie movieName = MovieDAO.getById(res.getInt("movie"));
Session session = new Session(res.getInt("id"),
res.getInt("theater"),
res.getString("starts_at"),
res.getString("ends_at"),
res.getString("date"),
res.getBoolean("promotional"),
movieName.getName(),
res.getString("seat_map"),
res.getInt("ticket"),
movieName);
list.add(session);
}
return list;
} catch (SQLException e) {
conn.close();
e.printStackTrace();
}
return null;
}
public ObservableList<Session> readAll(String date) throws SQLException {
ObservableList<Session> list = FXCollections.observableArrayList();
Connection conn = ConnectionFactory.createConnection();
try {
String sql = "select * from session where date = ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setString(1, date);
ResultSet res = prep.executeQuery();
while (res.next()) {
MovieDAO movieDAO = new MovieDAO();
Movie movieName = MovieDAO.getById(res.getInt("movie"));
Session session = new Session(res.getInt("id"),
res.getInt("theater"),
res.getString("starts_at"),
res.getString("ends_at"),
res.getString("date"),
res.getBoolean("promotional"),
movieName.getName(),
res.getString("seat_map"),
res.getInt("ticket"),
movieName);
list.add(session);
}
return list;
} catch (SQLException e) {
conn.close();
e.printStackTrace();
}
return null;
}
@Override
public void save(Session f) throws SQLException {
Connection conn = ConnectionFactory.createConnection();
conn.setAutoCommit(false);
try {
int id = this.MaxId();
String sql = "insert into session (id, date, starts_at, ends_at, seat_map, movie, theater, ticket, promotional) " +
"values (?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setInt(1, id);
prep.setString(2, f.getDate());
prep.setString(3, f.getStarts());
prep.setString(4, f.getEnds());
prep.setString(5, f.getSeats());
prep.setInt(6, f.getMovie());
prep.setInt(7, f.getTheater());
prep.setInt(8, f.getTicket());
prep.setBoolean(9, f.isPromotional());
prep.execute();
prep.close();
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
conn.rollback();
} finally {
conn.close();
}
}
@Override
public void update(Session f) throws SQLException {
Connection conn = ConnectionFactory.createConnection();
conn.setAutoCommit(false);
try {
String sql = "update session set seat_map = ? where id = ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setString(1, f.getSeats());
prep.setInt(2, f.getId());
prep.execute();
prep.close();
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
conn.close();
}
}
@Override
public void delete(Session f) throws SQLException {
Connection conn = ConnectionFactory.createConnection();
conn.setAutoCommit(false);
try {
String sql = "delete from session where id = ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setInt(1, f.getId());
prep.execute();
conn.commit();
} catch (Exception e) {
mostrarAlerta("Sessão", "Erro ao deletar sessão.", "Existe ao menos um ingresso vendido para essa sessão.", Alert.AlertType.ERROR);
} finally {
conn.close();
}
}
public ResultSet checkSessions(Session f) throws SQLException {
Connection conn = ConnectionFactory.createConnection();
conn.setAutoCommit(false);
try {
String sql = "SELECT id " +
"FROM session " +
"WHERE " +
"(date = ? AND theater = ? AND starts_at >= ? AND starts_at <= ?) " +
"OR (date = ? AND theater = ? AND ends_at >= ? AND ends_at <= ?) " +
"OR (date = ? AND theater = ? AND starts_at < ? AND ends_at > ?) " +
"LIMIT 1";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setString(1, f.getDate());
prep.setInt(2, f.getTheater());
prep.setString(3, f.getStarts());
prep.setString(4, f.getEnds());
prep.setString(5, f.getDate());
prep.setInt(6, f.getTheater());
prep.setString(7, f.getStarts());
prep.setString(8, f.getEnds());
prep.setString(9, f.getDate());
prep.setInt(10, f.getTheater());
prep.setString(11, f.getStarts());
prep.setString(12, f.getEnds());
ResultSet res = prep.executeQuery();
return res;
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.close();
}
return null;
}
public int MaxId() throws SQLException {
Connection conn = ConnectionFactory.createConnection();
try {
String sql = "select max(id) as id from session";
PreparedStatement prep = conn.prepareStatement(sql);
ResultSet res = prep.executeQuery();
int max = res.getInt("id") + 1;
return max;
} catch (SQLException e) {
e.printStackTrace();
} finally {
conn.close();
}
return 0;
}
}
| 37.479087 | 143 | 0.516587 |
834543e44d42c7d1ec0d7d2348a03b6f6b0a2503
| 369 |
package com.app.notebook.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/** notebook-api Created by Catalin on 10/21/2020 */
@RestController
@RequiredArgsConstructor
@RequestMapping(path = "/api/v1/users")
public class UserController {}
| 30.75 | 62 | 0.821138 |
2c59e4ddb97041d364e5685f5dbae747802f1a86
| 1,213 |
package org.ainlolcat.idea.plugin.openshift.client.impl;
import org.ainlolcat.idea.plugin.openshift.client.OSEntity;
import org.ainlolcat.idea.plugin.openshift.client.OpenshiftClient;
import org.ainlolcat.idea.plugin.openshift.client.OpenshiftClientFactory;
import org.ainlolcat.idea.plugin.openshift.client.https.HttpsClientFactory;
import org.ainlolcat.idea.plugin.openshift.client.https.okhttp3.OkHttpsClientFactory;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by ain on 11.12.16.
*/
public class OpenshiftClientFactoryImpl extends OpenshiftClientFactory {
private HttpsClientFactory httpsClientFactory;
private ConcurrentHashMap<OSEntity.Server, OpenshiftClient> clients = new ConcurrentHashMap();
public OpenshiftClientFactoryImpl() {
httpsClientFactory = new OkHttpsClientFactory();
}
public OpenshiftClient getClient(OSEntity.Server server){
if (! clients.containsKey(server)){
synchronized (this) {
if (! clients.containsKey(server)) {
clients.put(server, new OpenshiftClientImpl(server, httpsClientFactory));
}
}
}
return clients.get(server);
}
}
| 35.676471 | 98 | 0.732069 |
7d058e0a1b11743b33d72d9d6fc03f1e88b0816f
| 24,200 |
package com.cloudoa.framework.form.web;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudoa.framework.form.entity.AutoPrev;
import com.cloudoa.framework.form.entity.Form;
import com.cloudoa.framework.form.service.FormService;
import com.cloudoa.framework.orm.Page;
import com.cloudoa.framework.orm.PropertyFilter;
import com.cloudoa.framework.security.shiro.ShiroUtils;
import com.cloudoa.framework.utils.DbConn;
import com.cloudoa.framework.utils.MsgUtils;
/**
* 动态表单管理Controller
* @author yuqs
* @since 0.1
*/
@Controller
@RequestMapping(value = "/form")
public class FormController {
private static Logger logger = Logger.getLogger(FormController.class);
public static final String PARA_PROCESSID = "processId";
public static final String PARA_ORDERID = "orderId";
public static final String PARA_TASKID = "taskId";
@Autowired
private FormService formService;
@Autowired
private DbConn db;
@RequestMapping(value = "list",method = RequestMethod.GET)
public String list(Model model, Page<Form> page, HttpServletRequest request, String lookup) {
List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
//设置默认排序方式
if (!page.isOrderBySetted()) {
page.setOrderBy("id");
page.setOrder(Page.ASC);
}
page = formService.findPage(page, filters);
model.addAttribute("page", page);
model.addAttribute("lookup", lookup);
return "form/formList";
}
@RequestMapping(value = "create", method = RequestMethod.GET)
public String create(Model model) {
model.addAttribute("form", new Form());
return "form/formEdit";
}
@RequestMapping(value = "view/{id}", method = RequestMethod.GET)
public String view(@PathVariable("id") Long id, Model model) {
model.addAttribute("form", formService.get(id));
return "form/formView";
}
@RequestMapping(value = "update/{id}", method = RequestMethod.GET)
public String edit(@PathVariable("id") Long id, Model model) {
model.addAttribute("form", formService.get(id));
return "form/formEdit";
}
@RequestMapping(value = "update", method = RequestMethod.POST)
@ResponseBody
public Object update(Form form) {
form.setCreator(ShiroUtils.getUsername());
form.setCreateTime(null);
form.setFieldNum(0);
formService.save(form);
return MsgUtils.returnOk("");
}
@RequestMapping(value = "delete/{id}")
public String delete(@PathVariable("id") Long id) {
formService.delete(id);
return "redirect:/form/list";
}
@RequestMapping(value = "findForm")
@ResponseBody
public Object findForm(Long formType, Model model) {
List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
PropertyFilter f = new PropertyFilter("EQS_formType", formType.toString());
filters.add(f);
return MsgUtils.returnOk("",formService.find(filters));
}
@RequestMapping(value = "findFormField")
@ResponseBody
public Object findFormField(Long formid, Model model) {
Form f = formService.get(formid);
return MsgUtils.returnOk("",f.getFields());
}
@RequestMapping(value = "parseSql")
@ResponseBody
public Object parseSql(String sql) {
return MsgUtils.returnOk("",formService.parseSql(sql));
}
@RequestMapping(value = "findAutoPrev")
@ResponseBody
public Object findAutoPrev() {
JSONObject jobj = new JSONObject();
jobj.put("auto", formService.findAutoPrev());
jobj.put("depart", formService.findAllOrg());
return jobj.toString();
}
@RequestMapping(value = "saveAutoPrev")
@ResponseBody
public Object saveAutoPrev(AutoPrev prev) {
prev = formService.saveAutoPrev(prev);
return MsgUtils.returnOk("",prev);
}
/**
* 删除自增序列
* @param id
* @return
*/
@RequestMapping(value = "deleteAutoPrev")
@ResponseBody
public Object delAutoPrev(Long id) {
formService.deleteAutoPrev(id);
return MsgUtils.returnOk("");
}
/**
* 流程表单打开
* @param model
* @param request
* @return
*/
@RequestMapping(value = "views", method = RequestMethod.GET)
@ResponseBody
public Object views(Model model,HttpServletRequest request) {
String formsid = request.getParameter("forms");
String executionId = request.getParameter("executionId");
List<Form> forms = new ArrayList<Form>();
if(formsid != ""){
String[] ids = formsid.split(",");
for(String id : ids){
forms.add(formService.get(Long.valueOf(id),executionId));
}
}
//model.addAttribute("forms", forms);
//return "form/views";
Map<String,Object> obj = new HashMap<String,Object>();
obj.put("forms", forms);
obj.put("user", ShiroUtils.getUser());
return JSONObject.toJSONString(MsgUtils.returnOk("",obj));
}
/**
* 查询sql语句数据
* @param model
* @param request
* @return
*/
@RequestMapping(value = "findSqlData")
@ResponseBody
public Object findSqlData(Model model,HttpServletRequest request) {
String sql = request.getParameter("sql");
List<Map<String,Object>> list = null;
if(sql != null && !"".equals(sql)){
list = db.getList(sql, null);
}
return JSONObject.toJSONString(MsgUtils.returnOk("",list));
}
/**
* 查询字典数据
* @param model
* @param request
* @return
*/
@RequestMapping(value = "findDictData")
@ResponseBody
public Object findDictData(Model model,HttpServletRequest request) {
String name = request.getParameter("name");
List<Map<String,Object>> list = null;
if(name != null && !"".equals(name)){
String sql = "select code as value,name from conf_dictitem where dictionary=(select id from conf_dictionary where cn_name='"+name+"')";
list = db.getList(sql, null);
}
return JSONObject.toJSONString(MsgUtils.returnOk("",list));
}
//input输入选择
@RequestMapping(value = "/findCallBack")
@ResponseBody
public Object findCallBack(HttpServletRequest request,HttpServletResponse response,Page<Map<String,Object>> page){
try{
String sql = request.getParameter("sql"); //sql语句
if(sql != null && !"".equals(sql)){
sql = sql.replaceAll("\\[userid\\]", ShiroUtils.getUserId().toString())
.replaceAll("\\[deptid\\]", ShiroUtils.getOrgId().toString());
//搜索条件
Enumeration em = request.getParameterNames();
String where = "",key;
while(em.hasMoreElements()){
key = (String)em.nextElement();
if(key.startsWith("col_") && !"".equals(request.getParameter(key))){
where += key.substring(4)+ " like '%"+request.getParameter(key)+"%' and ";
}
}
if(!"".equals(where)){
where += " 1=1";
if(sql.toLowerCase().contains("where")){
sql += " and "+ where;
}else{
sql += " where "+where;
}
}
if(page == null){
page = new Page<Map<String,Object>>();
}
page = db.getPage(page, new StringBuffer(sql), null);
List<Map<String,Object>> data = page.getResult();
Map<String,Object> obj = new HashMap<String,Object>();
obj.put("page", page);
if(data!= null && data.size()>0){
Set<String> keys = data.get(0).keySet();
List<Map<String,String>> kkey = new ArrayList<Map<String,String>>();
String[] ks;
for(String k : keys){
ks = k.split("#");
Map<String,String> m = new HashMap<String,String>();
if("rowid".equals(k)){
continue;
}
if(ks.length>1){//sql
m.put("columnkey", k);
m.put("kkey", ks[0]);
m.put("show", ks[1]);
}else{
m.put("columnkey", k);
m.put("kkey", k);
m.put("show", ks[0]);
}
kkey.add(m);
}
obj.put("keys", kkey);
}
return MsgUtils.returnOk("", obj);
}else{
return MsgUtils.returnError("查询不可为空");
}
}catch(Exception e){
logger.error(e.getMessage(),e);
return MsgUtils.returnError(e.getMessage());
}
}
/**
* 保存表单数据
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/saveFormData")
public String saveFormData(HttpServletRequest request,HttpServletResponse response){
JSONObject result = new JSONObject();
try{
String ids = request.getParameter("forms");//表单
String executionId = request.getParameter("executionId");//实例
String userid = ShiroUtils.getUserId().toString();
String fields = request.getParameter("fields"); //可以编辑元素
Map<String,List<String>> files = this.update(request, "upload");
if(ids != null && !"".equals(ids)){
//表单
List<Form> forms = new ArrayList<Form>();
if(ids != null && !"".equals(ids)){
String[] id = ids.split(",");
for(int i=0; i<id.length; i++){
forms.add(formService.get(Long.valueOf(id[i])));
}
}
//
List<String> sqls = new ArrayList<String>();
List<String> uids = new ArrayList<String>();
String sql = "insert into df_form_DATA(execution_id,form_id,field_id,char_value,num_value,date_value,writer)values(?,?,?,?,?,?,?)";
List<List<Object>> params = new ArrayList<List<Object>>();
String[] vals;
if(fields != null && !"".equals(fields)){//只删除可以编辑的,保存只保存可以编辑的数据,否则所有数据
sqls.add("delete from df_form_data where form_id in ("+ids+") and execution_id="+executionId+" and field_id in ("+fields+")");
}else{
sqls.add("delete from df_form_data where form_id in ("+ids+") and execution_id="+executionId);
}
for(int i=0; i<forms.size(); i++){
for(int j=0; j<forms.get(i).getFields().size(); j++){
if(!fields.contains(String.valueOf(forms.get(i).getFields().get(j).getId()))){//只读跳过
continue;
}
String val = "";
if("checkbox".equals(forms.get(i).getFields().get(j).getShowType())){
String[] vs = request.getParameterValues(forms.get(i).getFields().get(j).getEnname());
if(vs!=null && vs.length>0){
for(int nn=0; nn<vs.length; nn++){
if(nn == 0){
val +=vs[nn];
}else{
val += ","+vs[nn];
}
}
}
}else{
val = request.getParameter(forms.get(i).getFields().get(j).getEnname());
}
List<Object> p = new ArrayList<Object>();
p.add(executionId);
p.add(forms.get(i).getId());
p.add(forms.get(i).getFields().get(j).getId());
if("char".equals(forms.get(i).getFields().get(j).getDataType())){
//文件
if("file".equals(forms.get(i).getFields().get(j).getExtType())){
List<String> f = files.get(forms.get(i).getFields().get(j).getEnname());
if(f != null && f.size()>0){
StringBuffer s = new StringBuffer();
for(int fi=0; fi<f.size(); fi++){
s.append(f.get(fi));
s.append(",");
}
val = s.toString().substring(0,s.toString().length()-1);
}else{
val = request.getParameter("file_"+forms.get(i).getFields().get(j).getEnname());
}
}
//人员,部门
if("user".equals(forms.get(i).getFields().get(j).getExtType())||
"dept".equals(forms.get(i).getFields().get(j).getExtType())
){
uids.add(forms.get(i).getFields().get(j).getEnname()+"_ids"+"#"+forms.get(i).getFields().get(j).getId());
}
p.add(val);
p.add(null);
p.add(null);
p.add(userid);
}
if("num".equals(forms.get(i).getFields().get(j).getDataType())){
p.add(null);
if(val != null && !"".equals(val)){
p.add(Double.valueOf(val));
}else{
p.add(null);
}
p.add(null);
p.add(userid);
}
if("date".equals(forms.get(i).getFields().get(j).getDataType())){
SimpleDateFormat formatter = new SimpleDateFormat(forms.get(i).getFields().get(j).getDateFormat());
p.add(null);
p.add(null);
if("".equals(forms.get(i).getFields().get(j).getDateFormat()) || "".equals(val) ){
p.add(null);
}else{
p.add(new java.sql.Timestamp(formatter.parse(val).getTime()));
}
p.add(userid);
}
if("text".equals(forms.get(i).getFields().get(j).getDataType())){
p.add(val);
p.add(null);
p.add(null);
p.add(userid);
}
params.add(p);
}
/*//二维表
if(forms.get(i).getf!=null && forms.get(i).getTwiceFormatElement().size()>0){
for(int v=0; v<forms.get(i).getTwiceFormatElement().size(); v++){
vals = request.getParameterValues("twice_"+forms.get(i).getTwiceFormatElement().get(v).getWe_English_Name());
if(vals != null && vals.length>0){
for(int n=0; n<vals.length; n++){
List<Object> p = new ArrayList<Object>();
p.add(exampleId);
p.add(forms.get(i).getId());
p.add(forms.get(i).getTwiceFormatElement().get(v).getId());
p.add(vals[n]);
p.add(null);
p.add(null);
p.add(null);
p.add(userid);
params.add(p);
}
}
}
}*/
}
sqls.add(sql);
//会签数据
String mutiEles = request.getParameter("mutiElesName");
String mutiElesId = request.getParameter("mutiElesId");
String acdo = request.getParameter("acdo");//下一步还是保存,空保存,sub下一步
if(mutiEles != null && !"".equals(mutiEles)){
if(acdo == null || "".equals(acdo)){
acdo = "save";
}
String[] els = mutiEles.split(",");
String[] eids = mutiElesId.split(",");
for(int i=0; i<els.length; i++){
if(!fields.contains(eids[i])){//只读跳过
continue;
}
//只操作自己的意见
sqls.add("delete from df_form_data_expand where execution_id="+executionId+" and field_id="+eids[i]+" and writer='"+userid+"'");
String[] writer = request.getParameterValues("signwriter_"+els[i]);
String[] value = request.getParameterValues("sign_"+els[i]);
String[] date = request.getParameterValues("signdate_"+els[i]);
for(int j=0; j<writer.length; j++){
if(!"".equals(value[j]) && userid.equals(writer[j])){
sqls.add("insert into df_form_data_expand(execution_id,field_id,writer,value,writetime,opertype)values("+executionId+","+eids[i]+",'"+writer[j]+"','"+value[j]+"','"+date[j]+"','"+acdo+"')");
}
}
}
}
//人员
if(uids.size()>0){
for(int i=0; i<uids.size(); i++){
String[] tkey = uids.get(i).split("#");
String v = request.getParameter(tkey[0]);
if(v != null && !"".equals(v)){
String[] vids = v.split(",");
sqls.add("delete from df_form_data_expand where execution_id="+executionId+" and field_id="+tkey[1]);
for(int j=0; j<vids.length; j++){
if(!"".equals(vids[j])){
sqls.add("insert into df_form_data_expand(execution_id,field_id,writer,value)values("+executionId+","+tkey[1]+",'','"+vids[j]+"')");
}
}
}
}
}
if(db.execUpdates(sqls,1, params)){
result.put("status", true);
}else{
result.put("status", false);
result.put("msg", "数据错误");
}
}else{
result.put("status", false);
result.put("msg", "参数错误");
}
request.setAttribute("msg", result.toString());
return "form/callback";
}catch(Exception e){
logger.error(e.getMessage(),e);
result.put("status", false);
result.put("msg", e.getMessage());
request.setAttribute("msg", result.toString());
return "form/callback";
}
}
/**
* 多文件控件上传
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/uploadFormFile")
public String uploadFile(HttpServletRequest request,HttpServletResponse response){
try {
JSONObject jobj = (JSONObject) JSONObject.toJSON(this.update(request, "upload"));
String callback = request.getParameter("callback");
if("1".equals(callback)){
request.setAttribute("msg", jobj.toString());
return "form/callback";
}else{
response.setCharacterEncoding("UTF-8");
PrintWriter out;
out = response.getWriter();
out.print(jobj.toString());
out.flush();
return null;
}
} catch (IOException e) {
logger.error(e.getMessage(),e);
return "error";
}
}
@RequestMapping(value = "/downLoadFile")
public String downLoadFile(HttpServletRequest request,
HttpServletResponse response) throws IOException{
try{
String path = request.getParameter("path");
String name = request.getParameter("name");
response.setContentType("application/octet-stream");
String fileName = new String(name.getBytes("GB2312"), "ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
String fpath = request.getSession().getServletContext().getRealPath("/")+"/"+path;
File f = new File(fpath);
if(f.exists()){
FileInputStream fis = new FileInputStream(fpath);
byte[] buf = new byte[10240];
int len = -1;
while((len = fis.read(buf)) != -1){
response.getOutputStream().write(buf, 0, len);
}
response.getOutputStream().flush();
fis.close();
}
response.getOutputStream().flush();
}catch(Exception e){
logger.error(e.getMessage(),e);
}
return null;
}
//用户选择控件
@RequestMapping(value = "/findSelUser")
@ResponseBody
public Object findSelUser(HttpServletRequest request,HttpServletResponse response){
try {
String sql = "select id,case when parent_org is null then 0 else parent_org end pid,name,'d' type from sec_org "+
" union all "+
"select id,case when org is null then 0 else org end pid,fullname name,'u' type from sec_user ";
List<Map<String,Object>> list = db.getList(sql, null);
return MsgUtils.returnOk("", list);
} catch (Exception e) {
logger.error(e.getMessage(),e);
return MsgUtils.returnError(e.getMessage());
}
}
//部门选择控件
@RequestMapping(value = "/findSelDept")
@ResponseBody
public Object findSelDept(HttpServletRequest request,HttpServletResponse response){
try {
String sql = "select id,case when parent_org is null then 0 else parent_org end pid,name,'d' type from sec_org ";
List<Map<String,Object>> list = db.getList(sql, null);
return MsgUtils.returnOk("", list);
} catch (Exception e) {
logger.error(e.getMessage(),e);
return MsgUtils.returnError(e.getMessage());
}
}
//用户部门选择控件数据
@RequestMapping(value = "/findUserData")
@ResponseBody
public Object findUserData(HttpServletRequest request,HttpServletResponse response){
try {
String exampleid = request.getParameter("executionId");
String fid = request.getParameter("formId");
String eid = request.getParameter("fieldId");
String sql = "select value from df_form_data_expand where execution_id="+exampleid+" and field_id="+eid;
List<Map<String,Object>> list = db.getList(sql, null);
List<String> val = new ArrayList<String>();
for(Map<String,Object> m : list){
val.add(m.get("value").toString());
}
return MsgUtils.returnOk("", val);
} catch (Exception e) {
logger.error(e.getMessage(),e);
return MsgUtils.returnError(e.getMessage());
}
}
//会签数据
@RequestMapping(value = "/findJoinSignData")
public String findJoinSignData(HttpServletRequest request,HttpServletResponse response){
try {
String eid = request.getParameter("eid");
String exid = request.getParameter("exid");
String sql = "select a.id,a.value,a.writer,b.username,convert(varchar, a.writetime, 120) writetime,opertype from td_example_data_expand a,tab_userinfo b,Tab_Department c,Tab_HasUserDepartPos d where a.writer=b.userid and b.userid=d.UserId and c.Id=d.DepartId and a.element_id="+eid+" and example_id="+exid+" order by c.showorder,b.ShowOrder,a.writetime ";
List<Map<String,Object>> list = db.getList(sql, null);
JSONArray jarr = new JSONArray();
jarr.addAll(list);
response.setCharacterEncoding("UTF-8");
PrintWriter out;
out = response.getWriter();
out.print(jarr.toJSONString());
out.flush();
return null;
} catch (IOException e) {
logger.error(e.getMessage(),e);
return "error";
}
}
//删除上传文件
@RequestMapping(value = "/delUploadFile")
public String delUploadFile(HttpServletRequest request,HttpServletResponse response){
try {
String file = request.getParameter("file");
response.setCharacterEncoding("UTF-8");
JSONObject jobj = new JSONObject();
File f = new File(request.getSession(true).getServletContext().getRealPath("/")+file);
if(f.exists()){
f.delete();
}
jobj.put("result", true);
PrintWriter out;
out = response.getWriter();
out.print(jobj.toJSONString());
out.flush();
return null;
} catch (IOException e) {
logger.error(e.getMessage(),e);
return "error";
}
}
//文件上传
private Map<String,List<String>> update(HttpServletRequest request,String path){
Map<String,List<String>> files = new HashMap<String,List<String>>();
try{
String date = new SimpleDateFormat("yyyyMM").format(new Date());
path = path+"/"+date;
File f = new File(request.getSession(true).getServletContext().getRealPath("/")+path);
if(!f.exists()){
f.mkdirs();
}
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//判断 request 是否有文件上传,即多部分请求
if(multipartResolver.isMultipart(request)){
//转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
//取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
int i = 0;
while(iter.hasNext()){
//取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
if(file != null){
//取得当前上传文件的文件名称
String myFileName = file.getOriginalFilename();
//如果名称不为“”,说明该文件存在,否则说明该文件不存在
if(myFileName.trim() !=""){
String[] ext = file.getOriginalFilename().split("\\.");
String filepath = path+"/"+System.currentTimeMillis()+(++i)+"."+ext[ext.length-1];
if(files.get(file.getName()) == null){
files.put(file.getName(), new ArrayList<String>());
}
//添加文件上传人员
java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
files.get(file.getName()).add(myFileName+":"+filepath+":"+(ShiroUtils.getOrgName()==null ? "" : ShiroUtils.getOrgName())+"_"+ShiroUtils.getFullname()+"_"+df.format(new Date()));
//定义上传路径
file.transferTo(new File(request.getSession(true).getServletContext().getRealPath("/")+filepath));
}
}
}
}
}catch(Exception e){
e.printStackTrace();
}
return files;
}
}
| 34.620887 | 359 | 0.622066 |
bcde469c48a2d20ccf98758e6e3878c656f91ebe
| 881 |
package eu.suhajko.command.processor;
import eu.suhajko.movie.movieplayer.exception.MovieWebException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* Created by marek.melis on 4/10/17.
*/
@Component
public class BashCommandProcessorImpl implements BashCommandProcessor {
Logger logger = LoggerFactory.getLogger(getClass());
@Override public Process execute(String command) {
try {
return Runtime.getRuntime().exec(command);
}
catch (IOException e) {
logger.error("Exception thrown when trying to run command {}", command, e );
throw new MovieWebException("Exception thrown when trying to run command", e);
}
}
@Override public void shutDown(Process process) {
process.destroy();
}
}
| 26.69697 | 90 | 0.694665 |
36f8869c5bf4699950b29c1f576b2d1e60280c43
| 318 |
package phasicj.agent.instr.test.class_data.simple;
public class SynchBlock {
private static final int NUM_LOOPS = 5;
public static void main(String[] args) {
for (int idx = 0; idx < NUM_LOOPS; idx++) {
synchronized (SynchBlock.class) {
System.out.println("Hello, world!");
}
}
}
}
| 22.714286 | 51 | 0.641509 |
523e3cad4a6c9f1e97cddd7bf39ad70fad85753e
| 5,489 |
import java.util.Scanner;
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
boolean playnewround;
System.out.print("Name des ersten Spielers: ");
String name1 = scanner.next();
System.out.print("Name des zweiten Spielers: ");
String name2 = scanner.next();
Player player1 = new Player(name1, 'O');
Player player2 = new Player(name2, 'X');
do {
System.out.println("\n\n\n\n\n\n\n\n");
// Neues Spiel Ausgabe
System.out.println("========================================");
System.out.println("Neues Spiel, neues Glück!");
System.out.println("========================================");
System.out.println(player1);
System.out.println(player2);
System.out.println("========================================");
// Das Feld vorbereiten
Field.clearField();
Field.showField();
// Sieg auf false setzen
boolean player1Wins = false;
boolean player2Wins = false;
// Für 9 Züge:
for (int i = 1; i <= 9; i++) {
// Wenn noch niemand gewonnen hat:
if (!player1Wins && !player2Wins) {
// Spieler 1:
if (i % 2 != 0) {
System.out.println(player1.getName() + " ist an der Reihe");
String coordinates;
boolean finish;
// Frage nach Feld
do {
finish = false;
System.out.print("Bitte gebe ein Feld an: ");
coordinates = scanner.next();
if (Field.isPlaceAvailable(coordinates) && Field.isFree(coordinates)) {
Field.setSign(coordinates, player1);
finish = true;
} else {
System.out.println("Bitte gebe ein existierendes oder freies Feld an!");
}
} while (!finish);
System.out.println("\n\n\n\n\n");
Field.showField();
// Überprüfen, ob Spieler 1 gewonnen hat
player1Wins = Field.hasPlayer1ThreeInRow();
// Spieler 2:
} else {
System.out.println(player2.getName() + " ist an der Reihe");
String coordinates;
boolean finish;
// Frage nach Feld
do {
finish = false;
System.out.print("Bitte gebe ein Feld an: ");
coordinates = scanner.next();
if (Field.isPlaceAvailable(coordinates) && Field.isFree(coordinates)) {
Field.setSign(coordinates, player2);
finish = true;
} else {
System.out.println("Bitte gebe ein existierendes oder freies Feld an!");
}
} while (!finish);
System.out.println("\n\n\n\n\n");
Field.showField();
// Überprüfen, ob Spieler 2 gewonnen hat
player2Wins = Field.hasPlayer2ThreeInRow();
}
}
}
// SiegeScore hochsetzen
if (player1Wins) {
player1.setSiege(player1.getSiege() + 1);
System.out.println(player1.getName() + " hat gewonnen. Siege insgesamt: " + player1.getSiege());
} else if (player2Wins) {
player2.setSiege(player2.getSiege() + 1);
System.out.println(player2.getName() + " hat gewonnen. Siege insgesamt: " + player2.getSiege());
}
// Fragen, ob noch eine Runde gespielt werden soll
System.out.print("Weiter spielen (Ja/Nein): ");
String answer = scanner.next().toLowerCase();
playnewround = answer.equals("ja") || answer.equals("yes") || answer.equals("j") || answer.equals("y");
} while (playnewround);
System.out.println("\n\n");
// Engültige Ausgabe des Gewinners
System.out.println("====================================");
if (player1.getSiege() > player2.getSiege()) {
System.out.println(player1.getName() + " gewinnt mit insgesamt " + player1.getSiege() + " Siegen!");
System.out.println(player2.getName() + " verliert mit insgesamt " + player2.getSiege() + " Siegen!");
} else if (player2.getSiege() > player1.getSiege()) {
System.out.println(player2.getName() + " gewinnt mit insgesamt " + player2.getSiege() + " Siegen!");
System.out.println(player1.getName() + " verliert mit insgesamt " + player1.getSiege() + " Siegen!");
} else {
System.out.println("Unentschieden: Beide haben insgesamt " + player1.getSiege() + " Siege");
}
System.out.println("====================================");
System.out.println("Vielen Dank fürs Spielen!");
}
}
| 42.223077 | 115 | 0.456185 |
30ae5c853855deb0ed43740ca62b03c4606cc92d
| 479 |
package com.thomaskuenneth.farbfolge;
enum Farbe {
ROT(0xff800000, 0xffff0000),
GELB(0xff808000, 0xffffff00),
GRUEN(0xff008000, 0xff00ff00),
BLAU(0xff000080, 0xff0000ff);
private int farbeDunkel;
private int farbeHell;
Farbe(int dunkel, int hell) {
farbeDunkel = dunkel;
farbeHell = hell;
}
public int getFarbeDunkel() {
return farbeDunkel;
}
public int getFarbeHell() {
return farbeHell;
}
}
| 18.423077 | 37 | 0.636743 |
6c125ca9a3080fc52bc1b407dd208c4829514219
| 1,302 |
package br.lostpets.project.repository;
import static org.junit.Assert.assertEquals;
import javax.transaction.Transactional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import br.lostpets.project.model.Usuario;
@Transactional
@SpringBootTest
@RunWith(SpringRunner.class)
public class UsuarioRepositoryTest {
@Autowired
private UsuarioRepository usuarioRepository;
private Usuario usuario;
@Test
public void permitirUsuario() {
usuario = new Usuario("nome", "email", "celular", "telefone");
usuarioRepository.save(usuario);
Usuario usuarioEncontrado = usuarioRepository.getOne(usuario.getIdPessoa());
assertEquals(usuario, usuarioEncontrado);
}
@Test
public void cadastraTodoUsuario() {
usuario = new Usuario("Nome", "Fixo", "Celular","Email","Senha","Imagem","Cep","Rua","Bairro","Cidade","Uf",0,0);
usuarioRepository.save(usuario);
Usuario usuarioEmail = usuarioRepository.validarAcesso(usuario.getEmail(), usuario.getSenha());
assertEquals(usuario.getEmail(), usuarioEmail.getEmail());
assertEquals(usuario.getSenha(), usuarioEmail.getSenha());
}
}
| 27.702128 | 115 | 0.771889 |
b0e989a1e41942d474d2866791054f0d756a0f6a
| 179 |
package com.andrey7mel.testrx.other;
public class TestConst {
public static final String TEST_OWNER = "TEST_OWNER";
public static final String TEST_REPO = "TEST_REPO";
}
| 25.571429 | 57 | 0.75419 |
8fdde0a5e9c7d56b818d154d4afdbe714c8555e4
| 542 |
package com.yukong.panda.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan({"com.yukong.panda.common", "com.yukong.panda.gateway"})
@EnableZuulProxy
@SpringBootApplication
public class PandaGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(PandaGatewayApplication.class, args);
}
}
| 30.111111 | 71 | 0.830258 |
81d902d89150d2db1bfa89ffff61aa3b9b076e19
| 453 |
package uk.gov.pay.connector.events.model.charge;
import uk.gov.pay.connector.events.eventdetails.charge.RefundAvailabilityUpdatedEventDetails;
import java.time.ZonedDateTime;
public class RefundAvailabilityUpdated extends PaymentEvent {
public RefundAvailabilityUpdated(String resourceExternalId, RefundAvailabilityUpdatedEventDetails eventDetails, ZonedDateTime timestamp) {
super(resourceExternalId, eventDetails, timestamp);
}
}
| 34.846154 | 142 | 0.83223 |
9ebf03bbe91b3be26febc2debce30b2ebc7c4897
| 2,475 |
// This file contains material supporting section 10.9 of the textbook:
// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com
/*
* SimpleClient.java 2001-02-08
*
* Copyright (c) 2001 Robert Laganiere and Timothy C. Lethbridge.
* All Rights Reserved.
*
*/
package ocsftester;
import java.awt.List;
import java.awt.Color;
import ocsf.client.*;
/**
* The <code> SimpleClient </code> class is a simple subclass
* of the <code> ocsf.server.AbstractClient </code> class.
* It allows testing of the functionalities offered by the
* OCSF framework. The <code> java.awt.List </code> instance
* is used to display informative messages.
* This list is
* pink when the connection has been closed, red
* when an exception is received,
* and green when connected to the server.
*
* @author Dr. Robert Laganière
* @version February 2001
* @see ocsf.server.AbstractServer
*/
public class SimpleClient extends AbstractClient
{
private List liste;
public SimpleClient(List liste)
{
super("localhost",12345);
this.liste = liste;
}
public SimpleClient(int port, List liste)
{
super("localhost",port);
this.liste = liste;
}
public SimpleClient(String host, int port, List liste)
{
super(host,port);
this.liste = liste;
}
/**
* Hook method called after the connection has been closed.
*/
protected void connectionClosed()
{
liste.add("**Connection closed**");
liste.makeVisible(liste.getItemCount()-1);
liste.setBackground(Color.pink);
}
/**
* Hook method called each time an exception is thrown by the
* client's thread that is waiting for messages from the server.
*
* @param exception the exception raised.
*/
protected void connectionException(Exception exception)
{
liste.add("**Connection exception: " + exception);
liste.makeVisible(liste.getItemCount()-1);
liste.setBackground(Color.red);
}
/**
* Hook method called after a connection has been established.
*/
protected void connectionEstablished()
{
liste.add("--Connection established");
liste.makeVisible(liste.getItemCount()-1);
liste.setBackground(Color.green);
}
/**
* Handles a message sent from the server to this client.
*
* @param msg the message sent.
*/
protected void handleMessageFromServer(Object msg)
{
liste.add(msg.toString());
liste.makeVisible(liste.getItemCount()-1);
}
}
| 25 | 77 | 0.697778 |
2388c33907b0f01abd73c3957e61a0c5c7f00d83
| 1,044 |
/* *******************************************************************
* Copyright (c) 1999-2001 Xerox Corporation,
* 2002 Palo Alto Research Center, Incorporated (PARC).
* 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:
* Xerox/PARC initial implementation
* ******************************************************************/
package org.aspectj.tools.ajbrowser.ui;
import org.aspectj.ajde.IdeUIAdapter;
import org.aspectj.tools.ajbrowser.BrowserManager;
/**
* AjBrowser implementation if IdeUIAdapter which displays the provided
* information in the status bar at the bottom of the AjBrowser GUI.
*/
public class BrowserUIAdapter implements IdeUIAdapter {
public void displayStatusInformation(String message) {
BrowserManager.getDefault().setStatusInformation(message);
}
}
| 34.8 | 71 | 0.651341 |
ee7ad25be08ad95eda70e3f1ea2678e46dfff098
| 2,254 |
/*
* 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.netbeans.modules.editor.actions;
import java.awt.event.ActionEvent;
import java.util.Map;
import javax.swing.text.JTextComponent;
import org.netbeans.api.editor.EditorActionNames;
import org.netbeans.api.editor.EditorActionRegistration;
import org.netbeans.api.editor.EditorActionRegistrations;
import org.netbeans.spi.editor.AbstractEditorAction;
/**
* Zoom editor pane's text in/out.
*
* @author Miloslav Metelka
* @since 1.11
*/
@EditorActionRegistrations({
@EditorActionRegistration(
name = EditorActionNames.zoomTextIn
),
@EditorActionRegistration(
name = EditorActionNames.zoomTextOut
)
})
public class ZoomTextAction extends AbstractEditorAction {
private static final long serialVersionUID = 1L;
private static final String TEXT_ZOOM_PROPERTY = "text-zoom"; // Defined in DocumentView in editor.lib2
@Override
public void actionPerformed(ActionEvent evt, JTextComponent target) {
String actionName = actionName();
int delta = (EditorActionNames.zoomTextIn.equals(actionName)) ? +1 : -1;
if (target != null) {
int newZoom = 0;
Integer currentZoom = (Integer) target.getClientProperty(TEXT_ZOOM_PROPERTY);
if (currentZoom != null) {
newZoom += currentZoom;
}
newZoom += delta;
target.putClientProperty(TEXT_ZOOM_PROPERTY, newZoom);
}
}
}
| 35.21875 | 107 | 0.713842 |
cb8cd0b3f332f772510a5acd9234bca831fdd2ae
| 159 |
package com.zandero.rest.test.data;
public class Token {
public final String token;
public Token(String token) {
this.token = token;
}
}
| 15.9 | 35 | 0.647799 |
92bcb6949d5843e59afbc2c973a221a53793e560
| 3,099 |
package com.norswap.nanoeth.trees.verkle;
import com.norswap.nanoeth.crypto.Crypto;
import com.norswap.nanoeth.crypto.Curve;
import com.norswap.nanoeth.utils.Randomness;
import org.bouncycastle.math.ec.ECPoint;
import java.math.BigInteger;
public class Test {
// ---------------------------------------------------------------------------------------------
/** The curve used for proofs. */
public static final Curve CURVE = Curve.SECP256K1;
// ---------------------------------------------------------------------------------------------
/** A set of nothing-up-my-sleeve points used to construct vector commitments. */
private static final ECPoint[] PEDERSEN_BASIS =
Crypto.nothingUpMySleevePoints(Curve.SECP256K1, 513);
// ---------------------------------------------------------------------------------------------
// TODO: how do I open a commitment to a specific position?
public static void main (String[] args) {
testVectorsProof();
testNonHidingVectorsProof();
testInnerProof();
}
// ---------------------------------------------------------------------------------------------
private static void testVectorsProof() {
int numVectors = 4;
int vectorSize = 100;
var randoms = Randomness.randomIntegers(numVectors);
var vectors = new BigInteger[numVectors][];
for (int i = 0; i < vectors.length; i++)
vectors[i] = Randomness.randomIntegers(vectorSize);;
var commitments = new ECPoint[numVectors];
for (int i = 0; i < commitments.length; i++)
commitments[i] = Crypto.pedersenCommitment(randoms[i], vectors[i], PEDERSEN_BASIS);
var proof = new VectorsProof(PEDERSEN_BASIS, vectorSize, randoms, vectors);
System.out.println(proof.verify(commitments));
}
// ---------------------------------------------------------------------------------------------
private static void testNonHidingVectorsProof() {
int numVectors = 4;
int vectorSize = 100;
var vectors = new BigInteger[numVectors][];
for (int i = 0; i < vectors.length; i++)
vectors[i] = Randomness.randomIntegers(vectorSize);;
var commitments = new ECPoint[numVectors];
for (int i = 0; i < commitments.length; i++)
commitments[i] = Crypto.pedersenCommitment(vectors[i], PEDERSEN_BASIS);
var proof = new NonHidingVectorsProof(PEDERSEN_BASIS, vectorSize, vectors);
System.out.println(proof.verify(commitments));
}
// ---------------------------------------------------------------------------------------------
private static void testInnerProof() {
int vectorSize = 256;
var vector1 = Randomness.randomIntegers(vectorSize);
var vector2 = Randomness.randomIntegers(vectorSize);
var proof = new InnerProductProof(CURVE, PEDERSEN_BASIS, vector1, vector2);
System.out.println(proof.verify());
}
// ---------------------------------------------------------------------------------------------
}
| 41.878378 | 100 | 0.515005 |
04fef33ea815302a6a0d78a94d76be41949e059c
| 2,498 |
package com.atguigu.gmall.index.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
public class DistributeLock {
@Autowired
private StringRedisTemplate redisTemplate;
private Thread thread;
public Boolean tryLock(String lockName, String uuid, Long expire){
String script = "if (redis.call('exists', KEYS[1]) == 0 or redis.call('hexists', KEYS[1], ARGV[1]) == 1) " +
"then redis.call('hincrby', KEYS[1], ARGV[1], 1); redis.call('expire', KEYS[1], ARGV[2]); return 1; " +
"else return 0; end;";
if(this.redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList(lockName), uuid, expire.toString()) == 0){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
tryLock(lockName, uuid, expire);
}
renewTime(lockName, uuid, expire);
return true;
}
public void unLock(String lockName, String uuid){
String script = "if (redis.call('hexists', KEYS[1], ARGV[1]) == 0) then return nil end; " +
"if (redis.call('hincrby', KEYS[1], ARGV[1], -1) > 0) then return 0 " +
"else redis.call('del', KEYS[1]) return 1 end;";
if(this.redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList(lockName), uuid) == null){
throw new IllegalArgumentException("attempt to unlock lock, lockname: " + lockName + ", uuid: " + uuid);
}
this.thread.interrupt();
}
private void renewTime(String lockName, String uuid, Long expire){
String script = "if (redis.call('hexists', KEYS[1], ARGV[1]) == 1) " +
"then return redis.call('expire', KEYS[1], ARGV[2]) end;";
this.thread = new Thread(() -> {
while(true){
try {
Thread.sleep(expire * 1000 * 2 / 3);
this.redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList(lockName), uuid, expire.toString());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
this.thread.start();
}
}
| 41.633333 | 143 | 0.592474 |
cfbcc48f7fd934435fa8ad12a9b0a3fa4fcea2b2
| 19,270 |
/*
* 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.nifi.hdfs.repository;
import static org.apache.nifi.hdfs.repository.HdfsContentRepository.CORE_SITE_DEFAULT_PROPERTY;
import static org.apache.nifi.hdfs.repository.HdfsContentRepository.FAILURE_TIMEOUT_PROPERTY;
import static org.apache.nifi.hdfs.repository.HdfsContentRepository.FULL_PERCENTAGE_PROPERTY;
import static org.apache.nifi.hdfs.repository.HdfsContentRepository.OPERATING_MODE_PROPERTY;
import static org.apache.nifi.hdfs.repository.PropertiesBuilder.config;
import static org.apache.nifi.hdfs.repository.PropertiesBuilder.prop;
import static org.apache.nifi.hdfs.repository.PropertiesBuilder.props;
import static org.apache.nifi.util.NiFiProperties.REPOSITORY_CONTENT_PREFIX;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import org.apache.commons.lang3.SystemUtils;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FsStatus;
import org.apache.hadoop.fs.Path;
import org.apache.nifi.util.NiFiProperties;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class ContainerHealthMonitorTest {
@BeforeClass
public static void setUpSuite() {
Assume.assumeTrue("Test only runs on *nix", !SystemUtils.IS_OS_WINDOWS);
}
@Test
public void isGroupHealthyTest() {
NiFiProperties props = props(
prop(REPOSITORY_CONTENT_PREFIX + "disk1", "target/test-repo1"),
prop(REPOSITORY_CONTENT_PREFIX + "disk2", "target/test-repo2"),
prop(CORE_SITE_DEFAULT_PROPERTY, "src/test/resources/empty-core-site.xml"),
prop(FAILURE_TIMEOUT_PROPERTY, "1 minute")
);
RepositoryConfig config = config(props);
ContainerHealthMonitor monitor = new ContainerHealthMonitor(null, null, null, config);
// null groups should always return true since this is only
// called for the secondary group, and the return value doesn't matter
assertTrue(monitor.isGroupHealthy(null));
ContainerGroup group = new ContainerGroup(props, config, null, null);
assertTrue(monitor.isGroupHealthy(group));
// all failed test
for (Container container : group) {
container.failureOcurred();
}
// since all containers are failed, the group is not healthy
assertFalse(monitor.isGroupHealthy(group));
for (Container container : group) {
assertTrue(container.isFailedRecently());
}
// partial failure test - one container is failed, the other is not, so overall
// the group is healthy
group.atModIndex(0).clearFailure(group.atModIndex(0).getLastFailure());
assertTrue(monitor.isGroupHealthy(group));
}
@Test
public void isGroupHealthyRecoveryTest() throws IOException {
NiFiProperties props = props(
prop(REPOSITORY_CONTENT_PREFIX + "disk1", "target/test-repo1"),
prop(REPOSITORY_CONTENT_PREFIX + "disk2", "target/test-repo2"),
prop(CORE_SITE_DEFAULT_PROPERTY, "src/test/resources/empty-core-site.xml"),
prop(FAILURE_TIMEOUT_PROPERTY, "1 minute")
);
RepositoryConfig config = config(props);
ContainerGroup group = new ContainerGroup(props, config, null, null) {
TimeAdjustingFailureContainer indexOneContainer = null;
@Override
public Iterator<Container> iterator() {
if (indexOneContainer == null) {
try {
indexOneContainer = new TimeAdjustingFailureContainer(atModIndex(1));
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
return Arrays.asList(atModIndex(0), indexOneContainer).iterator();
}
};
ContainerHealthMonitor monitor = new ContainerHealthMonitor(null, null, null, config);
assertTrue(monitor.isGroupHealthy(group));
for (Container container : group) {
container.failureOcurred();
assertTrue(container.isFailedRecently());
}
// the group should still be healthy and the one
// container should now be marked as not recently failed
assertTrue(monitor.isGroupHealthy(group));
Iterator<Container> containerIter = group.iterator();
Container one = containerIter.next();
assertFalse(one.isActive());
assertTrue(one.isFailedRecently());
Container two = containerIter.next();
assertTrue(two.isActive());
assertFalse(two.isFailedRecently());
}
@Test
public void checkDiskHealthTest() throws IOException {
NiFiProperties props = props(
prop(REPOSITORY_CONTENT_PREFIX + "disk1", "target/test-repo1"),
prop(REPOSITORY_CONTENT_PREFIX + "disk2", "target/test-repo2"),
prop(CORE_SITE_DEFAULT_PROPERTY, "src/test/resources/empty-core-site.xml"),
prop(FULL_PERCENTAGE_PROPERTY, "99%")
);
RepositoryConfig config = config(props);
ContainerHealthMonitor monitor = new ContainerHealthMonitor(null, null, null, config);
// null groups should always return true since this is only
// called for the secondary group, and the return value doesn't matter
assertTrue(monitor.doesGroupHaveFreeSpace(null));
ContainerGroup realGroup = new ContainerGroup(props, config, null, null);
assertTrue(monitor.doesGroupHaveFreeSpace(realGroup));
//
// get the file system to say it's full
//
Container realContainer = realGroup.atModIndex(0);
FileSystem realFs = realContainer.getFileSystem();
FsStatus realStatus = realFs.getStatus(realContainer.getPath());
Container fullContainer = spy(realContainer);
FileSystem fullFs = spy(realFs);
FsStatus fullStatus = spy(realStatus);
when(fullStatus.getUsed()).thenReturn(realStatus.getCapacity());
when(fullStatus.getRemaining()).thenReturn(0L);
when(fullFs.getStatus(any(Path.class))).thenReturn(fullStatus);
when(fullContainer.getFileSystem()).thenReturn(fullFs);
ContainerGroup oneFullGroup = spy(realGroup);
when(oneFullGroup.iterator()).thenReturn(Arrays.asList(fullContainer, realGroup.atModIndex(1)).iterator());
assertFalse(fullContainer.isFull());
assertTrue(fullContainer.isActive());
// the group should still have space because one of the containers is
// not full. Make sure the 'full' container is now marked as full
assertTrue(monitor.doesGroupHaveFreeSpace(oneFullGroup));
assertTrue(fullContainer.isFull());
assertFalse(fullContainer.isActive());
// reset the full container's state
fullContainer.setFull(false);
assertFalse(fullContainer.isFull());
assertTrue(fullContainer.isActive());
// now get the other container to say it's full as well
ContainerGroup completelyFull = spy(realGroup);
Container fullContainerTwo = spy(realGroup.atModIndex(1));
when(fullContainerTwo.getFileSystem()).thenReturn(fullFs);
when(completelyFull.iterator()).thenReturn(Arrays.asList(fullContainer, fullContainerTwo).iterator());
// since both containers are full, there should no longer be any free space
assertFalse(monitor.doesGroupHaveFreeSpace(completelyFull));
// both containers should be marked full and inactive
for (Container container : completelyFull) {
assertTrue(container.isFull());
assertFalse(container.isActive());
}
}
@Test
public void switchActiveTest() {
//
// Make sure the monitor switches between primary/secondary
// properly with each subsequent call to switchActive()
//
HdfsContentRepository repo = mock(HdfsContentRepository.class);
ContainerGroup primary = mock(ContainerGroup.class);
ContainerGroup secondary = mock(ContainerGroup.class);
ContainerHealthMonitor monitor = new ContainerHealthMonitor(repo, primary, secondary, config(props()));
monitor.switchActive("test");
verify(repo, times(1)).setActiveGroup(any(ContainerGroup.class));
verify(repo, times(1)).setActiveGroup(eq(secondary));
monitor.switchActive("test");
verify(repo, times(2)).setActiveGroup(any(ContainerGroup.class));
verify(repo, times(1)).setActiveGroup(eq(secondary));
verify(repo, times(1)).setActiveGroup(eq(primary));
monitor.switchActive("test");
verify(repo, times(3)).setActiveGroup(any(ContainerGroup.class));
verify(repo, times(2)).setActiveGroup(eq(secondary));
verify(repo, times(1)).setActiveGroup(eq(primary));
monitor.switchActive("test");
verify(repo, times(4)).setActiveGroup(any(ContainerGroup.class));
verify(repo, times(2)).setActiveGroup(eq(secondary));
verify(repo, times(2)).setActiveGroup(eq(primary));
}
@Test
public void capacityFallbackTest() {
HdfsContentRepository repo = mock(HdfsContentRepository.class);
ContainerGroup primary = mock(ContainerGroup.class);
ContainerGroup secondary = mock(ContainerGroup.class);
RepositoryConfig config = config(props(
prop(OPERATING_MODE_PROPERTY, "CapacityFallback")
));
ContainerHealthMonitor monitor = new ContainerHealthMonitor(repo, primary, secondary, config);
monitor = spy(monitor);
when(monitor.doesGroupHaveFreeSpace(any(ContainerGroup.class))).thenReturn(
true, true, // CALL #1
false, false, // CALL #2
false, false, // CALL #3
true, true // CALL #4
);
when(monitor.isGroupHealthy(any(ContainerGroup.class))).thenReturn(true);
// CALL #1
// first run, the primary group will have free space, so no switch should happen
monitor.run();
verify(repo, times(0)).setActiveGroup(any(ContainerGroup.class));
verify(monitor, times(1)).doesGroupHaveFreeSpace(eq(primary));
verify(monitor, times(1)).doesGroupHaveFreeSpace(eq(secondary));
// CALL #2
// now run it again, and primary should be full, so we should switch to the secondary
monitor.run();
verify(repo, times(1)).setActiveGroup(any(ContainerGroup.class));
verify(repo, times(1)).setActiveGroup(eq(secondary));
verify(monitor, times(2)).doesGroupHaveFreeSpace(eq(primary));
verify(monitor, times(2)).doesGroupHaveFreeSpace(eq(secondary));
// CALL #3
// running again should have no affect since the primary is still full
monitor.run();
verify(repo, times(1)).setActiveGroup(any(ContainerGroup.class));
verify(monitor, times(3)).doesGroupHaveFreeSpace(eq(primary));
verify(monitor, times(3)).doesGroupHaveFreeSpace(eq(secondary));
// CALL #4
// running one last time, primary should no longer be full, and should be set to active again
monitor.run();
verify(repo, times(2)).setActiveGroup(any(ContainerGroup.class));
verify(repo, times(1)).setActiveGroup(eq(secondary));
verify(repo, times(1)).setActiveGroup(eq(primary));
verify(monitor, times(4)).doesGroupHaveFreeSpace(eq(primary));
verify(monitor, times(4)).doesGroupHaveFreeSpace(eq(secondary));
}
@Test
public void failureFallbackTest() {
HdfsContentRepository repo = mock(HdfsContentRepository.class);
ContainerGroup primary = mock(ContainerGroup.class);
ContainerGroup secondary = mock(ContainerGroup.class);
RepositoryConfig config = config(props(
prop(OPERATING_MODE_PROPERTY, "FailureFallback"),
prop(FAILURE_TIMEOUT_PROPERTY, "1 minute")
));
ContainerHealthMonitor monitor = new ContainerHealthMonitor(repo, primary, secondary, config);
monitor = spy(monitor);
when(monitor.isGroupHealthy(any(ContainerGroup.class))).thenReturn(
true, true, // CALL #1
false, false, // CALL #2
false, false, // CALL #3
true, true // CALL #4
);
when(monitor.doesGroupHaveFreeSpace(any(ContainerGroup.class))).thenReturn(true);
// CALL #1
// first run, the primary group will be healthy, so no switch should happen
monitor.run();
verify(repo, times(0)).setActiveGroup(any(ContainerGroup.class));
verify(monitor, times(1)).isGroupHealthy(eq(primary));
verify(monitor, times(1)).isGroupHealthy(eq(secondary));
// CALL #2
// now run it again, and primary should be unhealthy, so we should switch to the secondary
monitor.run();
verify(repo, times(1)).setActiveGroup(any(ContainerGroup.class));
verify(repo, times(1)).setActiveGroup(eq(secondary));
verify(monitor, times(2)).isGroupHealthy(eq(primary));
verify(monitor, times(2)).isGroupHealthy(eq(secondary));
// CALL #3
// running again should have no affect since the primary is still unhealthy
monitor.run();
verify(repo, times(1)).setActiveGroup(any(ContainerGroup.class));
verify(monitor, times(3)).isGroupHealthy(eq(primary));
verify(monitor, times(3)).isGroupHealthy(eq(secondary));
// CALL #4
// running one last time, primary should be healthy again, and should be set to active again
monitor.run();
verify(repo, times(2)).setActiveGroup(any(ContainerGroup.class));
verify(repo, times(1)).setActiveGroup(eq(secondary));
verify(repo, times(1)).setActiveGroup(eq(primary));
verify(monitor, times(4)).isGroupHealthy(eq(primary));
verify(monitor, times(4)).isGroupHealthy(eq(secondary));
}
@Test
public void monitorOnlyFullTest() {
HdfsContentRepository repo = mock(HdfsContentRepository.class);
ContainerGroup primary = mock(ContainerGroup.class);
ContainerGroup secondary = mock(ContainerGroup.class);
RepositoryConfig config = config(props());
ContainerHealthMonitor monitor = new ContainerHealthMonitor(repo, primary, secondary, config);
monitor = spy(monitor);
when(monitor.isGroupHealthy(any(ContainerGroup.class))).thenReturn(false);
when(monitor.doesGroupHaveFreeSpace(any(ContainerGroup.class))).thenReturn(true);
// since fallback isn't enabled, no switching should happen even though primary is full
monitor.run();
verify(repo, times(0)).setActiveGroup(any(ContainerGroup.class));
// double check
monitor.run();
verify(repo, times(0)).setActiveGroup(any(ContainerGroup.class));
}
@Test
public void monitorOnlyFailureTest() {
HdfsContentRepository repo = mock(HdfsContentRepository.class);
ContainerGroup primary = mock(ContainerGroup.class);
ContainerGroup secondary = mock(ContainerGroup.class);
RepositoryConfig config = config(props());
ContainerHealthMonitor monitor = new ContainerHealthMonitor(repo, primary, secondary, config);
monitor = spy(monitor);
when(monitor.isGroupHealthy(any(ContainerGroup.class))).thenReturn(true);
when(monitor.doesGroupHaveFreeSpace(any(ContainerGroup.class))).thenReturn(false);
// since fallback isn't enabled, no switching should happen even though primary is unhealthy
monitor.run();
verify(repo, times(0)).setActiveGroup(any(ContainerGroup.class));
// double check
monitor.run();
verify(repo, times(0)).setActiveGroup(any(ContainerGroup.class));
}
@Test
public void monitorOnlyBothTest() {
HdfsContentRepository repo = mock(HdfsContentRepository.class);
ContainerGroup primary = mock(ContainerGroup.class);
ContainerGroup secondary = mock(ContainerGroup.class);
RepositoryConfig config = config(props());
ContainerHealthMonitor monitor = new ContainerHealthMonitor(repo, primary, secondary, config);
monitor = spy(monitor);
when(monitor.isGroupHealthy(any(ContainerGroup.class))).thenReturn(false);
when(monitor.doesGroupHaveFreeSpace(any(ContainerGroup.class))).thenReturn(false);
// since fallback isn't enabled, no switching should happen even though primary is unhealthy and full
monitor.run();
verify(repo, times(0)).setActiveGroup(any(ContainerGroup.class));
// double check
monitor.run();
verify(repo, times(0)).setActiveGroup(any(ContainerGroup.class));
}
@Ignore
private static class TimeAdjustingFailureContainer extends Container {
private final Container delegate;
private long useLastFailureTime = 0;
public TimeAdjustingFailureContainer(Container delegate) throws IOException {
super("test-adjust", new Path("file:/this/path/doesnt/exist"), null, 0, 0, true);
this.delegate = delegate;
}
@Override
public void failureOcurred() {
delegate.failureOcurred();
useLastFailureTime = System.currentTimeMillis() - 1000 * 60 * 60 * 60;
}
@Override
public long getLastFailure() {
return useLastFailureTime;
}
@Override
public boolean isActive() {
return delegate.isActive();
}
@Override
public boolean isFailedRecently() {
return delegate.isFailedRecently();
}
@Override
public synchronized boolean clearFailure(long expectedLastFailure) {
if (expectedLastFailure == useLastFailureTime) {
assertTrue(delegate.clearFailure(delegate.getLastFailure()));
return true;
}
return false;
}
}
}
| 40.398323 | 115 | 0.672548 |
8a00eff1a729dc38ec4284c9332964cd1b15e44c
| 775 |
package javajdk.logging.tyz.use;
import java.util.logging.Level;
import java.util.logging.Logger;
public class JDKLoggerTest {
//private static Logger logger = Logger.getLogger("com.bes.logging");
public static void main(String argv[]) {
// Log a FINEtracing message
System.setProperty("java.util.logging.config.file", "//resource//logging.properties");
Logger logger = Logger.getLogger("com.bes.logging");
logger.info("Main running.");
logger.fine("doingstuff");
logger.log(Level.CONFIG, "config");
try {
Thread.currentThread().sleep(1000);// do some work
} catch (Exception ex) {
logger.log(Level.WARNING, "trouble sneezing", ex);
}
logger.fine("done");
System.out.println(System.getProperty("java.util.logging.config.file"));
}
}
| 26.724138 | 88 | 0.709677 |
bd66f7f1058ac8ed8ce4efbac51cb474916eb292
| 4,468 |
package org.nikkii.embedhttp.impl;
import org.nikkii.embedhttp.util.HttpUtil;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Represents an Http request
*
* @author Nikki
*/
public class HttpRequest {
/**
* The session which constructed this request
*/
private HttpSession session;
/**
* The request method
*/
private HttpMethod method;
/**
* The requested URI
*/
private String uri;
/**
* The request headers
*/
private Map<String, String> headers;
/**
* Raw Query String
*/
private String queryString;
/**
* Raw POST data (Not applicable for form-encoded, automatically parsed)
*/
private String data;
/**
* The parsed GET data
*/
private Map<String, Object> getData;
/**
* The parsed POST data
*/
private Map<String, Object> postData;
/**
* The list of parsed cookies
*/
private Map<String, HttpCookie> cookies;
/**
* Construct a new HTTP request
*
* @param session The session which initiated the request
* @param method The method used to request this page
* @param uri The URI of the request
* @param headers The request headers
*/
public HttpRequest(HttpSession session, HttpMethod method, String uri, Map<String, String> headers) {
this.session = session;
this.method = method;
this.uri = uri;
this.headers = headers;
}
/**
* Get the session which initiated this request
*
* @return The session
*/
public HttpSession getSession() {
return session;
}
/**
* Get the request method
*
* @return The request method
*/
public HttpMethod getMethod() {
return method;
}
/**
* Get the request uri
*
* @return The request uri
*/
public String getUri() {
return uri;
}
/**
* Get the request headers
*
* @return The request headers
*/
public Map<String, String> getHeaders() {
return headers;
}
/**
* Gets a request header
*
* @param key The request header key
* @return The header value
*/
public String getHeader(String key) {
return headers.get(HttpUtil.capitalizeHeader(key));
}
/**
* Set the request's raw POST data
*
* @param data The data to set
*/
public void setData(String data) {
this.data = data;
}
/**
* Set the request's parsed GET data
*
* @param getData The parsed data map to set
*/
public void setGetData(Map<String, Object> getData) {
this.getData = getData;
}
/**
* Set the request's parsed POST data
*
* @param postData The parsed data map to set
*/
public void setPostData(Map<String, Object> postData) {
this.postData = postData;
}
/**
* Set the request's URI
*
* @param uri The uri to set
*/
public void setUri(String uri) {
this.uri = uri;
}
/**
* Sets the request's query string
*
* @param queryString The query string to set
*/
public void setQueryString(String queryString) {
this.queryString = queryString;
}
/**
* Gets the request's query string
*
* @return The query string
*/
public String getQueryString() {
return queryString;
}
/**
* Get the request's raw POST data
*
* @return The request's POST data
*/
public String getData() {
return data;
}
/**
* Get the request's parsed GET data
*
* @return the parsed data map
*/
public Map<String, Object> getGetData() {
return getData;
}
/**
* Get the request's parsed POST data
*
* @return The parsed data map
*/
public Map<String, Object> getPostData() {
return postData;
}
/**
* Set the request's cookies
*
* @param cookies The cookie list
*/
public void setCookies(List<HttpCookie> cookies) {
Map<String, HttpCookie> map = new HashMap<String, HttpCookie>();
for (HttpCookie cookie : cookies) {
map.put(cookie.getName(), cookie);
}
this.cookies = map;
}
/**
* Get a cookie with the specified name
*
* @param name The cookie name
* @return The cookie
*/
public HttpCookie getCookie(String name) {
return cookies.get(name);
}
/**
* Get the request's cookies
*
* @return The cookie list
*/
public Collection<HttpCookie> getCookies() {
return cookies == null ? null : cookies.values();
}
@Override
public void finalize() {
if (postData != null) {
for (Object value : postData.values()) {
if (value instanceof HttpFileUpload) {
HttpFileUpload u = (HttpFileUpload) value;
if (!u.getTempFile().delete()) {
u.getTempFile().deleteOnExit();
}
}
}
}
}
}
| 17.872 | 102 | 0.649731 |
4119641a4717ab0ecd044a4987ffe859144690fb
| 261 |
package observer;
public class BObServer extends ObServer {
public BObServer(Subject subject) {
this.subject = subject;
subject.register(this);
}
@Override
public void update() {
System.out.println("BObServer state : " + subject.getState());
}
}
| 16.3125 | 64 | 0.708812 |
0479f8780c79331f9ea1b9e85876a3dc3abde196
| 447 |
package com.android.wm.shell.common.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Qualifier;
/** Annotates a method or qualifies a provider that runs on the Shell animation-thread */
@Documented
@Inherited
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface ShellAnimationThread {}
| 29.8 | 89 | 0.825503 |
4fa8260fd9de41f2e3cd662e452ecdd82c7e5cd0
| 1,498 |
/**
*
* Copyright 2020, Optimizely and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.optimizely.ab.optimizelyjson;
/**
* Test types for parsing JSON strings to Java objects (OptimizelyJSON)
*/
public class TestTypes {
public static class MD1 {
public String k1;
public boolean k2;
public MD2 k3;
}
public static class MD2 {
public double kk1;
public MD3 kk2;
}
public static class MD3 {
public boolean kkk1;
public double kkk2;
public String kkk3;
public Object[] kkk4;
}
// Invalid parse type
public static class NotMatchingType {
public String x99;
}
// Test types for integer parsing tests
public static class MDN1 {
public int k1;
public double k2;
public MDN2 k3;
}
public static class MDN2 {
public int kk1;
public double kk2;
}
}
| 24.16129 | 78 | 0.640187 |
ee180603707298d12628aba45b52dfce6ea0d7f7
| 133 |
package actors;
public class ChooseBeerProtocol {
public static class QueryLcbo {
// is this really necessary?
}
}
| 14.777778 | 36 | 0.669173 |
eeaf889907be9f32b0d943cd6e40bb0ed9d2a1c6
| 1,154 |
package org.synyx.urlaubsverwaltung.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Is thrown in case of the security configuration (LDAP/AD) seems to be invalid.
*/
public class InvalidSecurityConfigurationException extends IllegalStateException {
public InvalidSecurityConfigurationException(String message) {
super(message);
}
@Controller
@RequestMapping("/login")
public static class LoginController {
private final String applicationVersion;
@Autowired
public LoginController(@Value("${info.app.version}") String applicationVersion) {
this.applicationVersion = applicationVersion;
}
@GetMapping("")
public String login(Model model) {
model.addAttribute("version", applicationVersion);
return "login/login";
}
}
}
| 28.146341 | 89 | 0.72617 |
2f63d8ebaa6064ac36b2b591a985023320ab6328
| 766 |
package com.twu.biblioteca.core;
/**
* @Author Joker
* @Description
* @Date Create in 下午4:04 2018/4/26
*/
public class Book {
private final String name;
private final String author;
private final int year;
public Book(String name, String author, int year) {
this.name = name;
this.author = author;
this.year = year;
}
public String getName() {
return name;
}
public String getAuthor() {
return author;
}
public int getYear() {
return year;
}
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", author='" + author + '\'' +
", year=" + year +
'}';
}
}
| 19.15 | 55 | 0.503916 |
beedd3ec467fad233f7941b78793c217d0822cad
| 713 |
package Sorting;
public class SelectionSort {
static void selectionSort(int arr[])
{
for (int i=0;i< arr.length;i++)
{
int minindex=i;
int temp;
for (int j=i+1;j< arr.length;j++)
{
if(arr[j]<arr[minindex])
{
minindex=j;
}
}
temp=arr[i];
arr[i]= arr[minindex];
arr[minindex]=temp;
}
}
public static void main(String[] args) {
int arr[]={10,5,8,20,2,18};
selectionSort(arr);
for (int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
}
}
| 23 | 46 | 0.402525 |
dd15f18c803cf198524fd99e3a954468a5ffea00
| 345 |
package edu.columbia.psl.cc.pojo;
public class MultiNewArrayNode extends InstNode{
private String desc;
private int dim;
public void setDesc(String desc) {
this.desc = desc;
}
public String getDesc() {
return this.desc;
}
public void setDim(int dim) {
this.dim = dim;
}
public int getDim() {
return this.dim;
}
}
| 13.269231 | 48 | 0.672464 |
348daa8e7777192571207133d72da3ca86c69a3f
| 4,673 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.management.vanilla.network.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.annotation.JsonFlatten;
import com.azure.core.management.Resource;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** The ServiceEndpointPolicy model. */
@JsonFlatten
@Fluent
public class ServiceEndpointPolicy extends Resource {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ServiceEndpointPolicy.class);
/*
* A unique read-only string that changes whenever the resource is updated.
*/
@JsonProperty(value = "etag", access = JsonProperty.Access.WRITE_ONLY)
private String etag;
/*
* A collection of service endpoint policy definitions of the service
* endpoint policy.
*/
@JsonProperty(value = "properties.serviceEndpointPolicyDefinitions")
private List<ServiceEndpointPolicyDefinition> serviceEndpointPolicyDefinitions;
/*
* A collection of references to subnets.
*/
@JsonProperty(value = "properties.subnets", access = JsonProperty.Access.WRITE_ONLY)
private List<Subnet> subnets;
/*
* The resource GUID property of the service endpoint policy resource.
*/
@JsonProperty(value = "properties.resourceGuid", access = JsonProperty.Access.WRITE_ONLY)
private String resourceGuid;
/*
* The provisioning state of the service endpoint policy resource.
*/
@JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY)
private ProvisioningState provisioningState;
/*
* Resource ID.
*/
@JsonProperty(value = "id")
private String id;
/**
* Get the etag property: A unique read-only string that changes whenever the resource is updated.
*
* @return the etag value.
*/
public String getEtag() {
return this.etag;
}
/**
* Get the serviceEndpointPolicyDefinitions property: A collection of service endpoint policy definitions of the
* service endpoint policy.
*
* @return the serviceEndpointPolicyDefinitions value.
*/
public List<ServiceEndpointPolicyDefinition> getServiceEndpointPolicyDefinitions() {
return this.serviceEndpointPolicyDefinitions;
}
/**
* Set the serviceEndpointPolicyDefinitions property: A collection of service endpoint policy definitions of the
* service endpoint policy.
*
* @param serviceEndpointPolicyDefinitions the serviceEndpointPolicyDefinitions value to set.
* @return the ServiceEndpointPolicy object itself.
*/
public ServiceEndpointPolicy setServiceEndpointPolicyDefinitions(
List<ServiceEndpointPolicyDefinition> serviceEndpointPolicyDefinitions) {
this.serviceEndpointPolicyDefinitions = serviceEndpointPolicyDefinitions;
return this;
}
/**
* Get the subnets property: A collection of references to subnets.
*
* @return the subnets value.
*/
public List<Subnet> getSubnets() {
return this.subnets;
}
/**
* Get the resourceGuid property: The resource GUID property of the service endpoint policy resource.
*
* @return the resourceGuid value.
*/
public String getResourceGuid() {
return this.resourceGuid;
}
/**
* Get the provisioningState property: The provisioning state of the service endpoint policy resource.
*
* @return the provisioningState value.
*/
public ProvisioningState getProvisioningState() {
return this.provisioningState;
}
/**
* Get the id property: Resource ID.
*
* @return the id value.
*/
public String getId() {
return this.id;
}
/**
* Set the id property: Resource ID.
*
* @param id the id value to set.
* @return the ServiceEndpointPolicy object itself.
*/
public ServiceEndpointPolicy setId(String id) {
this.id = id;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (getServiceEndpointPolicyDefinitions() != null) {
getServiceEndpointPolicyDefinitions().forEach(e -> e.validate());
}
if (getSubnets() != null) {
getSubnets().forEach(e -> e.validate());
}
}
}
| 30.94702 | 116 | 0.684999 |
b521de1420a0aea7a5c310b58d025b19e13d7f3d
| 497 |
package com.atguigu.gmall.pms.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;
import com.atguigu.gmall.pms.entity.SpuDescEntity;
import java.util.Map;
/**
* spu信息介绍
*
* @author daruange
* @email daruange@atguigu.com
* @date 2021-01-18 19:14:24
*/
public interface SpuDescService extends IService<SpuDescEntity> {
PageResultVo queryPage(PageParamVo paramVo);
}
| 22.590909 | 65 | 0.778672 |
5547a910b3928726f2e2ba315cb88da72e85dbf3
| 41,878 |
/*******************************************************************************
* Copyright 2012 Geoscience Australia
*
* 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 au.gov.ga.earthsci.worldwind.common.layers.volume;
import gov.nasa.worldwind.View;
import gov.nasa.worldwind.WorldWindow;
import gov.nasa.worldwind.avlist.AVKey;
import gov.nasa.worldwind.avlist.AVList;
import gov.nasa.worldwind.event.SelectEvent;
import gov.nasa.worldwind.event.SelectListener;
import gov.nasa.worldwind.geom.Angle;
import gov.nasa.worldwind.geom.Extent;
import gov.nasa.worldwind.geom.Intersection;
import gov.nasa.worldwind.geom.LatLon;
import gov.nasa.worldwind.geom.Line;
import gov.nasa.worldwind.geom.Matrix;
import gov.nasa.worldwind.geom.Plane;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.geom.Vec4;
import gov.nasa.worldwind.globes.Globe;
import gov.nasa.worldwind.layers.AbstractLayer;
import gov.nasa.worldwind.render.DrawContext;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Comparator;
import javax.media.opengl.GL2;
import org.gdal.osr.CoordinateTransformation;
import au.gov.ga.earthsci.worldwind.common.WorldWindowRegistry;
import au.gov.ga.earthsci.worldwind.common.layers.Bounds;
import au.gov.ga.earthsci.worldwind.common.layers.Wireframeable;
import au.gov.ga.earthsci.worldwind.common.render.fastshape.FastShape;
import au.gov.ga.earthsci.worldwind.common.render.fastshape.FastShapeRenderListener;
import au.gov.ga.earthsci.worldwind.common.util.AVKeyMore;
import au.gov.ga.earthsci.worldwind.common.util.ColorMap;
import au.gov.ga.earthsci.worldwind.common.util.CoordinateTransformationUtil;
import au.gov.ga.earthsci.worldwind.common.util.GeometryUtil;
import au.gov.ga.earthsci.worldwind.common.util.Util;
import au.gov.ga.earthsci.worldwind.common.util.Validate;
import com.jogamp.opengl.util.awt.TextureRenderer;
/**
* Basic implementation of the {@link VolumeLayer} interface.
*
* @author Michael de Hoog (michael.dehoog@ga.gov.au)
*/
public class BasicVolumeLayer extends AbstractLayer implements VolumeLayer, Wireframeable, SelectListener,
FastShapeRenderListener
{
protected URL context;
protected String url;
protected String dataCacheName;
protected VolumeDataProvider dataProvider;
protected Double minimumDistance;
protected double maxVariance = 0;
protected CoordinateTransformation coordinateTransformation;
protected String paintedVariable;
protected ColorMap colorMap;
protected Color noDataColor;
protected boolean reverseNormals = false;
protected boolean useOrderedRendering = false;
protected final Object dataLock = new Object();
protected boolean dataAvailable = false;
protected FastShape topSurface, bottomSurface;
protected TopBottomFastShape minXCurtain, maxXCurtain, minYCurtain, maxYCurtain;
protected FastShape boundingBoxShape;
protected TextureRenderer topTexture, bottomTexture, minXTexture, maxXTexture, minYTexture, maxYTexture;
protected int topOffset = 0, bottomOffset = 0, minXOffset = 0, maxXOffset = 0, minYOffset = 0, maxYOffset = 0;
protected int lastTopOffset = -1, lastBottomOffset = -1, lastMinXOffset = -1, lastMaxXOffset = -1,
lastMinYOffset = -1, lastMaxYOffset = -1;
protected double lastVerticalExaggeration = -Double.MAX_VALUE;
protected final double[] curtainTextureMatrix = new double[] { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
protected boolean minXClipDirty = false, maxXClipDirty = false, minYClipDirty = false, maxYClipDirty = false,
topClipDirty = false, bottomClipDirty = false;
protected final double[] topClippingPlanes = new double[4 * 4];
protected final double[] bottomClippingPlanes = new double[4 * 4];
protected final double[] curtainClippingPlanes = new double[4 * 4];
protected boolean wireframe = false;
protected boolean dragging = false;
protected Position dragStartPosition;
protected int dragStartSlice;
protected Vec4 dragStartCenter;
/**
* Create a new {@link BasicVolumeLayer}, using the provided layer params.
*
* @param params
*/
public BasicVolumeLayer(AVList params)
{
context = (URL) params.getValue(AVKeyMore.CONTEXT_URL);
url = params.getStringValue(AVKey.URL);
dataCacheName = params.getStringValue(AVKey.DATA_CACHE_NAME);
dataProvider = (VolumeDataProvider) params.getValue(AVKeyMore.DATA_LAYER_PROVIDER);
minimumDistance = (Double) params.getValue(AVKeyMore.MINIMUM_DISTANCE);
colorMap = (ColorMap) params.getValue(AVKeyMore.COLOR_MAP);
noDataColor = (Color) params.getValue(AVKeyMore.NO_DATA_COLOR);
Double d = (Double) params.getValue(AVKeyMore.MAX_VARIANCE);
if (d != null)
{
maxVariance = d;
}
String s = (String) params.getValue(AVKey.COORDINATE_SYSTEM);
if (s != null)
{
coordinateTransformation = CoordinateTransformationUtil.getTransformationToWGS84(s);
}
s = (String) params.getValue(AVKeyMore.PAINTED_VARIABLE);
if (s != null)
{
paintedVariable = s;
}
Integer i = (Integer) params.getValue(AVKeyMore.INITIAL_OFFSET_MIN_U);
if (i != null)
{
minXOffset = i;
}
i = (Integer) params.getValue(AVKeyMore.INITIAL_OFFSET_MAX_U);
if (i != null)
{
maxXOffset = i;
}
i = (Integer) params.getValue(AVKeyMore.INITIAL_OFFSET_MIN_V);
if (i != null)
{
minYOffset = i;
}
i = (Integer) params.getValue(AVKeyMore.INITIAL_OFFSET_MAX_V);
if (i != null)
{
maxYOffset = i;
}
i = (Integer) params.getValue(AVKeyMore.INITIAL_OFFSET_MIN_W);
if (i != null)
{
topOffset = i;
}
i = (Integer) params.getValue(AVKeyMore.INITIAL_OFFSET_MAX_W);
if (i != null)
{
bottomOffset = i;
}
Boolean b = (Boolean) params.getValue(AVKeyMore.REVERSE_NORMALS);
if (b != null)
{
reverseNormals = b;
}
b = (Boolean) params.getValue(AVKeyMore.ORDERED_RENDERING);
if (b != null)
{
useOrderedRendering = b;
}
Validate.notBlank(url, "Model data url not set");
Validate.notBlank(dataCacheName, "Model data cache name not set");
Validate.notNull(dataProvider, "Model data provider is null");
WorldWindowRegistry.INSTANCE.addSelectListener(this);
}
@Override
public URL getUrl() throws MalformedURLException
{
return new URL(context, url);
}
@Override
public String getDataCacheName()
{
return dataCacheName;
}
@Override
public boolean isLoading()
{
return dataProvider.isLoading();
}
@Override
public void addLoadingListener(LoadingListener listener)
{
dataProvider.addLoadingListener(listener);
}
@Override
public void removeLoadingListener(LoadingListener listener)
{
dataProvider.removeLoadingListener(listener);
}
@Override
public Bounds getBounds()
{
return dataProvider.getBounds();
}
@Override
public boolean isFollowTerrain()
{
return false;
}
@Override
public void dataAvailable(VolumeDataProvider provider)
{
calculateSurfaces();
dataAvailable = true;
}
/**
* Calculate the 4 curtain and 2 horizontal surfaces used to render this
* volume. Should be called once after the {@link VolumeDataProvider}
* notifies this layer that the data is available.
*/
protected void calculateSurfaces()
{
double topElevation = 0;
double bottomElevation = -dataProvider.getDepth();
minXCurtain = dataProvider.createXCurtain(0);
minXCurtain.addRenderListener(this);
minXCurtain.setLighted(true);
minXCurtain.setCalculateNormals(true);
minXCurtain.setReverseNormals(reverseNormals);
minXCurtain.setTopElevationOffset(topElevation);
minXCurtain.setBottomElevationOffset(bottomElevation);
minXCurtain.setTextureMatrix(curtainTextureMatrix);
minXCurtain.setUseOrderedRendering(useOrderedRendering);
maxXCurtain = dataProvider.createXCurtain(dataProvider.getXSize() - 1);
maxXCurtain.addRenderListener(this);
maxXCurtain.setLighted(true);
maxXCurtain.setCalculateNormals(true);
maxXCurtain.setReverseNormals(!reverseNormals);
maxXCurtain.setTopElevationOffset(topElevation);
maxXCurtain.setBottomElevationOffset(bottomElevation);
maxXCurtain.setTextureMatrix(curtainTextureMatrix);
maxXCurtain.setUseOrderedRendering(useOrderedRendering);
minYCurtain = dataProvider.createYCurtain(0);
minYCurtain.addRenderListener(this);
minYCurtain.setLighted(true);
minYCurtain.setCalculateNormals(true);
minYCurtain.setReverseNormals(!reverseNormals);
minYCurtain.setTopElevationOffset(topElevation);
minYCurtain.setBottomElevationOffset(bottomElevation);
minYCurtain.setTextureMatrix(curtainTextureMatrix);
minYCurtain.setUseOrderedRendering(useOrderedRendering);
maxYCurtain = dataProvider.createYCurtain(dataProvider.getYSize() - 1);
maxYCurtain.addRenderListener(this);
maxYCurtain.setLighted(true);
maxYCurtain.setCalculateNormals(true);
maxYCurtain.setReverseNormals(reverseNormals);
maxYCurtain.setTopElevationOffset(topElevation);
maxYCurtain.setBottomElevationOffset(bottomElevation);
maxYCurtain.setTextureMatrix(curtainTextureMatrix);
maxYCurtain.setUseOrderedRendering(useOrderedRendering);
Rectangle rectangle = new Rectangle(0, 0, dataProvider.getXSize(), dataProvider.getYSize());
topSurface = dataProvider.createHorizontalSurface((float) maxVariance, rectangle);
topSurface.addRenderListener(this);
topSurface.setLighted(true);
topSurface.setCalculateNormals(true);
topSurface.setReverseNormals(reverseNormals);
topSurface.setElevation(topElevation);
topSurface.setUseOrderedRendering(useOrderedRendering);
bottomSurface = dataProvider.createHorizontalSurface((float) maxVariance, rectangle);
bottomSurface.addRenderListener(this);
bottomSurface.setLighted(true);
bottomSurface.setCalculateNormals(true);
bottomSurface.setReverseNormals(!reverseNormals);
bottomSurface.setElevation(bottomElevation);
bottomSurface.setUseOrderedRendering(useOrderedRendering);
//update each shape's wireframe property so they match the layer's
setWireframe(isWireframe());
}
/**
* Recalculate any surfaces that require recalculation. This includes
* regenerating textures when the user has dragged a surface to a different
* slice.
*/
protected void recalculateSurfaces()
{
if (!dataAvailable)
{
return;
}
int xSize = dataProvider.getXSize();
int ySize = dataProvider.getYSize();
int zSize = dataProvider.getZSize();
//ensure the min/max offsets don't overlap one-another
minXOffset = Util.clamp(minXOffset, 0, xSize - 1);
maxXOffset = Util.clamp(maxXOffset, 0, xSize - 1 - minXOffset);
minYOffset = Util.clamp(minYOffset, 0, ySize - 1);
maxYOffset = Util.clamp(maxYOffset, 0, ySize - 1 - minYOffset);
topOffset = Util.clamp(topOffset, 0, zSize - 1);
bottomOffset = Util.clamp(bottomOffset, 0, zSize - 1 - topOffset);
int maxXSlice = xSize - 1 - maxXOffset;
int maxYSlice = ySize - 1 - maxYOffset;
int bottomSlice = zSize - 1 - bottomOffset;
//only recalculate those that have changed
boolean recalculateMinX = lastMinXOffset != minXOffset;
boolean recalculateMaxX = lastMaxXOffset != maxXOffset;
boolean recalculateMinY = lastMinYOffset != minYOffset;
boolean recalculateMaxY = lastMaxYOffset != maxYOffset;
boolean recalculateTop = lastTopOffset != topOffset;
boolean recalculateBottom = lastBottomOffset != bottomOffset;
Dimension xTextureSize = new Dimension(ySize, zSize);
Dimension yTextureSize = new Dimension(xSize, zSize);
Dimension zTextureSize = new Dimension(xSize, ySize);
double topPercent = dataProvider.getSliceElevationPercent(topOffset);
double bottomPercent = dataProvider.getSliceElevationPercent(bottomSlice);
if (recalculateMinX)
{
minXClipDirty = true;
TopBottomFastShape newMinXCurtain = dataProvider.createXCurtain(minXOffset);
minXCurtain.setPositions(newMinXCurtain.getPositions());
updateTexture(generateTexture(0, minXOffset, xTextureSize), minXTexture, minXCurtain);
lastMinXOffset = minXOffset;
}
if (recalculateMaxX)
{
maxXClipDirty = true;
TopBottomFastShape newMaxXCurtain = dataProvider.createXCurtain(xSize - 1 - maxXOffset);
maxXCurtain.setPositions(newMaxXCurtain.getPositions());
updateTexture(generateTexture(0, maxXSlice, xTextureSize), maxXTexture, maxXCurtain);
lastMaxXOffset = maxXOffset;
}
if (recalculateMinY)
{
minYClipDirty = true;
TopBottomFastShape newMinYCurtain = dataProvider.createYCurtain(minYOffset);
minYCurtain.setPositions(newMinYCurtain.getPositions());
updateTexture(generateTexture(1, minYOffset, yTextureSize), minYTexture, minYCurtain);
lastMinYOffset = minYOffset;
}
if (recalculateMaxY)
{
maxYClipDirty = true;
TopBottomFastShape newMaxYCurtain = dataProvider.createYCurtain(ySize - 1 - maxYOffset);
maxYCurtain.setPositions(newMaxYCurtain.getPositions());
updateTexture(generateTexture(1, maxYSlice, yTextureSize), maxYTexture, maxYCurtain);
lastMaxYOffset = maxYOffset;
}
if (recalculateTop)
{
topClipDirty = true;
double elevation = -dataProvider.getDepth() * topPercent;
updateTexture(generateTexture(2, topOffset, zTextureSize), topTexture, topSurface);
lastTopOffset = topOffset;
topSurface.setElevation(elevation);
minXCurtain.setTopElevationOffset(elevation);
maxXCurtain.setTopElevationOffset(elevation);
minYCurtain.setTopElevationOffset(elevation);
maxYCurtain.setTopElevationOffset(elevation);
recalculateTextureMatrix(topPercent, bottomPercent);
}
if (recalculateBottom)
{
bottomClipDirty = true;
double elevation = -dataProvider.getDepth() * bottomPercent;
updateTexture(generateTexture(2, bottomSlice, zTextureSize), bottomTexture, bottomSurface);
lastBottomOffset = bottomOffset;
bottomSurface.setElevation(elevation);
minXCurtain.setBottomElevationOffset(elevation);
maxXCurtain.setBottomElevationOffset(elevation);
minYCurtain.setBottomElevationOffset(elevation);
maxYCurtain.setBottomElevationOffset(elevation);
recalculateTextureMatrix(topPercent, bottomPercent);
}
}
/**
* Recalculate the curtain texture matrix. When the top and bottom surface
* offsets aren't 0, the OpenGL texture matrix is used to offset the curtain
* textures.
*
* @param topPercent
* Location of the top surface (normalized to 0..1)
* @param bottomPercent
* Location of the bottom surface (normalized to 0..1)
*/
protected void recalculateTextureMatrix(double topPercent, double bottomPercent)
{
Matrix m =
Matrix.fromTranslation(0, topPercent, 0).multiply(Matrix.fromScale(1, bottomPercent - topPercent, 1));
m.toArray(curtainTextureMatrix, 0, false);
}
/**
* Recalculate the clipping planes used to clip the surfaces when the user
* drags them.
*
* @param dc
*/
protected void recalculateClippingPlanes(DrawContext dc)
{
if (!dataAvailable || dataProvider.isSingleSliceVolume())
{
return;
}
boolean verticalExaggerationChanged = lastVerticalExaggeration != dc.getVerticalExaggeration();
lastVerticalExaggeration = dc.getVerticalExaggeration();
boolean minX = minXClipDirty || verticalExaggerationChanged;
boolean maxX = maxXClipDirty || verticalExaggerationChanged;
boolean minY = minYClipDirty || verticalExaggerationChanged;
boolean maxY = maxYClipDirty || verticalExaggerationChanged;
boolean sw = minX || minY;
boolean nw = minX || maxY;
boolean se = maxX || minY;
boolean ne = maxX || maxY;
minX |= topClipDirty || bottomClipDirty;
maxX |= topClipDirty || bottomClipDirty;
minY |= topClipDirty || bottomClipDirty;
maxY |= topClipDirty || bottomClipDirty;
if (!(minX || maxX || minY || maxY))
{
return;
}
int maxXSlice = dataProvider.getXSize() - 1 - maxXOffset;
int maxYSlice = dataProvider.getYSize() - 1 - maxYOffset;
int bottomSlice = dataProvider.getZSize() - 1 - bottomOffset;
double top = dataProvider.getTop();
double depth = dataProvider.getDepth();
double topPercent = dataProvider.getSliceElevationPercent(topOffset);
double bottomPercent = dataProvider.getSliceElevationPercent(bottomSlice);
double topElevation = top - topPercent * depth;
double bottomElevation = top - bottomPercent * depth;
Position swPosTop = dataProvider.getPosition(minXOffset, minYOffset);
Position nwPosTop = dataProvider.getPosition(minXOffset, maxYSlice);
Position sePosTop = dataProvider.getPosition(maxXSlice, minYOffset);
Position nePosTop = dataProvider.getPosition(maxXSlice, maxYSlice);
if (depth != 0 && dc.getVerticalExaggeration() > 0)
{
Position origin = dataProvider.getPosition(0, 0);
Position originPlusOne = dataProvider.getPosition(1, 1);
Angle azimuth = LatLon.linearAzimuth(originPlusOne, origin);
double delta = 0.005;
double sin = azimuth.sin() * delta;
double cos = azimuth.cos() * delta;
if (se)
{
Position sePosBottom = new Position(sePosTop, sePosTop.elevation - depth);
Position otherPos = sePosTop.add(Position.fromDegrees(cos, sin, 0));
insertClippingPlaneForPositions(dc, curtainClippingPlanes, 8, sePosTop, otherPos, sePosBottom);
}
if (ne)
{
Position nePosBottom = new Position(nePosTop, nePosTop.elevation - depth);
Position otherPos = nePosTop.add(Position.fromDegrees(-sin, cos, 0));
insertClippingPlaneForPositions(dc, curtainClippingPlanes, 12, nePosTop, nePosBottom, otherPos);
}
if (nw)
{
Position nwPosBottom = new Position(nwPosTop, nwPosTop.elevation - depth);
Position otherPos = nwPosTop.add(Position.fromDegrees(-cos, -sin, 0));
insertClippingPlaneForPositions(dc, curtainClippingPlanes, 4, nwPosTop, otherPos, nwPosBottom);
}
if (sw)
{
Position swPosBottom = new Position(swPosTop, swPosTop.elevation - depth);
Position otherPos = swPosTop.add(Position.fromDegrees(sin, -cos, 0));
insertClippingPlaneForPositions(dc, curtainClippingPlanes, 0, swPosTop, swPosBottom, otherPos);
}
}
//the following only works for a spherical earth (as opposed to flat earth), as it relies on adjacent
//points not being colinear (3 points along a latitude are not colinear when wrapped around a sphere)
if (minX)
{
Position middlePos = dataProvider.getPosition(minXOffset, (maxYSlice + minYOffset) / 2);
middlePos = midpointPositionIfEqual(middlePos, nwPosTop, swPosTop);
insertClippingPlaneForLatLons(dc, topClippingPlanes, 0, middlePos, nwPosTop, swPosTop, topElevation);
insertClippingPlaneForLatLons(dc, bottomClippingPlanes, 0, middlePos, nwPosTop, swPosTop, bottomElevation);
}
if (maxX)
{
Position middlePos = dataProvider.getPosition(maxXSlice, (maxYSlice + minYOffset) / 2);
middlePos = midpointPositionIfEqual(middlePos, sePosTop, nePosTop);
insertClippingPlaneForLatLons(dc, topClippingPlanes, 4, middlePos, sePosTop, nePosTop, topElevation);
insertClippingPlaneForLatLons(dc, bottomClippingPlanes, 4, middlePos, sePosTop, nePosTop, bottomElevation);
}
if (minY)
{
Position middlePos = dataProvider.getPosition((maxXSlice + minXOffset) / 2, minYOffset);
middlePos = midpointPositionIfEqual(middlePos, swPosTop, sePosTop);
insertClippingPlaneForLatLons(dc, topClippingPlanes, 8, middlePos, swPosTop, sePosTop, topElevation);
insertClippingPlaneForLatLons(dc, bottomClippingPlanes, 8, middlePos, swPosTop, sePosTop, bottomElevation);
}
if (maxY)
{
Position middlePos = dataProvider.getPosition((maxXSlice + minXOffset) / 2, maxYSlice);
middlePos = midpointPositionIfEqual(middlePos, nePosTop, nwPosTop);
insertClippingPlaneForLatLons(dc, topClippingPlanes, 12, middlePos, nePosTop, nwPosTop, topElevation);
insertClippingPlaneForLatLons(dc, bottomClippingPlanes, 12, middlePos, nePosTop, nwPosTop, bottomElevation);
}
minXClipDirty = maxXClipDirty = minYClipDirty = maxYClipDirty = topClipDirty = bottomClipDirty = false;
}
/**
* Return the midpoint of the two end positions if the given middle position
* is equal to one of the ends.
*
* @param middle
* @param end1
* @param end2
* @return Midpoint between end1 and end2 if middle equals end1 or end2.
*/
protected Position midpointPositionIfEqual(Position middle, Position end1, Position end2)
{
if (middle.equals(end1) || middle.equals(end2))
{
return Position.interpolate(0.5, end1, end2);
}
return middle;
}
/**
* Insert a clipping plane vector into the given array. The vector is
* calculated by finding a plane that intersects the three given positions.
*
* @param dc
* @param clippingPlaneArray
* Array to insert clipping plane vector into
* @param arrayOffset
* Array start offset to begin inserting values at
* @param p1
* First position that the plane must intersect
* @param p2
* Second position that the plane must intersect
* @param p3
* Third position that the plane must intersect
*/
protected void insertClippingPlaneForPositions(DrawContext dc, double[] clippingPlaneArray, int arrayOffset,
Position p1, Position p2, Position p3)
{
Globe globe = dc.getGlobe();
Vec4 v1 = globe.computePointFromPosition(p1, p1.getElevation() * dc.getVerticalExaggeration());
Vec4 v2 = globe.computePointFromPosition(p2, p2.getElevation() * dc.getVerticalExaggeration());
Vec4 v3 = globe.computePointFromPosition(p3, p3.getElevation() * dc.getVerticalExaggeration());
insertClippingPlaneForPoints(clippingPlaneArray, arrayOffset, v1, v2, v3);
}
/**
* Insert a clipping plane vector into the given array. The vector is
* calculated by finding a plane that intersects the three given latlons at
* the given elevation.
*
* @param dc
* @param clippingPlaneArray
* Array to insert clipping plane vector into
* @param arrayOffset
* Array start offset to begin inserting values at
* @param l1
* First latlon that the plane must intersect
* @param l2
* Second latlon that the plane must intersect
* @param l3
* Third latlon that the plane must intersect
* @param elevation
* Elevation of the latlons
*/
protected void insertClippingPlaneForLatLons(DrawContext dc, double[] clippingPlaneArray, int arrayOffset,
LatLon l1, LatLon l2, LatLon l3, double elevation)
{
Globe globe = dc.getGlobe();
double exaggeratedElevation = elevation * dc.getVerticalExaggeration();
Vec4 v1 = globe.computePointFromPosition(l1, exaggeratedElevation);
Vec4 v2 = globe.computePointFromPosition(l2, exaggeratedElevation);
Vec4 v3 = globe.computePointFromPosition(l3, exaggeratedElevation);
insertClippingPlaneForPoints(clippingPlaneArray, arrayOffset, v1, v2, v3);
}
/**
* Insert a clipping plane vector into the given array. The vector is
* calculated by finding a plane that intersects the three given points.
*
* @param clippingPlaneArray
* Array to insert clipping plane vector into
* @param arrayOffset
* Array start offset to begin inserting values at
* @param v1
* First point that the plane must intersect
* @param v2
* Second point that the plane must intersect
* @param v3
* Third point that the plane must intersect
*/
protected void insertClippingPlaneForPoints(double[] clippingPlaneArray, int arrayOffset, Vec4 v1, Vec4 v2, Vec4 v3)
{
if (v1 == null || v2 == null || v3 == null || v1.equals(v2) || v1.equals(v3))
{
return;
}
Line l1 = Line.fromSegment(v1, v3);
Line l2 = Line.fromSegment(v1, v2);
Plane plane = GeometryUtil.createPlaneContainingLines(l1, l2);
Vec4 v = plane.getVector();
clippingPlaneArray[arrayOffset + 0] = v.x;
clippingPlaneArray[arrayOffset + 1] = v.y;
clippingPlaneArray[arrayOffset + 2] = v.z;
clippingPlaneArray[arrayOffset + 3] = v.w;
}
/**
* Generate a texture slice through the volume at the given position. Uses a
* {@link ColorMap} to map values to colors (or simply interpolates the hue
* if no colormap is provided - assumes values between 0 and 1).
*
* @param axis
* Slicing axis (0 for a longitude slice, 1 for a latitude slice,
* 2 for an elevation slice).
* @param position
* Longitude, latitude, or elevation at which to slice.
* @param size
* Size of the texture to generate.
* @return A {@link BufferedImage} containing a representation of the volume
* slice.
*/
protected BufferedImage generateTexture(int axis, int position, Dimension size)
{
int zSubsamples = dataProvider.getZSubsamples();
boolean subsample = axis != 2 && zSubsamples > 1;
int height = size.height;
if (subsample)
{
height *= zSubsamples;
}
BufferedImage image = new BufferedImage(size.width, height, BufferedImage.TYPE_INT_ARGB);
float minimum = dataProvider.getMinValue();
float maximum = dataProvider.getMaxValue();
for (int y = 0; y < height; y++)
{
for (int x = 0; x < size.width; x++)
{
int vx = axis == 2 ? x : axis == 1 ? x : position;
int vy = axis == 2 ? y : axis == 1 ? position : x;
int vz = axis == 2 ? position : y;
float value;
if (subsample)
{
double percent = y / (double) (height - 1);
double z = dataProvider.getElevationPercentSlice(percent);
int z1 = (int) Math.floor(z);
int z2 = (int) Math.ceil(z);
float value1 = dataProvider.getValue(vx, vy, z1);
float value2 = dataProvider.getValue(vx, vy, z2);
float zp = (float) (z % 1.0);
value = value1 * (1f - zp) + value2 * zp;
}
else
{
value = dataProvider.getValue(vx, vy, vz);
}
int rgb = noDataColor != null ? noDataColor.getRGB() : 0;
if (value != dataProvider.getNoDataValue())
{
if (colorMap != null)
{
rgb = colorMap.calculateColorNotingIsValuesPercentages(value, minimum, maximum).getRGB();
}
else
{
rgb = Color.HSBtoRGB(-0.3f - value * 0.7f, 1.0f, 1.0f);
}
}
image.setRGB(x, y, rgb);
}
}
return image;
}
/**
* Update the given {@link TextureRenderer} with the provided image, and
* sets the {@link FastShape}'s texture it.
*
* @param image
* Image to update texture with
* @param texture
* Texture to update
* @param shape
* Shape to set texture in
*/
protected void updateTexture(BufferedImage image, TextureRenderer texture, FastShape shape)
{
Graphics2D g = null;
try
{
g = (Graphics2D) texture.getImage().getGraphics();
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC));
g.drawImage(image, 0, 0, null);
}
finally
{
if (g != null)
{
g.dispose();
}
}
texture.markDirty(0, 0, texture.getWidth(), texture.getHeight());
shape.setTexture(texture.getTexture());
}
@Override
public CoordinateTransformation getCoordinateTransformation()
{
return coordinateTransformation;
}
@Override
public String getPaintedVariableName()
{
return paintedVariable;
}
@Override
protected void doPick(DrawContext dc, Point point)
{
if (!dataProvider.isSingleSliceVolume())
{
doRender(dc);
}
}
@Override
protected void doRender(DrawContext dc)
{
if (!isEnabled())
{
return;
}
dataProvider.requestData(this);
synchronized (dataLock)
{
if (!dataAvailable)
{
return;
}
if (topTexture == null)
{
topTexture = new TextureRenderer(dataProvider.getXSize(), dataProvider.getYSize(), true, true);
bottomTexture = new TextureRenderer(dataProvider.getXSize(), dataProvider.getYSize(), true, true);
minXTexture = new TextureRenderer(dataProvider.getYSize(),
dataProvider.getZSize() * dataProvider.getZSubsamples(), true, true);
maxXTexture = new TextureRenderer(dataProvider.getYSize(),
dataProvider.getZSize() * dataProvider.getZSubsamples(), true, true);
minYTexture = new TextureRenderer(dataProvider.getXSize(),
dataProvider.getZSize() * dataProvider.getZSubsamples(), true, true);
maxYTexture = new TextureRenderer(dataProvider.getXSize(),
dataProvider.getZSize() * dataProvider.getZSubsamples(), true, true);
}
//recalculate surfaces and clipping planes each frame (in case user drags one of the surfaces)
recalculateSurfaces();
recalculateClippingPlanes(dc);
//when only one slice is shown in any given direction, only one of the curtains needs to be rendered
boolean singleXSlice = dataProvider.getXSize() - minXOffset - maxXOffset <= 1;
boolean singleYSlice = dataProvider.getYSize() - minYOffset - maxYOffset <= 1;
boolean singleZSlice = dataProvider.getZSize() - topOffset - bottomOffset <= 1;
boolean anySingleSlice = singleXSlice || singleYSlice || singleZSlice;
FastShape[] shapes =
anySingleSlice ? new FastShape[] { singleXSlice ? maxXCurtain : singleYSlice ? minYCurtain
: topSurface } : new FastShape[] { topSurface, bottomSurface, minXCurtain, maxXCurtain,
minYCurtain, maxYCurtain };
//sort the shapes from back-to-front
if (!anySingleSlice)
{
Arrays.sort(shapes, new ShapeComparator(dc));
}
//test all the shapes with the minimum distance, culling them if they are outside
if (minimumDistance != null)
{
for (int i = 0; i < shapes.length; i++)
{
Extent extent = shapes[i].getExtent();
if (extent != null)
{
double distanceToEye =
extent.getCenter().distanceTo3(dc.getView().getEyePoint()) - extent.getRadius();
if (distanceToEye > minimumDistance)
{
shapes[i] = null;
}
}
}
}
//draw each shape
for (FastShape shape : shapes)
{
if (shape != null)
{
shape.setTwoSidedLighting(anySingleSlice);
if (dc.isPickingMode())
{
shape.pick(dc, dc.getPickPoint());
}
else
{
shape.render(dc);
}
}
}
if (dragging)
{
//render a bounding box around the data if the user is dragging a surface
renderBoundingBox(dc);
}
}
}
@Override
public void shapePreRender(DrawContext dc, FastShape shape)
{
//push the OpenGL clipping plane state on the attribute stack
dc.getGL().getGL2().glPushAttrib(GL2.GL_TRANSFORM_BIT);
setupClippingPlanes(dc, shape == topSurface, shape == bottomSurface);
}
@Override
public void shapePostRender(DrawContext dc, FastShape shape)
{
dc.getGL().getGL2().glPopAttrib();
}
protected void setupClippingPlanes(DrawContext dc, boolean top, boolean bottom)
{
boolean minX = minXOffset > 0;
boolean maxX = maxXOffset > 0;
boolean minY = minYOffset > 0;
boolean maxY = maxYOffset > 0;
boolean[] enabled;
double[] array;
GL2 gl = dc.getGL().getGL2();
if (top || bottom)
{
array = top ? topClippingPlanes : bottomClippingPlanes;
enabled = new boolean[] { minX, maxX, minY, maxY };
}
else
{
array = curtainClippingPlanes;
boolean sw = minX || minY;
boolean nw = minX || maxY;
boolean se = maxX || minY;
boolean ne = maxX || maxY;
enabled = new boolean[] { sw, nw, se, ne };
}
for (int i = 0; i < 4; i++)
{
gl.glClipPlane(GL2.GL_CLIP_PLANE0 + i, array, i * 4);
if (enabled[i])
{
gl.glEnable(GL2.GL_CLIP_PLANE0 + i);
}
else
{
gl.glDisable(GL2.GL_CLIP_PLANE0 + i);
}
}
}
/**
* Render a bounding box around the data. Used when dragging surfaces, so
* user has an idea of where the data extents lie when slicing.
*
* @param dc
*/
protected void renderBoundingBox(DrawContext dc)
{
if (boundingBoxShape == null)
{
boundingBoxShape = dataProvider.createBoundingBox();
}
boundingBoxShape.render(dc);
}
@Override
public boolean isWireframe()
{
return wireframe;
}
@Override
public void setWireframe(boolean wireframe)
{
this.wireframe = wireframe;
synchronized (dataLock)
{
if (topSurface != null)
{
topSurface.setWireframe(wireframe);
bottomSurface.setWireframe(wireframe);
minXCurtain.setWireframe(wireframe);
maxXCurtain.setWireframe(wireframe);
minYCurtain.setWireframe(wireframe);
maxYCurtain.setWireframe(wireframe);
}
}
}
@Override
public void selected(SelectEvent event)
{
//ignore this event if ctrl, alt, or shift are down
if (event.getMouseEvent() != null)
{
int onmask = MouseEvent.SHIFT_DOWN_MASK | MouseEvent.CTRL_DOWN_MASK | MouseEvent.ALT_DOWN_MASK;
if ((event.getMouseEvent().getModifiersEx() & onmask) != 0)
{
return;
}
}
//don't allow dragging if there's only one layer in any one direction
if (dataProvider.isSingleSliceVolume())
{
return;
}
//we only care about drag events
boolean drag = event.getEventAction().equals(SelectEvent.DRAG);
boolean dragEnd = event.getEventAction().equals(SelectEvent.DRAG_END);
if (!(drag || dragEnd))
{
return;
}
Object topObject = event.getTopObject();
FastShape pickedShape = topObject instanceof FastShape ? (FastShape) topObject : null;
if (pickedShape == null)
{
return;
}
boolean top = pickedShape == topSurface;
boolean bottom = pickedShape == bottomSurface;
boolean minX = pickedShape == minXCurtain;
boolean maxX = pickedShape == maxXCurtain;
boolean minY = pickedShape == minYCurtain;
boolean maxY = pickedShape == maxYCurtain;
if (top || bottom || minX || maxX || minY || maxY)
{
if (dragEnd)
{
dragging = false;
event.consume();
}
else if (drag)
{
if (!dragging || dragStartCenter == null)
{
Extent extent = pickedShape.getExtent();
if (extent != null)
{
dragStartCenter = extent.getCenter();
}
}
if (dragStartCenter != null)
{
WorldWindow wwd = WorldWindowRegistry.INSTANCE.getRendering();
if (wwd != null)
{
View view = wwd.getView();
if (top || bottom)
{
dragElevation(event.getPickPoint(), pickedShape, view);
}
else if (minX || maxX)
{
dragX(event.getPickPoint(), pickedShape, view);
}
else
{
dragY(event.getPickPoint(), pickedShape, view);
}
}
}
dragging = true;
event.consume();
}
}
}
/**
* Drag an elevation surface up and down.
*
* @param pickPoint
* Point at which the user is dragging the mouse.
* @param shape
* Shape to drag
*/
protected void dragElevation(Point pickPoint, FastShape shape, View view)
{
// Calculate the plane projected from screen y=pickPoint.y
Line screenLeftRay = view.computeRayFromScreenPoint(pickPoint.x - 100, pickPoint.y);
Line screenRightRay = view.computeRayFromScreenPoint(pickPoint.x + 100, pickPoint.y);
// As the two lines are very close to parallel, use an arbitrary line joining them rather than the two lines to avoid precision problems
Line joiner = Line.fromSegment(screenLeftRay.getPointAt(500), screenRightRay.getPointAt(500));
Plane screenPlane = GeometryUtil.createPlaneContainingLines(screenLeftRay, joiner);
if (screenPlane == null)
{
return;
}
// Calculate the origin-marker ray
Globe globe = view.getGlobe();
Line centreRay = Line.fromSegment(globe.getCenter(), dragStartCenter);
Vec4 intersection = screenPlane.intersect(centreRay);
if (intersection == null)
{
return;
}
Position intersectionPosition = globe.computePositionFromPoint(intersection);
if (!dragging)
{
dragStartPosition = intersectionPosition;
dragStartSlice = shape == topSurface ? topOffset : bottomOffset;
}
else
{
double deltaElevation =
(dragStartPosition.elevation - intersectionPosition.elevation)
/ (lastVerticalExaggeration == 0 ? 1 : lastVerticalExaggeration);
double deltaPercentage = deltaElevation / dataProvider.getDepth();
int sliceMovement = (int) (deltaPercentage * (dataProvider.getZSize() - 1));
if (shape == topSurface)
{
topOffset = Util.clamp(dragStartSlice + sliceMovement, 0, dataProvider.getZSize() - 1);
bottomOffset = Util.clamp(bottomOffset, 0, dataProvider.getZSize() - 1 - topOffset);
}
else
{
bottomOffset = Util.clamp(dragStartSlice - sliceMovement, 0, dataProvider.getZSize() - 1);
topOffset = Util.clamp(topOffset, 0, dataProvider.getZSize() - 1 - bottomOffset);
}
}
}
/**
* Drag a X curtain left and right.
*
* @param pickPoint
* Point at which the user is dragging the mouse.
* @param shape
* Shape to drag
*/
protected void dragX(Point pickPoint, FastShape shape, View view)
{
Globe globe = view.getGlobe();
double centerElevation = globe.computePositionFromPoint(dragStartCenter).elevation;
// Compute the ray from the screen point
Line ray = view.computeRayFromScreenPoint(pickPoint.x, pickPoint.y);
Intersection[] intersections = globe.intersect(ray, centerElevation);
if (intersections == null || intersections.length == 0)
{
return;
}
Vec4 intersection = ray.nearestIntersectionPoint(intersections);
if (intersection == null)
{
return;
}
Position position = globe.computePositionFromPoint(intersection);
if (!dragging)
{
dragStartPosition = position;
dragStartSlice = shape == minXCurtain ? minXOffset : maxXOffset;
}
else
{
Position p0 = dataProvider.getPosition(0, dataProvider.getYSize() / 2);
Position p1 = dataProvider.getPosition(dataProvider.getXSize() - 1, dataProvider.getYSize() / 2);
Angle volumeAzimuth = LatLon.linearAzimuth(p0, p1);
Angle volumeDistance = LatLon.linearDistance(p0, p1);
Angle movementAzimuth = LatLon.linearAzimuth(position, dragStartPosition);
Angle movementDistance = LatLon.linearDistance(position, dragStartPosition);
Angle deltaAngle = volumeAzimuth.subtract(movementAzimuth);
double delta = movementDistance.degrees * deltaAngle.cos();
double deltaPercentage = delta / volumeDistance.degrees;
int sliceMovement = (int) (-deltaPercentage * (dataProvider.getXSize() - 1));
if (shape == minXCurtain)
{
minXOffset = Util.clamp(dragStartSlice + sliceMovement, 0, dataProvider.getXSize() - 1);
maxXOffset = Util.clamp(maxXOffset, 0, dataProvider.getXSize() - 1 - minXOffset);
}
else
{
maxXOffset = Util.clamp(dragStartSlice - sliceMovement, 0, dataProvider.getXSize() - 1);
minXOffset = Util.clamp(minXOffset, 0, dataProvider.getXSize() - 1 - maxXOffset);
}
}
}
/**
* Drag a Y curtain left and right.
*
* @param pickPoint
* Point at which the user is dragging the mouse.
* @param shape
* Shape to drag
*/
protected void dragY(Point pickPoint, FastShape shape, View view)
{
Globe globe = view.getGlobe();
double centerElevation = globe.computePositionFromPoint(dragStartCenter).elevation;
// Compute the ray from the screen point
Line ray = view.computeRayFromScreenPoint(pickPoint.x, pickPoint.y);
Intersection[] intersections = globe.intersect(ray, centerElevation);
if (intersections == null || intersections.length == 0)
{
return;
}
Vec4 intersection = ray.nearestIntersectionPoint(intersections);
if (intersection == null)
{
return;
}
Position position = globe.computePositionFromPoint(intersection);
if (!dragging)
{
dragStartPosition = position;
dragStartSlice = shape == minYCurtain ? minYOffset : maxYOffset;
}
else
{
Position p0 = dataProvider.getPosition(dataProvider.getXSize() / 2, 0);
Position p1 = dataProvider.getPosition(dataProvider.getXSize() / 2, dataProvider.getYSize() - 1);
Angle volumeAzimuth = LatLon.linearAzimuth(p0, p1);
Angle volumeDistance = LatLon.linearDistance(p0, p1);
Angle movementAzimuth = LatLon.linearAzimuth(position, dragStartPosition);
Angle movementDistance = LatLon.linearDistance(position, dragStartPosition);
Angle deltaAngle = volumeAzimuth.subtract(movementAzimuth);
double delta = movementDistance.degrees * deltaAngle.cos();
double deltaPercentage = delta / volumeDistance.degrees;
int sliceMovement = (int) (-deltaPercentage * (dataProvider.getYSize() - 1));
if (shape == minYCurtain)
{
minYOffset = Util.clamp(dragStartSlice + sliceMovement, 0, dataProvider.getYSize() - 1);
maxYOffset = Util.clamp(maxYOffset, 0, dataProvider.getYSize() - 1 - minYOffset);
}
else
{
maxYOffset = Util.clamp(dragStartSlice - sliceMovement, 0, dataProvider.getYSize() - 1);
minYOffset = Util.clamp(minYOffset, 0, dataProvider.getYSize() - 1 - maxYOffset);
}
}
}
/**
* {@link Comparator} used to sort {@link FastShape}s from back-to-front
* (from the view eye point).
*/
protected class ShapeComparator implements Comparator<FastShape>
{
private final DrawContext dc;
public ShapeComparator(DrawContext dc)
{
this.dc = dc;
}
@Override
public int compare(FastShape o1, FastShape o2)
{
if (o1 == o2)
{
return 0;
}
if (o2 == null)
{
return -1;
}
if (o1 == null)
{
return 1;
}
Extent e1 = o1.getExtent();
Extent e2 = o2.getExtent();
if (e2 == null)
{
return -1;
}
if (e1 == null)
{
return 1;
}
Vec4 eyePoint = dc.getView().getEyePoint();
double d1 = e1.getCenter().distanceToSquared3(eyePoint);
double d2 = e2.getCenter().distanceToSquared3(eyePoint);
return -Double.compare(d1, d2);
}
}
}
| 32.43842 | 138 | 0.716152 |
89c368d54043ad57fc9e3aaee10e31c03c827ab6
| 1,393 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: security.proto
package trinsic.okapi.security;
public interface CreateOberonTokenRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:okapi.security.CreateOberonTokenRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* raw BLS key bytes
* </pre>
*
* <code>bytes sk = 1;</code>
* @return The sk.
*/
com.google.protobuf.ByteString getSk();
/**
* <pre>
* data is the public part of the oberon protocol and can be any data
* </pre>
*
* <code>bytes data = 2;</code>
* @return The data.
*/
com.google.protobuf.ByteString getData();
/**
* <pre>
* optional blinding for the token
* </pre>
*
* <code>repeated bytes blinding = 3;</code>
* @return A list containing the blinding.
*/
java.util.List<com.google.protobuf.ByteString> getBlindingList();
/**
* <pre>
* optional blinding for the token
* </pre>
*
* <code>repeated bytes blinding = 3;</code>
* @return The count of blinding.
*/
int getBlindingCount();
/**
* <pre>
* optional blinding for the token
* </pre>
*
* <code>repeated bytes blinding = 3;</code>
* @param index The index of the element to return.
* @return The blinding at the given index.
*/
com.google.protobuf.ByteString getBlinding(int index);
}
| 23.610169 | 90 | 0.640345 |
dac52332700931dcfb6de6f13a8eac23434f7608
| 562 |
package com.leeup.javase.day24.threadMethod;
public class Demo2_CurrentThread {
public static void main(String[] args) {
new Thread() {
public void run() {
System.out.println(this.getName()+"////aaaa");
}
}.start();;
new Thread(
new Runnable() {
@Override
public void run() {
//获取当前正在执行的线然后再拿到名字
System.out.println(Thread.currentThread().getName()+"////bbbb");
}
}).start();;
Thread.currentThread().setName("我是主线程");
//卸载主线程中,意味着获取主线程的名字
System.out.println(Thread.currentThread().getName());
}
}
| 20.071429 | 69 | 0.631673 |
fc9b6d39af044ad6b243301e7eb1c4ef17a46a6e
| 583 |
package org.min.watergap.common.thread;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 线程工厂
*
* @Create by metaX.h on 2022/3/13 11:28
*/
public class CustomThreadFactory implements ThreadFactory {
private String groupName;
private AtomicInteger nextId = new AtomicInteger(1);
public CustomThreadFactory(String prefixName) {
this.groupName = prefixName + "_thread_";
}
@Override
public Thread newThread(Runnable r) {
return new Thread(groupName + nextId.incrementAndGet());
}
}
| 22.423077 | 64 | 0.715266 |
5d6125b3eff61cca0af44aae19f39e33392147bd
| 2,321 |
/*
* Copyright 2016 Goldman Sachs.
*
* 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.gs.dmn.runtime;
public class Range {
private final boolean startIncluded;
private final Object start;
private final boolean endIncluded;
private final Object end;
public Range(boolean startIncluded, Object start, boolean endIncluded, Object end) {
this.startIncluded = startIncluded;
this.start = start;
this.endIncluded = endIncluded;
this.end = end;
}
public boolean isStartIncluded() {
return startIncluded;
}
public Object getStart() {
return start;
}
public boolean isEndIncluded() {
return endIncluded;
}
public Object getEnd() {
return end;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Range range = (Range) o;
if (this.startIncluded != range.startIncluded) return false;
if (this.endIncluded != range.endIncluded) return false;
if (this.start != null ? !this.start.equals(range.start) : range.start != null) return false;
return this.end != null ? this.end.equals(range.end) : range.end == null;
}
@Override
public int hashCode() {
int result = (this.startIncluded ? 1 : 0);
result = 31 * result + (this.start != null ? this.start.hashCode() : 0);
result = 31 * result + (this.endIncluded ? 1 : 0);
result = 31 * result + (this.end != null ? this.end.hashCode() : 0);
return result;
}
@Override
public String toString() {
return String.format("Range(%s,%s,%s,%s)", this.startIncluded, this.start.toString(), this.end.toString(), this.endIncluded);
}
}
| 32.690141 | 133 | 0.642826 |
fa94c7841c3674b56cc78368f89af1da233cb07a
| 1,468 |
package com.seedfinding.mcfeature.loot;
import com.seedfinding.mccore.version.MCVersion;
import com.seedfinding.mcfeature.loot.function.LootFunction;
import com.seedfinding.mcfeature.loot.item.ItemStack;
import java.util.Collection;
import java.util.function.Consumer;
import java.util.function.Function;
public abstract class LootGenerator {
public Function<MCVersion, LootFunction>[] supplierLootFunctions = null;
public LootFunction[] lootFunctions;
public LootFunction combinedLootFunction;
public LootGenerator() {
this.apply((Collection<Function<MCVersion, LootFunction>>)null);
}
@SuppressWarnings("unchecked")
public LootGenerator apply(Collection<Function<MCVersion, LootFunction>> lootFunctions) {
if(lootFunctions != null) {
this.supplierLootFunctions = lootFunctions.toArray(new Function[0]);
} else {
this.lootFunctions = new LootFunction[0];
this.combinedLootFunction = (baseStack, context) -> baseStack;
}
return this;
}
public LootGenerator apply(MCVersion version) {
if(supplierLootFunctions != null) {
this.lootFunctions = new LootFunction[supplierLootFunctions.length];
int i = 0;
for(Function<MCVersion, LootFunction> function : supplierLootFunctions) {
this.lootFunctions[i++] = function.apply(version);
}
this.combinedLootFunction = LootFunction.combine(this.lootFunctions);
}
return this;
}
public abstract void generate(LootContext context, Consumer<ItemStack> stackConsumer);
}
| 30.583333 | 90 | 0.775204 |
cfcd710eb38ce89076f305ad3da84b128100a1c3
| 6,883 |
/*
*A simple GUI for the Ski score Calculator
*that was built for EOX. It provides a graphical
*way of selecting input files and
* some basic functionality buttons
*
* @author Konstantinos Peratinos
*/
package Ski;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.PrintStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
public class skiGui
extends JFrame {
private JButton Calculate;
private JButton browse;
private JFileChooser jFileChooser1;
private JLabel jLabel1;
private JLabel jLabel2;
private JLabel jLabel3;
private JTextField path;
private JTextField path1;
public skiGui() {
initComponents();
}
private void initComponents() {
this.jFileChooser1 = new JFileChooser();
this.path = new JTextField();
this.browse = new JButton();
this.jLabel1 = new JLabel();
this.jLabel2 = new JLabel();
this.path1 = new JTextField();
this.Calculate = new JButton();
this.jLabel3 = new JLabel();
this.jFileChooser1.setDialogTitle("Θέση Αρχείου");
this.jFileChooser1.setFileFilter(new xlsFilter());
setDefaultCloseOperation(3);
setTitle("Point Calculator");
this.path.setFont(new Font("Tahoma", 0, 10));
this.path.setText("C:\\");
this.path.setToolTipText("");
this.path.setEnabled(false);
this.path.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
skiGui.this.pathActionPerformed(evt);
}
});
this.browse.setFont(new Font("Tahoma", 1, 9));
this.browse.setText("Εξευρεύνησε");
this.browse.setToolTipText("");
this.browse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
skiGui.this.browseActionPerformed(evt);
}
});
this.jLabel1.setFont(new Font("Times New Roman", 1, 11));
this.jLabel1.setHorizontalAlignment(0);
this.jLabel1.setText("Διαδρομή Αρχείου");
this.jLabel2.setFont(new Font("Times New Roman", 1, 11));
this.jLabel2.setHorizontalAlignment(0);
this.jLabel2.setText("Νέο Αρχείο");
this.path1.setFont(new Font("Tahoma", 0, 10));
this.path1.setText("Αποτελέσματα");
this.path1.setToolTipText("");
this.path1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
skiGui.this.path1ActionPerformed(evt);
}
});
this.Calculate.setFont(new Font("Tahoma", 1, 11));
this.Calculate.setText("Υπολόγισε!");
this.Calculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
skiGui.this.CalculateActionPerformed(evt);
}
});
this.jLabel3.setFont(new Font("Tunga", 1, 11));
this.jLabel3.setText("Copyright [2013] [Konstantinos]");
this.jLabel3.setToolTipText("");
this.jLabel3.setVerticalAlignment(3);
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(GroupLayout
.Alignment.TRAILING, false).addComponent(this.jLabel2, GroupLayout.Alignment.LEADING, -1, -1, 32767)
.addComponent(this.jLabel1, GroupLayout.Alignment.LEADING, -1, 97, 32767)).addPreferredGap(LayoutStyle
.ComponentPlacement.RELATED).addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup().addComponent(this.path1, -2, 271, -2).addContainerGap())
.addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.path, -2, 271, -2).addComponent(this.Calculate, -2, 193, -2))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(this.browse, -1, -1, 32767).addComponent(this.jLabel3, -1, -1, 32767))))));
layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30).addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.jLabel1)
.addComponent(this.path, -2, 21, -2).addComponent(this.browse)).addGroup(layout.createParallelGroup(GroupLayout
.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.path1, -2, 21, -2)
.addComponent(this.jLabel2)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 31, 32767)
.addComponent(this.Calculate).addGap(11, 11, 11)).addGroup(GroupLayout.Alignment.TRAILING, layout
.createSequentialGroup().addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, -1, 32767).addComponent(this.jLabel3)))));
pack();
}
private void browseActionPerformed(ActionEvent evt) {
int returnVal = this.jFileChooser1.showOpenDialog(this);
if (returnVal == 0) {
File file = this.jFileChooser1.getSelectedFile();
try {
this.path.setText(file.getAbsolutePath());
} catch (Exception ex) {
System.out.println("problem accessing file" + file.getAbsolutePath());
}
} else {
System.out.println("File access cancelled by user.");
}
}
private void pathActionPerformed(ActionEvent evt) {}
private void path1ActionPerformed(ActionEvent evt) {}
private void CalculateActionPerformed(ActionEvent evt) {
calc calc1 = new calc();
String fpath = this.path.getText();
String fname = this.path1.getText();
calc.pointCalc(fpath, fname);
}
public static void main(String[] args) {
try {
for (UIManager.LookAndFeelInfo info: ) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(skiGui.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(skiGui.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(skiGui.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(skiGui.class.getName()).log(Level.SEVERE, null, ex);
}
EventQueue.invokeLater(new Runnable() {
public void run() {
new skiGui().setVisible(true);
}
});
}
}
| 37.407609 | 128 | 0.748947 |
8526c5c320c0a9a157c465709b46a23b98ca1cbb
| 1,508 |
package org.example;
import org.apache.pulsar.client.api.*;
import java.util.concurrent.ExecutionException;
public class SimpleConsumer {
public static String PULSAR_URL = "{{ pulsar_url }}";
public static String PULSAR_JWT = "{{ pulsar_jwt }}";
public static String PULSAR_TOPIC = "persistent://{{pulsar_tenant}}/{{pulsar_namespace}}/java-simple";
public static String PULSAR_SUBSCRIPTION_NAME = "sample";
public static void main(String[] argv) {
try (PulsarClient client = PulsarClient.builder()
.serviceUrl(PULSAR_URL)
.proxyServiceUrl(PULSAR_URL, ProxyProtocol.SNI)
.authentication(AuthenticationFactory.token(PULSAR_JWT))
.build()) {
try (Consumer<byte[]> consumer = client.newConsumer()
.topic(PULSAR_TOPIC)
.subscriptionName(PULSAR_SUBSCRIPTION_NAME)
.subscribe()) {
Message<byte[]> message = consumer.receive();
try {
System.out.printf("Message Received with Data : %s\n", new String(message.getData()));
consumer.acknowledge(message);
} catch (Exception e ) {
consumer.negativeAcknowledge(message);
e.printStackTrace();
} finally {
consumer.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 36.780488 | 106 | 0.56366 |
ca17165c5ad02bd276e94dc4cebc9f7af6cb18dd
| 397 |
package ru.trickyfoxy.lab2.Attacks;
import ru.ifmo.se.pokemon.*;
public class LowSweep extends PhysicalMove {
public LowSweep() {
super(Type.FIGHTING, 65, 100);
}
@Override
protected String describe() {
return "uses Low Sweep";
}
protected void applyOppEffects(Pokemon pokemon) {
pokemon.setCondition(new Effect().stat(Stat.SPEED, -1));
}
}
| 20.894737 | 64 | 0.649874 |
9e1b24519f4fd768a85ebbed2152c7cc9b349a20
| 891 |
/*
* Copyright 2008-2013 Exigen Insurance Solutions, Inc. All Rights Reserved.
*
*/
package com.exigeninsurance.x4j.analytic.xlsx.core.node;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import com.exigeninsurance.x4j.analytic.xlsx.transform.MergedRegion;
import com.exigeninsurance.x4j.analytic.xlsx.transform.xlsx.XLXContext;
public class MergedCellsNode extends Node {
public MergedCellsNode(XSSFSheet sheet) {
super(sheet);
}
@Override
public void process(XLXContext context) throws Exception {
List<MergedRegion> regions = context.getNewMergedCells();
if (!regions.isEmpty()) {
context.write("<mergeCells count=\"" + regions.size() + "\">");
for (MergedRegion region : regions) {
context.write("<mergeCell ref=\"" + region.toString() + "\"/>");
}
context.write("</mergeCells>");
}
}
}
| 24.75 | 77 | 0.69248 |
ddd1d6a2a26549ea691d19cc8379b0d4f5a0f77f
| 114 |
package com.dharma.patterns.di.withdi.service;
public interface Service {
void send(String msg, String rec);
}
| 16.285714 | 46 | 0.763158 |
2a3e82ab800deebc25fed37febb891a738dccb82
| 442 |
package com.company;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.Reader;
import java.io.Writer;
public class Helper {
public static Reader openReader(String name) throws IOException{
return Files.newBufferedReader(Paths.get(name));
}
public static Writer openWriter(String name) throws IOException{
return Files.newBufferedWriter(Paths.get(name));
}
}
| 24.555556 | 68 | 0.739819 |
da0d82e4ebb728fbc766ce810b1228ecb3ce2d80
| 553 |
package factory;
/**
* @author Khalid Elshafie <abolkog@gmail.com>
* @created 08/03/2018.
*/
public class EnemyFactory {
public static final int BIRD = 1;
public static final int TURTLE = 2;
public static final int DINOSAUR = 3;
public static Enemy createEnemy(int id) {
switch (id) {
case BIRD:
return new Bird();
case TURTLE:
return new Turtle();
case DINOSAUR:
return new Dinosaur();
default: return null;
}
}
}
| 22.12 | 46 | 0.544304 |
f7cef56401a31d12d3576337c932d0aebe2daf67
| 3,367 |
package com.sciatta.netty.example.echo.nio;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;
/**
* Created by yangxiaoyu on 2021/11/29<br>
* All Rights Reserved(C) 2017 - 2021 SCIATTA<br><p/>
* EchoNioServer
*/
@Slf4j
public class EchoNioServer {
public static void main(String[] args) {
EchoNioServer server = new EchoNioServer(EchoNioClient.PORT);
server.start();
log.info("server start");
}
private final int port;
private Selector selector;
public EchoNioServer(int port) {
this.port = port;
}
private void newSelector() throws IOException {
selector = Selector.open();
}
private void newServerSocketChannel() throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(port)); // 绑定端口
serverSocketChannel.configureBlocking(false); // 非阻塞模式
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); // 注册
}
private void processSelectionKeys(Set<SelectionKey> selectionKeys) throws IOException {
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
SelectionKey next = iterator.next();
iterator.remove();
if (next.isAcceptable()) {
processAccept(next);
} else if (next.isReadable()) {
processRead(next);
}
}
}
private void processRead(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int length = channel.read(buffer);
if (length <= 0) return; // close connection?
byte[] array = buffer.array();
buffer.clear();
log.info("Server received byte length: " + length + ", buffer length:" + array.length);
String output = new String(array, 0, length);
log.info("Server received: " + output);
// 原样输出
channel.write(ByteBuffer.wrap(output.getBytes(StandardCharsets.UTF_8)));
}
private void processAccept(SelectionKey key) throws IOException {
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel client = server.accept();
client.configureBlocking(false); // 非阻塞模式
client.register(selector, SelectionKey.OP_READ); // 注册
}
private void start() {
new Thread(() -> {
try {
newSelector();
newServerSocketChannel();
while (true) {
int select = selector.select();
if (select <= 0) return;
processSelectionKeys(selector.selectedKeys());
}
} catch (IOException e) {
log.error(e.getMessage());
}
}).start();
}
}
| 30.609091 | 95 | 0.57529 |
f9c931b749efceca3b808914477676f1874a6c62
| 1,295 |
package baavgai.textgame.framework;
// our natural language processor is dumb as dirt
// we just care about verb - noun pairs
public final class UserAction {
public final String verb, noun;
public UserAction(String verb, String noun) {
this.verb = verb;
this.noun = noun;
}
private boolean isMatch(String s, String other) {
return (s==null || other==null) ? false : s.equalsIgnoreCase(other);
}
private boolean isMatch(String s, String [] others) {
if (s==null || others==null) { return false; }
for(String other : others ) { if (isMatch(s, other)) { return true; } }
return false;
}
public boolean isVerbMatch(String [] others) { return isMatch(verb, others); }
public boolean isVerbMatch(String other) { return isMatch(verb, other); }
public boolean isNounMatch(String [] others) { return isMatch(noun, others); }
public boolean isNounMatch(String other) { return isMatch(noun, other); }
// parser logic provided here
public static UserAction getUserAction(String userEntry) {
if (userEntry==null) { return null; }
String [] list = userEntry.split(" ");
String verb = list[0].trim().toUpperCase();
if (verb.length()==0) { return null; }
String noun = (list.length>1) ? list[1].trim().toUpperCase() : null;
return new UserAction(verb, noun);
}
}
| 35.972222 | 79 | 0.693436 |
f4eb81361e2b4c8f3882df6d7e3ac1b63e3b3bb1
| 589 |
package no.ssb.dc.api;
import java.util.function.Consumer;
public class PositionObserver {
private final Consumer<Integer> expectedCallback;
private final Consumer<Integer> completedCallback;
public PositionObserver(Consumer<Integer> expectedCallback, Consumer<Integer> completedCallback) {
this.expectedCallback = expectedCallback;
this.completedCallback = completedCallback;
}
public void expected(int count) {
expectedCallback.accept(count);
}
public void completed(int count) {
completedCallback.accept(count);
}
}
| 25.608696 | 102 | 0.726655 |
2738d01e6341cef44de671ee4610088148d60378
| 3,375 |
/*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.debug.jdi.tests;
import com.sun.jdi.AbsentInformationException;
import com.sun.jdi.ClassNotLoadedException;
import com.sun.jdi.LocalVariable;
/**
* Tests for JDI com.sun.jdi.LocalVariable.
*/
public class LocalVariableTest extends AbstractJDITest {
private LocalVariable fVar;
/**
* Creates a new test.
*/
public LocalVariableTest() {
super();
}
/**
* Init the fields that are used by this test only.
*/
@Override
public void localSetUp() {
// Wait for the program to be ready
waitUntilReady();
// Get local variable "t" in the frame running MainClass.run()
fVar = getLocalVariable();
}
/**
* Run all tests and output to standard output.
* @param args
*/
public static void main(java.lang.String[] args) {
new LocalVariableTest().runSuite(args);
}
/**
* Gets the name of the test case.
* @see junit.framework.TestCase#getName()
*/
@Override
public String getName() {
return "com.sun.jdi.LocalVariable";
}
/**
* Test JDI equals() and hashCode().
*/
public void testJDIEquality() {
assertTrue("1", fVar.equals(fVar));
LocalVariable other = null;
try {
other = getFrame(RUN_FRAME_OFFSET).visibleVariableByName("o");
} catch (AbsentInformationException e) {
assertTrue("2", false);
}
assertTrue("3", !fVar.equals(other));
assertTrue("4", !fVar.equals(new Object()));
assertTrue("5", !fVar.equals(null));
assertTrue("6", fVar.hashCode() != other.hashCode());
}
/**
* Test JDI isArgument().
*/
public void testJDIIsArgument() {
assertTrue("1", !fVar.isArgument());
}
/**
* Test JDI isVisible(StackFrame).
*/
public void testJDIIsVisible() {
assertTrue("1", fVar.isVisible(getFrame(RUN_FRAME_OFFSET)));
boolean gotException = false;
try {
fVar.isVisible(getFrame(0));
} catch (IllegalArgumentException e) {
gotException = true;
}
assertTrue("2", gotException);
}
/**
* Test JDI name().
*/
public void testJDIName() {
assertEquals("1", "t", fVar.name());
}
/**
* Test JDI signature().
*/
public void testJDISignature() {
assertEquals("1", "Ljava/lang/Thread;", fVar.signature());
}
/**
* Test JDI type().
*/
public void testJDIType() {
try {
assertEquals("1", fVM.classesByName("java.lang.Thread").get(0), fVar.type());
} catch (ClassNotLoadedException e) {
assertTrue("2", false);
}
}
/**
* Test JDI typeName().
*/
public void testJDITypeName() {
assertEquals("1", "java.lang.Thread", fVar.typeName());
}
}
| 26.162791 | 89 | 0.570074 |
69fc969be5f288d1f29cbd1cd076a2ccf70bc67a
| 7,402 |
package bookmark;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* Represents a single bookmark. The object contains a list of Field objects
* corresponding to the fields of the bookmark.
*/
public class Bookmark {
private List<Field> fields;
private List<Comment> comments;
private String addedOn;
private String readOn;
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");
public Bookmark(List<Field> entries) {
this.fields = entries;
this.comments = new ArrayList<Comment>();
}
public Bookmark() {
this(new ArrayList<Field>());
}
public void addComment(String content) {
Comment comment = new Comment();
comment.setContent(content);
comment.setAddedOn();
comments.add(comment);
}
public List<Comment> getComments() {
return comments;
}
public boolean isRead() {
return readOn != null;
}
public void markAsRead() {
LocalDateTime now = LocalDateTime.now();
this.readOn = formatter.format(now);
}
public String getReadOn() {
return readOn;
}
public List<String> getAllSingleFieldNames() {
return fields.stream()
.filter(x -> x.isSingleField())
.map(x -> x.getName())
.collect(Collectors.toList());
}
public boolean containsField(String fieldName) {
return fieldByName(fieldName) != null;
}
public void setListField(String field, List<String> newContent) {
Field entry = fieldByName(field);
if (entry == null) {
entry = new Field(field, newContent);
this.fields.add(entry);
} else {
entry.setData(newContent);
}
}
public void setSingleField(String field, String data) {
Field entry = fieldByName(field);
if (entry == null) {
entry = new Field(field, data);
this.fields.add(entry);
} else {
entry.setData(data);
}
}
/**
* Add a new element to a list field.
*
* @param fieldName
* @param newElement
*/
public void addToField(String fieldName, String newElement) {
Field field = fieldByName(fieldName);
if (field == null) {
fields.add(new Field(fieldName, newElement));
} else {
field.addToList(newElement);
}
}
private Field fieldByName(String name) {
return fields.stream()
.filter(entry -> entry.getName().toLowerCase().equals(name.toLowerCase()))
.findFirst()
.orElse(null);
}
public List<String> getListField(String title) {
Field entry = fieldByName(title);
if (entry != null) {
return entry.getList();
}
return new ArrayList<>();
}
public String getSingleField(String title) {
Field entry = fieldByName(title);
if (entry != null) {
return entry.getFirst();
}
return "";
}
public List<String> getFieldNames() {
return fields.stream()
.map(field -> field.getName())
.collect(Collectors.toList());
}
public List<String> getEmptyFields() {
return getFieldNames().stream()
.filter(f -> fieldByName(f).isEmpty())
.collect(Collectors.toList());
}
public boolean titleAuthorOrDescriptionContains(String content) {
List<String> fieldsToSearch = new ArrayList();
fieldsToSearch.add("title");
fieldsToSearch.add("author");
fieldsToSearch.add("description");
return fieldsToSearch.stream().anyMatch(field -> fieldContains(field, content));
}
public boolean fieldContains(String fieldName, String content) {
Field entry = fieldByName(fieldName);
if (entry == null) {
return false;
}
return entry.contains(content);
}
public boolean fieldContainsAny(String fieldName, List<String> content) {
Field entry = fieldByName(fieldName);
if (entry == null) {
return false;
}
return entry.containsAny(content);
}
public boolean fieldIsSingle(String fieldName) {
Field field = fieldByName(fieldName);
return field.isSingleField();
}
public void setAddedOn() {
LocalDateTime now = LocalDateTime.now();
this.addedOn = formatter.format(now);
}
public String getAddedOn() {
return this.addedOn;
}
@Override
public String toString() {
return fields.stream()
.map(entry -> entry.toString())
.collect(Collectors.joining("\n"))
+ "\nAdded on: " + this.addedOn
+ (isRead() ? "\nRead on: " + this.readOn : "")
+ (!comments.isEmpty() ? "\nComments:\n"
+ comments.stream()
.map(entry -> entry.toString())
.collect(Collectors.joining("\n")) : "");
}
public static Bookmark createBook(String title, String author, String isbn) {
List<Field> entries = new ArrayList<>();
entries.add(new Field("Title", title));
entries.add(new Field("Author", author));
entries.add(new Field("ISBN", isbn));
entries.add(new Field("URL", ""));
entries.add(new Field("Description", ""));
entries.add(new Field("Tags", new ArrayList<String>()));
return new Bookmark(entries);
}
public static Bookmark createBook() {
List<Field> entries = new ArrayList<>();
entries.add(new Field("Title", ""));
entries.add(new Field("Author", ""));
entries.add(new Field("ISBN", ""));
entries.add(new Field("URL", ""));
entries.add(new Field("Description", ""));
entries.add(new Field("Tags", new ArrayList<String>()));
return new Bookmark(entries);
}
/**
* Create a new Bookmark. String fields are initialized with empty strings.
* List fields are initialized with empty lists.
*/
public static Bookmark createBookmark() {
List<Field> entries = new ArrayList<>();
entries.add(new Field("Title", ""));
entries.add(new Field("URL", ""));
entries.add(new Field("Description", ""));
entries.add(new Field("Author", ""));
entries.add(new Field("ISBN", ""));
entries.add(new Field("Tags", new ArrayList<String>()));
entries.add(new Field("Prerequisite courses", new ArrayList<String>()));
entries.add(new Field("Related courses", new ArrayList<String>()));
return new Bookmark(entries);
}
public static LocalDateTime parser(Bookmark bm) {
LocalDateTime dateTime = LocalDateTime.parse(bm.getAddedOn(), formatter);
return dateTime;
}
public static String serializeBookmark(Bookmark bm) {
Gson gson = new Gson();
return gson.toJson(bm);
}
public static Bookmark deserializeBookmark(String json) {
Gson gson = new Gson();
Bookmark bm = gson.fromJson(json, Bookmark.class);
return bm;
}
}
| 30.460905 | 103 | 0.584572 |
5ef3fc83e7611dffc05bfb64d4e657bee08b48ce
| 1,044 |
import java.util.Scanner;
public class J3From1987 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String n = sc.nextLine();
int temp = Integer.parseInt(n) + 1;
n = Integer.toString(temp);
boolean found = false;
if (temp < 10) {
System.out.println(temp);
return;
}
while (!found) {
boolean good = true;
int nInt = Integer.parseInt(n);
label:
for (int j = 0; j < n.length(); j++) {
for (int i = j + 1; i < n.length(); i++) {
if (n.charAt(j) == n.charAt(i)) {
good = false;
break label;
} else if (good && j == n.length() - 2 && i == n.length() - 1) {
System.out.println(n);
found = true;
}
}
}
nInt++;
n = Integer.toString(nInt);
}
}
}
| 29.828571 | 84 | 0.396552 |
8e9e7b8e906aa572c6edc36e9e73b310b47e9e07
| 3,138 |
/**
* 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.smartdata.hdfs.action.move;
import com.google.common.base.Preconditions;
import org.smartdata.hdfs.CompatibilityHelperLoader;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Storage map.
*/
public class StorageMap {
private final StorageGroupMap<Source> sources;
private final StorageGroupMap<StorageGroup> targets;
private final Map<String, List<StorageGroup>> targetStorageTypeMap;
public StorageMap() {
this.sources = new StorageGroupMap<>();
this.targets = new StorageGroupMap<>();
this.targetStorageTypeMap = new HashMap<>();
for (String t : CompatibilityHelperLoader.getHelper().getMovableTypes()) {
targetStorageTypeMap.put(t, new LinkedList<StorageGroup>());
}
}
public void add(Source source, StorageGroup target) {
sources.put(source);
if (target != null) {
targets.put(target);
getTargetStorages(target.getStorageType()).add(target);
}
}
public Source getSource(MLocation ml) {
return get(sources, ml);
}
public StorageGroupMap<StorageGroup> getTargets() {
return targets;
}
public StorageGroup getTarget(String uuid, String storageType) {
return targets.get(uuid, storageType);
}
public static <G extends StorageGroup> G get(StorageGroupMap<G> map, MLocation ml) {
return map.get(ml.datanode.getDatanodeUuid(), ml.storageType);
}
public List<StorageGroup> getTargetStorages(String t) {
return targetStorageTypeMap.get(t);
}
public static class StorageGroupMap<G extends StorageGroup> {
private static String toKey(String datanodeUuid, String storageType) {
return datanodeUuid + ":" + storageType;
}
private final Map<String, G> map = new HashMap<String, G>();
public G get(String datanodeUuid, String storageType) {
return map.get(toKey(datanodeUuid, storageType));
}
public void put(G g) {
final String key = toKey(g.getDatanodeInfo().getDatanodeUuid(), g.getStorageType());
final StorageGroup existing = map.put(key, g);
Preconditions.checkState(existing == null);
}
int size() {
return map.size();
}
void clear() {
map.clear();
}
public Collection<G> values() {
return map.values();
}
}
}
| 30.173077 | 90 | 0.709688 |
11d3811f130d1983078a39554813f002edd5b150
| 114 |
package com.discount.domain.enums;
public enum CustomerType {
EMPLOYEE,
AFFILIATE,
CUSTOMER
}
| 14.25 | 35 | 0.666667 |
b5c94915b81ca444e9363d0befe69464a137f41d
| 96 |
package io.sunshower.common.configuration;
public interface ValueHolder {
String value();
}
| 13.714286 | 42 | 0.770833 |
128eada611157065bbd3733dcc5c05ba30bde1b3
| 132 |
package todolist.entity;
import javax.persistence.*;
@Entity
@Table(name = "tasks")
public class Task {
//TODO:Implement me...
}
| 13.2 | 27 | 0.704545 |
18e17cd72de5e51e5aade307a7673ccc82b45cd7
| 200 |
package ru.job4j.calculator.loop;
public class Factorial {
public int calc(int n) {
int res=1;
for(int i=1;i<=n;i++){
res=res*i;
}
return res;
}
}
| 16.666667 | 33 | 0.495 |
354a0d28378cc9bacd67579e3cb6990561705769
| 1,164 |
package io.quarkus.test.junit.mockito.internal;
import io.quarkus.test.junit.QuarkusMock;
import io.quarkus.test.junit.callback.QuarkusTestBeforeEachCallback;
import io.quarkus.test.junit.callback.QuarkusTestMethodContext;
public class SetMockitoMockAsBeanMockCallback implements QuarkusTestBeforeEachCallback {
@Override
public void beforeEach(QuarkusTestMethodContext context) {
MockitoMocksTracker.getMocks(context.getTestInstance()).forEach(this::installMock);
}
private void installMock(MockitoMocksTracker.Mocked mocked) {
try {
QuarkusMock.installMockForInstance(mocked.mock, mocked.beanInstance);
} catch (Exception e) {
throw new RuntimeException(mocked.beanInstance
+ " is not a normal scoped CDI bean, make sure the bean is a normal scope like @ApplicationScoped or @RequestScoped."
+ " Alternatively you can use '@InjectMock(convertScopes=true)' instead of '@InjectMock' if you would like"
+ " Quarkus to automatically make that conversion (you should only use this if you understand the implications).");
}
}
}
| 46.56 | 137 | 0.721649 |
17ce1c8aa54edfcd60707c6eb3c2e8f355a7dc25
| 7,511 |
package common;
import java.io.Serializable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class ChangeLog implements Serializable {
public static final int CHANGE_ADD = 1;
public static final int CHANGE_ADDNEW = 2;
public static final int CHANGE_UPDATE = 3;
public static final int CHANGE_DELETE = 4;
protected List changes = new LinkedList();
protected long preid = 0L;
protected long postid = 0L;
protected String name;
public int size() {
return this.changes.size();
}
public boolean isDifferent() {
return this.changes.size() > 0;
}
public ChangeLog(String var1) {
this.name = var1;
}
public void add(String var1, Map var2) {
this.changes.add(new ChangeLog.ChangeEntry(1, var1, var2));
}
public void addnew(String var1, Map var2) {
this.changes.add(new ChangeLog.ChangeEntry(2, var1, var2));
}
public void update(String var1, Map var2) {
this.changes.add(new ChangeLog.ChangeEntry(3, var1, var2));
}
public void delete(String var1) {
this.changes.add(new ChangeLog.ChangeEntry(4, var1, (Map)null));
}
protected long pre(Map var1) {
long var2 = 0L;
if (this.preid == 0L) {
this.preid = var2;
} else if (var2 != this.preid) {
}
return var2;
}
protected void post(Map var1, long var2) {
}
public void applyOptimize(Map var1) {
long var2 = this.pre(var1);
Iterator var4 = this.changes.iterator();
while(var4.hasNext()) {
ChangeLog.ChangeEntry var5 = (ChangeLog.ChangeEntry)var4.next();
this.actOptimize(var5, var1);
if (!var5.isNeccessary()) {
var4.remove();
}
}
this.post(var1, var2);
}
public void applyForce(Map var1) {
long var2 = this.pre(var1);
Iterator var4 = this.changes.iterator();
while(var4.hasNext()) {
ChangeLog.ChangeEntry var5 = (ChangeLog.ChangeEntry)var4.next();
this.actForce(var5, var1);
}
this.post(var1, var2);
}
protected boolean same(Map var1, Map var2) {
if (var1.size() != var2.size()) {
return false;
} else {
Iterator var3 = var1.entrySet().iterator();
Entry var4;
Object var5;
do {
do {
if (!var3.hasNext()) {
return true;
}
var4 = (Entry)var3.next();
var5 = var2.get(var4.getKey());
} while(var5 == null && var4.getValue() == null);
if (var5 == null && var4.getValue() != null) {
return false;
}
if (var5 != null && var4.getValue() == null) {
return false;
}
} while(var5 == null || var4.getValue() == null || var5.toString().equals(var4.getValue().toString()));
return false;
}
}
protected void actForce(ChangeLog.ChangeEntry var1, Map var2) {
switch(var1.type()) {
case 1:
var2.put(var1.key(), var1.entry());
break;
case 2:
if (!var2.containsKey(var1.key())) {
var2.put(var1.key(), var1.entry());
}
break;
case 3:
if (var2.containsKey(var1.key())) {
Map var3 = (Map)var2.get(var1.key());
Iterator var4 = var1.entry().entrySet().iterator();
while(var4.hasNext()) {
Entry var5 = (Entry)var4.next();
var3.put(var5.getKey(), var5.getValue());
}
return;
}
var2.put(var1.key(), var1.entry());
break;
case 4:
var2.remove(var1.key());
}
}
protected void actOptimize(ChangeLog.ChangeEntry var1, Map var2) {
Map var3;
switch(var1.type()) {
case 1:
if (var2.containsKey(var1.key())) {
var3 = (Map)var2.get(var1.key());
if (!this.same(var3, var1.entry())) {
var2.put(var1.key(), var1.entry());
} else {
var1.kill();
}
} else {
var2.put(var1.key(), var1.entry());
}
break;
case 2:
if (!var2.containsKey(var1.key())) {
var2.put(var1.key(), var1.entry());
} else {
var1.kill();
}
break;
case 3:
if (var2.containsKey(var1.key())) {
var3 = (Map)var2.get(var1.key());
boolean var4 = false;
Iterator var5 = var1.entry().entrySet().iterator();
while(true) {
while(true) {
Entry var6;
Object var7;
do {
if (!var5.hasNext()) {
if (!var4) {
var1.kill();
}
return;
}
var6 = (Entry)var5.next();
var7 = var3.get(var6.getKey());
} while(var7 == null && var6.getValue() == null);
if (var7 == null && var6.getValue() != null) {
var3.put(var6.getKey(), var6.getValue());
var4 = true;
} else if (var7 != null && var6.getValue() != null) {
if (!var6.getValue().toString().equals(var7.toString())) {
var3.put(var6.getKey(), var6.getValue());
var4 = true;
}
} else if (var7 != null && var6.getValue() == null) {
var3.put(var6.getKey(), var6.getValue());
var4 = true;
}
}
}
}
var2.put(var1.key(), var1.entry());
break;
case 4:
if (var2.containsKey(var1.key())) {
var2.remove(var1.key());
} else {
var1.kill();
}
}
}
public void print() {
CommonUtils.print_info("Change Log...");
Iterator var1 = this.changes.iterator();
while(var1.hasNext()) {
ChangeLog.ChangeEntry var2 = (ChangeLog.ChangeEntry)var1.next();
var2.print();
}
}
public class ChangeEntry implements Serializable {
protected int type;
protected String key;
protected Map entry;
protected boolean needed = true;
public ChangeEntry(int var2, String var3, Map var4) {
this.type = var2;
this.key = var3;
this.entry = var4;
}
public void kill() {
this.needed = false;
}
public boolean isNeccessary() {
return this.needed;
}
public String key() {
return this.key;
}
public int type() {
return this.type;
}
public Map entry() {
return this.entry;
}
public void print() {
switch(this.type) {
case 1:
CommonUtils.print_info("\tAdd:\n\t\t" + this.key + "\n\t\t" + this.entry);
break;
case 2:
CommonUtils.print_info("\tAddNew:\n\t\t" + this.key + "\n\t\t" + this.entry);
break;
case 3:
CommonUtils.print_info("\tUpdate:\n\t\t" + this.key + "\n\t\t" + this.entry);
break;
case 4:
CommonUtils.print_info("\tDelete:\n\t\t" + this.key);
}
}
}
}
| 26.447183 | 112 | 0.49088 |
e7858f66571f2fc2ef957f87f839a42f0ddd2c3e
| 495 |
package main;
import lexicalAnalyzer.LexicalAnalyzer;
import java.io.*;
public class Main {
public static void main(String[] args) {
/*if(args.length == 0) {
System.out.println("입력받은 파일이 없습니다.");
System.exit(0);
}*/
File file = new File("C:\\Users\\tony1\\Desktop\\Lexical-Analyzer\\compiler-term-project-lexical-analyzer\\LexicalAnalyzer\\src\\Input.java");
LexicalAnalyzer lexicalAnalyzer = new LexicalAnalyzer(file);
}
}
| 23.571429 | 150 | 0.638384 |
b8d2d953702cfd2e1802b6098e807b8977864953
| 2,650 |
package com.gooroomee.api.comment;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.gooroomee.api.post.detail.PostDetailService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@Controller
@Slf4j
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
@RequestMapping("/comments")
public class CommentsController {
private final CommentsService commentsService;
@PostMapping("/{post_id}")
public ResponseEntity storeComments(@PathVariable Long post_id,
// @RequestParam(value = "parentId", required = false) Long parentId,
@RequestBody @Valid CommentsDto commentsDto) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null)
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
String visitorId = authentication.getName();
Comments comment = this.commentsService.storeComments(visitorId, post_id, commentsDto);
return ResponseEntity.ok().body(comment);
}
@GetMapping("/{post_id}")
public ResponseEntity getComments(@PathVariable Long post_id) {
List<CommentsDto> commentsDto = this.commentsService.getComments(post_id);
return ResponseEntity.ok().body(commentsDto);
}
@GetMapping("/reply/{comments_id}")
public ResponseEntity getCommentReplies(@PathVariable Long comments_id) {
List<CommentsDto> commentsDto = this.commentsService.findCommentReplies(comments_id);
return ResponseEntity.ok().body(commentsDto);
}
@DeleteMapping("/{comments_id}")
public ResponseEntity deletePost(@PathVariable Long comments_id) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null)
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
String visitorId = authentication.getName();
try {
Comments comments = this.commentsService.deleteComment(comments_id, visitorId);
return ResponseEntity.ok(comments);
} catch (IllegalArgumentException e) {
return ResponseEntity.badRequest().build();
}
}
}
| 40.769231 | 108 | 0.723019 |
246c9d9a5a37552f16dc0a200f3526f09fa5aaba
| 1,234 |
package app.roana0229.org.android_screentracker_sample;
import android.content.Context;
import android.content.Intent;
import app.roana0229.org.android_screentracker_sample.activity.CompleteActivity;
import app.roana0229.org.android_screentracker_sample.activity.DetailActivity;
import app.roana0229.org.android_screentracker_sample.activity.HomeActivity;
import app.roana0229.org.android_screentracker_sample.activity.SettingActivity;
import app.roana0229.org.android_screentracker_sample.model.DummyContent;
public class Navigator {
private final Context context;
public Navigator(Context context) {
this.context = context;
}
public void showHome() {
Intent intent = HomeActivity.getIntent(context);
context.startActivity(intent);
}
public void showDetail(DummyContent.DummyItem item) {
Intent intent = DetailActivity.getIntent(context, item);
context.startActivity(intent);
}
public void showComplete() {
Intent intent = CompleteActivity.getIntent(context);
context.startActivity(intent);
}
public void showSetting() {
Intent intent = SettingActivity.getIntent(context);
context.startActivity(intent);
}
}
| 30.85 | 80 | 0.753647 |
7b477667b47b0427dd6206430b8fab48fa3b1664
| 1,957 |
package evemanutool.gui.general.tabel;
import java.awt.BorderLayout;
import java.util.Collection;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.SwingConstants;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import evemanutool.constants.DBConstants;
@SuppressWarnings("serial")
public class ScrollableTablePanel<T> extends JPanel implements DBConstants, SwingConstants{
//Table components.
private final AdjustingTable table;
private final SimpleTableModel<T> model;
private final RowSorter<TableModel> sorter;
public ScrollableTablePanel(SimpleTableModel<T> model) {
//Set layout.
setLayout(new BorderLayout());
//Setup table.
this.model = model;
table = new AdjustingTable(model);
sorter = new TableRowSorter<TableModel>(model);
table.setRowSorter(sorter);
table.getTableHeader().setReorderingAllowed(false);
//Renderer.
table.setDefaultRenderer(Long.class, new LongNumberCellRenderer(""));
table.setDefaultRenderer(Double.class, new DecimalNumberCellRenderer(""));
table.setDefaultRenderer(Integer.class, new IntegerNumberCellRenderer(""));
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.getTableHeader().setDefaultRenderer(new HeaderRenderer(table, model.getColumnAlign(), model.getEditableColumns()));
//Fixes background color of boolean cells.
((JComponent) table.getDefaultRenderer(Boolean.class)).setOpaque(true);
//ScrollPane.
JScrollPane pane = new JScrollPane(table);
add(pane, BorderLayout.CENTER);
}
public void setData(Collection<T> l) {
model.setData(l);
}
public JTable getTable() {
return table;
}
public SimpleTableModel<T> getModel() {
return model;
}
public RowSorter<TableModel> getSorter() {
return sorter;
}
}
| 28.779412 | 124 | 0.744507 |
93747a6bf2c34f7dbbaa4e603fb28fad75561bfa
| 2,049 |
package cluedo.model;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import cluedo.model.CluedoGame.Weapon;
/**
* A game token displayed on the board to represent a weapon.
* @author Maria
*
*/
public class WeaponToken extends Token {
private static final String IMAGE_PATH = "images/";
private String name;
private char symbol;
private BufferedImage image;
/**
* Creates a weapon token.
* @param name
*/
public WeaponToken(String name) {
super(name);
this.name = name;
getImage();
}
/**
* Returns a cluedo weapon from a string
* @param str
* @return
*/
private Weapon getWeapon(String str) {
Weapon res = null;
switch(str.toUpperCase()){
case "CANDLESTICK":
res = Weapon.CANDLESTICK;
break;
case "KNIFE":
res = Weapon.KNIFE;
break;
case "LEAD_PIPE":
res = Weapon.LEAD_PIPE;
break;
case "REVOLVER":
res = Weapon.REVOLVER;
break;
case "ROPE":
res = Weapon.ROPE;
break;
case "WRENCH":
res = Weapon.WRENCH;
break;
}
return res;
}
/**
* Returns an basic image associated with this weapon.
* @return
*/
private void getImage() {
try{
switch(name){
case "CANDLESTICK":
image = ImageIO.read(new File(IMAGE_PATH + "candlestick.png"));
case "KNIFE":
image = ImageIO.read(new File(IMAGE_PATH + "knife.png"));
case "LEAD_PIPE":
image = ImageIO.read(new File(IMAGE_PATH + "pipe.png"));
case "REVOLVER":
image = ImageIO.read(new File(IMAGE_PATH + "revolver.png"));
case "ROPE":
image = ImageIO.read(new File(IMAGE_PATH + "rope.png"));
case "WRENCH":
image = ImageIO.read(new File(IMAGE_PATH + "wrench.png"));
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Returns the image associated with this weapon.
* @return
*/
public BufferedImage image(){
return image;
}
@Override
public String toString(){
return name;
}
}
| 20.088235 | 68 | 0.647633 |
5546cba6634563dd2afec7a36321643e6f40bcdb
| 1,205 |
package stu.napls.clouderweb.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import stu.napls.clouderweb.core.dictionary.StatusCode;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "web_user")
@EntityListeners(AuditingEntityListener.class)
@Data
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "uuid")
private String uuid;
@Column(name = "name")
private String name;
@Column(name = "avatar")
private String avatar;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "depository", referencedColumnName = "id")
private Depository depository;
@JsonIgnore
@Column(name = "status", columnDefinition = "integer default " + StatusCode.NORMAL)
private int status;
@Column(name = "createDate")
@CreatedDate
private Date createDate;
@Column(name = "updateDate")
@LastModifiedDate
private Date updateDate;
}
| 25.104167 | 87 | 0.7361 |
4bd53bb58138ff3e1986cbf70ce2f102383e0901
| 2,434 |
package com.company.models;
import java.sql.Timestamp;
public class Participant {
private Long id_user;
private Long id_category;
private String description;
private Timestamp show_start_time;
private Timestamp show_end_time;
private String attached_file;
private boolean is_accepted;
public Participant() {
}
public Participant(Long id_user, Long id_category, String description, Timestamp show_start_time,
Timestamp show_end_time, String attached_file, Boolean is_accepted) {
super();
this.id_user = id_user;
this.id_category = id_category;
this.description = description;
this.show_start_time = show_start_time;
this.show_end_time = show_end_time;
this.attached_file = attached_file;
this.is_accepted = is_accepted;
}
public Long getId_user() {
return id_user;
}
public void setId_user(Long id_user) {
this.id_user = id_user;
}
public Long getId_category() {
return id_category;
}
public void setId_category(Long id_category) {
this.id_category = id_category;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Timestamp getShow_start_time() {
return show_start_time;
}
public void setShow_start_time(Timestamp show_start_time) {
this.show_start_time = show_start_time;
}
public Timestamp getShow_end_time() {
return show_end_time;
}
public void setShow_end_time(Timestamp show_end_time) {
this.show_end_time = show_end_time;
}
public String getAttached_file() {
return attached_file;
}
public void setAttached_file(String attached_file) {
this.attached_file = attached_file;
}
public boolean getIs_accepted() {
return is_accepted;
}
public void setIs_accepted(Boolean is_accepted) {
this.is_accepted = is_accepted;
}
@Override
public String toString() {
return "Participant [id_user=" + id_user + ", id_category=" + id_category + ", description=" + description
+ ", show_start_time=" + show_start_time + ", show_end_time=" + show_end_time + ", attached_file="
+ attached_file + ", is_accepted=" + is_accepted + "]";
}
}
| 30.425 | 114 | 0.658998 |
f6cf31d9f6f0cfb91e19e7597c81f5d9b95438d0
| 7,978 |
package gnu.text;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;
public class Options {
public static final int BOOLEAN_OPTION = 1;
public static final int STRING_OPTION = 2;
public static final String UNKNOWN = "unknown option name";
OptionInfo first;
HashMap<String, OptionInfo> infoTable;
OptionInfo last;
Options previous;
HashMap<String, Object> valueTable;
public static final class OptionInfo {
Object defaultValue;
String documentation;
String key;
int kind;
OptionInfo next;
}
public Options() {
}
public Options(Options previous2) {
this.previous = previous2;
}
public OptionInfo add(String key, int kind, String documentation) {
return add(key, kind, null, documentation);
}
public OptionInfo add(String key, int kind, Object defaultValue, String documentation) {
if (this.infoTable == null) {
this.infoTable = new HashMap<>();
} else if (this.infoTable.get(key) != null) {
throw new RuntimeException("duplicate option key: " + key);
}
OptionInfo info = new OptionInfo();
info.key = key;
info.kind = kind;
info.defaultValue = defaultValue;
info.documentation = documentation;
if (this.first == null) {
this.first = info;
} else {
this.last.next = info;
}
this.last = info;
this.infoTable.put(key, info);
return info;
}
static Object valueOf(OptionInfo info, String argument) {
if ((info.kind & 1) == 0) {
return argument;
}
if (argument == null || argument.equals("1") || argument.equals("on") || argument.equals("yes") || argument.equals("true")) {
return Boolean.TRUE;
}
if (argument.equals("0") || argument.equals("off") || argument.equals("no") || argument.equals("false")) {
return Boolean.FALSE;
}
return null;
}
private void error(String message, SourceMessages messages) {
if (messages == null) {
throw new RuntimeException(message);
}
messages.error('e', message);
}
public void set(String key, Object value) {
set(key, value, null);
}
public void set(String key, Object value, SourceMessages messages) {
OptionInfo info = getInfo(key);
if (info == null) {
error("invalid option key: " + key, messages);
return;
}
if ((info.kind & 1) != 0) {
if (value instanceof String) {
value = valueOf(info, (String) value);
}
if (!(value instanceof Boolean)) {
error("value for option " + key + " must be boolean or yes/no/true/false/on/off/1/0", messages);
return;
}
} else if (value == null) {
value = "";
}
if (this.valueTable == null) {
this.valueTable = new HashMap<>();
}
this.valueTable.put(key, value);
}
public void reset(String key, Object oldValue) {
if (this.valueTable == null) {
this.valueTable = new HashMap<>();
}
if (oldValue == null) {
this.valueTable.remove(key);
} else {
this.valueTable.put(key, oldValue);
}
}
public String set(String key, String argument) {
OptionInfo info = getInfo(key);
if (info == null) {
return UNKNOWN;
}
Object value = valueOf(info, argument);
if (value == null && (info.kind & 1) != 0) {
return "value of option " + key + " must be yes/no/true/false/on/off/1/0";
}
if (this.valueTable == null) {
this.valueTable = new HashMap<>();
}
this.valueTable.put(key, value);
return null;
}
public OptionInfo getInfo(String key) {
OptionInfo info = this.infoTable == null ? null : (OptionInfo) this.infoTable.get(key);
if (info == null && this.previous != null) {
info = this.previous.getInfo(key);
}
return info;
}
public Object get(String key, Object defaultValue) {
OptionInfo info = getInfo(key);
if (info != null) {
return get(info, defaultValue);
}
throw new RuntimeException("invalid option key: " + key);
}
/* JADX WARNING: Code restructure failed: missing block: B:12:0x0022, code lost:
if (r0.defaultValue == null) goto L_0x0026;
*/
/* JADX WARNING: Code restructure failed: missing block: B:13:0x0024, code lost:
r7 = r0.defaultValue;
*/
/* JADX WARNING: Code restructure failed: missing block: B:14:0x0026, code lost:
r1 = r1.previous;
*/
public Object get(OptionInfo key, Object defaultValue) {
Options options = this;
while (options != null) {
OptionInfo info = key;
while (true) {
Object val = options.valueTable == null ? null : options.valueTable.get(info.key);
if (val == null) {
if (!(info.defaultValue instanceof OptionInfo)) {
break;
}
info = (OptionInfo) info.defaultValue;
} else {
return val;
}
}
}
return defaultValue;
}
public Object get(OptionInfo key) {
return get(key, (Object) null);
}
public Object getLocal(String key) {
if (this.valueTable == null) {
return null;
}
return this.valueTable.get(key);
}
public boolean getBoolean(String key) {
return ((Boolean) get(key, (Object) Boolean.FALSE)).booleanValue();
}
public boolean getBoolean(String key, boolean defaultValue) {
return ((Boolean) get(key, (Object) defaultValue ? Boolean.TRUE : Boolean.FALSE)).booleanValue();
}
public boolean getBoolean(OptionInfo key, boolean defaultValue) {
return ((Boolean) get(key, (Object) defaultValue ? Boolean.TRUE : Boolean.FALSE)).booleanValue();
}
public boolean getBoolean(OptionInfo key) {
Object value = get(key, (Object) null);
if (value == null) {
return false;
}
return ((Boolean) value).booleanValue();
}
public void pushOptionValues(Vector options) {
int len = options.size();
int i = 0;
while (i < len) {
int i2 = i + 1;
String key = (String) options.elementAt(i);
int i3 = i2 + 1;
options.setElementAt(options.elementAt(i2), i2);
int i4 = i3 + 1;
set(key, options.elementAt(i3));
i = i4;
}
}
public void popOptionValues(Vector options) {
int i = options.size();
while (true) {
i -= 3;
if (i >= 0) {
String key = (String) options.elementAt(i);
Object oldValue = options.elementAt(i + 1);
options.setElementAt(null, i + 1);
reset(key, oldValue);
} else {
return;
}
}
}
public ArrayList<String> keys() {
ArrayList<String> allKeys = new ArrayList<>();
for (Options options = this; options != null; options = options.previous) {
if (options.infoTable != null) {
for (String k : options.infoTable.keySet()) {
if (!allKeys.contains(k)) {
allKeys.add(k);
}
}
}
}
return allKeys;
}
public String getDoc(String key) {
OptionInfo info = getInfo(key);
if (key == null) {
return null;
}
return info.documentation;
}
}
| 31.042802 | 133 | 0.533592 |
b07b94fc1805dc30162e3d0f8613af9c45b2824c
| 188 |
package l2f.gameserver.listener.actor.player;
import l2f.gameserver.listener.PlayerListener;
public interface OnAnswerListener extends PlayerListener
{
void sayYes();
void sayNo();
}
| 17.090909 | 56 | 0.803191 |
4792dcd9e65400ef6fa0645d580af75cbaf09a5f
| 1,940 |
package com.example.icard.model.dto;
import java.math.BigDecimal;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import io.swagger.annotations.ApiModel;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonInclude(Include.NON_NULL)
@ApiModel(description = "Class representing a transaction authorization.")
public class TransactionAuthorizationDTO {
@JsonProperty("cartao")
private String cardNumber;
@JsonProperty("validade")
private String expirantionDate;
@JsonProperty("cvv")
private String cvv;
@JsonProperty("estabelecimento")
private String client;
@JsonProperty("valor")
private BigDecimal saleValue;
@JsonProperty("senha")
private String password;
public TransactionAuthorizationDTO() {
}
public TransactionAuthorizationDTO(String cardNumber, String expirantionDate, String cvv, String client,
BigDecimal saleValue, String password) {
this.cardNumber = cardNumber;
this.expirantionDate = expirantionDate;
this.cvv = cvv;
this.client = client;
this.saleValue = saleValue;
this.password = password;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getExpirantionDate() {
return expirantionDate;
}
public void setExpirantionDate(String expirantionDate) {
this.expirantionDate = expirantionDate;
}
public String getCvv() {
return cvv;
}
public void setCvv(String cvv) {
this.cvv = cvv;
}
public String getClient() {
return client;
}
public void setClient(String client) {
this.client = client;
}
public BigDecimal getSaleValue() {
return saleValue;
}
public void setSaleValue(BigDecimal saleValue) {
this.saleValue = saleValue;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| 20.208333 | 105 | 0.756186 |
283602c5da8d541ff23697116c8bc1936219342f
| 469 |
package de.digitalcollections.model.identifiable.entity;
/** All entity types cudami can handle */
public enum EntityType {
AGENT,
ARTICLE,
AUDIO,
BOOK,
COLLECTION,
CORPORATE_BODY,
DIGITAL_OBJECT,
ENTITY,
EVENT,
EXPRESSION,
FAMILY,
GEOLOCATION,
HEADWORD_ENTRY,
IMAGE,
ITEM,
MANIFESTATION,
OBJECT_3D,
PERSON,
PLACE,
PROJECT,
TOPIC,
VIDEO,
WEBSITE,
WORK;
@Override
public String toString() {
return name();
}
}
| 13.4 | 56 | 0.678038 |
2716b78cdacdb418dd2696643d6ff5e30e5047db
| 1,020 |
package me.jrubio.todo.List;
import me.jrubio.todo.model.Entity.Todo;
/**
* Example To.Do list app using MVP pattern.
* Using android-support-v7 to support old Android versions.
*
* @author Jose I. Rubio (@joseirs)
*
*/
public interface IListPresenter {
/**
* Refresh data in view layer
*/
void refreshSession();
/**
* Action when the user click on Fab button
*/
void onAddTodoButtonClick();
/**
* Action when the user click to edit on To.Do item
*
* @param todo
*/
void onClickTodoItemToEdit(Todo todo);
/**
* Action when the user long click on To.Do item
*
* @param todo
*/
void onLongClickTodoItem(Todo todo);
/**
* Update To.Do completed property
*
* @param todo
* @param completed
* @param position
*/
void updateTodoIsCompleted(Todo todo, boolean completed, int position);
/**
* Delete old To.Do
*
* @param todo
*/
void delete(Todo todo);
}
| 18.545455 | 75 | 0.593137 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.