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
|
|---|---|---|---|---|---|
1e97e9d0af17bdf9305986969f927339e1068e65
| 6,506
|
package study.huhao.demo.domain.contexts.blogcontext.blog;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import study.huhao.demo.domain.core.common.excpetions.EntityNotFoundException;
import java.util.Optional;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.*;
class BlogServiceTest {
private BlogRepository blogRepository;
private BlogService blogService;
@BeforeEach
void setUp() {
blogRepository = mock(BlogRepository.class);
blogService = new BlogService(blogRepository);
}
@Nested
class create {
@Test
void should_create_correctly() {
Blog createdBlog = blogService
.create("Test Blog", "Something...", UUID.randomUUID());
verify(blogRepository).save(any(Blog.class));
assertThat(createdBlog.getId()).isNotNull();
}
}
@Nested
class get {
@Test
void should_get_correctly() {
// Given
Blog mockBlog = mock(Blog.class);
given(blogRepository.findById(mockBlog.getId())).willReturn(Optional.of(mockBlog));
// When
Blog foundBlog = blogService.get(mockBlog.getId());
// Then
assertThat(foundBlog).isSameAs(mockBlog);
}
@Test
void should_throw_EntityNotFoundException_when_blog_not_found() {
Blog mockBlog = mock(Blog.class);
given(blogRepository.findById(mockBlog.getId())).willReturn(Optional.empty());
assertThatThrownBy(() -> blogService.get(mockBlog.getId()))
.isInstanceOf(EntityNotFoundException.class)
.hasMessage("cannot find the blog with id " + mockBlog.getId());
}
}
@Nested
class getPublished {
@Test
void should_get_published_blog() {
Blog mockPublishedBlog = mock(Blog.class);
given(mockPublishedBlog.isPublished()).willReturn(true);
given(blogRepository.findById(mockPublishedBlog.getId())).willReturn(Optional.of(mockPublishedBlog));
Blog foundPublishedBlog = blogService.getPublished(mockPublishedBlog.getId());
assertThat(foundPublishedBlog).isSameAs(mockPublishedBlog);
}
@Test
void should_throw_EntityNotFoundException_when_blog_not_found() {
Blog mockPublishedBlog = mock(Blog.class);
given(blogRepository.findById(mockPublishedBlog.getId())).willReturn(Optional.empty());
assertThatThrownBy(() -> blogService.getPublished(mockPublishedBlog.getId()))
.isInstanceOf(EntityNotFoundException.class)
.hasMessage("cannot find the published blog with id " + mockPublishedBlog.getId());
}
@Test
void should_throw_EntityNotFoundException_when_published_blog_not_found() {
Blog mockPublishedBlog = mock(Blog.class);
given(mockPublishedBlog.isPublished()).willReturn(false);
given(blogRepository.findById(mockPublishedBlog.getId())).willReturn(Optional.of(mockPublishedBlog));
assertThatThrownBy(() -> blogService.getPublished(mockPublishedBlog.getId()))
.isInstanceOf(EntityNotFoundException.class)
.hasMessage("cannot find the published blog with id " + mockPublishedBlog.getId());
}
}
@Nested
class saveDraft {
@Test
void should_save_correctly() {
Blog mockBlog = mock(Blog.class);
given(blogRepository.findById(mockBlog.getId())).willReturn(Optional.of(mockBlog));
blogService.saveDraft(mockBlog.getId(), "Updated Title", "Updated...");
InOrder inOrder = inOrder(mockBlog, blogRepository);
inOrder.verify(mockBlog).saveDraft("Updated Title", "Updated...");
inOrder.verify(blogRepository).save(mockBlog);
}
@Test
void should_throw_EntityNotFoundException_when_blog_not_found() {
Blog mockBlog = mock(Blog.class);
given(blogRepository.findById(mockBlog.getId())).willReturn(Optional.empty());
assertThatThrownBy(() -> blogService.saveDraft(mockBlog.getId(), "Updated Title", "Updated..."))
.isInstanceOf(EntityNotFoundException.class)
.hasMessage("cannot find the blog with id " + mockBlog.getId());
}
}
@Nested
class delete {
@Test
void should_delete_correctly() {
Blog mockBlog = mock(Blog.class);
given(blogRepository.existsById(mockBlog.getId())).willReturn(true);
blogService.delete(mockBlog.getId());
verify(blogRepository).deleteById(mockBlog.getId());
}
@Test
void should_throw_EntityNotFoundException_when_blog_not_found() {
Blog mockBlog = mock(Blog.class);
given(blogRepository.existsById(mockBlog.getId())).willReturn(false);
assertThatThrownBy(() -> blogService.delete(mockBlog.getId()))
.isInstanceOf(EntityNotFoundException.class)
.hasMessage("cannot find the blog with id " + mockBlog.getId());
}
}
@Nested
class publish {
@Test
void should_publish_correctly() {
Blog mockBlog = mock(Blog.class);
given(blogRepository.findById(mockBlog.getId())).willReturn(Optional.of(mockBlog));
Blog createdBlog = blogService.publish(mockBlog.getId());
InOrder inOrder = inOrder(mockBlog, blogRepository);
inOrder.verify(mockBlog).publish();
inOrder.verify(blogRepository).save(mockBlog);
assertThat(createdBlog).isSameAs(mockBlog);
}
@Test
void should_throw_EntityNotFoundException_when_blog_not_found() {
Blog mockBlog = mock(Blog.class);
given(blogRepository.findById(mockBlog.getId())).willReturn(Optional.empty());
assertThatThrownBy(() -> blogService.publish(mockBlog.getId()))
.isInstanceOf(EntityNotFoundException.class)
.hasMessage("cannot find the blog with id " + mockBlog.getId());
}
}
}
| 35.358696
| 113
| 0.637412
|
983e341dd11648d92dd0653604133918c9a35bf9
| 17,222
|
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.location.suplclient.asn1.supl2.lpp;
// Copyright 2008 Google Inc. All Rights Reserved.
/*
* This class is AUTOMATICALLY GENERATED. Do NOT EDIT.
*/
//
//
import com.google.location.suplclient.asn1.base.Asn1Boolean;
import com.google.location.suplclient.asn1.base.Asn1Object;
import com.google.location.suplclient.asn1.base.Asn1Sequence;
import com.google.location.suplclient.asn1.base.Asn1Tag;
import com.google.location.suplclient.asn1.base.BitStream;
import com.google.location.suplclient.asn1.base.BitStreamReader;
import com.google.location.suplclient.asn1.base.SequenceComponent;
import com.google.common.collect.ImmutableList;
import java.util.Collection;
import javax.annotation.Nullable;
/**
*
*/
public class A_GNSS_RequestCapabilities extends Asn1Sequence {
//
private static final Asn1Tag TAG_A_GNSS_RequestCapabilities
= Asn1Tag.fromClassAndNumber(-1, -1);
public A_GNSS_RequestCapabilities() {
super();
}
@Override
@Nullable
protected Asn1Tag getTag() {
return TAG_A_GNSS_RequestCapabilities;
}
@Override
protected boolean isTagImplicit() {
return true;
}
public static Collection<Asn1Tag> getPossibleFirstTags() {
if (TAG_A_GNSS_RequestCapabilities != null) {
return ImmutableList.of(TAG_A_GNSS_RequestCapabilities);
} else {
return Asn1Sequence.getPossibleFirstTags();
}
}
/**
* Creates a new A_GNSS_RequestCapabilities from encoded stream.
*/
public static A_GNSS_RequestCapabilities fromPerUnaligned(byte[] encodedBytes) {
A_GNSS_RequestCapabilities result = new A_GNSS_RequestCapabilities();
result.decodePerUnaligned(new BitStreamReader(encodedBytes));
return result;
}
/**
* Creates a new A_GNSS_RequestCapabilities from encoded stream.
*/
public static A_GNSS_RequestCapabilities fromPerAligned(byte[] encodedBytes) {
A_GNSS_RequestCapabilities result = new A_GNSS_RequestCapabilities();
result.decodePerAligned(new BitStreamReader(encodedBytes));
return result;
}
@Override protected boolean isExtensible() {
return true;
}
@Override public boolean containsExtensionValues() {
for (SequenceComponent extensionComponent : getExtensionComponents()) {
if (extensionComponent.isExplicitlySet()) return true;
}
return false;
}
private A_GNSS_RequestCapabilities.gnss_SupportListReqType gnss_SupportListReq_;
public A_GNSS_RequestCapabilities.gnss_SupportListReqType getGnss_SupportListReq() {
return gnss_SupportListReq_;
}
/**
* @throws ClassCastException if value is not a A_GNSS_RequestCapabilities.gnss_SupportListReqType
*/
public void setGnss_SupportListReq(Asn1Object value) {
this.gnss_SupportListReq_ = (A_GNSS_RequestCapabilities.gnss_SupportListReqType) value;
}
public A_GNSS_RequestCapabilities.gnss_SupportListReqType setGnss_SupportListReqToNewInstance() {
gnss_SupportListReq_ = new A_GNSS_RequestCapabilities.gnss_SupportListReqType();
return gnss_SupportListReq_;
}
private A_GNSS_RequestCapabilities.assistanceDataSupportListReqType assistanceDataSupportListReq_;
public A_GNSS_RequestCapabilities.assistanceDataSupportListReqType getAssistanceDataSupportListReq() {
return assistanceDataSupportListReq_;
}
/**
* @throws ClassCastException if value is not a A_GNSS_RequestCapabilities.assistanceDataSupportListReqType
*/
public void setAssistanceDataSupportListReq(Asn1Object value) {
this.assistanceDataSupportListReq_ = (A_GNSS_RequestCapabilities.assistanceDataSupportListReqType) value;
}
public A_GNSS_RequestCapabilities.assistanceDataSupportListReqType setAssistanceDataSupportListReqToNewInstance() {
assistanceDataSupportListReq_ = new A_GNSS_RequestCapabilities.assistanceDataSupportListReqType();
return assistanceDataSupportListReq_;
}
private A_GNSS_RequestCapabilities.locationVelocityTypesReqType locationVelocityTypesReq_;
public A_GNSS_RequestCapabilities.locationVelocityTypesReqType getLocationVelocityTypesReq() {
return locationVelocityTypesReq_;
}
/**
* @throws ClassCastException if value is not a A_GNSS_RequestCapabilities.locationVelocityTypesReqType
*/
public void setLocationVelocityTypesReq(Asn1Object value) {
this.locationVelocityTypesReq_ = (A_GNSS_RequestCapabilities.locationVelocityTypesReqType) value;
}
public A_GNSS_RequestCapabilities.locationVelocityTypesReqType setLocationVelocityTypesReqToNewInstance() {
locationVelocityTypesReq_ = new A_GNSS_RequestCapabilities.locationVelocityTypesReqType();
return locationVelocityTypesReq_;
}
@Override public Iterable<? extends SequenceComponent> getComponents() {
ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder();
builder.add(new SequenceComponent() {
Asn1Tag tag = Asn1Tag.fromClassAndNumber(2, 0);
@Override public boolean isExplicitlySet() {
return getGnss_SupportListReq() != null;
}
@Override public boolean hasDefaultValue() {
return false;
}
@Override public boolean isOptional() {
return false;
}
@Override public Asn1Object getComponentValue() {
return getGnss_SupportListReq();
}
@Override public void setToNewInstance() {
setGnss_SupportListReqToNewInstance();
}
@Override public Collection<Asn1Tag> getPossibleFirstTags() {
return tag == null ? A_GNSS_RequestCapabilities.gnss_SupportListReqType.getPossibleFirstTags() : ImmutableList.of(tag);
}
@Override
public Asn1Tag getTag() {
return tag;
}
@Override
public boolean isImplicitTagging() {
return true;
}
@Override public String toIndentedString(String indent) {
return "gnss_SupportListReq : "
+ getGnss_SupportListReq().toIndentedString(indent);
}
});
builder.add(new SequenceComponent() {
Asn1Tag tag = Asn1Tag.fromClassAndNumber(2, 1);
@Override public boolean isExplicitlySet() {
return getAssistanceDataSupportListReq() != null;
}
@Override public boolean hasDefaultValue() {
return false;
}
@Override public boolean isOptional() {
return false;
}
@Override public Asn1Object getComponentValue() {
return getAssistanceDataSupportListReq();
}
@Override public void setToNewInstance() {
setAssistanceDataSupportListReqToNewInstance();
}
@Override public Collection<Asn1Tag> getPossibleFirstTags() {
return tag == null ? A_GNSS_RequestCapabilities.assistanceDataSupportListReqType.getPossibleFirstTags() : ImmutableList.of(tag);
}
@Override
public Asn1Tag getTag() {
return tag;
}
@Override
public boolean isImplicitTagging() {
return true;
}
@Override public String toIndentedString(String indent) {
return "assistanceDataSupportListReq : "
+ getAssistanceDataSupportListReq().toIndentedString(indent);
}
});
builder.add(new SequenceComponent() {
Asn1Tag tag = Asn1Tag.fromClassAndNumber(2, 2);
@Override public boolean isExplicitlySet() {
return getLocationVelocityTypesReq() != null;
}
@Override public boolean hasDefaultValue() {
return false;
}
@Override public boolean isOptional() {
return false;
}
@Override public Asn1Object getComponentValue() {
return getLocationVelocityTypesReq();
}
@Override public void setToNewInstance() {
setLocationVelocityTypesReqToNewInstance();
}
@Override public Collection<Asn1Tag> getPossibleFirstTags() {
return tag == null ? A_GNSS_RequestCapabilities.locationVelocityTypesReqType.getPossibleFirstTags() : ImmutableList.of(tag);
}
@Override
public Asn1Tag getTag() {
return tag;
}
@Override
public boolean isImplicitTagging() {
return true;
}
@Override public String toIndentedString(String indent) {
return "locationVelocityTypesReq : "
+ getLocationVelocityTypesReq().toIndentedString(indent);
}
});
return builder.build();
}
@Override public Iterable<? extends SequenceComponent>
getExtensionComponents() {
ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder();
return builder.build();
}
// Copyright 2008 Google Inc. All Rights Reserved.
/*
* This class is AUTOMATICALLY GENERATED. Do NOT EDIT.
*/
//
/**
*
*/
public static class gnss_SupportListReqType extends Asn1Boolean {
//
private static final Asn1Tag TAG_gnss_SupportListReqType
= Asn1Tag.fromClassAndNumber(-1, -1);
public gnss_SupportListReqType() {
super();
}
@Override
@Nullable
protected Asn1Tag getTag() {
return TAG_gnss_SupportListReqType;
}
@Override
protected boolean isTagImplicit() {
return true;
}
public static Collection<Asn1Tag> getPossibleFirstTags() {
if (TAG_gnss_SupportListReqType != null) {
return ImmutableList.of(TAG_gnss_SupportListReqType);
} else {
return Asn1Boolean.getPossibleFirstTags();
}
}
/**
* Creates a new gnss_SupportListReqType from encoded stream.
*/
public static gnss_SupportListReqType fromPerUnaligned(byte[] encodedBytes) {
gnss_SupportListReqType result = new gnss_SupportListReqType();
result.decodePerUnaligned(new BitStreamReader(encodedBytes));
return result;
}
/**
* Creates a new gnss_SupportListReqType from encoded stream.
*/
public static gnss_SupportListReqType fromPerAligned(byte[] encodedBytes) {
gnss_SupportListReqType result = new gnss_SupportListReqType();
result.decodePerAligned(new BitStreamReader(encodedBytes));
return result;
}
@Override public Iterable<BitStream> encodePerUnaligned() {
return super.encodePerUnaligned();
}
@Override public Iterable<BitStream> encodePerAligned() {
return super.encodePerAligned();
}
@Override public void decodePerUnaligned(BitStreamReader reader) {
super.decodePerUnaligned(reader);
}
@Override public void decodePerAligned(BitStreamReader reader) {
super.decodePerAligned(reader);
}
@Override public String toString() {
return toIndentedString("");
}
public String toIndentedString(String indent) {
return "gnss_SupportListReqType = " + getValue() + ";\n";
}
}
// Copyright 2008 Google Inc. All Rights Reserved.
/*
* This class is AUTOMATICALLY GENERATED. Do NOT EDIT.
*/
//
/**
*
*/
public static class assistanceDataSupportListReqType extends Asn1Boolean {
//
private static final Asn1Tag TAG_assistanceDataSupportListReqType
= Asn1Tag.fromClassAndNumber(-1, -1);
public assistanceDataSupportListReqType() {
super();
}
@Override
@Nullable
protected Asn1Tag getTag() {
return TAG_assistanceDataSupportListReqType;
}
@Override
protected boolean isTagImplicit() {
return true;
}
public static Collection<Asn1Tag> getPossibleFirstTags() {
if (TAG_assistanceDataSupportListReqType != null) {
return ImmutableList.of(TAG_assistanceDataSupportListReqType);
} else {
return Asn1Boolean.getPossibleFirstTags();
}
}
/**
* Creates a new assistanceDataSupportListReqType from encoded stream.
*/
public static assistanceDataSupportListReqType fromPerUnaligned(byte[] encodedBytes) {
assistanceDataSupportListReqType result = new assistanceDataSupportListReqType();
result.decodePerUnaligned(new BitStreamReader(encodedBytes));
return result;
}
/**
* Creates a new assistanceDataSupportListReqType from encoded stream.
*/
public static assistanceDataSupportListReqType fromPerAligned(byte[] encodedBytes) {
assistanceDataSupportListReqType result = new assistanceDataSupportListReqType();
result.decodePerAligned(new BitStreamReader(encodedBytes));
return result;
}
@Override public Iterable<BitStream> encodePerUnaligned() {
return super.encodePerUnaligned();
}
@Override public Iterable<BitStream> encodePerAligned() {
return super.encodePerAligned();
}
@Override public void decodePerUnaligned(BitStreamReader reader) {
super.decodePerUnaligned(reader);
}
@Override public void decodePerAligned(BitStreamReader reader) {
super.decodePerAligned(reader);
}
@Override public String toString() {
return toIndentedString("");
}
public String toIndentedString(String indent) {
return "assistanceDataSupportListReqType = " + getValue() + ";\n";
}
}
// Copyright 2008 Google Inc. All Rights Reserved.
/*
* This class is AUTOMATICALLY GENERATED. Do NOT EDIT.
*/
//
/**
*
*/
public static class locationVelocityTypesReqType extends Asn1Boolean {
//
private static final Asn1Tag TAG_locationVelocityTypesReqType
= Asn1Tag.fromClassAndNumber(-1, -1);
public locationVelocityTypesReqType() {
super();
}
@Override
@Nullable
protected Asn1Tag getTag() {
return TAG_locationVelocityTypesReqType;
}
@Override
protected boolean isTagImplicit() {
return true;
}
public static Collection<Asn1Tag> getPossibleFirstTags() {
if (TAG_locationVelocityTypesReqType != null) {
return ImmutableList.of(TAG_locationVelocityTypesReqType);
} else {
return Asn1Boolean.getPossibleFirstTags();
}
}
/**
* Creates a new locationVelocityTypesReqType from encoded stream.
*/
public static locationVelocityTypesReqType fromPerUnaligned(byte[] encodedBytes) {
locationVelocityTypesReqType result = new locationVelocityTypesReqType();
result.decodePerUnaligned(new BitStreamReader(encodedBytes));
return result;
}
/**
* Creates a new locationVelocityTypesReqType from encoded stream.
*/
public static locationVelocityTypesReqType fromPerAligned(byte[] encodedBytes) {
locationVelocityTypesReqType result = new locationVelocityTypesReqType();
result.decodePerAligned(new BitStreamReader(encodedBytes));
return result;
}
@Override public Iterable<BitStream> encodePerUnaligned() {
return super.encodePerUnaligned();
}
@Override public Iterable<BitStream> encodePerAligned() {
return super.encodePerAligned();
}
@Override public void decodePerUnaligned(BitStreamReader reader) {
super.decodePerUnaligned(reader);
}
@Override public void decodePerAligned(BitStreamReader reader) {
super.decodePerAligned(reader);
}
@Override public String toString() {
return toIndentedString("");
}
public String toIndentedString(String indent) {
return "locationVelocityTypesReqType = " + getValue() + ";\n";
}
}
@Override public Iterable<BitStream> encodePerUnaligned() {
return super.encodePerUnaligned();
}
@Override public Iterable<BitStream> encodePerAligned() {
return super.encodePerAligned();
}
@Override public void decodePerUnaligned(BitStreamReader reader) {
super.decodePerUnaligned(reader);
}
@Override public void decodePerAligned(BitStreamReader reader) {
super.decodePerAligned(reader);
}
@Override public String toString() {
return toIndentedString("");
}
public String toIndentedString(String indent) {
StringBuilder builder = new StringBuilder();
builder.append("A_GNSS_RequestCapabilities = {\n");
final String internalIndent = indent + " ";
for (SequenceComponent component : getComponents()) {
if (component.isExplicitlySet()) {
builder.append(internalIndent)
.append(component.toIndentedString(internalIndent));
}
}
if (isExtensible()) {
builder.append(internalIndent).append("...\n");
for (SequenceComponent component : getExtensionComponents()) {
if (component.isExplicitlySet()) {
builder.append(internalIndent)
.append(component.toIndentedString(internalIndent));
}
}
}
builder.append(indent).append("};\n");
return builder.toString();
}
}
| 29.091216
| 140
| 0.705609
|
bc9227e21a7da026d4ca4de1aebbdc25f7c00e7b
| 1,290
|
package com.penglecode.xmodule.rabbitmq.examples.example1;
import com.penglecode.xmodule.rabbitmq.examples.AbstractSpringAmqpExample;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
/**
* 示例1:简单队列(模式):一个生产者对应一个消费者
*
* @author pengpeng
* @version 1.0
* @since 2021/11/10 13:52
*/
public class Example1SpringAmqpConsumer extends AbstractSpringAmqpExample {
private final String queueName = "springamqp_simplest_queue";
@Test
public void consume() throws Exception {
System.out.println("【Example1Consumer】消费启动...");
Thread.currentThread().join();
}
/**
* queuesToDeclare:自动声明queue(如果该队列不存在的话)
*/
@RabbitListener(ackMode="NONE", queuesToDeclare=@Queue(name=queueName, durable="true", autoDelete="false"))
public void handleMessage(Message message) {
System.out.println("=====================================================================================");
System.out.println("【Example1Consumer】message.properties:" + message.getMessageProperties());
System.out.println("【Example1Consumer】message.body:" + new String(message.getBody()));
}
}
| 34.864865
| 116
| 0.683721
|
82e30f02ed5fe88a4d489498f4a16fca108d89b4
| 2,489
|
package io.smallrye.mutiny.operators.uni.builders;
import static io.smallrye.mutiny.helpers.EmptyUniSubscription.propagateFailureEvent;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
import io.smallrye.mutiny.operators.AbstractUni;
import io.smallrye.mutiny.subscription.UniSubscriber;
import io.smallrye.mutiny.subscription.UniSubscription;
public class UniCreateFromCompletionStage<T> extends AbstractUni<T> {
private final Supplier<? extends CompletionStage<? extends T>> supplier;
public UniCreateFromCompletionStage(Supplier<? extends CompletionStage<? extends T>> supplier) {
this.supplier = supplier; // Already checked
}
@Override
public void subscribe(UniSubscriber<? super T> subscriber) {
CompletionStage<? extends T> stage;
try {
stage = supplier.get();
} catch (Throwable e) {
propagateFailureEvent(subscriber, e);
return;
}
if (stage == null) {
propagateFailureEvent(subscriber, new NullPointerException("The produced CompletionStage is `null`"));
return;
}
new CompletionStageUniSubscription<T>(subscriber, stage).forward();
}
static class CompletionStageUniSubscription<T> implements UniSubscription {
private final UniSubscriber<? super T> subscriber;
private final CompletionStage<? extends T> stage;
private volatile boolean cancelled = false;
CompletionStageUniSubscription(UniSubscriber<? super T> subscriber, CompletionStage<? extends T> stage) {
this.subscriber = subscriber;
this.stage = stage;
}
public void forward() {
subscriber.onSubscribe(this);
stage.whenComplete(this::forwardResult);
}
private void forwardResult(T res, Throwable fail) {
if (!cancelled) {
if (fail != null) {
if (fail instanceof CompletionException) {
subscriber.onFailure(fail.getCause());
} else {
subscriber.onFailure(fail);
}
} else {
subscriber.onItem(res);
}
}
}
@Override
public void cancel() {
cancelled = true;
stage.toCompletableFuture().cancel(false);
}
}
}
| 33.186667
| 114
| 0.62274
|
4210f4e5e5b947729c80e4635ffb616781b9cd25
| 756
|
package jp.co.tis.logic;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;
import oscana.s2n.seasar.framework.beans.util.BeanMap;
import javax.inject.Inject;
import java.io.Serializable;
import oscana.s2n.struts.GenericsUtil;
import nablarch.core.db.connection.DbConnectionContext;
import oscana.s2n.common.ParamFilter;
import nablarch.fw.dicontainer.web.RequestScoped;
import nablarch.fw.dicontainer.web.SessionScoped;
import nablarch.fw.dicontainer.Prototype;
import javax.inject.Singleton;
/**
* 変換用テストデータファイル
*
* @author Ko Ho
*/
@RequestScoped
public class TestAddScopeAnotationToClassLogic extends OscanaAbstractLogic implements Serializable{
}
| 23.625
| 101
| 0.784392
|
ca67213192bae158655b3d507075cb9938f398b3
| 4,045
|
package xyz.gupton.nickolas.beepsky;
import discord4j.core.DiscordClient;
import discord4j.core.GatewayDiscordClient;
import discord4j.core.object.entity.User;
import discord4j.core.object.entity.channel.Channel.Type;
import discord4j.core.object.entity.channel.GuildChannel;
import discord4j.core.object.entity.channel.MessageChannel;
import discord4j.core.spec.EmbedCreateSpec;
import discord4j.core.spec.MessageCreateSpec;
import discord4j.rest.util.Color;
import discord4j.rest.util.Permission;
import discord4j.rest.util.PermissionSet;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.ServiceLoader;
/**
* General utilities required by the bot.
*/
public class BotUtils {
static final String VERSION = BotUtils.class.getPackage().getImplementationVersion();
public static DiscordClient CLIENT;
public static GatewayDiscordClient GATEWAY;
public static final String PREFIX = ";";
public static final ServiceLoader<Command> commands = ServiceLoader.load(Command.class);
static long startTime;
/**
* Sends a message with default color (dark gray).
*
* @param channel MessageChannel, channel to send the message to.
* @param author User, author of the original commands we are replying to.
* @param title String, title of the message to send.
* @param description String, body of the message to send.
*/
public static void sendMessage(MessageChannel channel, User author, String title,
String description) {
sendMessage(channel, author, title, description, Color.of(44, 47, 51));
}
/**
* Sends a message.
*
* @param channel MessageChannel, channel to send the message to.
* @param author User, author of the original commands we are replying to.
* @param title String, title of the message to send.
* @param description String, body of the message to send.
* @param color Color, color of the message to send.
*/
public static void sendMessage(MessageChannel channel, User author, String title,
String description, Color color) {
if (channel.getType() == Type.GUILD_TEXT) {
PermissionSet ps = ((GuildChannel) channel)
.getEffectivePermissions(BotUtils.GATEWAY.getSelfId()).block();
if (ps != null && !ps.contains(Permission.SEND_MESSAGES)) {
return;
}
}
channel.createMessage(
MessageCreateSpec.builder()
.addEmbed(
EmbedCreateSpec.builder()
.title(title)
.description(description)
.footer("Requested by: " + author.getUsername() + '#' + author.getDiscriminator()
+ " | Version: " + VERSION, null)
.color(color)
.build()
).build()
).block();
//TODO: replace this with ScheduledExecutorService
//if its not a private channel cleanup the messages after a few minutes
//if (channel.getType() != Type.DM) {
// Timer timer = new Timer();
// timer.schedule(new TimerTask() {
// @Override
// public void run() {
// try {
// message.block().delete();
// } catch (NullPointerException e) {
// e.printStackTrace();
// }
// }
// }, TimeUnit.MINUTES.toMillis(5));
//}
}
/**
* Tests if the provided user is banned.
*
* @param userId String, ID of the Discord user to check.
* @return boolean, true if they are banned
*/
public static boolean isBanned(String userId) {
try (BufferedReader banBuffer =
Files.newBufferedReader(Path.of("banned.txt"), StandardCharsets.UTF_8)) {
String line;
while ((line = banBuffer.readLine()) != null) {
if (line.equals(userId)) {
banBuffer.close();
return true;
}
}
return false;
} catch (NoSuchFileException e) {
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
| 32.620968
| 91
| 0.670952
|
fa2b872c479903196c097cc0a880c9384ba597e7
| 11,445
|
package net.smackem.jobotwar.lang;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.List;
import java.util.Objects;
/**
* Executes a compiled {@link Program}.
*/
public final class Interpreter {
private static final Logger log = LoggerFactory.getLogger(Interpreter.class);
private final Program program;
private final List<Instruction> code;
private final RuntimeEnvironment runtime;
private final java.util.Stack<Integer> stackFrames = new java.util.Stack<>();//
private final Stack stack = new Stack();
private boolean registerStored;
private boolean yield;
private int pc;
/**
* Initializes a new instance of {@link Interpreter}.
* @param program The {@link Program} to execute.
* @param runtime The {@link RuntimeEnvironment} that provides access to
* robot registers and sensors.
*/
public Interpreter(Program program, RuntimeEnvironment runtime) {
this.program = Objects.requireNonNull(program);
this.code = new ArrayList<>(program.instructions());
this.runtime = Objects.requireNonNull(runtime);
}
/**
* @return The {@link Program} to execute.
*/
public Program program() {
return this.program;
}
/**
* @return The {@link RuntimeEnvironment} that provides access to robot registers and sensors.
*/
public RuntimeEnvironment runtime() {
return this.runtime;
}
/**
* Executes the next program step.
* @return {@code true} if the program is not at its end, {@code false} if it has executed completely
* @throws StackException in the case of a stack underflow or overflow.
*/
public boolean runNext() throws StackException {
final int codeSize = this.code.size();
while (this.pc < codeSize) {
final int target;
final Instruction instr = this.code.get(this.pc);
try {
target = executeInstruction(instr);
} catch (StackException e) {
e.pc = this.pc;
e.instruction = instr;
throw e;
} catch (EmptyStackException e) {
final StackException se = new StackException("Return without stack frame");
se.pc = this.pc;
se.instruction = instr;
throw se;
}
if (target >= 0) {
this.pc = target;
} else {
this.pc++;
}
if (this.yield) {
return true;
}
}
return false;
}
private int stackFrameOffset() {
return this.stackFrames.size() > 0 ? this.stackFrames.peek() : 0;
}
private int executeInstruction(Instruction instr) throws StackException {
this.yield = false;
switch (instr.opCode()) {
case LD_F64 -> this.stack.push(instr.f64Arg());
case LD_REG -> this.stack.push(loadRegister(instr.strArg()));
case LD_LOC -> this.stack.push(this.stack.get(stackFrameOffset() + instr.intArg()));
case LD_GLB -> this.stack.push(this.stack.get(instr.intArg()));
case ST_GLB -> {
final double right = this.stack.pop();
this.stack.set(instr.intArg(), right);
}
case ST_LOC -> {
final double right = this.stack.pop();
this.stack.set(stackFrameOffset() + instr.intArg(), right);
}
case ST_REG -> {
final double right = this.stack.pop();
storeRegister(instr.strArg(), right);
this.registerStored = true;
}
case ADD -> this.stack.push(this.stack.pop() + this.stack.pop());
case SUB -> {
final double right = this.stack.pop();
this.stack.push(this.stack.pop() - right);
}
case MUL -> this.stack.push(this.stack.pop() * this.stack.pop());
case DIV -> {
final double right = this.stack.pop();
this.stack.push(this.stack.pop() / right);
}
case MOD -> {
final double right = this.stack.pop();
this.stack.push(this.stack.pop() % right);
}
case OR -> {
final double right = this.stack.pop();
this.stack.push(toDouble(toBool(this.stack.pop()) || toBool(right)));
}
case AND -> {
final double right = this.stack.pop();
this.stack.push(toDouble(toBool(this.stack.pop()) && toBool(right)));
}
case EQ -> this.stack.push(toDouble(this.stack.pop() == this.stack.pop()));
case NEQ -> this.stack.push(toDouble(this.stack.pop() != this.stack.pop()));
case GT -> {
final double right = this.stack.pop();
this.stack.push(toDouble(this.stack.pop() > right));
}
case GE -> {
final double right = this.stack.pop();
this.stack.push(toDouble(this.stack.pop() >= right));
}
case LT -> {
final double right = this.stack.pop();
this.stack.push(toDouble(this.stack.pop() < right));
}
case LE -> {
final double right = this.stack.pop();
this.stack.push(toDouble(this.stack.pop() <= right));
}
case LABEL -> {
if (this.registerStored) {
this.registerStored = false;
this.yield = true;
}
}
case BR -> {
this.yield = true;
return instr.intArg();
}
case BR_ZERO -> {
if (toBool(this.stack.pop()) == false) {
return instr.intArg();
}
}
case DUP -> {
final double right = this.stack.pop();
this.stack.push(right);
this.stack.push(right);
}
case NOT -> this.stack.push(toDouble(toBool(this.stack.pop()) == false));
case INVOKE -> this.stack.push(invoke(instr.strArg(), this.stack.pop()));
case CALL -> {
this.yield = true;
final double argCount = this.stack.pop();
this.stack.insert(this.stack.tail - (int)argCount, this.pc + 1);
this.stackFrames.push(this.stack.tail - (int)argCount);
return instr.intArg();
}
case RET -> {
this.yield = true;
this.stack.tail = this.stackFrames.pop();
return (int) this.stack.pop();
}
case RET_VAL -> {
this.yield = true;
final double retVal = this.stack.pop(); // return value
this.stack.tail = this.stackFrames.pop();
final int retPC = (int) this.stack.pop();
this.stack.push(retVal);
return retPC;
}
case LOG -> this.runtime.log(instr.strArg(), this.stack.pop());
case SWAP -> {
final double right = this.stack.pop();
final double left = this.stack.pop();
this.stack.push(right);
this.stack.push(left);
}
}
return -1;
}
private double invoke(String strArg, double arg) throws StackException {
return switch (strArg) {
case "abs" -> Math.abs(arg);
case "tan" -> Math.tan(Math.toRadians(arg));
case "sin" -> Math.sin(Math.toRadians(arg));
case "cos" -> Math.cos(Math.toRadians(arg));
case "atan" -> Math.toDegrees(Math.atan(arg));
case "asin" -> Math.toDegrees(Math.asin(arg));
case "acos" -> Math.toDegrees(Math.acos(arg));
case "sqrt" -> Math.sqrt(arg);
case "trunc" -> Math.floor(arg);
case "sign" -> Math.signum(arg);
case "min" -> Math.min(this.stack.pop(), arg);
case "max" -> Math.max(this.stack.pop(), arg);
case "hypot" -> Math.hypot(arg, this.stack.pop());
case "atan2" -> Math.toDegrees(Math.atan2(this.stack.pop(), arg));
default -> throw new IllegalArgumentException("Unknown built-in function: '" + strArg + "'");
};
}
private double loadRegister(String strArg) {
return switch (strArg) {
case "AIM" -> this.runtime.readAim();
case "RADAR" -> this.runtime.readRadar();
case "SPEEDX" -> this.runtime.readSpeedX();
case "SPEEDY" -> this.runtime.readSpeedY();
case "X" -> this.runtime.readX();
case "Y" -> this.runtime.readY();
case "DAMAGE" -> this.runtime.readDamage();
case "SHOT" -> this.runtime.readShot();
case "RANDOM" -> this.runtime.getRandom();
default -> throw new IllegalArgumentException("Unknown register: '" + strArg + "'");
};
}
private void storeRegister(String strArg, double d) {
switch (strArg) {
case "AIM" -> this.runtime.writeAim(d);
case "RADAR" -> this.runtime.writeRadar(d);
case "SPEEDX" -> this.runtime.writeSpeedX(d);
case "SPEEDY" -> this.runtime.writeSpeedY(d);
case "SHOT" -> this.runtime.writeShot(d);
default -> throw new IllegalArgumentException("Unknown register: '" + strArg + "'");
}
}
private static boolean toBool(double d) {
return d != 0.0;
}
private static double toDouble(boolean b) {
return b ? 1.0 : 0.0;
}
private static class Stack {
final double[] array = new double[64];
int tail;
void push(double d) throws StackException {
if (this.tail >= array.length) {
throw new StackException("Stack overflow");
}
this.array[this.tail] = d;
this.tail++;
}
double pop() throws StackException {
if (this.tail <= 0) {
throw new StackException("Stack underflow");
}
this.tail--;
return this.array[this.tail];
}
void insert(int index, double value) {
Objects.checkIndex(index, this.tail + 1);
if (index < this.tail) {
System.arraycopy(this.array, index, this.array, index + 1, this.tail - index);
}
this.array[index] = value;
this.tail++;
}
double get(int i) {
Objects.checkIndex(i, this.tail);
return this.array[i];
}
void set(int i, double d) {
Objects.checkIndex(i, this.tail);
this.array[i] = d;
}
}
public static class StackException extends Exception {
private int pc;
private Instruction instruction;
private StackException(String message) {
super(message);
}
public int pc() {
return this.pc;
}
public Instruction instruction() {
return this.instruction;
}
}
}
| 36.449045
| 105
| 0.517868
|
81fdd2e400c3bee1d2fae9dfe66ff127a693bff6
| 1,560
|
/*******************************************************************************
* Copyright (c) 2016 Royal Bank of Scotland
*
* 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.std.ie.ethiso.iso.domain;
import com.fasterxml.jackson.annotation.JsonProperty;
public class OriginalGroupInformation {
private String originalMessageIdentification;
private String originalMessageName;
@JsonProperty("OrgnlMsgId")
public String getOriginalMessageIdentification() {
return originalMessageIdentification;
}
public void setOriginalMessageIdentification(String originalMessageIdentification) {
this.originalMessageIdentification = originalMessageIdentification;
}
@JsonProperty("OrgnlMsgNmId")
public String getOriginalMessageName() {
return originalMessageName;
}
public void setOriginalMessageName(String originalMessageName) {
this.originalMessageName = originalMessageName;
}
}
| 35.454545
| 88
| 0.677564
|
1e72580f82692cf6d77c27e54e1315da4552e9d6
| 2,244
|
/*
* MIT License (MIT)
* Copyright © 2016 WISEKIDDO.com - https://github.com/wisekiddo/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
* IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package com.wisekiddo.library.transition.indicators;
import android.animation.ValueAnimator;
import java.util.ArrayList;
/**
*/
public class LineScalePulseOutIndicator extends LineScaleIndicator {
@Override
public ArrayList<ValueAnimator> onCreateAnimators() {
ArrayList<ValueAnimator> animators=new ArrayList<>();
long[] delays=new long[]{500,250,0,250,500};
for (int i = 0; i < 5; i++) {
final int index=i;
ValueAnimator scaleAnim=ValueAnimator.ofFloat(1,0.3f,1);
scaleAnim.setDuration(900);
scaleAnim.setRepeatCount(-1);
scaleAnim.setStartDelay(delays[i]);
addUpdateListener(scaleAnim,new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
scaleYFloats[index] = (float) animation.getAnimatedValue();
postInvalidate();
}
});
animators.add(scaleAnim);
}
return animators;
}
}
| 39.368421
| 84
| 0.688503
|
d9a3b48a5b4fbf9960e4ff98be9dc3495a9b0f68
| 4,110
|
/*
* Copyright (C) 2011 Everit Kft. (http://www.everit.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.everit.jira.querydsl.schema;
import static com.querydsl.core.types.PathMetadataFactory.*;
import com.querydsl.core.types.dsl.*;
import com.querydsl.core.types.PathMetadata;
import javax.annotation.Generated;
import com.querydsl.core.types.Path;
import com.querydsl.sql.ColumnMetadata;
import java.sql.Types;
/**
* QCwdMembership is a Querydsl query type for QCwdMembership
*/
@Generated("com.querydsl.sql.codegen.MetaDataSerializer")
public class QCwdMembership extends com.querydsl.sql.RelationalPathBase<QCwdMembership> {
private static final long serialVersionUID = 1115609902;
public static final QCwdMembership cwdMembership = new QCwdMembership("cwd_membership");
public final NumberPath<Long> childId = createNumber("childId", Long.class);
public final StringPath childName = createString("childName");
public final NumberPath<Long> directoryId = createNumber("directoryId", Long.class);
public final StringPath groupType = createString("groupType");
public final NumberPath<Long> id = createNumber("id", Long.class);
public final StringPath lowerChildName = createString("lowerChildName");
public final StringPath lowerParentName = createString("lowerParentName");
public final StringPath membershipType = createString("membershipType");
public final NumberPath<Long> parentId = createNumber("parentId", Long.class);
public final StringPath parentName = createString("parentName");
public final com.querydsl.sql.PrimaryKey<QCwdMembership> cwdMembershipPk = createPrimaryKey(id);
public QCwdMembership(String variable) {
super(QCwdMembership.class, forVariable(variable), "public", "cwd_membership");
addMetadata();
}
public QCwdMembership(String variable, String schema, String table) {
super(QCwdMembership.class, forVariable(variable), schema, table);
addMetadata();
}
public QCwdMembership(Path<? extends QCwdMembership> path) {
super(path.getType(), path.getMetadata(), "public", "cwd_membership");
addMetadata();
}
public QCwdMembership(PathMetadata metadata) {
super(QCwdMembership.class, metadata, "public", "cwd_membership");
addMetadata();
}
public void addMetadata() {
addMetadata(childId, ColumnMetadata.named("child_id").withIndex(3).ofType(Types.NUMERIC).withSize(18));
addMetadata(childName, ColumnMetadata.named("child_name").withIndex(8).ofType(Types.VARCHAR).withSize(255));
addMetadata(directoryId, ColumnMetadata.named("directory_id").withIndex(10).ofType(Types.NUMERIC).withSize(18));
addMetadata(groupType, ColumnMetadata.named("group_type").withIndex(5).ofType(Types.VARCHAR).withSize(60));
addMetadata(id, ColumnMetadata.named("id").withIndex(1).ofType(Types.NUMERIC).withSize(18).notNull());
addMetadata(lowerChildName, ColumnMetadata.named("lower_child_name").withIndex(9).ofType(Types.VARCHAR).withSize(255));
addMetadata(lowerParentName, ColumnMetadata.named("lower_parent_name").withIndex(7).ofType(Types.VARCHAR).withSize(255));
addMetadata(membershipType, ColumnMetadata.named("membership_type").withIndex(4).ofType(Types.VARCHAR).withSize(60));
addMetadata(parentId, ColumnMetadata.named("parent_id").withIndex(2).ofType(Types.NUMERIC).withSize(18));
addMetadata(parentName, ColumnMetadata.named("parent_name").withIndex(6).ofType(Types.VARCHAR).withSize(255));
}
}
| 41.515152
| 129
| 0.741363
|
ecd86f8e59bccfd1748815900cd9e7ec30eb1356
| 5,841
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0.5-b02-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2007.08.13 at 09:28:43 PM MSD
//
package org.riverock.webmill.template.schema;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="charset" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="defer">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN">
* <enumeration value="defer"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" />
* <attribute name="src" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="type" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute ref="{http://www.w3.org/XML/1998/namespace}space fixed="preserve""/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"content"
})
@XmlRootElement(name = "script")
public class Script {
@XmlValue
protected String content;
@XmlAttribute
protected String charset;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String defer;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
protected String id;
@XmlAttribute
protected String src;
@XmlAttribute(required = true)
protected String type;
@XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String space;
/**
* Gets the value of the content property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContent() {
return content;
}
/**
* Sets the value of the content property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContent(String value) {
this.content = value;
}
/**
* Gets the value of the charset property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCharset() {
return charset;
}
/**
* Sets the value of the charset property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCharset(String value) {
this.charset = value;
}
/**
* Gets the value of the defer property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDefer() {
return defer;
}
/**
* Sets the value of the defer property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDefer(String value) {
this.defer = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the src property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSrc() {
return src;
}
/**
* Sets the value of the src property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSrc(String value) {
this.src = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the space property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSpace() {
if (space == null) {
return "preserve";
} else {
return space;
}
}
/**
* Sets the value of the space property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSpace(String value) {
this.space = value;
}
}
| 23.457831
| 117
| 0.557952
|
e05fb1ad9688dcc538926d7f9829283c046869dc
| 3,982
|
package com.atexpose.dispatcher.channels;
import com.atexpose.ProjectProperties;
import com.atexpose.errors.RuntimeError;
import com.atexpose.util.ByteStorage;
import com.atexpose.util.FileRW;
import io.schinzel.basicutils.Checker;
import io.schinzel.basicutils.UTF8;
import io.schinzel.basicutils.state.State;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
/**
* The purpose of this class is to read a text file containing one or several commands.
*
* @author Schinzel
*/
public class ScriptFileChannel implements IChannel {
/** If a line starts with a comment qualifier, that line is ignored. */
private static final String COMMENT_QUALIFIER = "#";
/** The name of the file to read. */
private final String mFilename;
/** The time it took to read a line. For logging and statistics. */
private long mLineReadTime;
/** Used to read the file. */
private final BufferedReader mBufferedReader;
//------------------------------------------------------------------------
// CONSTRUCTORS AND SHUTDOWN
//------------------------------------------------------------------------
/**
* @param filename The name of the file to read
*/
public ScriptFileChannel(String filename) {
mFilename = filename;
if (Checker.isEmpty(mFilename)) {
throw new RuntimeError("Empty filename was given as argument.");
}
if (!FileRW.fileExists(filename)) {
throw new RuntimeError("No such file or it cannot be read '" + filename + "'");
}
InputStream is = FileRW.getInputStream(filename);
mBufferedReader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
}
@Override
public void shutdown(Thread thread) {
// No need to shutdown a script file reader so no code here
}
@Override
public IChannel getClone() {
throw new RuntimeError("Script File Channels are single threaded.");
}
//------------------------------------------------------------------------
// MESSAGING
//------------------------------------------------------------------------
@Override
public boolean getRequest(ByteStorage request) {
mLineReadTime = System.currentTimeMillis();
String line;
try {
//Read lines, while line is not null
while ((line = mBufferedReader.readLine()) != null
//AND (does not start with a common qualifier OR is not empty)
&& (line.startsWith(COMMENT_QUALIFIER) || line.trim().isEmpty())) {
}
//If was end of file
if (line == null) {
mBufferedReader.close();
return false;
}
} catch (IOException ioe) {
throw new RuntimeException("Error while reading script file " + ioe.toString());
}
request.add(line);
mLineReadTime = System.currentTimeMillis() - mLineReadTime;
return true;
}
@Override
public void writeResponse(byte[] response) {
if (!Checker.isEmpty(response)) {
try {
System.out.write(response);
System.out.write(UTF8.getBytes(ProjectProperties.OS_LINE_SEPARATOR));
} catch (IOException e) {
throw new RuntimeError("Error while writing to CLI.");
}
}
}
@Override
public long responseWriteTime() {
return 0;
}
@Override
public long requestReadTime() {
return mLineReadTime;
}
@Override
public String senderInfo() {
return mFilename;
}
@Override
public State getState() {
return State.getBuilder()
.add("File", mFilename)
.add("CommentQualifier", COMMENT_QUALIFIER)
.build();
}
}
| 30.166667
| 96
| 0.571823
|
cc6cebfc1bc5b88705f69950e91fc87ad0379aa5
| 130
|
import java.lang.*;
class future
{
public static void main(String args[])
{
System.out.println("Yaswanth Marries Soundarya");
}
}
| 14.444444
| 49
| 0.730769
|
95e44e2f736d232a2adea0037c2fd132df5d5e1f
| 7,065
|
package com.jadaptive.app.role;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jadaptive.api.db.SearchField;
import com.jadaptive.api.db.TenantAwareObjectDatabase;
import com.jadaptive.api.entity.ObjectException;
import com.jadaptive.api.permissions.AuthenticatedService;
import com.jadaptive.api.repository.AssignableUUIDEntity;
import com.jadaptive.api.role.Role;
import com.jadaptive.api.role.RoleService;
import com.jadaptive.api.tenant.Tenant;
import com.jadaptive.api.tenant.TenantAware;
import com.jadaptive.api.user.User;
import com.jadaptive.api.user.UserAware;
@Service
public class RoleServiceImpl extends AuthenticatedService implements RoleService, TenantAware, UserAware {
private static final String ADMINISTRATOR_UUID = "1bfbaf16-e5af-4825-8f8a-83ce2f5bf81f";
private static final String EVERYONE_UUID = "c4b54f49-c478-46cc-8cfa-aaebaa4ea50f";
private static final String EVERYONE = "Everyone";
private static final String ADMINISTRATION = "Administration";
@Autowired
private TenantAwareObjectDatabase<Role> repository;
@Override
public Integer getOrder() {
return Integer.MIN_VALUE;
}
@Override
public void initializeSystem(boolean newSchema) {
initializeTenant(getCurrentTenant(), newSchema);
}
@Override
public void initializeTenant(Tenant tenant, boolean newSchema) {
if(newSchema) {
setupDefaultRoles(tenant);
}
}
private void setupDefaultRoles(Tenant tenant) {
Role role = new Role();
role.setUuid(ADMINISTRATOR_UUID);
role.setName(ADMINISTRATION);
role.setSystem(true);
role.setAllPermissions(true);
repository.saveOrUpdate(role);
role = new Role();
role.setUuid(EVERYONE_UUID);
role.setName(EVERYONE);
role.setSystem(true);
role.setAllUsers(true);
repository.saveOrUpdate(role);
}
@Override
public Role getAdministrationRole() {
return repository.get(ADMINISTRATOR_UUID, Role.class);
}
@Override
public Role getEveryoneRole() {
return repository.get(EVERYONE_UUID, Role.class);
}
@Override
public Collection<Role> getRoles(User user) {
Set<Role> roles = new HashSet<>();
roles.addAll(getRolesByUser(user));
roles.addAll(getAllUserRoles());
return roles;
}
@Override
public Role getRoleByName(String name) {
assertRead(Role.RESOURCE_KEY);
return repository.get(Role.class, SearchField.eq("name", name));
}
@Override
public Role createRole(String roleName, User... users) {
return createRole(roleName, Arrays.asList(users));
}
@Override
public Role createRole(String roleName, Collection<User> users) {
assertWrite(Role.RESOURCE_KEY);
Role role = new Role();
role.setName(roleName);
repository.saveOrUpdate(role);
doAssign(role, users.toArray(new User[0]));
return role;
}
@Override
public void assignRole(Role role, User... users) {
assertWrite(Role.RESOURCE_KEY);
doAssign(role, users);
}
private void doAssign(Role role, User... users) {
if(EVERYONE_UUID.equals(role.getUuid())) {
throw new ObjectException("You cannot assign a user to the Everyone role");
}
Set<String> uuids = new HashSet<>();
for(User user : users) {
uuids.add(user.getUuid());
}
role.getUsers().addAll(uuids);
repository.saveOrUpdate(role);
}
@Override
public void grantPermission(Role role, String... permissions) {
assertWrite(Role.RESOURCE_KEY);
Set<String> resolved = new HashSet<>();
for(String permission : permissions) {
if(!isValidPermission(permission)) {
throw new ObjectException(String.format("%s is not a valid permission", permission));
}
if(role.getPermissions().contains(permission)) {
throw new ObjectException(String.format("%s is already granted on %s", permission, role.getName()));
}
resolved.add(permission);
}
role.getPermissions().addAll(resolved);
repository.saveOrUpdate(role);
}
@Override
public void revokePermission(Role role, String... permissions) {
assertWrite(Role.RESOURCE_KEY);
Set<String> resolved = new HashSet<>();
for(String permission : permissions) {
if(!isValidPermission(permission)) {
throw new ObjectException(String.format("%s is not a valid permission", permission));
}
if(!role.getPermissions().contains(permission)) {
throw new ObjectException(String.format("%s is not granted on %s", permission, role.getName()));
}
resolved.add(permission);
}
role.getPermissions().removeAll(resolved);
repository.saveOrUpdate(role);
}
@Override
public void unassignRole(Role role, User... users) {
assertWrite(Role.RESOURCE_KEY);
Set<String> uuids = new HashSet<>();
for(User user : users) {
uuids.add(user.getUuid());
}
if(ADMINISTRATOR_UUID.equals(role.getUuid())) {
Set<String> roleUuids = new HashSet<>(role.getUsers());
roleUuids.removeAll(uuids);
if(roleUuids.isEmpty()) {
throw new ObjectException("This operation would remove the last user from the Administration role");
}
}
if(EVERYONE_UUID.equals(role.getUuid())) {
throw new ObjectException("You cannot unassign a user from the Everyone role");
}
role.getUsers().removeAll(uuids);
repository.saveOrUpdate(role);
}
@Override
public boolean hasRole(User user, Collection<Role> roles) {
Collection<Role> userRoles = getRoles(user);
return !Collections.disjoint(userRoles, roles);
}
@Override
public boolean hasRole(User user, Role... roles) {
return hasRole(user, Arrays.asList(roles));
}
@Override
public void deleteRole(Role role) {
assertWrite(Role.RESOURCE_KEY);
repository.delete(role);
}
@Override
public Iterable<Role> listRoles() {
assertRead(Role.RESOURCE_KEY);
return repository.list(Role.class);
}
@Override
public Role getRoleByUUID(String uuid) {
return repository.get(uuid, Role.class);
}
@Override
public void onDeleteUser(User user) {
for(Role role : repository.list(Role.class)) {
if(role.getUsers().contains(user.getUuid())) {
role.getUsers().remove(user.getUuid());
repository.saveOrUpdate(role);
}
}
}
@Override
public Collection<Role> getRolesByUser(User user) {
List<Role> results = new ArrayList<>(getAllUserRoles());
results.addAll(repository.searchObjects(Role.class, SearchField.in("users", user.getUuid())));
return results;
}
@Override
public Collection<Role> getAllUserRoles() {
return repository.searchObjects(Role.class, SearchField.eq("allUsers", true));
}
@Override
public Iterable<Role> allRoles() {
return repository.list(Role.class);
}
@Override
public boolean isAssigned(AssignableUUIDEntity obj, User user) {
if(obj.getUsers().contains(user.getUuid())) {
return true;
}
for(Role role : getRoles(user)) {
if(obj.getRoles().contains(role.getUuid())) {
return true;
}
}
return false;
}
}
| 24.616725
| 106
| 0.724416
|
c9cabe7b086c22b7b9de0f81584df9ed7d39a818
| 318
|
package space.devport.wertik.tracker.system.struct;
import lombok.Getter;
import space.devport.wertik.tracker.ClientVersion;
public class VersionEntry extends TrackEntry {
@Getter
private final ClientVersion version;
public VersionEntry(ClientVersion version) {
this.version = version;
}
}
| 21.2
| 51
| 0.754717
|
fd439c476607d2a8b4ae20fe496534e20f8b4c0f
| 4,690
|
package org.usfirst.frc.team1746.auton;
import org.usfirst.frc.team1746.robot.Conveyor;
import org.usfirst.frc.team1746.robot.Drivetrain;
import org.usfirst.frc.team1746.robot.GearIntake;
import org.usfirst.frc.team1746.robot.Loader;
import org.usfirst.frc.team1746.robot.Shooter;
import org.usfirst.frc.team1746.robot.subsystems.Turret;
import org.usfirst.frc.team1746.vision.VisionBase;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class AutonBase {
SendableChooser<String> autonSelector = new SendableChooser<>();
SendableChooser<String> allianceSelector = new SendableChooser<>();
SendableChooser<Boolean> shootSelector = new SendableChooser<>();
private Drivetrain m_drive;
private GearIntake m_gear;
private Loader m_loader;
private Shooter m_shooter;
private Conveyor m_conveyor;
private VisionBase m_vision;
private Turret m_turret;
public AutonBase(Drivetrain drive, GearIntake gear, Loader loader, Shooter shooter, Conveyor conveyor, VisionBase vision, Turret turret){
m_drive = drive;
m_gear = gear;
m_loader = loader;
m_shooter = shooter;
m_conveyor = conveyor;
m_vision = vision;
m_turret = turret;
}
AutonConstants aConstants = new AutonConstants();
GearLeft gear_l;
GearCenter gear_c;
GearRight gear_r;
Forward forward;
Hopper hopper;
int loops = 0;
public void init(){
gear_l = new GearLeft(m_drive, m_gear, m_loader, m_conveyor, m_shooter, m_vision);
gear_c = new GearCenter(m_drive, m_gear, m_loader, m_conveyor, m_shooter);
gear_r = new GearRight(m_drive, m_gear, m_loader, m_conveyor, m_shooter, m_vision);
forward = new Forward(m_drive);
hopper = new Hopper(m_drive, m_gear, m_shooter, m_conveyor, m_loader, m_turret);
gear_l.init();
gear_c.init();
gear_r.init();
forward.init();
hopper.init();
}
public void initSmartDashboard() {
initAutonSelector();
initAllianceSelector();
initShootSelector();
SmartDashboard.putBoolean("Reset Auton", false);
hopper.initSmartDashboard();
}
public void updateSmartDashboard(){
SmartDashboard.putString("Selected Alliance", selectedAlliance());
SmartDashboard.putString("Selected Auton", selectedAuton());
SmartDashboard.putBoolean("Selected Shoot", selectedShoot());
SmartDashboard.putString("Current State", currentState());
if(SmartDashboard.getBoolean("Reset Auton", false)){
resetAll();
SmartDashboard.putBoolean("Reset Auton", false);
}
hopper.updateSmartDashboard();
}
public void initAllianceSelector(){
allianceSelector.addDefault("Red", "red");
allianceSelector.addObject("Blue", "blue");
SmartDashboard.putData("Alliance Selector", allianceSelector);
}
public void initAutonSelector(){
autonSelector.addDefault("Left Gear", "gear_l");
autonSelector.addObject("Center Gear", "gear_c");
autonSelector.addObject("Right Gear", "gear_r");
autonSelector.addObject("Hopper", "hopper");
autonSelector.addObject("Drive Forward", "forward");
autonSelector.addObject("None", "none");
SmartDashboard.putData("Auton Selector", autonSelector);
}
public void initShootSelector(){
shootSelector.addDefault("No", false);
shootSelector.addObject("Yes", true);
SmartDashboard.putData("Shooter", shootSelector);
}
public void resetAll(){
gear_r.reset();
gear_c.reset();
gear_l.reset();
hopper.reset();
m_drive.resetEncoders();
m_drive.resetGyro();
}
public String selectedAuton(){
return autonSelector.getSelected();
}
public String selectedAlliance(){
return allianceSelector.getSelected();
}
public boolean selectedShoot(){
return shootSelector.getSelected();
}
public String currentState(){
if(selectedAuton().equalsIgnoreCase("gear_r")) return gear_r.currentState();
if(selectedAuton().equalsIgnoreCase("gear_c")) return gear_c.currentState();
if(selectedAuton().equalsIgnoreCase("gear_l")) return gear_l.currentState();
if(selectedAuton().equalsIgnoreCase("hopper")) return hopper.currentState();
else return "";
}
public void run(){
m_gear.smartFlaps();
if(selectedAuton().equalsIgnoreCase("gear_r")){
gear_r.auton(selectedAlliance(), selectedShoot());
}
if(selectedAuton().equalsIgnoreCase("gear_c")){
gear_c.auton(selectedAlliance(), selectedShoot(), false);
}
if(selectedAuton().equalsIgnoreCase("gear_l")){
gear_l.auton(selectedAlliance(), selectedShoot());
}
if(selectedAuton().equalsIgnoreCase("forward")){
forward.auton();
}
if(selectedAuton().equalsIgnoreCase("hopper")){
hopper.auton(selectedAlliance());
}
if(selectedAuton().equalsIgnoreCase("none")){
}
}
public void getCurrentState(){
}
}
| 30.064103
| 138
| 0.744136
|
29ad3c816e10888613f26100d3011be345cabe7b
| 6,201
|
/*
* Copyright (c) 2015 Washington State Department of Transportation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package com.imaginedreal.mgwt.trafficflow.client.plugins.admob;
import com.google.gwt.core.client.JavaScriptObject;
public class AdMobOptions extends JavaScriptObject {
protected AdMobOptions() {}
/**
* Defines the sizes for the banner Ad.
*/
public enum AdSize {
SMART_BANNER("SMART_BANNER"), // Default
BANNER("BANNER"),
MEDIUM_RECTANGLE("MEDIUM_RECTANGLE"),
FULL_BANNER("FULL_BANNER"),
LEADERBOARD("LEADERBOARD"),
SKYSCRAPER("SKYSCRAPER"),
CUSTOM("CUSTOM");
private String size;
private AdSize(String s) {
size = s;
}
public String getSize() {
return size;
}
}
/**
* Defines the position of the banner Ad.
*/
public enum AdPosition {
NO_CHANGE(0),
TOP_LEFT(1),
TOP_CENTER(2), // Default
TOP_RIGHT(3),
LEFT(4),
CENTER(5),
RIGHT(6),
BOTTOM_LEFT(7),
BOTTOM_CENTER(8),
BOTTOM_RIGHT(9),
POS_XY(10);
private int position;
private AdPosition(int p) {
position = p;
}
public int getPosition() {
return position;
}
}
public final native String getAdId() /*-{
return this.adId;
}-*/;
/**
*
* @param adId the Ad unit Id for banner
*/
public final native void setAdId(String adId) /*-{
this.adId = adId;
}-*/;
public final native boolean isOffsetTopBar() /*-{
return this.offsetTopBar;
}-*/;
/**
*
* @param offset offset position of banner and webview to avoid overlap
* by status bar (iOS7+)
*/
public final native void setOffsetTopBar(boolean offset) /*-{
this.offsetTopBar = offset;
}-*/;
public final native boolean isAutoShow() /*-{
return this.autoShow;
}-*/;
/**
*
* @param show auto show interstitial ad when loaded, set to false if plan to
* control the show timing with prepareInterstitial/showInterstitial
*/
public final native void setAutoShow(boolean show) /*-{
this.autoShow = show;
}-*/;
public final native String getAdSize() /*-{
return this.adSize;
}-*/;
/**
*
* @param size banner Ad size, Default: SMART_BANNER. Can be one of:
* <p><ul>
* <li>AdSize.SMART_BANNER
* <li>AdSize.BANNER,
* <li>AdSize.MEDIUM_RECTANGLE
* <li>AdSize.FULL_BANNER
* <li>AdSize.LEADERBOARD
* <li>AdSize.SKYSCRAPER
* <li>AdSize.CUSTOM
* </ul></p>
* <p>Example:</p>
* <pre>{@code
* AdSize.SMART_BANNER.getSize()
* }</pre>
*/
public final native void setAdSize(String size) /*-{
this.adSize = size;
}-*/;
public final native int getWidth() /*-{
return this.width;
}-*/;
/**
*
* @param w banner width, valid when set adSize: CUSTOM. Default: 0
*/
public final native void setWidth(int w) /*-{
this.width = w;
}-*/;
public final native int getHeight() /*-{
return this.height;
}-*/;
/**
*
* @param h banner height, valid when set adSize: CUSTOM. Default: 0
*/
public final native void setHeight(int h) /*-{
this.height = h;
}-*/;
public final native int getPosition() /*-{
return this.position;
}-*/;
/**
*
* @param pos position of banner Ad, Default: TOP_CENTER. Can be one of:
* <p><ul>
* <li>AdPosition.NO_CHANGE
* <li>AdPosition.AD_POSITION.TOP_LEFT
* <li>AdPosition.AD_POSITION.TOP_CENTER
* <li>AdPosition.AD_POSITION.TOP_RIGHT
* <li>AdPosition.AD_POSITION.LEFT
* <li>AdPosition.AD_POSITION.CENTER
* <li>AdPosition.AD_POSITION.RIGHT
* <li>AdPosition.AD_POSITION.BOTTOM_LEFT
* <li>AdPosition.AD_POSITION.BOTTOM_CENTER
* <li>AdPosition.AD_POSITION.BOTTOM_RIGHT
* <li>AdPosition.AD_POSITION.POS_XY
* </ul></p>
* <p>Example:</p>
* <pre>{@code
* AdPosition.TOP_CENTER.getPosition()
* }</pre>
*/
public final native void setPosition(int pos) /*-{
this.position = pos;
}-*/;
public final native int getX() /*-{
return this.x;
}-*/;
/**
*
* @param x in pixels. Offset from screen left
*/
public final native void setX(int x) /*-{
this.x = x;
}-*/;
public final native int getY() /*-{
return this.y;
}-*/;
/**
*
* @param y in pixels. Offset from screen top
*/
public final native void setY(int y) /*-{
this.y = y;
}-*/;
public final native boolean isTesting() /*-{
return this.isTesting;
}-*/;
/**
*
* @param testing set to true, to receiving test ad for testing purpose
*/
public final native void setIsTesting(boolean testing) /*-{
this.isTesting = testing;
}-*/;
public final native String getBgColor() /*-{
return this.bgColor;
}-*/;
/**
*
* @param color background color of parent view, value may be color name
* like 'black', 'white', etc, or '#RRGGBB'
*/
public final native void setBgColor(String color) /*-{
this.bgColor = color;
}-*/;
}
| 25.623967
| 85
| 0.563619
|
022a4fb64b1933ed59e078cfb14079deefea5cfe
| 1,845
|
package com.firetower.data_generator.common.models;
import com.firetower.data_generator.common.enums.MetricType;
import com.firetower.data_generator.common.enums.OperatingSystemType;
import javax.persistence.*;
import java.util.Date;
public class Metric {
private Long id;
private Date date;
private OperatingSystemType operatingSystemType;
private MetricType metricType;
private Integer value;
private Long serverId;
private Boolean used;
public Metric(Date date, OperatingSystemType operatingSystemType, MetricType metricType, Integer value, Long serverId) {
this.date = date;
this.operatingSystemType = operatingSystemType;
this.metricType = metricType;
this.value = value;
this.serverId = serverId;
}
public Metric(){
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public OperatingSystemType getOperatingSystemType() {
return operatingSystemType;
}
public void setOperatingSystemType(OperatingSystemType operatingSystemType) {
this.operatingSystemType = operatingSystemType;
}
public MetricType getMetricType() {
return metricType;
}
public void setMetricType(MetricType metricType) {
this.metricType = metricType;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public Long getServerId() {
return serverId;
}
public void setServerId(Long serverId) {
this.serverId = serverId;
}
public Long getId() {
return id;
}
public Boolean getUsed() {
return used;
}
public void setUsed(Boolean used) {
this.used = used;
}
}
| 19.83871
| 124
| 0.659079
|
3184267e3f965cf10deccac14baedcdb4eb699df
| 3,350
|
/*------------------------------------------------------------------------------
* COPYRIGHT Ericsson 2013
*
* The copyright to the computer program(s) herein is the property of
* Ericsson Inc. The programs may be used and/or copied only with written
* permission from Ericsson Inc. or in accordance with the terms and
* conditions stipulated in the agreement/contract under which the
* program(s) have been supplied.
*----------------------------------------------------------------------------*/
package com.ericsson.jigsaw.redis.pool;
import redis.clients.jedis.Protocol;
/**
* All information for redis connection.
*/
public class ConnectionInfo {
public static final String DEFAULT_PASSWORD = null;
public static final String DEFAULT_POOLNAME = "NotSpecified";
private int database = Protocol.DEFAULT_DATABASE;
private String password = DEFAULT_PASSWORD;
private int timeout = Protocol.DEFAULT_TIMEOUT;
private String poolName = DEFAULT_POOLNAME;
public ConnectionInfo() {
}
public ConnectionInfo(String poolName) {
if (poolName != null) {
this.poolName = poolName;
}
}
public ConnectionInfo(int database, String password, int timeout) {
this.timeout = timeout;
this.password = password;
this.database = database;
}
public ConnectionInfo(int database, String password, int timeout, String poolName) {
this(database, password, timeout);
if (poolName != null) {
this.poolName = poolName;
}
}
public int getDatabase() {
return database;
}
public void setDatabase(int database) {
this.database = database;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public String getPoolName() {
return poolName;
}
public void setPoolName(String poolName) {
this.poolName = poolName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ConnectionInfo that = (ConnectionInfo) o;
if (database != that.database) {
return false;
}
if (timeout != that.timeout) {
return false;
}
if (password != null ? !password.equals(that.password) : that.password != null) {
return false;
}
if (poolName != null ? !poolName.equals(that.poolName) : that.poolName != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = database;
result = 31 * result + (password != null ? password.hashCode() : 0);
result = 31 * result + timeout;
result = 31 * result + (poolName != null ? poolName.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ConnectionInfo [database=" + database + ", password=" + password + ", timeout=" + timeout
+ ", poolName=" + poolName + "]";
}
}
| 27.235772
| 105
| 0.571642
|
e31718471673fe5a67717b31f5ee87e676e28eae
| 3,347
|
package book.ui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import net.miginfocom.swing.MigLayout;
import book.io.PurchasesReport.Item;
/**
* @author Terry Tianwei Lun
*
*/
@SuppressWarnings("serial")
public class PurchaseDialog extends JDialog {
private static final Logger LOG = LogManager.getLogger(PurchaseDialog.class);
/**
* Create the dialog.
*/
public PurchaseDialog(List<Item> purchases) {
setTitle("Purchase List");
setBounds(100, 100, 800, 500);
getContentPane().setLayout(new BorderLayout());
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
Object[] columnNames = { "Customer Name", "Book Title", "Price" };
Object[][] rowData = new Object[purchases.size()][11];
int i = 0;
for (Item purchase : purchases) {
try {
rowData[i][0] = purchase.getFirstName().concat(" ").concat(purchase.getLastName());
rowData[i][1] = purchase.getTitle();
rowData[i][2] = String.format("$%,.2f", purchase.getPrice());
++i;
} catch (Exception e) {
LOG.error("ERROR -", e);
}
}
final JTable table = new JTable(rowData, columnNames);
int width = this.getWidth();
int height = this.getHeight();
contentPanel.setLayout(new MigLayout("", "[772px]", "[][600px]"));
table.setPreferredScrollableViewportSize(new Dimension(width - 30, height - 30));
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setDefaultEditor(Object.class, null);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
JScrollPane scrollPane = new JScrollPane(table);
contentPanel.add(scrollPane, "cell 0 1,alignx left,aligny top");
getContentPane().add(contentPanel, BorderLayout.CENTER);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PurchaseDialog.this.dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PurchaseDialog.this.dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
}
protected static void callDialog(List<Item> purchases) {
try {
PurchaseDialog dialog = new PurchaseDialog(purchases);
dialog.setModalityType(ModalityType.APPLICATION_MODAL);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception ex) {
LOG.error("ERROR -", ex);
}
}
}
| 28.12605
| 87
| 0.714969
|
a59735fcfba15c8f151cf0939ea79c0a92fc7a6f
| 2,558
|
/*
* Copyright 2017 The Mochalog 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 io.mochalog.util.format;
import java.util.IllegalFormatException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Abstract implementation of string formatter interface
*/
public abstract class AbstractFormatter implements Formatter
{
// Regex pattern to apply for substitution rule identifiers
private final Pattern RULE_PATTERN;
// Formatting rule specification
private final FormatSpec FORMAT_SPEC;
/**
* Constructor.
*/
protected AbstractFormatter()
{
// Precompile regex pattern (faster performance)
RULE_PATTERN = Pattern.compile("@\\w+");
FORMAT_SPEC = new FormatSpec();
}
@Override
public String format(String str, Object... args) throws IllegalFormatException
{
final int RULE_BEGIN_INDEX = 1;
// Apply rule pattern to input string to
// find inline matches
Matcher matcher = RULE_PATTERN.matcher(str);
// Formatted string buffer
StringBuffer formatBuffer = new StringBuffer();
// Find all inline rules within the input string
for (int i = 0; matcher.find() && i < args.length; ++i)
{
// Remove $ from the matched rule string
String rule = matcher.group().substring(RULE_BEGIN_INDEX);
Object arg = args[i];
// Format the specified rule according to given specifications
String replacement = FORMAT_SPEC.applyRule(rule, arg);
// Ensure replacement string is converted into literal
// string (ensure \ and $ characters are treated correctly)
matcher.appendReplacement(formatBuffer, Matcher.quoteReplacement(replacement));
}
matcher.appendTail(formatBuffer);
return formatBuffer.toString();
}
@Override
public void setRule(String identifier, FormattingRule rule)
{
FORMAT_SPEC.setRule(identifier, rule);
}
}
| 32.794872
| 91
| 0.678264
|
f621542f13d60cd45cdc9971c4ed520fef7df68d
| 3,053
|
package org.motechproject.scheduletracking.api.domain.search;
import org.junit.Test;
import org.motechproject.scheduletracking.api.domain.Enrollment;
import org.motechproject.scheduletracking.api.domain.Schedule;
import org.motechproject.scheduletracking.api.repository.AllEnrollments;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static ch.lambdaj.Lambda.extract;
import static ch.lambdaj.Lambda.on;
import static java.util.Arrays.asList;
import static junit.framework.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MetadataCriterionTest {
@Test
public void shouldFetchFromDbUsingCriteria() {
AllEnrollments allEnrollments = mock(AllEnrollments.class);
List<Enrollment> result = mock(List.class);
when(allEnrollments.findByMetadataProperty("foo", "bar")).thenReturn(result);
assertEquals(result, new MetadataCriterion("foo", "bar").fetch(allEnrollments, null));
}
@Test
public void shouldFilterByMetadata() {
Schedule schedule = new Schedule("my_schedule");
List<Enrollment> enrollments = new ArrayList<Enrollment>();
HashMap<String,String> metadata1 = new HashMap<String, String>(),metadata2 = new HashMap<String, String>(), metadata3 = new HashMap<String, String>(), metadata4 = new HashMap<String, String>();
metadata1.put("foo","bar");
metadata1.put("fuu", "bar");
enrollments.add(new Enrollment().setExternalId("entity1").setSchedule(schedule).setCurrentMilestoneName(null).setStartOfSchedule(null).setEnrolledOn(null).setPreferredAlertTime(null).setStatus(null).setMetadata(metadata1));
metadata2.put("foo", "baz");
metadata2.put("fuu", "biz");
enrollments.add(new Enrollment().setExternalId("entity2").setSchedule(schedule).setCurrentMilestoneName(null).setStartOfSchedule(null).setEnrolledOn(null).setPreferredAlertTime(null).setStatus(null).setMetadata(metadata2));
metadata3.put("foo","bar");
enrollments.add(new Enrollment().setExternalId("entity3").setSchedule(schedule).setCurrentMilestoneName(null).setStartOfSchedule(null).setEnrolledOn(null).setPreferredAlertTime(null).setStatus(null).setMetadata(metadata3));
metadata4.put("foo", "boz");
metadata4.put("fuu", "ber");
enrollments.add(new Enrollment().setExternalId("entity4").setSchedule(schedule).setCurrentMilestoneName(null).setStartOfSchedule(null).setEnrolledOn(null).setPreferredAlertTime(null).setStatus(null).setMetadata(metadata4));
enrollments.add(new Enrollment().setExternalId("entity5").setSchedule(schedule).setCurrentMilestoneName(null).setStartOfSchedule(null).setEnrolledOn(null).setPreferredAlertTime(null).setStatus(null).setMetadata(null));
List<Enrollment> filtered = new MetadataCriterion("foo", "bar").filter(enrollments, null);
assertEquals(asList(new String[]{ "entity1", "entity3" }), extract(filtered, on(Enrollment.class).getExternalId()));
}
}
| 52.637931
| 231
| 0.75172
|
f23676cbdf7b5515d82d659e875c49bb7cd463d7
| 6,943
|
import java.io.*;
import java.util.*;
public class DataParser {
File file;
String filepath = "C:/Users/JonFrankline/Desktop/cs445data";
BufferedReader br;
FileReader fr;
BufferedWriter bw;
FileWriter fw;
String readpath;
String writepath;
public DataParser(String readname, String writename){
readpath = filepath + "/" + readname;
writepath = filepath + "/" + writename;
}
public void processMovieData(){
int i = 0;
String line;
String[] data = new String[50];
try{
fr = new FileReader(readpath);
br = new BufferedReader(fr);
}
catch(FileNotFoundException fof){
System.out.println("Couldn't find the file.");
}
try{
fw = new FileWriter(writepath);
bw = new BufferedWriter(fw);
}
catch(IOException io){
System.out.println("Oopsie");
}
try{
while((line = br.readLine()) != null){
data = line.split("\t");
// switch(data[0]){
// case "Title":
if(data[0].equals("Title")){
bw.write(data[1]);
bw.write("\t");
bw.flush();
line = br.readLine();
data = line.split("\t");
if(data[0].equals("Year")){
bw.write(data[1]);
bw.write("\t");
bw.flush();
}
else{
bw.write("\t");
bw.flush();
}
line = br.readLine();
data = line.split("\t");
if(data[0].equals("Running Time")){
line = br.readLine();
data = line.split("\t");
if(data[0].equals("MPAA Rating")){
bw.write(data[1]);
bw.newLine();
bw.flush();
}
else{
bw.newLine();
bw.flush();
}
}
else if(data[0].equals("MPAA Rating")){
bw.write(data[1]);
bw.newLine();
bw.flush();
}
bw.flush();
}
// break;
// case "Year":
// else if(data[0].equals("Year")){
// bw.write(data[1]);
// bw.flush();
// }
// else if(data[0].equals("MPAA Rating")){
// bw.write(data[1]);
//
// }
// break;
// }
continue;
}
bw.flush();
bw.close();
}
catch(IOException io){
System.out.println("woopsie");
}
}
public void processPeopleData(){
String line;
String[] data = new String[50];
try{
fr = new FileReader(readpath);
br = new BufferedReader(fr);
}
catch(FileNotFoundException fof){
System.out.println("Couldn't find the file.");
}
try{
fw = new FileWriter(writepath);
bw = new BufferedWriter(fw);
}
catch(IOException io){
System.out.println("Oopsie");
}
try{
while((line = br.readLine()) != null){
data = line.split("\t");
if(data[0].equals("Actor")){
bw.write(data[1]);
bw.newLine();
bw.flush();
}
else if(data[0].equals("Actress")){
bw.write(data[1]);
bw.newLine();
bw.flush();
}
else if(data[0].equals("Producers")){
for(String s : data){
if(!s.equals("Producers")){
bw.write(s);
bw.newLine();
bw.flush();
}
}
}
else if(data[0].equals("Directors")){
for(String s : data){
if(!s.equals("Directors")){
bw.write(s);
bw.newLine();
bw.flush();
}
}
}
continue;
}
bw.flush();
bw.close();
removeDuplicates(writepath);
}
catch(IOException io){
System.out.println("woopsie");
}
}
public void processMpaaData(){
String line;
String[] data = new String[50];
try{
fr = new FileReader(readpath);
br = new BufferedReader(fr);
}
catch(FileNotFoundException fof){
System.out.println("Couldn't find the file.");
}
try{
fw = new FileWriter(writepath);
bw = new BufferedWriter(fw);
}
catch(IOException io){
System.out.println("woopsie");
}
try{
while((line = br.readLine()) != null){
data = line.split("\t");
bw.write(data[0] + "\t" + data[2]);
bw.newLine();
continue;
}
bw.flush();
bw.close();
}
catch(IOException io){
System.out.println("woopsie");
}
}
public void processActorData(){
String line;
String[] data = new String[50];
try{
fr = new FileReader(readpath);
br = new BufferedReader(fr);
}
catch(FileNotFoundException fof){
System.out.println("Couldn't find the file.");
}
try{
fw = new FileWriter(writepath);
bw = new BufferedWriter(fw);
}
catch(IOException io){
System.out.println("woopsie");
}
try{
while((line = br.readLine()) != null){
data = line.split("\t");
if(data[0].equals("Actor")){
bw.write(data[1]);
bw.newLine();
bw.flush();
}
else if(data[0].equals("Actress")){
bw.write(data[1]);
bw.newLine();
bw.flush();
}
continue;
}
bw.flush();
bw.close();
removeDuplicates(writepath);
}
catch(IOException io){
System.out.println("woopsie");
}
}
public void processProducerData(){
String line;
String[] data = new String[50];
try{
fr = new FileReader(readpath);
br = new BufferedReader(fr);
}
catch(FileNotFoundException fof){
System.out.println("Couldn't find the file.");
}
try{
fw = new FileWriter(writepath);
bw = new BufferedWriter(fw);
}
catch(IOException io){
System.out.println("woopsie");
}
try{
while((line = br.readLine()) != null){
data = line.split("\t");
if(data[0].equals("Producers")){
for(String s : data){
if(!s.equals("Producers")){
bw.write(s);
bw.newLine();
bw.flush();
}
}
}
continue;
}
bw.flush();
bw.close();
removeDuplicates(writepath);
}
catch(IOException io){
System.out.println("woopsie");
}
}
public void processDirectorData(){
String line;
String[] data = new String[50];
try{
fr = new FileReader(readpath);
br = new BufferedReader(fr);
}
catch(FileNotFoundException fof){
System.out.println("Couldn't find the file.");
}
try{
fw = new FileWriter(writepath);
bw = new BufferedWriter(fw);
}
catch(IOException io){
System.out.println("woopsie");
}
try{
while((line = br.readLine()) != null){
data = line.split("\t");
if(data[0].equals("Directors")){
for(String s : data){
if(!s.equals("Directors")){
bw.write(s);
bw.newLine();
bw.flush();
}
}
}
continue;
}
bw.flush();
bw.close();
removeDuplicates(writepath);
}
catch(IOException io){
System.out.println("woopsie");
}
}
public void removeDuplicates(String filename) throws FileNotFoundException, IOException {
BufferedReader reader = new BufferedReader(new FileReader(filename));
Set<String> lines = new LinkedHashSet<String>(1000000);
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
reader.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
for (String unique : lines) {
writer.write(unique);
writer.newLine();
}
writer.close();
}
}
| 19.668555
| 90
| 0.563589
|
5c24784870f6454987768fed10e029f354fefc44
| 247
|
public class IgneousRock extends Rock
{
public IgneousRock(int num, double grams)
{
super(num, grams);
setDescription("Igneous rocks are crystalline solids " +
"\nwhich form directly from the cooling of magma.");
}
}
| 24.7
| 62
| 0.668016
|
b6110affc2fbd6450a0234cd0995c6328615b866
| 681
|
package ru.yandex.qatools.allure.data.providers;
import ru.yandex.qatools.allure.data.AllureXUnit;
/**
* @author Dmitry Baev charlie@yandex-team.ru
* Date: 06.12.13
*/
public class XUnitDataProvider extends AbstractDataProvider {
private static final String TEST_RUN_TO_XUNIT_XSL = "xsl/testrun-to-xunit.xsl";
public static final String XUNIT_JSON = "xunit.json";
@Override
public String[] getXslTransformations() {
return new String[]{TEST_RUN_TO_XUNIT_XSL};
}
@Override
public String getJsonFileName() {
return XUNIT_JSON;
}
@Override
public Class<?> getType() {
return AllureXUnit.class;
}
}
| 22.7
| 83
| 0.684288
|
2ec0e6a2897c5b76dee761cae8ff14e7e82f69e5
| 722
|
package com.template.springboot.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.template.springboot.dao.IEmployeeDAO;
import com.template.springboot.model.Employee;
import com.template.springboot.model.Employees;
@Service
public class EmployeeService implements IEmployeeService {
@Autowired
IEmployeeDAO employeeDao;
@Override
public int createEmployee(Employee employee) {
Integer id = employeeDao.getAllEmployees().getEmployeeList().size() + 1;
employee.setId(id);
employeeDao.addEmployee(employee);
return id;
}
@Override
public Employees getEmployees() {
return employeeDao.getAllEmployees();
}
}
| 24.066667
| 74
| 0.785319
|
14e60a459fe9e512cab97fbe88625472ca71692b
| 2,595
|
package com.lvshandian.lemeng.adapter.mine;
import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.lvshandian.lemeng.R;
import com.lvshandian.lemeng.adapter.CommonAdapter;
import com.lvshandian.lemeng.adapter.ViewHolder;
import com.lvshandian.lemeng.entity.MyContributionBeanBack;
import com.lvshandian.lemeng.utils.GrademipmapUtils;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by Administrator on 2017/2/25.
*/
public class MyContributionListAdapter extends CommonAdapter<MyContributionBeanBack> {
private List<MyContributionBeanBack> mDatas;
public MyContributionListAdapter(Context context, List<MyContributionBeanBack> mDatas, int itemLayoutId) {
super(context, mDatas, itemLayoutId);
this.mDatas = mDatas;
}
@Override
public void convert(ViewHolder helper, MyContributionBeanBack item, int position) {
ImageView iv_gender = helper.getView(R.id.iv_gender);
ImageView iv_rank = helper.getView(R.id.iv_rank);
ImageView iv_level = helper.getView(R.id.iv_level);
ImageView iv_header = helper.getView(R.id.iv_header);
TextView tv_name = helper.getView(R.id.tv_name);
TextView tv_gong_xian = helper.getView(R.id.tv_gong_xian);
TextView tv_no = helper.getView(R.id.tv_no);
MyContributionBeanBack bean = mDatas.get(position);
if (position == 0) {
iv_rank.setVisibility(View.VISIBLE);
tv_no.setVisibility(View.GONE);
iv_rank.setImageResource(R.mipmap.yinpai);
} else if (position == 1) {
iv_rank.setVisibility(View.VISIBLE);
tv_no.setVisibility(View.GONE);
iv_rank.setImageResource(R.mipmap.tongpiao);
} else {
tv_no.setVisibility(View.VISIBLE);
iv_rank.setVisibility(View.GONE);
}
String gender = bean.getGender();
iv_gender.setImageResource(android.text.TextUtils.equals(gender, "1") ? R.mipmap.male : R.mipmap.female);
int level = Integer.valueOf(bean.getLevel());
iv_level.setImageResource(GrademipmapUtils.LevelImg[level - 1]);
String nickName = bean.getNickName();
tv_name.setText(nickName);
tv_gong_xian.setText(mContext.getResources().getString(R.string.contribution_lepiao_num,String.valueOf(bean.getContributeCoin())));
String picUrl = bean.getPicUrl();
Picasso.with(mContext).load(picUrl).into(iv_header);
tv_no.setText("No." + (position + 2));
}
}
| 35.547945
| 139
| 0.700193
|
0173ff3873a92b003145798b2eef3d02c5371a36
| 287
|
/**
* Open-source Game Boy inspired game.
*
* Created by tom_mai78101. Hobby game programming only.
*
* All rights copyrighted to The Pokémon Company and Nintendo.
*/
package common;
public interface Tileable {
public static int WIDTH = 16;
public static int HEIGHT = 16;
}
| 19.133333
| 63
| 0.714286
|
948ddda52e2d5255b722894310e6b441737f0a2c
| 1,189
|
package com.ruoyi.ware.service;
import com.ruoyi.ware.domain.WareOrderTask;
import java.util.List;
/**
* 库存工作单Service接口
*
* @author xuxing
* @date 2021-08-23
*/
public interface IWareOrderTaskService
{
/**
* 查询库存工作单
*
* @param id 库存工作单主键
* @return 库存工作单
*/
public WareOrderTask selectWareOrderTaskById(Long id);
/**
* 查询库存工作单列表
*
* @param wareOrderTask 库存工作单
* @return 库存工作单集合
*/
public List<WareOrderTask> selectWareOrderTaskList(WareOrderTask wareOrderTask);
/**
* 新增库存工作单
*
* @param wareOrderTask 库存工作单
* @return 结果
*/
public int insertWareOrderTask(WareOrderTask wareOrderTask);
/**
* 修改库存工作单
*
* @param wareOrderTask 库存工作单
* @return 结果
*/
public int updateWareOrderTask(WareOrderTask wareOrderTask);
/**
* 批量删除库存工作单
*
* @param ids 需要删除的库存工作单主键集合
* @return 结果
*/
public int deleteWareOrderTaskByIds(Long[] ids);
/**
* 删除库存工作单信息
*
* @param id 库存工作单主键
* @return 结果
*/
public int deleteWareOrderTaskById(Long id);
WareOrderTask selectOrderTaskByOrderSn(String orderSn);
}
| 18.292308
| 84
| 0.617325
|
2e7d5d2b9a9e2a44054548ff304ca56912a11965
| 2,371
|
package nl.saalks.springbootvuejs.service;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.springframework.test.util.AssertionErrors.assertTrue;
class Day2Test implements AdventOfCodeTest {
Day2 fixture;
@BeforeEach
void setUp() {
fixture = new Day2();
}
@Test
@DisplayName("2.1 - 1989265 plannedCourse for example")
void pilotTheSubWithExampleData() {
List<String> lines = new ArrayList<>();
lines.add("forward 5");
lines.add("down 5");
lines.add("forward 8");
lines.add("up 3");
lines.add("down 8");
lines.add("forward 2");
int plannedCourse = fixture.pilotTheSub(lines);
assertTrue("planned course in report should be: ", plannedCourse == 150);
}
@Test
@DisplayName("2.1 - 1989265 plannedCourse for file")
void pilotTheSubWithInputFile() {
List<String> lines = readFile("input-planned-course.txt");
int plannedCourse = fixture.pilotTheSub(lines);
assertTrue("planned course in report should be: ", plannedCourse == 1989265);
}
@Test
@DisplayName("2.2 - 900 plannedCourse for file")
void aimTheSubWithExampleData() {
List<String> lines = new ArrayList<>();
lines.add("forward 5");
lines.add("down 5");
lines.add("forward 8");
lines.add("up 3");
lines.add("down 8");
lines.add("forward 2");
int plannedCourse = fixture.aimTheSub(lines);
assertTrue("planned course in report should be: ", plannedCourse == 900);
}
@Test
@DisplayName("2.2 - 2089174012 plannedCourse for file")
void aimTheSubWithInputFile() {
List<String> lines = readFile("input-planned-course.txt");
int plannedCourse = fixture.aimTheSub(lines);
assertTrue("planned course in report should be: ", plannedCourse == 2089174012);
}
@Test
@DisplayName("2.2 - 2089174012 plannedCourse for file")
void aimTheSubHashMapWithInputFile() {
List<String> lines = readFile("input-planned-course.txt");
int plannedCourse = fixture.aimTheSubHashMap(lines);
assertTrue("planned course in report should be: ", plannedCourse == 2089174012);
}
}
| 29.6375
| 88
| 0.647828
|
b3f6f17b9e1d7e2fe749eb8b1bc31fe0b623ba3f
| 5,020
|
package com.jagex;
public class Class18 implements Interface12, Interface5 {
Object[][] anObjectArrayArray184;
Class454[][] aClass454ArrayArray185;
void method627(RSByteBuffer var1, int var2) {
if(var2 == 3) {
int var3 = var1.readUnsignedByte(520834722);
if(null == this.anObjectArrayArray184) {
this.anObjectArrayArray184 = new Object[var3][];
this.aClass454ArrayArray185 = new Class454[var3][];
}
for(int var4 = var1.readUnsignedByte(1502482750); var4 != 255; var4 = var1.readUnsignedByte(524976110)) {
int var5 = var1.readUnsignedByte(623233252);
Class454[] var6 = new Class454[var5];
for(int var7 = 0; var7 < var5; ++var7) {
var6[var7] = (Class454)Class561.findIdentifiable(Class454.method5391(1508098173), var1.readSmart(), (byte)-9);
}
this.anObjectArrayArray184[var4] = Class71.method1098(var1, var6, (byte)-21);
this.aClass454ArrayArray185[var4] = var6;
}
}
}
void method628(RSByteBuffer var1, int var2) {
if(var2 == 3) {
int var3 = var1.readUnsignedByte(-2090225019);
if(null == this.anObjectArrayArray184) {
this.anObjectArrayArray184 = new Object[var3][];
this.aClass454ArrayArray185 = new Class454[var3][];
}
for(int var4 = var1.readUnsignedByte(1082437887); var4 != 255; var4 = var1.readUnsignedByte(-1956776481)) {
int var5 = var1.readUnsignedByte(-1964081159);
Class454[] var6 = new Class454[var5];
for(int var7 = 0; var7 < var5; ++var7) {
var6[var7] = (Class454)Class561.findIdentifiable(Class454.method5391(1508098173), var1.readSmart(), (byte)-20);
}
this.anObjectArrayArray184[var4] = Class71.method1098(var1, var6, (byte)-104);
this.aClass454ArrayArray185[var4] = var6;
}
}
}
public Object[] method629(int var1, int var2) {
return this.anObjectArrayArray184 == null?null:this.anObjectArrayArray184[var1];
}
void method630(RSByteBuffer var1, int var2, int var3) {
if(var2 == 3) {
int var4 = var1.readUnsignedByte(1234528173);
if(null == this.anObjectArrayArray184) {
this.anObjectArrayArray184 = new Object[var4][];
this.aClass454ArrayArray185 = new Class454[var4][];
}
for(int var5 = var1.readUnsignedByte(1299896565); var5 != 255; var5 = var1.readUnsignedByte(-1793462305)) {
int var6 = var1.readUnsignedByte(-641057793);
Class454[] var7 = new Class454[var6];
for(int var8 = 0; var8 < var6; ++var8) {
var7[var8] = (Class454)Class561.findIdentifiable(Class454.method5391(1508098173), var1.readSmart(), (byte)-82);
}
this.anObjectArrayArray184[var5] = Class71.method1098(var1, var7, (byte)-120);
this.aClass454ArrayArray185[var5] = var7;
}
}
}
public void method81(int var1) {
}
public void method49(int var1, int var2) {
}
public void method83(RSByteBuffer var1) {
while(true) {
int var2 = var1.readUnsignedByte(-2020898673);
if(0 == var2) {
return;
}
this.method630(var1, var2, -234427867);
}
}
public void method85() {
}
void method631(RSByteBuffer var1, int var2) {
if(var2 == 3) {
int var3 = var1.readUnsignedByte(-2025537114);
if(null == this.anObjectArrayArray184) {
this.anObjectArrayArray184 = new Object[var3][];
this.aClass454ArrayArray185 = new Class454[var3][];
}
for(int var4 = var1.readUnsignedByte(853611339); var4 != 255; var4 = var1.readUnsignedByte(-1250724526)) {
int var5 = var1.readUnsignedByte(-1535381901);
Class454[] var6 = new Class454[var5];
for(int var7 = 0; var7 < var5; ++var7) {
var6[var7] = (Class454)Class561.findIdentifiable(Class454.method5391(1508098173), var1.readSmart(), (byte)-54);
}
this.anObjectArrayArray184[var4] = Class71.method1098(var1, var6, (byte)-122);
this.aClass454ArrayArray185[var4] = var6;
}
}
}
public void method51(int var1) {
}
public void method82(RSByteBuffer var1, int var2) {
while(true) {
int var3 = var1.readUnsignedByte(-1253596729);
if(0 == var3) {
return;
}
this.method630(var1, var3, -234427867);
}
}
public void method50(int var1) {
}
public void method84(RSByteBuffer var1) {
while(true) {
int var2 = var1.readUnsignedByte(33566461);
if(0 == var2) {
return;
}
this.method630(var1, var2, -234427867);
}
}
}
| 33.245033
| 127
| 0.574303
|
14a2a49728402dee2e317d949f10aebb865fa311
| 1,879
|
package com.github.wz2cool.elasticsearch.operator;
import com.github.wz2cool.elasticsearch.model.FilterMode;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import java.util.Objects;
public class MatchOperator implements IFilterOperator<String> {
private String value;
private String analyzer;
private String fuzziness;
private Float boost;
private Operator operator;
MatchOperator(String value) {
this.value = value;
}
@Override
public FilterMode getDefaultFilterMode() {
return FilterMode.MUST;
}
@Override
public QueryBuilder buildQuery(String columnName) {
final MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder(columnName, value);
if (Objects.nonNull(analyzer)) {
matchQueryBuilder.analyzer(analyzer);
}
if (Objects.nonNull(fuzziness)) {
matchQueryBuilder.fuzziness(fuzziness);
}
if (Objects.nonNull(operator)) {
matchQueryBuilder.operator(operator);
}
if (Objects.nonNull(boost)) {
matchQueryBuilder.boost(boost);
}
return matchQueryBuilder;
}
/**
* see also {@link MatchQueryBuilder#analyzer(String)}
*/
public MatchOperator analyzer(String analyzer) {
this.analyzer = analyzer;
return this;
}
/**
* see also {@link MatchQueryBuilder#fuzziness(Object)} )}
*/
public MatchOperator fuzziness(String fuzziness) {
this.fuzziness = fuzziness;
return this;
}
public MatchOperator operator(Operator operator) {
this.operator = operator;
return this;
}
public MatchOperator boost(Float boost) {
this.boost = boost;
return this;
}
}
| 26.464789
| 93
| 0.659393
|
fe5e894d1f6529a2dde11ae4f4820988956d8814
| 5,849
|
package org.firstinspires.ftc.teamcode.Movement;
import com.qualcomm.hardware.bosch.BNO055IMU;
import com.qualcomm.robotcore.hardware.DcMotor;
import org.firstinspires.ftc.teamcode.util.Constants;
import org.firstinspires.ftc.teamcode.util.Angle;
import org.firstinspires.ftc.teamcode.util.Hardware;
import org.firstinspires.ftc.teamcode.util.HardwareOld;
public class ActiveLocation implements Runnable{
//Hardware Set Up
private final BNO055IMU imu;
//TODO: Will be implemented once encoders are attached to bot
//private final DcMotor xDirectionEncoder;
//private final DcMotor yDirectionEncoder;
//Encoder values
private double yEncoderValue = 0;
private double xEncoderValue = 0;
//Sets the angle that the robot starts at, what it will be reset to if driver wishes, and what it started from
Angle angle = Angle.fromRadians(0);
Angle resetAngle = Angle.fromRadians(0);
Angle startAngle = Angle.fromRadians(0);
//Field Position, will be fully implemented when Encoders are added
double fieldXPosition = 0;
double fieldYPosition = 0;
//Boolean to control when Active Location Stops
private boolean isRunning = true;
//Constants for calculations
//Ticks per rotation is for encoders, and wheelCircumferance should be of encoders not mecanum wheels
final static double ticksPerRotation = 8192;
//TODO: Check calculation as size is different
final static double wheelCircumference = 90*Math.PI;
//Sets up the hardware and creates the class, Constructor
public ActiveLocation (Hardware robot){
this.imu = robot.imu;
//TODO: Will be implemented once encoders are attached to bot
//this.xDirectionEncoder = robot.backRightMotor;
//this.yDirectionEncoder = robot.frontLeftMotor;
}
public ActiveLocation(DcMotor xDirectionEncoder, DcMotor yDirectionEncoder,
BNO055IMU gyroscope) {
//TODO: Will be implemented once encoders are attached to bot
//this.yDirectionEncoder = yDirectionEncoder;
//this.xDirectionEncoder = xDirectionEncoder;
this.imu = gyroscope;
}
private static double tickToDistance(double ticks){
return ((ticks/ticksPerRotation)*wheelCircumference);
}
//Not gonna be very accurate
private static double distanceToTicks(double distanceInMiliMeters){
return ((distanceInMiliMeters/wheelCircumference)*ticksPerRotation);
}
public void setStartPosition(double startX, double startY, Angle startingAngle){
this.startAngle = startingAngle;
//TODO:Understand Math
this.xEncoderValue = startX * Math.cos(startAngle.getAngleInRadians())
- startY * Math.sin(startAngle.getAngleInRadians());
this.yEncoderValue = startX * Math.sin(startAngle.getAngleInRadians())
+ startY * Math.cos(startAngle.getAngleInRadians());
}
public void updateSensors(){
//yEncoderValue = yDirectionEncoder.getCurrentPosition();
//xEncoderValue = xDirectionEncoder.getCurrentPosition();
angle = Angle.fromRadians(-((imu.getAngularOrientation().firstAngle)
+ startAngle.getAngleInRadians() - resetAngle.getAngleInRadians()));
}
public void findFieldPosition() {
double internalPreviousY = fieldYPosition;
double internalPreviousX = fieldXPosition;
synchronized (this) {
//fieldYPosition = tickToDistance(yEncoder);
//fieldXPosition = ticksToDistance(xEncoder);
}
//double deltaY = internalCurrentY - internalPreviousY;
//double deltaX = internalCurrentX - internalPreviousX;
// fieldXPosition += deltaX * Math.cos(angle.getAngleInRadians())
// - deltaY * Math.sin(angle.getAngleInRadians());
// fieldYPosition += deltaX * Math.sin(angle.getAngleInRadians())
// + deltaY * Math.cos(angle.getAngleInRadians());
}
public double getFieldY(){
updateSensors();
findFieldPosition();
return fieldYPosition;
}
public double getFieldX(){
updateSensors();
findFieldPosition();
return fieldXPosition;
}
/**
* DO NOT USE THIS, USE getTrimmedAngleInRadians
* @return the angle of the bot in radians. Is based on the orientation of when the bot was started.
*/
public double getAngleInRadians(){
updateSensors();
return angle.getAngleInRadians();
}
/**
* DO NOT USE THIS, USE getTrimmedAngleInDegrees
* @return the angle of the bot in Degrees. Is based on the orientation of when the bot was started.
*/
public double getAngleInDegrees(){
updateSensors();
return angle.getAngleInDegrees();
}
/**
*
* @return the angle of the bot in Radians. Is based on the orientation of when the bot was started and returns an angle in a trimmed circle.
*/
public double getTrimmedAngleInRadians(){
updateSensors();
return angle.getTrimmedAngleInRadians();
}
/**
*
* @return the angle of the bot in Degrees. Is based on the orientation of when the bot was started and returns an angle in a trimmed circle.
*/
public double getTrimmedAngleInDegrees(){
updateSensors();
return angle.getTrimmedAngleInDegrees();
}
//Resets the orientation of the robot so the current direction is forward
public void setResetAngle(){
updateSensors();
resetAngle = angle;
}
/**
*Stops Active Location from running.
* */
public void stopActiveLocation() {
isRunning = false;
}
@Override
public void run(){
while (isRunning){
updateSensors();
findFieldPosition();
}
}
}
| 33.232955
| 145
| 0.674474
|
c1e13e1feea5a0bae692724ee625799115ebd369
| 1,872
|
/**
* Copyright 2016 StreamSets Inc.
* <p>
* Licensed under 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.pipeline.stage.processor.spark.util;
import com.streamsets.pipeline.api.Processor;
import com.streamsets.pipeline.api.Record;
public class RecordCloner {
private RecordCloner() {
}
/**
* Kryo loads the RecordImpl in Spark's classloader. So this one clones it to this stage's classloader.
*
* @param record Record to be cloned
* @param context The context of the {@linkplain Processor} to use to clone the record
* @return Cloned record
*/
public static Record clone(Record record, Processor.Context context) {
// Kryo loads the RecordImpl class during deserialization in a Spark's classloader.
// So directly using the deserialized RecordImpl gives a ClassCastException (RecordImpl -> RecordImpl).
// So create a new record and set its root field to be the deserialized one's root field.
Record r = context.createRecord(record);
r.set(record.get());
r.getHeader().setAllAttributes(record.getHeader().getAllAttributes());
return r;
}
}
| 40.695652
| 107
| 0.740385
|
dbb619176fb3f4edbab8995a57e319af834f175c
| 783
|
package net.arctics.clonk.c4script.typing;
import java.util.Iterator;
import net.arctics.clonk.Core;
public class ErroneousType implements IRefinedPrimitiveType {
private static final long serialVersionUID = Core.SERIAL_VERSION_UID;
private final String erroneousTypeString;
public ErroneousType(final String erroneousTypeString) {
super();
this.erroneousTypeString = erroneousTypeString;
}
@Override
public String typeName(final boolean special) { return String.format("Invalid type: '%s'", erroneousTypeString); }
@Override
public IType simpleType() { return PrimitiveType.ERRONEOUS; }
@Override
public Iterator<IType> iterator() { return PrimitiveType.ERRONEOUS.iterator(); }
@Override
public PrimitiveType primitiveType() { return PrimitiveType.ERRONEOUS; }
}
| 34.043478
| 115
| 0.795658
|
67f2e0b60487e3cb62b0f80bccfe17ff6a0f09df
| 1,519
|
package co.edu.javeriana.negocio;
import java.math.BigDecimal;
import java.util.Date;
public class Candidato extends Persona {
@SuppressWarnings("compatibility:3633362395647490550")
private static final long serialVersionUID = 1L;
private BigDecimal codigo;
private String nombreCompleto;
private Date fechaNacimiento;
public Candidato() {
super();
this.fechaNacimiento = new Date();
}
public void generarNombreCompleto(){
this.nombreCompleto = "";
this.nombreCompleto = this.nombreCompleto + this.getPrimerNombre();
this.nombreCompleto = this.nombreCompleto + (this.getSegundoNombre() != null ? " " + this.getSegundoNombre() : "");
this.nombreCompleto = this.nombreCompleto + (this.getPrimeroApellido() != null ? " " + this.getPrimeroApellido() : "");
this.nombreCompleto = this.nombreCompleto + (this.getSegundoApellido() != null ? " " + this.getSegundoApellido() : "");
}
public void setFechaNacimiento(Date fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public Date getFechaNacimiento() {
return fechaNacimiento;
}
public void setNombreCompleto(String nombreCompleto) {
this.nombreCompleto = nombreCompleto;
}
public String getNombreCompleto() {
return nombreCompleto;
}
public void setCodigo(BigDecimal codigo) {
this.codigo = codigo;
}
public BigDecimal getCodigo() {
return codigo;
}
}
| 29.211538
| 127
| 0.666228
|
1036cbae5228f82bc991c997b130d2f1e661f074
| 473
|
package com.me.diankun.drawdemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
/**
* Created by diankun on 2016/3/14.
*
* http://blog.csdn.net/stevenhu_223/article/details/9229337
*/
public class QuadLineActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quad_line);
}
}
| 23.65
| 61
| 0.712474
|
a972dd94395a8a13f436bb166d0763f1cf72837b
| 13,352
|
/**Copyright 2016, University of Messina.
*
* 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 API.EASTAPI;
import API.EASTAPI.Clients.EastBrRESTClient;
import API.EASTAPI.Clients.NetworkSegment;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import java.util.logging.Level;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.jclouds.openstack.neutron.v2.domain.Network;
import JClouds_Adapter.NeutronTest;
import JClouds_Adapter.OpenstackInfoContainer;
import MDBInt.DBMongo;
import MDBInt.FederatedUser;
import MDBInt.FederationUser;
import MDBInt.MDBIException;
import OSFFMIDM.SimpleIDM;
import javax.ws.rs.core.Response;
import org.json.simple.parser.ParseException;
//import OSFFM_ORC.OrchestrationManager;
/**
* REST Web Service
*
* @author gtricomi
*/
@Path("/fednet/eastBr/network")
public class NetworksegmentResource {
@Context
private String user,password;
private UriInfo context;
private SimpleIDM sidm;
private DBMongo db;
static final Logger LOGGER = Logger.getLogger(NetworksegmentResource.class);
/**
* Creates a new instance of NetworksegmentResource
*/
public NetworksegmentResource() {
String configFile="/home/beacon/beaconConf/configuration_bigDataPlugin.xml";//"/home/carmelo/NetBeansProjects/BeaconNetworkManagerDriver/web/WEB-INF/configuration_bigDataPlugin.xml";
//String configFile="/home/beacon/beaconConf/configuration_bigDataPlugin.xml";
sidm=new SimpleIDM(configFile);
this.db = new DBMongo();
this.db.init(configFile);
this.db.connectLocale("10.9.240.1");
}
/**
* Retrieves representation of an instance of EASTAPI.NetworksegmentResource
* @return an instance of java.lang.String
* @author gtricomi
*/
@PUT
@Consumes("application/json")
@Produces("application/json")
public String add_netSegment(String content) throws JSONException {
JSONObject reply = new JSONObject();
JSONParser parser = new JSONParser();
JSONObject input = null;
String OSF_network_segment_id = null;
String OSF_cmp_endpoint = null;
String OSF_token = null;
String OSF_tenant = null;
String OSF_user = null;
String OSF_region = null;
String OSF_cloud = null;
String response = "";
JSONObject network_info = null;
String netseg = null;
String datacenter_id = null;
String tenantDB = null;
try {
/*
{
"network_segment_id": "55b24c84-b96a-45ab-b007-9eee9c487c31",
"cmp_endpoint": "http://172.17.1.217:35357/v2.0",
"token": "86734b78980"
}
*/
//retrieve JSON value from REST request
input = new JSONObject(content);
OSF_token = (String) input.get("token");
OSF_network_segment_id = (String) input.get("network_segment_id");
OSF_cmp_endpoint = (String) input.get("cmp_endpoint");
} catch (JSONException e) {
reply.append("returncode", 1);
reply.append("errormesg", "Impossible to retrieve information from the BNM");
reply.append("network_info", "");
return reply.toString();
}
JSONObject federationcredential=null,federatedcredential=null;
try {
//verrà restituito l'OSFFM endpoint
//ricavare dal simple IDM gli elementi che mi mancano ovvero:
//String endpoint, String tenant, String user, String password, String region
tenantDB = this.db.getTenantName("token", OSF_token);
federationcredential = new JSONObject(this.db.getFederationCredential(tenantDB, OSF_token));
datacenter_id = this.db.getDatacenterIDfrom_cmpEndpoint(tenantDB, OSF_cmp_endpoint);
federatedcredential = new JSONObject(this.db.getFederatedCredentialfromTok(tenantDB, federationcredential.getString("federationUser"), OSF_token, datacenter_id));
System.out.println("DC ID: " + datacenter_id);
} catch (MDBIException e) {
reply.append("returncode", 1);
reply.append("errormesg", "Netegment Not present on cloud pointed by cmp_endpoint");
reply.append("network_info", "");
return reply.toString();
}
try {
netseg = this.db.getfedsdnNetSeg(OSF_network_segment_id, datacenter_id, tenantDB);
if (netseg == null) {
// boolean error=false;
//NeutronTest neutron = new NeutronTest(OSF_cmp_endpoint, federationcredential.getString("federationUser"), federatedcredential.getString("federatedUser"), federatedcredential.getString("federatedPassword"), "RegionOne");
//Network netSearched = neutron.getNetworkFromId(OSF_network_segment_id);
// if (error) {
reply.append("returncode", 1);
reply.append("errormesg", "Netegment Not present on cloud pointed by cmp_endpoint");
reply.append("network_info", "");
return reply.toString();
// }
} else {
network_info = new JSONObject();
JSONObject netseg_obj = new JSONObject(netseg);
reply.append("returncode", 0);
reply.append("errormesg", "");
network_info.put("internalId", OSF_network_segment_id);
//11-07-17: Questa informazione non dovrebbe servire...verificare !!!
//network_info.put("FedSDN_netSegId", OSF_network_segment_id);
network_info.put("network_address", netseg_obj.get("network_address"));
network_info.put("network_mask", netseg_obj.get("network_mask"));
network_info.put("size", netseg_obj.get("size"));
reply.append("network_info", network_info);
return reply.toString();
}
} catch (JSONException e) {
reply.append("returncode", 1);
reply.append("errormesg", "Error in creating the netsegment information object");
reply.append("network_info", "");
return reply.toString();
}
/*
//funzione che verifica l'esistenza del netsegment
NeutronTest neutron = new NeutronTest(OSF_cmp_endpoint, federationcredential.getString("federationUser"), federatedcredential.getString("federatedUser"), federatedcredential.getString("federatedPassword"), federatedcredential.getString("Region"));
Network netSearched = neutron.getNetworkFromId(OSF_network_segment_id);
if (netSearched == null) {
reply.append("returncode", 1);
reply.append("errormesg", "Netegment Not present on cloud pointed by cmp_endpoint");
reply.append("network_info", "");
return reply.toString();
} else {
//FOR FUTURE USAGE: these parameters will be provided from FEDSDN or DASHBOARD OS2OS?
HashMap params = new HashMap();
//////String dhcpEnable=(String)input.get("dhcpEnable");//FOR FUTURE USAGE
String dhcpEnable = null;
params.put("dhcpEnable", dhcpEnable);
//////String shared=(String)input.get("shared");//FOR FUTURE USAGE
String shared = null;
params.put("shared", shared);
//////String external=(String)input.get("external");//FOR FUTURE USAGE
String external = null;
params.put("external", external);
//////String adminStateUp=(String)input.get("adminStateUp");//FOR FUTURE USAGE
String adminStateUp = null;
params.put("adminStateUp", adminStateUp);
sidm = new SimpleIDM(); //>>>BEACON: VERIFY THIS POINT
String dbName = sidm.retrieve_TenantDB("federationTenant", OSF_tenant);
sidm.setDbName(dbName); //>>>BEACON: FOR THE MOMENT OUR TESTING DB IS CALLED beacon
//sidm.setDbName("beacon");
//FederationUser fu = sidm.getFederationU(OSF_token, OSF_cmp_endpoint);//OSF_cmp_endpoint questo non è usato
*/
/* //>>>BEACON: CREARE SERVIZIO SUL BEACON BROKER PER INVOCARE QUESTA FUNZIONALITÀ
OrchestrationManager om = new OrchestrationManager();
response = om.networkSegmentAdd(dbName, fu, OSF_network_segment_id, OSF_cloud, params).toString();
*/
/*
JSONObject job = new JSONObject();
JSONObject job_in = new JSONObject();
JSONObject j_map =new JSONObject(params);
job_in.put("token",OSF_token);
job_in.put("endpoint", OSF_cmp_endpoint);
job.put("fedUser", job_in);
job.put("dbName",dbName);
job.put("netSeg",OSF_network_segment_id);
job.put("CloudName",OSF_cloud);
job.put("hashMapParam",j_map);
String baseBBURL=""; ///////// OTTENERE BASE URL BB/////////////
// devo chiamare il put??
NetworkSegment ns = new NetworkSegment(user, password);
Response r;
r = ns.addNetSegm(job, baseBBURL);
org.json.simple.parser.JSONParser p = new org.json.simple.parser.JSONParser();
Object obj = null;
try {
obj = p.parse(r.readEntity(String.class));
} catch (ParseException ex) {
LOGGER.error("Exception occurred in Parsing JSON returned from FEDSDN \n" + ex.getMessage());
}
JSONObject output = (JSONObject) obj;
reply.append("returncode", output.get("returncode"));
reply.append("errormesg", output.get("errormesg"));
network_info.put("internalId", (String) ((org.json.JSONArray) output.get("ResponseArray")).getJSONObject(0).get("internalId"));
network_info.put("FedSDN_netSegId", (String) ((org.json.JSONArray) output.get("ResponseArray")).getJSONObject(0).get("FedSDN_netSegId"));
network_info.put("network_address", (String) ((org.json.JSONArray) output.get("ResponseArray")).getJSONObject(0).get("network_address"));
network_info.put("network_mask", (String) ((org.json.JSONArray) output.get("ResponseArray")).getJSONObject(0).get("network_mask"));
network_info.put("size", (String) ((org.json.JSONArray) output.get("ResponseArray")).getJSONObject(0).get("size"));
reply.append("network_info", network_info);
return reply.toString();
}
} catch (JSONException pe) {
System.out.println(pe.getMessage());
reply.append("returncode", 1);
reply.append("errormesg", "JSON_INPUT_UNPARSABLE: OPERATION ABORTED! " + pe.getMessage());
reply.append("network_info", "");
LOGGER.error(pe.getMessage());
return reply.toString();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
reply.append("returncode", 1);
reply.append("errormesg", "Generic Exception occurred! Contact Administrator.");
reply.append("network_info", "");
LOGGER.error(e.getMessage());
return reply.toString();
}
//Momentaneamente si lavora con una approccio end to end nei confronti del fedsdn quindi questa parte non và tenuta in considerazione e viene lasciata per futuri sviluppi
////L'APPROCCIO (di gestione di tutte le cloud da parte del fedsdn con un solo comando potrebbe essere corretto). UPDATE: È CORRETTO MA SONO COSTRETTO A RIEMPIRE MANUALMENTE LE INFORMAZIONI SUL FEDSDN
////FACENDO SI CHE LE RICHIESTE SIANO DIROTTATE SUL OSSFM(probabilmente l'approccio corretto è quello di aggiungere
//////manualmente attraverso chiamate ai REST webservice del fedsdn le informazioni sui vari cloud passando però come cmp_endpoint
//////l'indirizzo del OSFFM
////////UPDATE:28/07 il cmp_endpoint sul fedsdn è quello delle cloud
//return reply.toJSONString();
*/
}
}
| 47.516014
| 259
| 0.625674
|
fa7a7dcb68dda4be373adb5f7cd0b7ae933546f8
| 3,420
|
/*
* Copyright (C) 2018 Black Duck Software Inc.
* http://www.blackducksoftware.com/
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Black Duck Software ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Black Duck Software.
*/
package com.blackducksoftware.integration.cloudfoundry.perceiver.impl;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.blackducksoftware.integration.cloudfoundry.perceiver.api.ServiceProvisionRequest;
/**
* @author fisherj
*
*/
public class ServiceInstanceService {
private static final Logger logger = LoggerFactory.getLogger(ServiceInstanceService.class);
private final RestTemplate restTemplate;
private final String brokerBaseUrlString;
private final int brokerPort;
public ServiceInstanceService(RestTemplate restTemplate,
String brokerBaseUrlString,
int brokerPort) {
this.restTemplate = restTemplate;
this.brokerBaseUrlString = brokerBaseUrlString;
this.brokerPort = brokerPort;
}
public Set<String> getServiceInstances() {
logger.debug("Getting service instance ids from service instance backend");
URI brokerUri;
try {
URI brokerBaseUri = new URI(brokerBaseUrlString);
brokerUri = new URI(brokerBaseUri.getScheme(),
null,
brokerBaseUri.getHost(),
brokerPort,
"/service_instances",
null, null);
} catch (URISyntaxException e) {
logger.error("URI to broker backend not created successfully. app ids by binding ids not retrieved.", e);
return Collections.emptySet();
}
Set<String> resp = restTemplate.getForObject(brokerUri, Set.class);
return resp;
}
public boolean create(String id) {
logger.debug("Creating service instance with id: {} in service instance backend", id);
if (null == id) {
logger.warn("Invalid id. Cannot be null");
throw new IllegalStateException("id cannot be null");
}
ServiceProvisionRequest body = new ServiceProvisionRequest(id);
URI brokerUri;
try {
URI brokerBaseUri = new URI(brokerBaseUrlString);
brokerUri = new URI(brokerBaseUri.getScheme(),
null,
brokerBaseUri.getHost(),
brokerPort,
"/service_instances",
null, null);
} catch (URISyntaxException e) {
logger.error("URI to broker backend not created successfully. app ids by binding ids not retrieved.", e);
return false;
}
ResponseEntity<String> resp = restTemplate.postForEntity(brokerUri, body, String.class);
logger.info("Create service instance: {}, returned status: {}", resp.getBody(), resp.getStatusCode());
return (HttpStatus.CREATED == resp.getStatusCode());
}
}
| 36.774194
| 117
| 0.660819
|
6c697a4323b93f84a2f23ced0adb8026146e8fb2
| 10,624
|
/**
* 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.solr.analysis;
import junit.framework.TestCase;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* @author yonik
* @version $Id$
*/
public class TestSynonymFilter extends TestCase {
public List strings(String str) {
String[] arr = str.split(" ");
return Arrays.asList(arr);
}
/***
* Return a list of tokens according to a test string format:
* a b c => returns List<Token> [a,b,c]
* a/b => tokens a and b share the same spot (b.positionIncrement=0)
* a,3/b/c => a,b,c all share same position (a.positionIncrement=3, b.positionIncrement=0, c.positionIncrement=0)
*/
public List tokens(String str) {
String[] arr = str.split(" ");
List result = new ArrayList();
for (int i=0; i<arr.length; i++) {
String[] toks = arr[i].split("/");
String[] params = toks[0].split(",");
Token t = new Token(params[0],0,0,"TEST");
if (params.length > 1) t.setPositionIncrement(Integer.parseInt(params[1]));
result.add(t);
for (int j=1; j<toks.length; j++) {
t = new Token(toks[j],0,0,"TEST");
t.setPositionIncrement(0);
result.add(t);
}
}
return result;
}
public List getTokList(SynonymMap dict, String input, boolean includeOrig) throws IOException {
ArrayList lst = new ArrayList();
final List toks = tokens(input);
TokenStream ts = new TokenStream() {
Iterator iter = toks.iterator();
public Token next() throws IOException {
return iter.hasNext() ? (Token)iter.next() : null;
}
};
SynonymFilter sf = new SynonymFilter(ts, dict, true);
while(true) {
Token t = sf.next();
if (t==null) return lst;
lst.add(t);
}
}
public List tok2str(List tokLst) {
ArrayList lst = new ArrayList();
for (Iterator iter = tokLst.iterator(); iter.hasNext();) {
lst.add(((Token)(iter.next())).termText());
}
return lst;
}
public void assertTokEqual(List a, List b) {
assertTokEq(a,b);
assertTokEq(b,a);
}
private void assertTokEq(List a, List b) {
int pos=0;
for (Iterator iter = a.iterator(); iter.hasNext();) {
Token tok = (Token)iter.next();
pos += tok.getPositionIncrement();
if (!tokAt(b, tok.termText(), pos)) {
fail(a + "!=" + b);
}
}
}
public boolean tokAt(List lst, String val, int tokPos) {
int pos=0;
for (Iterator iter = lst.iterator(); iter.hasNext();) {
Token tok = (Token)iter.next();
pos += tok.getPositionIncrement();
if (pos==tokPos && tok.termText().equals(val)) return true;
}
return false;
}
public void testMatching() throws IOException {
SynonymMap map = new SynonymMap();
boolean orig = false;
boolean merge = true;
map.add(strings("a b"), tokens("ab"), orig, merge);
map.add(strings("a c"), tokens("ac"), orig, merge);
map.add(strings("a"), tokens("aa"), orig, merge);
map.add(strings("b"), tokens("bb"), orig, merge);
map.add(strings("z x c v"), tokens("zxcv"), orig, merge);
map.add(strings("x c"), tokens("xc"), orig, merge);
// System.out.println(map);
// System.out.println(getTokList(map,"a",false));
assertTokEqual(getTokList(map,"$",false), tokens("$"));
assertTokEqual(getTokList(map,"a",false), tokens("aa"));
assertTokEqual(getTokList(map,"a $",false), tokens("aa $"));
assertTokEqual(getTokList(map,"$ a",false), tokens("$ aa"));
assertTokEqual(getTokList(map,"a a",false), tokens("aa aa"));
assertTokEqual(getTokList(map,"b",false), tokens("bb"));
assertTokEqual(getTokList(map,"z x c v",false), tokens("zxcv"));
assertTokEqual(getTokList(map,"z x c $",false), tokens("z xc $"));
// repeats
map.add(strings("a b"), tokens("ab"), orig, merge);
map.add(strings("a b"), tokens("ab"), orig, merge);
assertTokEqual(getTokList(map,"a b",false), tokens("ab"));
// check for lack of recursion
map.add(strings("zoo"), tokens("zoo"), orig, merge);
assertTokEqual(getTokList(map,"zoo zoo $ zoo",false), tokens("zoo zoo $ zoo"));
map.add(strings("zoo"), tokens("zoo zoo"), orig, merge);
assertTokEqual(getTokList(map,"zoo zoo $ zoo",false), tokens("zoo zoo zoo zoo $ zoo zoo"));
}
public void testIncludeOrig() throws IOException {
SynonymMap map = new SynonymMap();
boolean orig = true;
boolean merge = true;
map.add(strings("a b"), tokens("ab"), orig, merge);
map.add(strings("a c"), tokens("ac"), orig, merge);
map.add(strings("a"), tokens("aa"), orig, merge);
map.add(strings("b"), tokens("bb"), orig, merge);
map.add(strings("z x c v"), tokens("zxcv"), orig, merge);
map.add(strings("x c"), tokens("xc"), orig, merge);
// System.out.println(map);
// System.out.println(getTokList(map,"a",false));
assertTokEqual(getTokList(map,"$",false), tokens("$"));
assertTokEqual(getTokList(map,"a",false), tokens("a/aa"));
assertTokEqual(getTokList(map,"a",false), tokens("a/aa"));
assertTokEqual(getTokList(map,"$ a",false), tokens("$ a/aa"));
assertTokEqual(getTokList(map,"a $",false), tokens("a/aa $"));
assertTokEqual(getTokList(map,"$ a !",false), tokens("$ a/aa !"));
assertTokEqual(getTokList(map,"a a",false), tokens("a/aa a/aa"));
assertTokEqual(getTokList(map,"b",false), tokens("b/bb"));
assertTokEqual(getTokList(map,"z x c v",false), tokens("z/zxcv x c v"));
assertTokEqual(getTokList(map,"z x c $",false), tokens("z x/xc c $"));
// check for lack of recursion
map.add(strings("zoo zoo"), tokens("zoo"), orig, merge);
assertTokEqual(getTokList(map,"zoo zoo $ zoo",false), tokens("zoo/zoo zoo/zoo $ zoo/zoo"));
map.add(strings("zoo"), tokens("zoo zoo"), orig, merge);
assertTokEqual(getTokList(map,"zoo zoo $ zoo",false), tokens("zoo/zoo zoo $ zoo/zoo zoo"));
}
public void testMapMerge() throws IOException {
SynonymMap map = new SynonymMap();
boolean orig = false;
boolean merge = true;
map.add(strings("a"), tokens("a5,5"), orig, merge);
map.add(strings("a"), tokens("a3,3"), orig, merge);
// System.out.println(map);
assertTokEqual(getTokList(map,"a",false), tokens("a3 a5,2"));
map.add(strings("b"), tokens("b3,3"), orig, merge);
map.add(strings("b"), tokens("b5,5"), orig, merge);
//System.out.println(map);
assertTokEqual(getTokList(map,"b",false), tokens("b3 b5,2"));
map.add(strings("a"), tokens("A3,3"), orig, merge);
map.add(strings("a"), tokens("A5,5"), orig, merge);
assertTokEqual(getTokList(map,"a",false), tokens("a3/A3 a5,2/A5"));
map.add(strings("a"), tokens("a1"), orig, merge);
assertTokEqual(getTokList(map,"a",false), tokens("a1 a3,2/A3 a5,2/A5"));
map.add(strings("a"), tokens("a2,2"), orig, merge);
map.add(strings("a"), tokens("a4,4 a6,2"), orig, merge);
assertTokEqual(getTokList(map,"a",false), tokens("a1 a2 a3/A3 a4 a5/A5 a6"));
}
public void testOverlap() throws IOException {
SynonymMap map = new SynonymMap();
boolean orig = false;
boolean merge = true;
map.add(strings("qwe"), tokens("qq/ww/ee"), orig, merge);
map.add(strings("qwe"), tokens("xx"), orig, merge);
map.add(strings("qwe"), tokens("yy"), orig, merge);
map.add(strings("qwe"), tokens("zz"), orig, merge);
assertTokEqual(getTokList(map,"$",false), tokens("$"));
assertTokEqual(getTokList(map,"qwe",false), tokens("qq/ww/ee/xx/yy/zz"));
// test merging within the map
map.add(strings("a"), tokens("a5,5 a8,3 a10,2"), orig, merge);
map.add(strings("a"), tokens("a3,3 a7,4 a9,2 a11,2 a111,100"), orig, merge);
assertTokEqual(getTokList(map,"a",false), tokens("a3 a5,2 a7,2 a8 a9 a10 a11 a111,100"));
}
public void testOffsets() throws IOException {
SynonymMap map = new SynonymMap();
boolean orig = false;
boolean merge = true;
// test that generated tokens start at the same offset as the original
map.add(strings("a"), tokens("aa"), orig, merge);
assertTokEqual(getTokList(map,"a,5",false), tokens("aa,5"));
assertTokEqual(getTokList(map,"a,0",false), tokens("aa,0"));
// test that offset of first replacement is ignored (always takes the orig offset)
map.add(strings("b"), tokens("bb,100"), orig, merge);
assertTokEqual(getTokList(map,"b,5",false), tokens("bb,5"));
assertTokEqual(getTokList(map,"b,0",false), tokens("bb,0"));
// test that subsequent tokens are adjusted accordingly
map.add(strings("c"), tokens("cc,100 c2,2"), orig, merge);
assertTokEqual(getTokList(map,"c,5",false), tokens("cc,5 c2,2"));
assertTokEqual(getTokList(map,"c,0",false), tokens("cc,0 c2,2"));
}
public void testOffsetsWithOrig() throws IOException {
SynonymMap map = new SynonymMap();
boolean orig = true;
boolean merge = true;
// test that generated tokens start at the same offset as the original
map.add(strings("a"), tokens("aa"), orig, merge);
assertTokEqual(getTokList(map,"a,5",false), tokens("a,5/aa"));
assertTokEqual(getTokList(map,"a,0",false), tokens("a,0/aa"));
// test that offset of first replacement is ignored (always takes the orig offset)
map.add(strings("b"), tokens("bb,100"), orig, merge);
assertTokEqual(getTokList(map,"b,5",false), tokens("bb,5/b"));
assertTokEqual(getTokList(map,"b,0",false), tokens("bb,0/b"));
// test that subsequent tokens are adjusted accordingly
map.add(strings("c"), tokens("cc,100 c2,2"), orig, merge);
assertTokEqual(getTokList(map,"c,5",false), tokens("cc,5/c c2,2"));
assertTokEqual(getTokList(map,"c,0",false), tokens("cc,0/c c2,2"));
}
}
| 37.146853
| 115
| 0.637895
|
f21fbefc977faf1119f38015b6ea3e95feb8f9aa
| 3,497
|
package rs.ac.ni.pmf.web.config;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import rs.ac.ni.pmf.web.exception.ErrorInfo;
import rs.ac.ni.pmf.web.exception.ErrorInfo.ErrorType;
import rs.ac.ni.pmf.web.exception.ErrorInfo.ResourceType;
@Configuration
@EnableWebSecurity
@Slf4j
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final String[] SWAGGER_WHITELIST = {
"/swagger-ui.html",
"/swagger-ui-bundle.js",
"/swagger-ui-standalone-preset.js",
"/springfox.js",
"/v2/api-docs",
"/webjars/**",
"/swagger-resources/**"
};
@Autowired
private ObjectMapper objectMapper;
@Bean(name = "passwordEncoder")
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//@formatter:off
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/services/rest/workers/*/**")
.hasRole("ADMIN")
.antMatchers(HttpMethod.GET, SWAGGER_WHITELIST)
.permitAll()
.antMatchers(HttpMethod.GET, "/services/rest/*/**")
.permitAll()
.anyRequest()
.authenticated()
// .permitAll()
.and()
.httpBasic()
.authenticationEntryPoint((request, response, e) -> {
log.error("Authentication error: {}", e.getMessage());
final ErrorInfo errorInfo = ErrorInfo.builder()
.errorType(ErrorType.AUTHENTICATION_ERROR)
.resourceType(ResourceType.ACCESS)
.message("Failed to authorize the user. Bad username and/or password")
.build();
response.setContentType("application/json;charset=UTF-8");
response.setHeader("WWW-Authenticate", "Basic");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.getWriter().write(objectMapper.writeValueAsString(errorInfo));
})
.and()
.exceptionHandling()
.accessDeniedHandler((reqest, response, e) -> {
log.error("Authorization error: {}", e.getMessage());
final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
final String message = "User" + (auth != null ? " '" + auth.getName() + "'" : "")
+ " attempted to access the protected URL: " + reqest.getRequestURI();
final ErrorInfo errorInfo = ErrorInfo.builder()
.errorType(ErrorType.UNAUTHORIZED)
.resourceType(ResourceType.ACCESS)
.message(message)
.build();
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(errorInfo));
});
//@formatter:on
}
}
| 36.427083
| 101
| 0.725193
|
c65c948a3da06676c76d78bb4e9407b629bea832
| 1,487
|
package com.alibaba.rocketmq.common.admin;
/**
* 按时间回溯消费进度
*
* @author: manhong.yqd<jodie.yqd@gmail.com>
* @since: 13-9-12
*/
public class RollbackStats {
private String brokerName;
private long queueId;
private long brokerOffset;
private long consumerOffset;
private long timestampOffset;
private long rollbackOffset;
public String getBrokerName() {
return brokerName;
}
public void setBrokerName(String brokerName) {
this.brokerName = brokerName;
}
public long getQueueId() {
return queueId;
}
public void setQueueId(long queueId) {
this.queueId = queueId;
}
public long getBrokerOffset() {
return brokerOffset;
}
public void setBrokerOffset(long brokerOffset) {
this.brokerOffset = brokerOffset;
}
public long getConsumerOffset() {
return consumerOffset;
}
public void setConsumerOffset(long consumerOffset) {
this.consumerOffset = consumerOffset;
}
public long getTimestampOffset() {
return timestampOffset;
}
public void setTimestampOffset(long timestampOffset) {
this.timestampOffset = timestampOffset;
}
public long getRollbackOffset() {
return rollbackOffset;
}
public void setRollbackOffset(long rollbackOffset) {
this.rollbackOffset = rollbackOffset;
}
}
| 19.311688
| 59
| 0.623403
|
4d8a5052251c1b8c06d7244899202ec87b90dc00
| 393
|
package org.patientview.api.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation to exclude methods from swagger documentation
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcludeFromApiDoc {
}
| 26.2
| 59
| 0.80916
|
c14e3cff53c4c1018fa485e5e983dbb46c7d9361
| 1,932
|
/*
* Copyright (c) 2021 dzikoysk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.reposilite.journalist.backend;
import com.reposilite.journalist.Channel;
import com.reposilite.journalist.ChannelIntention;
import java.io.PrintStream;
/**
* Uses {@link java.lang.System#in} and {@link java.lang.System#err} to log messages
*/
public class PrintStreamLogger extends DefaultLogger {
private final PrintStream out;
private final PrintStream err;
private final boolean newline;
public PrintStreamLogger(PrintStream out, PrintStream err, Channel threshold, boolean newline) {
super(threshold);
this.out = out;
this.err = err;
this.newline = newline;
}
/**
* Uses {@link com.reposilite.journalist.Channel#INFO} as default threshold.
*/
public PrintStreamLogger(PrintStream out, PrintStream err) {
this(out, err, Channel.ALL, true);
}
@Override
protected void internalLog(Channel channel, String message) {
if (channel.getIntention() == ChannelIntention.NEGATIVE) {
if (newline) {
err.println(message);
}
else {
err.print(message);
}
}
else {
if (newline) {
out.println(message);
}
else {
out.print(message);
}
}
}
}
| 28.411765
| 100
| 0.637681
|
fa1b7c7b9702e7a72c0d4a3f28766e231bf7142d
| 460
|
package presentacion.vistaPrincipal;
import java.awt.Component;
import javax.swing.JPanel;
public abstract class VistaPrincipal {
private static VistaPrincipal vistasPrincipal;
public static VistaPrincipal getInstance() {
if (vistasPrincipal == null)
vistasPrincipal = new VistaPrincipalImp();
return vistasPrincipal;
}
public abstract void initGUI();
public abstract void addPanelCentral(Component c);
public abstract JPanel getPanel();
}
| 20.909091
| 51
| 0.786957
|
c485376fd5814cf94a02fb94919c274b4094e179
| 5,792
|
package org.lagonette.app.app.widget.performer.portrait;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import org.lagonette.app.BuildConfig;
import org.lagonette.app.R;
import org.lagonette.app.app.activity.PresenterActivity;
import org.lagonette.app.app.widget.performer.impl.ShowcasePerformer;
import org.lagonette.app.tools.showcase.RoundRectangleShape;
import org.zxcv.functions.main.BooleanSupplier;
import org.zxcv.functions.main.IntConsumer;
import uk.co.deanwild.materialshowcaseview.MaterialShowcaseSequence;
import uk.co.deanwild.materialshowcaseview.MaterialShowcaseView;
import uk.co.deanwild.materialshowcaseview.target.ViewTarget;
public class PortraitShowcasePerformer extends ShowcasePerformer {
public static final String SEQUENCE_ID_FILTERS = BuildConfig.APPLICATION_ID + ".sequenceId:filters";
private final int mBottomSheetShapePadding;
private final int mBottomSheetXRadius;
private final int mBottomSheetYRadius;
@NonNull
public BooleanSupplier isFiltersLoaded = BooleanSupplier::getFalse;
public PortraitShowcasePerformer(@NonNull PresenterActivity activity) {
super(activity);
mBottomSheetXRadius = activity.getResources().getDimensionPixelSize(R.dimen.showcase_bottom_sheet_radius_x);
mBottomSheetYRadius = activity.getResources().getDimensionPixelSize(R.dimen.showcase_bottom_sheet_radius_y);
mBottomSheetShapePadding = activity.getResources().getDimensionPixelSize(R.dimen.showcase_bottom_sheet_shape_padding);
}
@NonNull
@Override
protected MaterialShowcaseSequence buildMainSequence(
@NonNull PresenterActivity activity, @NonNull MaterialShowcaseSequence sequence) {
return sequence
.addSequenceItem(
new MaterialShowcaseView.Builder(activity)
.setTarget(activity.findViewById(R.id.search_bar))
.setTitleText(R.string.showcase_search_title)
.setContentText(R.string.showcase_search_content)
.setDismissText(R.string.all_button_ok)
.setMaskColour(mMaskColor)
.setShapePadding(mShapePadding)
.setShape(
new RoundRectangleShape(
new ViewTarget(activity.findViewById(R.id.search_bar)).getBounds(),
mSearchRadius,
mSearchRadius
)
)
.setDelay(mFirstDelay)
.build()
)
.addSequenceItem(
new MaterialShowcaseView.Builder(activity)
.setTarget(activity.findViewById(R.id.my_location_fab))
.setTitleText(R.string.showcase_location_title)
.setContentText(R.string.showcase_location_content)
.setDismissText(R.string.all_button_ok)
.setTargetTouchable(checkForFineLocationPermission.get())
.setMaskColour(mMaskColor)
.setShapePadding(mShapePadding)
.setDelay(mDelay)
.build()
)
.addSequenceItem(
new MaterialShowcaseView.Builder(activity)
.setTarget(activity.findViewById(R.id.filters_fab))
.setTitleText(R.string.showcase_filters_fab_title)
.setContentText(R.string.showcase_filters_fab_content)
.setDismissText(R.string.all_button_ok)
.setTargetTouchable(true)
.setMaskColour(mMaskColor)
.setShapePadding(mShapePadding)
.setDelay(mDelay)
.build()
);
}
@NonNull
@Override
public IntConsumer appendBottomSheetListener(
@NonNull PresenterActivity activity,
@NonNull IntConsumer bottomSheetStateChanged) {
MaterialShowcaseSequence filtersSequence = new MaterialShowcaseSequence(activity, SEQUENCE_ID_FILTERS);
MaterialShowcaseSequence detailsSequence = new MaterialShowcaseSequence(activity, SEQUENCE_ID_DETAIL);
if (filtersSequence.hasFired() && detailsSequence.hasFired()) {
return bottomSheetStateChanged;
}
else {
return state -> {
if (state == BottomSheetBehavior.STATE_COLLAPSED) {
if (isFiltersLoaded.get()) {
startFiltersSequence(activity, filtersSequence);
}
else if (isLocationDetailLoaded.get()) {
startDetailSequence(activity, detailsSequence);
}
}
bottomSheetStateChanged.accept(state);
};
}
}
private void startFiltersSequence(
@NonNull PresenterActivity activity,
@NonNull MaterialShowcaseSequence sequence) {
sequence
.addSequenceItem(
new MaterialShowcaseView.Builder(activity)
.setTarget(activity.findViewById(R.id.bottom_sheet))
.setTitleText(R.string.showcase_filters_title)
.setContentText(R.string.showcase_filters_content)
.setDismissText(R.string.all_button_ok)
.setMaskColour(mMaskColor)
.setShapePadding(mBottomSheetShapePadding)
.setShape(
new RoundRectangleShape(
new ViewTarget(activity.findViewById(R.id.search_bar)).getBounds(),
mBottomSheetXRadius,
mBottomSheetYRadius
)
)
.setTargetTouchable(true)
.setDelay(mNoDelay)
.build()
)
.start();
}
private void startDetailSequence(
@NonNull PresenterActivity activity,
@NonNull MaterialShowcaseSequence sequence) {
sequence
.addSequenceItem(
new MaterialShowcaseView.Builder(activity)
.setTarget(activity.findViewById(R.id.bottom_sheet))
.setTitleText(R.string.showcase_details_title)
.setContentText(R.string.showcase_details_content)
.setDismissText(R.string.all_button_ok)
.setMaskColour(mMaskColor)
.setShapePadding(mBottomSheetShapePadding)
.setShape(
new RoundRectangleShape(
new ViewTarget(activity.findViewById(R.id.search_bar)).getBounds(),
mBottomSheetXRadius,
mBottomSheetYRadius
)
)
.setTargetTouchable(true)
.setDelay(mNoDelay)
.build()
)
.start();
}
}
| 35.317073
| 120
| 0.732044
|
8ca3ed5e04ed6481c6ad30a267256e17bf20ca5c
| 825
|
package edata.web.controller.nasa;
import edata.service.InformationService;
import edata.service.nasa.PowerPressureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(PressureController.BASE_URL)
public class PressureController {
public static final String BASE_URL="/nasa/temperature/";
private final PowerPressureService powerPressureService;
private final InformationService informationService;
@Autowired
public PressureController(PowerPressureService powerPressureService, InformationService informationService) {
this.powerPressureService = powerPressureService;
this.informationService = informationService;
}
}
| 34.375
| 113
| 0.82303
|
17bfe362819700b490e66d7ef4ca24b2bd5817c4
| 8,305
|
package com.ms.meizinewsapplication.features.base.view.iview;
import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import com.ms.meizinewsapplication.R;
import com.ms.meizinewsapplication.annotation.ActivityFragmentInject;
import com.ms.meizinewsapplication.features.ad.activity.WdAdActivity;
import com.ms.meizinewsapplication.features.base.fragment.FragmentPresenterImpl;
import com.ms.meizinewsapplication.features.base.listener.MyActionBarDrawerToggle;
import com.ms.meizinewsapplication.features.base.utils.tool.ConstantData;
import com.ms.meizinewsapplication.features.base.utils.tool.DebugUtil;
import com.ms.meizinewsapplication.features.base.utils.tool.Share;
import com.ms.meizinewsapplication.features.base.utils.tool.ViewUtil;
import com.ms.meizinewsapplication.features.collect.activity.CollectActivity;
import com.ms.meizinewsapplication.features.main.activity.MainMvpActivity;
import com.ms.meizinewsapplication.features.meizi.activity.MeiZiActivity;
import com.ms.meizinewsapplication.features.video.activity.VideoPageActivity;
import com.test.basepageradapterlibrary.basepager.BaseFragmentPagerAdapter;
import org.loader.view.ViewImpl;
import java.util.ArrayList;
import java.util.List;
/**
* Created by 啟成 on 2016/3/2.
*/
@ActivityFragmentInject(
menuDefaultCheckedItem = R.id.nav_news,
toolbarTitle = R.string.ic_news
)
public class MeunIView extends ViewImpl {
protected int mMenuDefaultCheckedItem;
protected int mToolbarTitle;
protected CoordinatorLayout coordinator_layout;
protected Toolbar toolbar;
protected DrawerLayout drawer;
protected NavigationView navigationView;
protected TabLayout tabLayout;
protected ViewPager viewpager;
protected BaseFragmentPagerAdapter<FragmentPresenterImpl> baseFragmentPagerAdapter;
protected List<FragmentPresenterImpl> fragments;
protected List<String> titles;
protected Class mClass;
protected MyActionBarDrawerToggle myActionBarDrawerToggle;
protected AppCompatActivity appCompatActivity;
@Override
public void created() {
super.created();
toolbar = findViewById(R.id.toolbar);
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
tabLayout = findViewById(R.id.tabLayout);
viewpager = findViewById(R.id.viewpager);
coordinator_layout = findViewById(R.id.coordinator_layout);
}
@Override
public int getLayoutId() {
return R.layout.activity_main_mvp;
}
public boolean onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
return true;
} else {
return false;
}
}
//TODO init==================================================
/**
* 初始化
*
* @param appCompatActivity
*/
public void init(AppCompatActivity appCompatActivity) {
this.appCompatActivity = appCompatActivity;
fragments = new ArrayList<>();
titles = new ArrayList<>();
initActivityFragmentInject();
initToolbar(appCompatActivity);
initDrawer(appCompatActivity);
initNavigationView();
initFragments(appCompatActivity);
initViewPager(appCompatActivity);
initTabLayout();
}
private void initActivityFragmentInject() {
if (getClass().isAnnotationPresent(ActivityFragmentInject.class)) {
ActivityFragmentInject annotation = getClass()
.getAnnotation(ActivityFragmentInject.class);
mToolbarTitle = annotation.toolbarTitle();
mMenuDefaultCheckedItem = annotation.menuDefaultCheckedItem();
} else {
throw new RuntimeException(
"Class must add annotations of ActivityFragmentInitParams.class");
}
}
//TODO view==================================================
protected void initToolbar(AppCompatActivity appCompatActivity) {
if (mToolbarTitle != -1 && mToolbarTitle != 0) {
toolbar.setTitle(mToolbarTitle);
}
appCompatActivity.setSupportActionBar(toolbar);
}
private void initDrawer(final AppCompatActivity appCompatActivity) {
myActionBarDrawerToggle = new MyActionBarDrawerToggle(
appCompatActivity,
drawer,
toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
);
drawer.addDrawerListener(myActionBarDrawerToggle);
myActionBarDrawerToggle.syncState();
}
private void initNavigationView() {
navigationView.setNavigationItemSelectedListener(
mOnNavigationItemSelectedListener
);
if (mMenuDefaultCheckedItem != -1 && mMenuDefaultCheckedItem != 0) {
navigationView.setCheckedItem(mMenuDefaultCheckedItem);
}
}
public void initFragments(AppCompatActivity appCompatActivity) {
}
private void initViewPager(AppCompatActivity appCompatActivity) {
baseFragmentPagerAdapter = new BaseFragmentPagerAdapter<>(
appCompatActivity.getSupportFragmentManager(),
fragments,
titles
);
viewpager.setAdapter(baseFragmentPagerAdapter);
}
protected void initTabLayout() {
// viewpager.setCurrentItem(0, false);
tabLayout.setupWithViewPager(viewpager);
// tabLayout.setScrollPosition(0, 0, true);
// 根据Tab的长度动态设置TabLayout的模式
ViewUtil.dynamicSetTablayoutMode(tabLayout);
}
//TODO Listener=====================================================
/**
* 侧滑监听
*/
NavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener =
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
mClass = null;
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id) {
case R.id.nav_news:
mClass = MainMvpActivity.class;
break;
case R.id.nav_meizi:
mClass = MeiZiActivity.class;
break;
case R.id.nav_slideshow:
mClass = VideoPageActivity.class;
break;
// case R.id.nav_manage:
// break;
case R.id.nav_share:
Share.shareText(appCompatActivity, ConstantData.SHARE_APP);
break;
case R.id.nav_collect:
mClass = CollectActivity.class;
break;
case R.id.nav_get_ad:
mClass = WdAdActivity.class;
break;
}
DebugUtil.debugLogD("OnNavigationItemSelectedListener++++\n" + id);
myActionBarDrawerToggle.setmClass(mClass);
drawer.closeDrawer(GravityCompat.START);
return false;
}
};
public void meunStartActivity(Activity aty, Class<?> cls) {
Intent intent = new Intent();
intent.setClass(aty, cls);
// 此标志用于启动一个Activity的时候,若栈中存在此Activity实例,则把它调到栈顶。不创建多一个
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
aty.startActivity(intent);
// overridePendingTransition(0, 0);
aty.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}
}
| 34.460581
| 87
| 0.639494
|
854a4d59195b289afb2f98d411bd19d6fe71fcd3
| 2,708
|
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.view.shadow;
import com.android.ide.common.rendering.api.LayoutLog;
import com.android.layoutlib.bridge.Bridge;
import com.android.tools.layoutlib.annotations.VisibleForTesting;
import android.graphics.Bitmap;
import android.view.math.Math3DHelper;
/**
* Generate spot shadow bitmap.
*/
class SpotShadowTriangulator {
private final SpotShadowConfig mShadowConfig;
private float[][] mStrips;
public SpotShadowTriangulator(SpotShadowConfig config) {
mShadowConfig = config;
}
/**
* Populate the shadow bitmap.
*/
public void triangulate() {
try {
float[] lightSources =
SpotShadowVertexCalculator.calculateLight(mShadowConfig.getLightRadius(),
mShadowConfig.getLightCoord()[0],
mShadowConfig.getLightCoord()[1], mShadowConfig.getLightCoord()[2]);
mStrips = new float[2][];
int[] sizes = SpotShadowVertexCalculator.getStripSizes(mShadowConfig.getPolyLength());
for (int i = 0; i < sizes.length; ++i) {
mStrips[i] = new float[3 * sizes[i]];
}
SpotShadowVertexCalculator.calculateShadow(lightSources,
mShadowConfig.getPoly(),
mShadowConfig.getPolyLength(),
mShadowConfig.getShadowStrength(),
mStrips);
} catch (IndexOutOfBoundsException|ArithmeticException mathError) {
Bridge.getLog().warning(LayoutLog.TAG_INFO, "Arithmetic error while drawing " +
"spot shadow",
null, mathError);
} catch (Exception ex) {
Bridge.getLog().warning(LayoutLog.TAG_INFO, "Error while drawing shadow",
null, ex);
}
}
/**
* @return true if generated shadow poly is valid. False otherwise.
*/
public boolean validate() {
return mStrips != null && mStrips[0].length >= 9;
}
public float[][] getStrips() {
return mStrips;
}
}
| 33.85
| 98
| 0.629985
|
76814f9647ebc26de6093cc82acb6ee6a76d1a07
| 8,514
|
package com.baomidou.plugin.idea.mybatisx.smartjpa.operate.dialect.oracle;
import com.baomidou.plugin.idea.mybatisx.smartjpa.common.SyntaxAppender;
import com.baomidou.plugin.idea.mybatisx.smartjpa.common.appender.AreaSequence;
import com.baomidou.plugin.idea.mybatisx.smartjpa.common.appender.JdbcTypeUtils;
import com.baomidou.plugin.idea.mybatisx.smartjpa.common.appender.operator.suffix.SuffixOperator;
import com.baomidou.plugin.idea.mybatisx.smartjpa.common.factory.ResultAppenderFactory;
import com.baomidou.plugin.idea.mybatisx.smartjpa.common.iftest.ConditionFieldWrapper;
import com.baomidou.plugin.idea.mybatisx.smartjpa.component.TxField;
import com.baomidou.plugin.idea.mybatisx.smartjpa.component.TxParameter;
import com.baomidou.plugin.idea.mybatisx.smartjpa.db.adaptor.DasTableAdaptor;
import com.baomidou.plugin.idea.mybatisx.smartjpa.exp.GenerateException;
import com.baomidou.plugin.idea.mybatisx.smartjpa.operate.dialect.mysql.MysqlInsertBatch;
import com.baomidou.plugin.idea.mybatisx.smartjpa.util.SyntaxAppenderWrapper;
import com.baomidou.plugin.idea.mybatisx.util.StringUtils;
import com.intellij.database.model.DasTableKey;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiParameter;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* oracle的批量插入
*/
public class OracleInsertBatchWithAll extends MysqlInsertBatch {
private DasTableAdaptor dasTable;
private String tableName;
/**
* Instantiates a new Oracle insert batch with all.
*
* @param dasTable the das table
* @param tableName the table name
*/
public OracleInsertBatchWithAll(DasTableAdaptor dasTable, String tableName) {
this.dasTable = dasTable;
this.tableName = tableName;
}
@Override
protected @NotNull String batchName() {
return "BatchWithAll";
}
@Override
@NotNull
protected SuffixOperator getSuffixOperator(List<TxField> mappingField) {
return new InsertBatchSuffixOperator(tableName,mappingField);
}
@Override
protected ResultAppenderFactory getResultAppenderFactory(List<TxField> mappingField, String newAreaName) {
ResultAppenderFactory appenderFactory = new InsertBatchResultAppenderFactory(newAreaName) {
@Override
public String getTemplateText(String tableName, PsiClass entityClass, LinkedList<TxParameter> parameters, LinkedList<SyntaxAppenderWrapper> collector, ConditionFieldWrapper conditionFieldWrapper) {
// 定制参数
SyntaxAppender suffixOperator = InsertCustomSuffixAppender.createInsertBySuffixOperator("BatchWithAll",
getSuffixOperator(mappingField),
AreaSequence.RESULT);
LinkedList<SyntaxAppenderWrapper> syntaxAppenderWrappers = new LinkedList<>();
syntaxAppenderWrappers.add(new SyntaxAppenderWrapper(suffixOperator));
return super.getTemplateText(tableName, entityClass, parameters, syntaxAppenderWrappers, conditionFieldWrapper);
}
};
return appenderFactory;
}
private class InsertBatchResultAppenderFactory extends ResultAppenderFactory {
/**
* Instantiates a new Insert batch result appender factory.
*
* @param areaPrefix the area prefix
*/
public InsertBatchResultAppenderFactory(String areaPrefix) {
super(areaPrefix);
}
@Override
public String getTemplateText(String tableName,
PsiClass entityClass,
LinkedList<TxParameter> parameters,
LinkedList<SyntaxAppenderWrapper> collector,
ConditionFieldWrapper conditionFieldWrapper) {
StringBuilder mapperXml = new StringBuilder("insert all ");
for (SyntaxAppenderWrapper syntaxAppenderWrapper : collector) {
String templateText = syntaxAppenderWrapper.getAppender().getTemplateText(tableName, entityClass, parameters, collector, conditionFieldWrapper);
mapperXml.append(templateText);
}
mapperXml.append("select 1 from dual");
return mapperXml.toString();
}
@Override
public List<TxParameter> getMxParameter(PsiClass entityClass, LinkedList<SyntaxAppenderWrapper> jpaStringList) {
// 遍历定义的类型
String defineName = Collection.class.getSimpleName() + "<" + entityClass.getName() + ">";
// 变量名称
String variableName = StringUtils.lowerCaseFirstChar(entityClass.getName()) + "Collection";
List<String> importClass = new ArrayList<>();
importClass.add(Collection.class.getName());
importClass.add(entityClass.getQualifiedName());
TxParameter parameter = TxParameter.createByOrigin(variableName,
defineName,
Collection.class.getName(),
true,
importClass);
return Collections.singletonList(parameter);
}
}
/**
* 批量插入
*/
private class InsertBatchSuffixOperator implements SuffixOperator {
private String tableName;
@NotNull
private List<TxField> mappingField;
/**
* Instantiates a new Insert batch suffix operator.
*
* @param tableName the table name
* @param mappingField the mapping field
*/
public InsertBatchSuffixOperator(String tableName, List<TxField> mappingField) {
this.tableName = tableName;
this.mappingField = mappingField;
}
@Override
public String getTemplateText(String fieldName, LinkedList<TxParameter> parameters, ConditionFieldWrapper conditionFieldWrapper) {
Optional<String> sequenceName = dasTable.findSequenceName(tableName);
StringBuilder stringBuilder = new StringBuilder();
String itemName = "item";
// 追加列名
final String columns = mappingField.stream()
.map(TxField::getColumnName)
.collect(Collectors.joining(",\n"));
final TxParameter collection = parameters.poll();
if (collection == null) {
throw new GenerateException("oracle insertBatch 生成失败, 无法获取集合名称");
}
final String collectionName = collection.getName();
final String fields = mappingField.stream()
.map(field -> {
String fieldStr = JdbcTypeUtils.wrapperField(itemName + "." + field.getFieldName(), field.getFieldType());
// 第一版写死字段变更, 后续重构
// 变更主键生成规则为自定义函数
if (sequenceName.isPresent() && dasTable != null) {
DasTableKey primaryKey = dasTable.getPrimaryKey();
// 当前字段是主键, 使用自定义函数替换主键
if (primaryKey != null && primaryKey.getColumnsRef().size() == 1) {
String pkFieldName = primaryKey.getColumnsRef().iterate().next();
if (pkFieldName.equals(field.getColumnName())) {
fieldStr = "GET_SEQ_NO('" + sequenceName.get() + "')";
}
}
}
fieldStr = conditionFieldWrapper.wrapDefaultDateIfNecessary(field.getColumnName(), fieldStr);
return fieldStr;
})
.collect(Collectors.joining(",\n"));
stringBuilder.append("<foreach collection=\"").append(collectionName).append("\"");
stringBuilder.append(" item=\"").append(itemName).append("\"").append(">").append("\n");
stringBuilder.append("INTO ").append(tableName).append("\n");
stringBuilder.append("(").append(columns).append(")").append("\n");
stringBuilder.append("VALUES").append("\n");
// values 连接符
stringBuilder.append("(").append("\n");
stringBuilder.append(fields).append("\n").append(")").append("\n");
stringBuilder.append("</foreach>").append("\n");
return stringBuilder.toString();
}
}
}
| 42.57
| 209
| 0.642824
|
d07438531499fc2c22eb87fc8fd826290227d1cf
| 1,798
|
package disaster.com.disastermanagement;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.TextView;
/**
* Created by WAKENSYS on 6/2/2017.
*/
public class CustomEmergencyNumberAdapter extends BaseAdapter {
Context context;
Activity activity;
String[] nameList, numberList;
public CustomEmergencyNumberAdapter(Context context, Activity activity, String[] nameList, String[] numberList){
this.context = context;
this.activity = activity;
this.nameList = nameList;
this.numberList = numberList;
}
@Override
public int getCount() {
return nameList.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gvContent = inflater.inflate(R.layout.emergency_number_item_layout, null);
Animation animation = AnimationUtils.loadAnimation(context, R.anim.fade_in);
gvContent.startAnimation(animation);
final TextView nameDisplay = (TextView) gvContent.findViewById(R.id.nameDisplay);
final TextView numberDisplay = (TextView) gvContent.findViewById(R.id.numberDisplay);
nameDisplay.setText(nameList[position]);
numberDisplay.setText(numberList[position]);
return gvContent;
}
}
| 28.539683
| 116
| 0.720245
|
5e7091dff80a101b0fe841fee9bcf549ed8c8820
| 7,940
|
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Eclipse Public License, Version 1.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.eclipse.org/org/documents/epl-v10.php
*
* 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.eclipse.andmore.internal.wizards.templates;
import static org.eclipse.andmore.internal.wizards.templates.NewProjectWizard.ATTR_BUILD_API;
import static org.eclipse.andmore.internal.wizards.templates.NewProjectWizard.ATTR_MIN_API;
import static org.eclipse.andmore.internal.wizards.templates.NewProjectWizard.ATTR_MIN_API_LEVEL;
import static org.eclipse.andmore.internal.wizards.templates.NewProjectWizard.ATTR_PACKAGE_NAME;
import static org.eclipse.andmore.internal.wizards.templates.NewProjectWizard.ATTR_TARGET_API;
import com.android.annotations.NonNull;
import org.eclipse.andmore.AndmoreAndroidPlugin;
import org.eclipse.andmore.AdtUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard;
import java.io.File;
import java.util.List;
import java.util.Set;
/**
* Template wizard which creates parameterized templates
*/
public class NewTemplateWizard extends TemplateWizard {
/** Template name and location under $sdk/templates for the default activity */
static final String BLANK_ACTIVITY = "activities/BlankActivity"; //$NON-NLS-1$
/** Template name and location under $sdk/templates for the custom view template */
static final String CUSTOM_VIEW = "other/CustomView"; //$NON-NLS-1$
protected NewTemplatePage mMainPage;
protected NewTemplateWizardState mValues;
private final String mTemplateName;
NewTemplateWizard(String templateName) {
mTemplateName = templateName;
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
super.init(workbench, selection);
mValues = new NewTemplateWizardState();
File template = TemplateManager.getTemplateLocation(mTemplateName);
if (template != null) {
mValues.setTemplateLocation(template);
}
hideBuiltinParameters();
List<IProject> projects = AdtUtils.getSelectedProjects(selection);
if (projects.size() == 1) {
mValues.project = projects.get(0);
}
mMainPage = new NewTemplatePage(mValues, true);
}
@Override
protected boolean shouldAddIconPage() {
return mValues.getIconState() != null;
}
/**
* Hide those parameters that the template requires but that we don't want
* to ask the users about, since we can derive it from the target project
* the template is written into.
*/
protected void hideBuiltinParameters() {
Set<String> hidden = mValues.hidden;
hidden.add(ATTR_PACKAGE_NAME);
hidden.add(ATTR_MIN_API);
hidden.add(ATTR_MIN_API_LEVEL);
hidden.add(ATTR_TARGET_API);
hidden.add(ATTR_BUILD_API);
}
@Override
public void addPages() {
super.addPages();
addPage(mMainPage);
}
@Override
public IWizardPage getNextPage(IWizardPage page) {
TemplateMetadata template = mValues.getTemplateHandler().getTemplate();
if (page == mMainPage && shouldAddIconPage()) {
WizardPage iconPage = getIconPage(mValues.getIconState());
mValues.updateIconState(mMainPage.getEvaluator());
return iconPage;
} else if (page == mMainPage
|| shouldAddIconPage() && page == getIconPage(mValues.getIconState())) {
if (template != null) {
if (InstallDependencyPage.isInstalled(template.getDependencies())) {
return getPreviewPage(mValues);
} else {
return getDependencyPage(template, true);
}
}
} else if (page == getDependencyPage(template, false)) {
return getPreviewPage(mValues);
}
return super.getNextPage(page);
}
@Override
@NonNull
protected IProject getProject() {
return mValues.project;
}
@Override
@NonNull
protected List<String> getFilesToOpen() {
TemplateHandler activityTemplate = mValues.getTemplateHandler();
return activityTemplate.getFilesToOpen();
}
@Override
@NonNull
protected List<Runnable> getFinalizingActions() {
TemplateHandler activityTemplate = mValues.getTemplateHandler();
return activityTemplate.getFinalizingActions();
}
@Override
protected List<Change> computeChanges() {
return mValues.computeChanges();
}
/**
* Opens the given set of files (as relative paths within a given project
*
* @param project the project containing the paths
* @param relativePaths the paths to files to open
* @param mWorkbench the workbench to open the files in
*/
public static void openFiles(
@NonNull final IProject project,
@NonNull final List<String> relativePaths,
@NonNull final IWorkbench mWorkbench) {
if (!relativePaths.isEmpty()) {
// This has to be delayed in order for focus handling to work correctly
AndmoreAndroidPlugin.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
for (String path : relativePaths) {
IResource resource = project.findMember(path);
if (resource != null) {
if (resource instanceof IFile) {
try {
AndmoreAndroidPlugin.openFile((IFile) resource, null, false);
} catch (PartInitException e) {
AndmoreAndroidPlugin.log(e, "Failed to open %1$s", //$NON-NLS-1$
resource.getFullPath().toString());
}
}
boolean isLast = relativePaths.size() == 1 ||
path.equals(relativePaths.get(relativePaths.size() - 1));
if (isLast) {
BasicNewResourceWizard.selectAndReveal(resource,
mWorkbench.getActiveWorkbenchWindow());
}
}
}
}
});
}
}
/**
* Specific New Custom View wizard
*/
public static class NewCustomViewWizard extends NewTemplateWizard {
/** Creates a new {@link NewCustomViewWizard} */
public NewCustomViewWizard() {
super(CUSTOM_VIEW);
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
super.init(workbench, selection);
setWindowTitle("New Custom View");
super.mMainPage.setTitle("New Custom View");
super.mMainPage.setDescription("Creates a new custom view");
}
}
}
| 37.45283
| 100
| 0.632997
|
c9be5ca55cdf6d0315d4306f916e7d7b2fbb1015
| 41,986
|
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.siddhi.doc.gen.core.utils;
import com.google.common.io.Files;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.wso2.siddhi.annotation.Example;
import org.wso2.siddhi.annotation.Extension;
import org.wso2.siddhi.annotation.Parameter;
import org.wso2.siddhi.annotation.ReturnAttribute;
import org.wso2.siddhi.annotation.SystemParameter;
import org.wso2.siddhi.doc.gen.commons.metadata.ExampleMetaData;
import org.wso2.siddhi.doc.gen.commons.metadata.ExtensionMetaData;
import org.wso2.siddhi.doc.gen.commons.metadata.ExtensionType;
import org.wso2.siddhi.doc.gen.commons.metadata.NamespaceMetaData;
import org.wso2.siddhi.doc.gen.commons.metadata.ParameterMetaData;
import org.wso2.siddhi.doc.gen.commons.metadata.ReturnAttributeMetaData;
import org.wso2.siddhi.doc.gen.commons.metadata.SystemParameterMetaData;
import org.wso2.siddhi.doc.gen.core.freemarker.FormatDescriptionMethod;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
/**
* Utility class for getting the meta data for the extension processors in Siddhi
*/
public class DocumentationUtils {
private DocumentationUtils() { // To prevent instantiating utils class
}
/**
* Returns the extension extension meta data
* Gets the meta data from the siddhi manager
*
* @param targetDirectoryPath The path of the target directory of the maven module containing extensions
* @param logger The maven plugin logger
* @return NamespaceMetaData namespace meta data list
* @throws MojoFailureException If this fails to access project dependencies
* @throws MojoExecutionException If the classes directory from which classes are loaded is invalid
*/
public static List<NamespaceMetaData> getExtensionMetaData(String targetDirectoryPath,
List<String> runtimeClasspathElements,
Log logger)
throws MojoFailureException, MojoExecutionException {
List<NamespaceMetaData> namespaceMetaDataList = new ArrayList<NamespaceMetaData>();
int urlCount = runtimeClasspathElements.size() + 1; // +1 to include the module's target/classes folder
// Creating a list of URLs with all project dependencies
URL[] urls = new URL[urlCount];
for (int i = 0; i < runtimeClasspathElements.size(); i++) {
try {
urls[i] = new File(runtimeClasspathElements.get(i)).toURI().toURL();
} catch (MalformedURLException e) {
throw new MojoFailureException("Unable to access project dependency: "
+ runtimeClasspathElements.get(i), e);
}
}
File classesDirectory = new File(targetDirectoryPath + File.separator + Constants.CLASSES_DIRECTORY);
try {
// Adding the generated classes to the class loader
urls[urlCount - 1] = classesDirectory.toURI().toURL();
ClassLoader urlClassLoader = AccessController.doPrivileged(
(PrivilegedAction<ClassLoader>) () -> new URLClassLoader(
urls, Thread.currentThread().getContextClassLoader()
)
);
// Getting extensions from all the class files in the classes directory
addExtensionInDirectory(classesDirectory, classesDirectory.getAbsolutePath(), urlClassLoader,
namespaceMetaDataList, logger);
} catch (MalformedURLException e) {
throw new MojoExecutionException("Invalid classes directory: " + classesDirectory.getAbsolutePath(), e);
}
for (NamespaceMetaData aNamespaceMetaData : namespaceMetaDataList) {
for (List<ExtensionMetaData> extensionMetaData : aNamespaceMetaData.getExtensionMap().values()) {
Collections.sort(extensionMetaData);
}
}
Collections.sort(namespaceMetaDataList);
return namespaceMetaDataList;
}
/**
* Generate documentation related files using metadata
*
* @param namespaceMetaDataList Metadata in this repository
* @param documentationBaseDirectory The path of the directory in which the documentation will be generated
* @param documentationVersion The version of the documentation being generated
* @param logger The logger to log errors
* @throws MojoFailureException if the Mojo fails to find template file or create new documentation file
*/
public static void generateDocumentation(List<NamespaceMetaData> namespaceMetaDataList,
String documentationBaseDirectory, String documentationVersion, Log logger)
throws MojoFailureException {
// Generating data model
Map<String, Object> rootDataModel = new HashMap<>();
rootDataModel.put("metaData", namespaceMetaDataList);
rootDataModel.put("formatDescription", new FormatDescriptionMethod());
rootDataModel.put("latestDocumentationVersion", documentationVersion);
String outputFileRelativePath = Constants.API_SUB_DIRECTORY + File.separator + documentationVersion
+ Constants.MARKDOWN_FILE_EXTENSION;
generateFileFromTemplate(
Constants.MARKDOWN_DOCUMENTATION_TEMPLATE + Constants.MARKDOWN_FILE_EXTENSION
+ Constants.FREEMARKER_TEMPLATE_FILE_EXTENSION,
rootDataModel, documentationBaseDirectory, outputFileRelativePath
);
File newVersionFile = new File(documentationBaseDirectory + File.separator + outputFileRelativePath);
File latestLabelFile = new File(documentationBaseDirectory + File.separator +
Constants.API_SUB_DIRECTORY + File.separator + Constants.LATEST_FILE_NAME +
Constants.MARKDOWN_FILE_EXTENSION);
try {
Files.copy(newVersionFile, latestLabelFile);
} catch (IOException e) {
logger.warn("Failed to generate latest.md file", e);
}
}
/**
* Update the documentation home page
*
* @param inputFile The path to the input file
* @param outputFile The path to the output file
* @param extensionRepositoryName The name of the extension repository
* @param latestDocumentationVersion The version of the latest documentation generated
* @param namespaceMetaDataList Metadata in this repository
* @throws MojoFailureException if the Mojo fails to find template file or create new documentation file
*/
public static void updateHeadingsInMarkdownFile(File inputFile, File outputFile,
String extensionRepositoryName,
String latestDocumentationVersion,
List<NamespaceMetaData> namespaceMetaDataList)
throws MojoFailureException {
// Retrieving the content of the README.md file
List<String> inputFileLines = new ArrayList<>();
try {
inputFileLines = Files.readLines(inputFile, Constants.DEFAULT_CHARSET);
} catch (IOException ignored) {
}
// Generating data model
Map<String, Object> rootDataModel = new HashMap<>();
rootDataModel.put("inputFileLines", inputFileLines);
rootDataModel.put("extensionRepositoryName", extensionRepositoryName);
rootDataModel.put("latestDocumentationVersion", latestDocumentationVersion);
rootDataModel.put("metaData", namespaceMetaDataList);
rootDataModel.put("formatDescription", new FormatDescriptionMethod());
generateFileFromTemplate(
Constants.MARKDOWN_HEADINGS_UPDATE_TEMPLATE + Constants.MARKDOWN_FILE_EXTENSION
+ Constants.FREEMARKER_TEMPLATE_FILE_EXTENSION,
rootDataModel, outputFile.getParent(), outputFile.getName()
);
}
/**
* Remove the snapshot version documentation files from docs/api directory
*
* @param mkdocsConfigFile The mkdocs configuration file
* @param documentationBaseDirectory The path of the base directory in which the documentation will be generated
* @param logger The maven plugin logger
*/
public static void removeSnapshotAPIDocs(File mkdocsConfigFile, String documentationBaseDirectory, Log logger) {
// Retrieving the documentation file names
File apiDocsDirectory = new File(documentationBaseDirectory
+ File.separator + Constants.API_SUB_DIRECTORY);
String[] documentationFileNames = apiDocsDirectory.list(
(directory, fileName) -> fileName.endsWith(Constants.MARKDOWN_FILE_EXTENSION)
);
if (documentationFileNames != null) {
// Removing snapshot files and creating a list of the files that are left out
for (String documentationFileName : documentationFileNames) {
if (documentationFileName.endsWith(Constants.SNAPSHOT_VERSION_POSTFIX
+ Constants.MARKDOWN_FILE_EXTENSION)) {
// Removing the snapshot documentation file
File documentationFile = new File(apiDocsDirectory.getAbsolutePath()
+ File.separator + documentationFileName);
if (!documentationFile.delete()) {
logger.warn("Failed to delete SNAPSHOT documentation file "
+ documentationFile.getAbsolutePath());
}
}
}
}
}
/**
* This add a new page to the list of pages in the mkdocs configuration
*
* @param mkdocsConfigFile The mkdocs configuration file
* @param documentationBaseDirectory The base directory of the documentation
* @throws FileNotFoundException If mkdocs configuration file is not found
*/
public static void updateAPIPagesInMkdocsConfig(File mkdocsConfigFile, String documentationBaseDirectory)
throws FileNotFoundException {
// Retrieving the documentation file names
File documentationDirectory = new File(documentationBaseDirectory
+ File.separator + Constants.API_SUB_DIRECTORY);
String[] documentationFiles = documentationDirectory.list(
(directory, fileName) -> fileName.endsWith(Constants.MARKDOWN_FILE_EXTENSION)
);
List<String> apiDirectoryContent;
if (documentationFiles == null) {
apiDirectoryContent = new ArrayList<>();
} else {
apiDirectoryContent = Arrays.asList(documentationFiles);
apiDirectoryContent.sort(new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
String[] s1s = s1.split("\\D+");
String[] s2s = s2.split("\\D+");
int i = 0;
while (s1s.length > i || s2s.length > i) {
String s1a = "0";
String s2a = "0";
if (s1s.length > i) {
s1a = s1s[i];
}
if (s2s.length > i) {
s2a = s2s[i];
}
int s1aInt = Integer.parseInt(s1a);
int s2aInt = Integer.parseInt(s2a);
if (s2aInt > s1aInt) {
return 1;
} else if (s2aInt < s1aInt) {
return -1;
}
i++;
}
return 0;
}
});
}
String latestVersionFile = null;
if (apiDirectoryContent.size() > 1) {
String first = apiDirectoryContent.get(0);
String second = apiDirectoryContent.get(1);
if (first.equals(Constants.LATEST_FILE_NAME + Constants.MARKDOWN_FILE_EXTENSION)) {
latestVersionFile = second;
}
}
// Creating yaml parser
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(dumperOptions);
// Reading the mkdocs configuration
Map<String, Object> yamlConfig = (Map<String, Object>) yaml.load(new InputStreamReader(
new FileInputStream(mkdocsConfigFile), Constants.DEFAULT_CHARSET)
);
// Getting the pages list
List<Map<String, Object>> yamlConfigPagesList =
(List<Map<String, Object>>) yamlConfig.get(Constants.MKDOCS_CONFIG_PAGES_KEY);
// Creating the new api pages list
List<Map<String, Object>> apiPagesList = new ArrayList<>();
for (String apiFile : apiDirectoryContent) {
String pageName = apiFile.substring(0, apiFile.length() - Constants.MARKDOWN_FILE_EXTENSION.length());
Map<String, Object> newPage = new HashMap<>();
if (latestVersionFile != null && pageName.equals(Constants.LATEST_FILE_NAME)) {
pageName = "Latest (" + latestVersionFile.substring(0, latestVersionFile.length() -
Constants.MARKDOWN_FILE_EXTENSION.length()) + ")";
}
newPage.put(pageName, Constants.API_SUB_DIRECTORY + Constants.MKDOCS_FILE_SEPARATOR + apiFile);
apiPagesList.add(newPage);
}
// Setting the new api pages
Map<String, Object> yamlConfigAPIPage = null;
for (Map<String, Object> yamlConfigPage : yamlConfigPagesList) {
if (yamlConfigPage.get(Constants.MKDOCS_CONFIG_PAGES_API_KEY) != null) {
yamlConfigAPIPage = yamlConfigPage;
break;
}
}
if (yamlConfigAPIPage == null) {
yamlConfigAPIPage = new HashMap<>();
yamlConfigPagesList.add(yamlConfigAPIPage);
}
yamlConfigAPIPage.put(Constants.MKDOCS_CONFIG_PAGES_API_KEY, apiPagesList);
// Saving the updated configuration
yaml.dump(yamlConfig, new OutputStreamWriter(
new FileOutputStream(mkdocsConfigFile), Constants.DEFAULT_CHARSET)
);
}
/**
* Generate a extension index file from the template file
*
* @param extensionRepositories The list of extension repository names
* @param extensionRepositoryOwner The extension repository owner's name
* @param documentationBaseDirectory The output directory path in which the extension index will be generated
* @param extensionsIndexFileName The name of the index file that will be generated
* @throws MojoFailureException if the Mojo fails to find template file or create new documentation file
*/
public static void createExtensionsIndex(List<String> extensionRepositories, String extensionRepositoryOwner,
String documentationBaseDirectory, String extensionsIndexFileName)
throws MojoFailureException {
// Separating Apache and GPL extensions based on siddhi repository prefix conventions
List<String> gplExtensionRepositories = new ArrayList<>();
List<String> apacheExtensionRepositories = new ArrayList<>();
for (String extensionRepository : extensionRepositories) {
if (extensionRepository.startsWith(Constants.GITHUB_GPL_EXTENSION_REPOSITORY_PREFIX)) {
gplExtensionRepositories.add(extensionRepository);
} else if (extensionRepository.startsWith(Constants.GITHUB_APACHE_EXTENSION_REPOSITORY_PREFIX)) {
apacheExtensionRepositories.add(extensionRepository);
}
}
// Generating data model
Map<String, Object> rootDataModel = new HashMap<>();
rootDataModel.put("extensionsOwner", extensionRepositoryOwner);
rootDataModel.put("gplExtensionRepositories", gplExtensionRepositories);
rootDataModel.put("apacheExtensionRepositories", apacheExtensionRepositories);
generateFileFromTemplate(
Constants.MARKDOWN_EXTENSIONS_INDEX_TEMPLATE + Constants.MARKDOWN_FILE_EXTENSION
+ Constants.FREEMARKER_TEMPLATE_FILE_EXTENSION,
rootDataModel, documentationBaseDirectory,
extensionsIndexFileName + Constants.MARKDOWN_FILE_EXTENSION
);
}
/**
* Build the mkdocs site using the mkdocs config file
*
* @param mkdocsConfigFile The mkdocs configuration file
* @param logger The maven logger
* @return true if the documentation generation is successful
*/
public static boolean generateMkdocsSite(File mkdocsConfigFile, Log logger) {
boolean isDocumentationGenerationSuccessful = false;
try {
// Building the mkdocs site
executeCommand(new String[]{Constants.MKDOCS_COMMAND,
Constants.MKDOCS_BUILD_COMMAND,
Constants.MKDOCS_BUILD_COMMAND_CLEAN_ARGUEMENT,
Constants.MKDOCS_BUILD_COMMAND_CONFIG_FILE_ARGUMENT,
mkdocsConfigFile.getAbsolutePath(),
Constants.MKDOCS_BUILD_COMMAND_SITE_DIRECTORY_ARGUMENT,
Constants.MKDOCS_SITE_DIRECTORY}, logger);
isDocumentationGenerationSuccessful = true;
} catch (Throwable t) {
logger.warn("Failed to generate the mkdocs site.", t);
}
return isDocumentationGenerationSuccessful;
}
/**
* Deploy the mkdocs website on GitHub pages
*
* @param version The version of the documentation
* @param baseDirectory The base directory of the project
* @param url The SCM URL
* @param scmUsername The SCM username
* @param scmPassword The SCM password
* @param logger The maven logger
*/
public static void deployMkdocsOnGitHubPages(String version, File baseDirectory, String url, String scmUsername,
String scmPassword, Log logger) {
try {
// Find initial branch name
List<String> gitStatusOutput = getCommandOutput(new String[]{Constants.GIT_COMMAND,
Constants.GIT_BRANCH_COMMAND}, logger);
String initialBranch = null;
for (String gitStatusOutputLine : gitStatusOutput) {
if (gitStatusOutputLine.startsWith(Constants.GIT_BRANCH_COMMAND_OUTPUT_CURRENT_BRANCH_PREFIX)) {
initialBranch = gitStatusOutputLine.substring(
Constants.GIT_BRANCH_COMMAND_OUTPUT_CURRENT_BRANCH_PREFIX.length());
}
}
if (initialBranch != null) {
// Stash changes
executeCommand(new String[]{Constants.GIT_COMMAND,
Constants.GIT_STASH_COMMAND}, logger);
// Change to gh-pages branch. This will not do anything if a new branch was created in the last command.
executeCommand(new String[]{Constants.GIT_COMMAND,
Constants.GIT_CHECKOUT_COMMAND,
Constants.GIT_GH_PAGES_BRANCH}, logger);
// Create branch if it does not exist. This will fail if the branch exists and will not do anything.
executeCommand(new String[]{Constants.GIT_COMMAND,
Constants.GIT_CHECKOUT_COMMAND,
Constants.GIT_CHECKOUT_COMMAND_ORPHAN_ARGUMENT,
Constants.GIT_GH_PAGES_BRANCH}, logger);
executeCommand(new String[]{Constants.GIT_COMMAND,
Constants.GIT_PULL_COMMAND,
Constants.GIT_REMOTE,
Constants.GIT_GH_PAGES_BRANCH}, logger);
// Getting the site that was built by mkdocs
File siteDirectory = new File(Constants.MKDOCS_SITE_DIRECTORY);
FileUtils.copyDirectory(siteDirectory, baseDirectory);
String[] siteDirectoryContent = siteDirectory.list();
// Pushing the site to GitHub (Assumes that site/ directory is ignored by git)
if (siteDirectoryContent != null && siteDirectoryContent.length > 0) {
List<String> gitAddCommand = new ArrayList<>();
Collections.addAll(gitAddCommand, Constants.GIT_COMMAND,
Constants.GIT_ADD_COMMAND);
Collections.addAll(gitAddCommand, siteDirectoryContent);
executeCommand(gitAddCommand.toArray(new String[gitAddCommand.size()]), logger);
List<String> gitCommitCommand = new ArrayList<>();
Collections.addAll(gitCommitCommand, Constants.GIT_COMMAND,
Constants.GIT_COMMIT_COMMAND,
Constants.GIT_COMMIT_COMMAND_MESSAGE_ARGUMENT,
String.format(Constants.GIT_COMMIT_COMMAND_MESSAGE_FORMAT, version, version),
Constants.GIT_COMMIT_COMMAND_FILES_ARGUMENT);
Collections.addAll(gitCommitCommand, siteDirectoryContent);
executeCommand(gitCommitCommand.toArray(new String[gitCommitCommand.size()]), logger);
if (scmUsername != null && scmPassword != null && url != null) {
// Using scm username and password env var values
String urlWithUsernameAndPassword = url.replaceFirst(Constants.GITHUB_URL,
Constants.GITHUB_URL_WITH_USERNAME_PASSWORD);
executeCommand(new String[]{Constants.GIT_COMMAND,
Constants.GIT_PUSH_COMMAND,
String.format(urlWithUsernameAndPassword, scmUsername, scmPassword),
Constants.GIT_GH_PAGES_BRANCH}, logger);
} else {
// Using git credential store
executeCommand(new String[]{Constants.GIT_COMMAND,
Constants.GIT_PUSH_COMMAND,
Constants.GIT_REMOTE,
Constants.GIT_GH_PAGES_BRANCH}, logger);
}
}
// Changing back to initial branch
executeCommand(new String[]{Constants.GIT_COMMAND,
Constants.GIT_CHECKOUT_COMMAND,
initialBranch}, logger);
executeCommand(new String[]{Constants.GIT_COMMAND,
Constants.GIT_STASH_COMMAND,
Constants.GIT_STASH_POP_COMMAND}, logger);
} else {
logger.warn("Unable to parse git-status command and retrieve current git branch. " +
"Skipping deployment.");
}
} catch (Throwable t) {
logger.warn("Failed to deploy the documentation on github pages.", t);
}
}
/**
* Commit the documentation directory and the mkdocs config file
*
* @param docsDirectory The docs drectory
* @param mkdocsConfigFile The mkdocs configuration file
* @param readmeFile The read me file
* @param version The version of the documentation
* @param logger The maven logger
*/
public static void updateDocumentationOnGitHub(String docsDirectory, File mkdocsConfigFile, File readmeFile,
String version, Log logger) {
try {
executeCommand(new String[]{Constants.GIT_COMMAND,
Constants.GIT_ADD_COMMAND,
docsDirectory, mkdocsConfigFile.getAbsolutePath(), readmeFile.getAbsolutePath()}, logger);
executeCommand(new String[]{Constants.GIT_COMMAND,
Constants.GIT_COMMIT_COMMAND,
Constants.GIT_COMMIT_COMMAND_MESSAGE_ARGUMENT,
String.format(Constants.GIT_COMMIT_COMMAND_MESSAGE_FORMAT, version, version),
Constants.GIT_COMMIT_COMMAND_FILES_ARGUMENT,
docsDirectory, mkdocsConfigFile.getAbsolutePath(), readmeFile.getAbsolutePath()}, logger);
} catch (Throwable t) {
logger.warn("Failed to update the documentation on GitHub repository", t);
}
}
/**
* Search for class files in the directory and add extensions from them
* This method recursively searches the sub directories
*
* @param moduleTargetClassesDirectory The directory from which the extension metadata will be loaded
* @param classesDirectoryPath The absolute path to the classes directory in the target folder in the module
* @param urlClassLoader The url class loader which should be used for loading the classes
* @param namespaceMetaDataList List of namespace meta data
* @param logger The maven logger
*/
private static void addExtensionInDirectory(File moduleTargetClassesDirectory, String classesDirectoryPath,
ClassLoader urlClassLoader,
List<NamespaceMetaData> namespaceMetaDataList, Log logger) {
File[] innerFiles = moduleTargetClassesDirectory.listFiles();
if (innerFiles != null) {
for (File innerFile : innerFiles) {
if (innerFile.isDirectory()) {
addExtensionInDirectory(innerFile, classesDirectoryPath, urlClassLoader, namespaceMetaDataList,
logger);
} else {
addExtensionInFile(innerFile, classesDirectoryPath, urlClassLoader, namespaceMetaDataList,
logger);
}
}
}
}
/**
* Add an extension annotation in a file
* This first checks if this is a class file and loads the class and adds the annotation if present
*
* @param file The file from which the extension metadata will be loaded
* @param classesDirectoryPath The absolute path to the classes directory in the target folder in the module
* @param urlClassLoader The url class loader which should be used for loading the classes
* @param namespaceMetaDataList List of namespace meta data
* @param logger The maven logger
*/
private static void addExtensionInFile(File file, String classesDirectoryPath, ClassLoader urlClassLoader,
List<NamespaceMetaData> namespaceMetaDataList, Log logger) {
String filePath = file.getAbsolutePath();
if (filePath.endsWith(Constants.CLASS_FILE_EXTENSION) &&
filePath.length() > classesDirectoryPath.length()) {
String relativePathToClass = filePath.substring((classesDirectoryPath + File.separator).length());
try {
// Loading class
Class<?> extensionClass = Class.forName(
relativePathToClass
.substring(0, relativePathToClass.length() - Constants.CLASS_FILE_EXTENSION.length())
.replace(File.separator, "."),
false, urlClassLoader
);
// Generating metadata and adding the it to the list of relevant extensions
addExtensionMetaDataIntoNamespaceList(namespaceMetaDataList, extensionClass, logger);
} catch (Throwable ignored) {
logger.warn("Ignoring the failed class loading from " + file.getAbsolutePath());
}
}
}
/**
* Generate extension meta data from the annotated data in the class
*
* @param namespaceList The list of namespaces to which the new extension will be added
* @param extensionClass Class from which meta data should be extracted from
* @param logger The maven plugin logger
*/
private static void addExtensionMetaDataIntoNamespaceList(List<NamespaceMetaData> namespaceList,
Class<?> extensionClass, Log logger) {
Extension extensionAnnotation = extensionClass.getAnnotation(Extension.class);
if (extensionAnnotation != null) { // Discarding extension classes without annotation
ExtensionMetaData extensionMetaData = new ExtensionMetaData();
// Finding extension type
String extensionType = null;
for (Map.Entry<ExtensionType, Class<?>> entry : ExtensionType.getSuperClassMap().entrySet()) {
Class<?> superClass = entry.getValue();
if (superClass.isAssignableFrom(extensionClass) && superClass != extensionClass) {
extensionType = entry.getKey().getValue();
break;
}
}
// Discarding the extension if it belongs to an unknown type
if (extensionType == null) {
logger.warn("Discarding extension (belonging to an unknown extension type): "
+ extensionClass.getCanonicalName());
return;
}
extensionMetaData.setName(extensionAnnotation.name());
extensionMetaData.setDescription(extensionAnnotation.description());
// Adding query parameters
ParameterMetaData[] parameters = new ParameterMetaData[extensionAnnotation.parameters().length];
for (int i = 0; i < extensionAnnotation.parameters().length; i++) {
Parameter parameterAnnotation = extensionAnnotation.parameters()[i];
ParameterMetaData parameter = new ParameterMetaData();
parameter.setName(parameterAnnotation.name());
parameter.setType(Arrays.asList(parameterAnnotation.type()));
parameter.setDescription(parameterAnnotation.description());
parameter.setOptional(parameterAnnotation.optional());
parameter.setDynamic(parameterAnnotation.dynamic());
parameter.setDefaultValue(parameterAnnotation.defaultValue());
parameters[i] = parameter;
}
extensionMetaData.setParameters(Arrays.asList(parameters));
// Adding system parameters
SystemParameterMetaData[] systemParameters =
new SystemParameterMetaData[extensionAnnotation.systemParameter().length];
for (int i = 0; i < extensionAnnotation.systemParameter().length; i++) {
SystemParameter systemParameterAnnotation = extensionAnnotation.systemParameter()[i];
SystemParameterMetaData systemParameter = new SystemParameterMetaData();
systemParameter.setName(systemParameterAnnotation.name());
systemParameter.setDescription(systemParameterAnnotation.description());
systemParameter.setDefaultValue(systemParameterAnnotation.defaultValue());
systemParameter.setPossibleParameters(Arrays.asList(systemParameterAnnotation.possibleParameters()));
systemParameters[i] = systemParameter;
}
extensionMetaData.setSystemParameters(Arrays.asList(systemParameters));
// Adding return attributes
ReturnAttributeMetaData[] returnAttributes =
new ReturnAttributeMetaData[extensionAnnotation.returnAttributes().length];
for (int i = 0; i < extensionAnnotation.returnAttributes().length; i++) {
ReturnAttribute parameterAnnotation = extensionAnnotation.returnAttributes()[i];
ReturnAttributeMetaData returnAttribute = new ReturnAttributeMetaData();
returnAttribute.setName(parameterAnnotation.name());
returnAttribute.setType(Arrays.asList(parameterAnnotation.type()));
returnAttribute.setDescription(parameterAnnotation.description());
returnAttributes[i] = returnAttribute;
}
extensionMetaData.setReturnAttributes(Arrays.asList(returnAttributes));
// Adding examples
ExampleMetaData[] examples = new ExampleMetaData[extensionAnnotation.examples().length];
for (int i = 0; i < extensionAnnotation.examples().length; i++) {
Example exampleAnnotation = extensionAnnotation.examples()[i];
ExampleMetaData exampleMetaData = new ExampleMetaData();
exampleMetaData.setSyntax(exampleAnnotation.syntax());
exampleMetaData.setDescription(exampleAnnotation.description());
examples[i] = exampleMetaData;
}
extensionMetaData.setExamples(Arrays.asList(examples));
// Finding the namespace
String namespaceName = extensionAnnotation.namespace();
if (Objects.equals(namespaceName, "")) {
namespaceName = Constants.CORE_NAMESPACE;
}
// Finding the relevant namespace in the namespace list
NamespaceMetaData namespace = null;
for (NamespaceMetaData existingNamespace : namespaceList) {
if (Objects.equals(existingNamespace.getName(), namespaceName)) {
namespace = existingNamespace;
break;
}
}
// Creating namespace if it doesn't exist
if (namespace == null) {
namespace = new NamespaceMetaData();
namespace.setName(namespaceName);
namespace.setExtensionMap(new TreeMap<>());
namespaceList.add(namespace);
}
// Adding to the relevant extension metadata list in the namespace
List<ExtensionMetaData> extensionMetaDataList = namespace.getExtensionMap()
.computeIfAbsent(extensionType, k -> new ArrayList<>());
extensionMetaDataList.add(extensionMetaData);
}
}
/**
* Generate a file from a template
*
* @param templateFile The template file name
* @param dataModel The data model to be used for generating the output files from template files
* @param outputDirectory The output directory in which the file will be generated
* @param outputFileName The name of the file that will be generated
* @throws MojoFailureException if the Mojo fails to find template file or create new documentation file
*/
private static void generateFileFromTemplate(String templateFile, Map<String, Object> dataModel,
String outputDirectory, String outputFileName)
throws MojoFailureException {
// Creating the free marker configuration
Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setClassForTemplateLoading(
DocumentationUtils.class,
File.separator + Constants.TEMPLATES_DIRECTORY
);
// Adding the constants to the freemarker data model
Map<String, String> constantsClassFieldMap = new HashMap<>();
for (Field field : Constants.class.getDeclaredFields()) {
try {
constantsClassFieldMap.put(field.getName(), field.get(null).toString());
} catch (IllegalAccessException ignored) { // Ignoring inaccessible variables
}
}
dataModel.put("CONSTANTS", constantsClassFieldMap);
// Adding the ExtensionType enum values to the freemarker data model
Map<String, String> extensionTypeEnumMap = new HashMap<>();
for (Field field : ExtensionType.class.getDeclaredFields()) {
try {
if (field.isEnumConstant()) {
extensionTypeEnumMap.put(field.getName(), ((ExtensionType) field.get(null)).getValue());
}
} catch (IllegalAccessException ignored) { // Ignoring inaccessible variables
}
}
dataModel.put("EXTENSION_TYPE", extensionTypeEnumMap);
try {
// Fetching the template
Template template = cfg.getTemplate(templateFile);
// Generating empty documentation files
File outputFile = new File(outputDirectory + File.separator + outputFileName);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
throw new MojoFailureException("Unable to create directory " + outputFile.getParentFile());
}
}
if (!outputFile.exists()) {
if (!outputFile.createNewFile()) {
throw new MojoFailureException("Unable to create file " + outputFile.getAbsolutePath());
}
}
// Writing to the documentation file
try (OutputStream outputStream = new FileOutputStream(outputFile)) {
try (Writer writer = new OutputStreamWriter(outputStream, Charset.defaultCharset())) {
template.process(dataModel, writer);
}
} catch (TemplateException e) {
throw new MojoFailureException("Invalid Free Marker template found in " + templateFile, e);
}
} catch (IOException e) {
throw new MojoFailureException("Unable to find template file " + templateFile, e);
}
}
/**
* Executing a command
*
* @param command The command to be executed
* @param logger The maven plugin logger
* @return The output lines from executing the command
* @throws Throwable if any error occurs during the execution of the command
*/
private static List<String> getCommandOutput(String[] command, Log logger) throws Throwable {
logger.info("Executing: " + String.join(" ", command));
Process process = Runtime.getRuntime().exec(command);
List<String> executionOutputLines = new ArrayList<>();
// Logging the output of the command execution
InputStream[] inputStreams = new InputStream[]{process.getInputStream(), process.getErrorStream()};
BufferedReader bufferedReader = null;
try {
for (InputStream inputStream : inputStreams) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, Constants.DEFAULT_CHARSET));
String commandOutput;
while (true) {
commandOutput = bufferedReader.readLine();
if (commandOutput == null) {
break;
}
executionOutputLines.add(commandOutput);
}
}
process.waitFor();
} finally {
IOUtils.closeQuietly(bufferedReader);
}
return executionOutputLines;
}
/**
* Executing a command.
*
* @param command The command to be executed
* @param logger The maven plugin logger
* @throws Throwable if any error occurs during the execution of the command
*/
private static void executeCommand(String[] command, Log logger) throws Throwable {
List<String> executionOutputLines = getCommandOutput(command, logger);
for (String executionOutputLine : executionOutputLines) {
logger.debug(executionOutputLine);
}
}
}
| 49.805457
| 120
| 0.628852
|
1e5289503cc89b06bdaf2a5de423c5f9bff2adf8
| 21,388
|
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenType;
import org.openapitools.codegen.SupportingFile;
import org.openapitools.codegen.meta.GeneratorMetadata;
import org.openapitools.codegen.meta.Stability;
import org.openapitools.codegen.utils.ModelUtils;
import java.io.File;
import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.camelize;
public class CppUE4ClientCodegen extends AbstractCppCodegen {
public static final String CPP_NAMESPACE = "cppNamespace";
public static final String CPP_NAMESPACE_DESC = "C++ namespace (convention: name::space::for::api).";
public static final String UNREAL_MODULE_NAME = "unrealModuleName";
public static final String UNREAL_MODULE_NAME_DESC = "Name of the generated unreal module (optional)";
public static final String OPTIONAL_PROJECT_FILE_DESC = "Generate Build.cs";
protected String unrealModuleName = "OpenAPI";
// Will be treated as pointer
protected Set<String> pointerClasses = new HashSet<String>();
// source folder where to write the files
protected String privateFolder = "Private";
protected String publicFolder = "Public";
protected String apiVersion = "1.0.0";
protected Map<String, String> namespaces = new HashMap<String, String>();
// Will be included using the <> syntax, not used in Unreal's coding convention
protected Set<String> systemIncludes = new HashSet<String>();
protected String cppNamespace = unrealModuleName;
protected boolean optionalProjectFileFlag = true;
public CppUE4ClientCodegen() {
super();
generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
.stability(Stability.BETA)
.build();
// set the output folder here
outputFolder = "generated-code/cpp-ue4";
// set modelNamePrefix as default for cpp-ue4
if ("".equals(modelNamePrefix)) {
modelNamePrefix = unrealModuleName;
}
/*
* Models. You can write model files using the modelTemplateFiles map.
* if you want to create one template for file, you can do so here.
* for multiple files for model, just put another entry in the `modelTemplateFiles` with
* a different extension
*/
modelTemplateFiles.put(
"model-header.mustache",
".h");
modelTemplateFiles.put(
"model-source.mustache",
".cpp");
/*
* Api classes. You can write classes for each Api file with the apiTemplateFiles map.
* as with models, add multiple entries with different extensions for multiple files per
* class
*/
apiTemplateFiles.put(
"api-header.mustache", // the template to use
".h"); // the extension for each file to write
apiTemplateFiles.put(
"api-source.mustache", // the template to use
".cpp"); // the extension for each file to write
apiTemplateFiles.put(
"api-operations-header.mustache", // the template to use
".h"); // the extension for each file to write
apiTemplateFiles.put(
"api-operations-source.mustache", // the template to use
".cpp"); // the extension for each file to write
/*
* Template Location. This is the location which templates will be read from. The generator
* will use the resource stream to attempt to read the templates.
*/
embeddedTemplateDir = templateDir = "cpp-ue4";
// CLI options
addOption(CPP_NAMESPACE, CPP_NAMESPACE_DESC, this.cppNamespace);
addOption(UNREAL_MODULE_NAME, UNREAL_MODULE_NAME_DESC, this.unrealModuleName);
addSwitch(CodegenConstants.OPTIONAL_PROJECT_FILE, OPTIONAL_PROJECT_FILE_DESC, this.optionalProjectFileFlag);
/*
* Additional Properties. These values can be passed to the templates and
* are available in models, apis, and supporting files
*/
additionalProperties.put("apiVersion", apiVersion);
additionalProperties().put("modelNamePrefix", modelNamePrefix);
additionalProperties().put("modelPackage", modelPackage);
additionalProperties().put("apiPackage", apiPackage);
additionalProperties().put("dllapi", unrealModuleName.toUpperCase(Locale.ROOT) + "_API");
additionalProperties().put("unrealModuleName", unrealModuleName);
// Write defaults namespace in properties so that it can be accessible in templates.
// At this point command line has not been parsed so if value is given
// in command line it will superseed this content
additionalProperties.put("cppNamespace", cppNamespace);
additionalProperties.put("unrealModuleName", unrealModuleName);
/*
* Language Specific Primitives. These types will not trigger imports by
* the client generator
*/
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"bool",
"int32",
"int64",
"float",
"double",
"FString",
"FDateTime",
"FGuid",
"TArray",
"TArray<uint8>", // For byte arrays
"TMap",
"TSharedPtr<FJsonObject>",
"TSharedPtr<FJsonValue>")
);
supportingFiles.add(new SupportingFile("model-base-header.mustache", publicFolder, modelNamePrefix + "BaseModel.h"));
supportingFiles.add(new SupportingFile("model-base-source.mustache", privateFolder, modelNamePrefix + "BaseModel.cpp"));
supportingFiles.add(new SupportingFile("helpers-header.mustache", publicFolder, modelNamePrefix + "Helpers.h"));
supportingFiles.add(new SupportingFile("helpers-source.mustache", privateFolder, modelNamePrefix + "Helpers.cpp"));
if (optionalProjectFileFlag) {
supportingFiles.add(new SupportingFile("Build.cs.mustache", unrealModuleName + ".Build.cs"));
supportingFiles.add(new SupportingFile("module-header.mustache", privateFolder, unrealModuleName + "Module.h"));
supportingFiles.add(new SupportingFile("module-source.mustache", privateFolder, unrealModuleName + "Module.cpp"));
}
super.typeMapping = new HashMap<String, String>();
// Maps C++ types during call to getSchemaType, see DefaultCodegen.getSchemaType and not the types/formats
// defined in openapi specification "array" is also used explicitly in the generator for containers
typeMapping.clear();
typeMapping.put("integer", "int32");
typeMapping.put("long", "int64");
typeMapping.put("float", "float");
typeMapping.put("number", "double");
typeMapping.put("double", "double");
typeMapping.put("string", "FString");
typeMapping.put("byte", "uint8");
typeMapping.put("binary", "TArray<uint8>");
typeMapping.put("ByteArray", "TArray<uint8>");
typeMapping.put("password", "FString");
typeMapping.put("boolean", "bool");
typeMapping.put("date", "FDateTime");
typeMapping.put("Date", "FDateTime");
typeMapping.put("date-time", "FDateTime");
typeMapping.put("DateTime", "FDateTime");
typeMapping.put("array", "TArray");
typeMapping.put("list", "TArray");
typeMapping.put("map", "TMap");
typeMapping.put("object", "TSharedPtr<FJsonObject>");
typeMapping.put("Object", "TSharedPtr<FJsonObject>");
typeMapping.put("file", "HttpFileInput");
typeMapping.put("UUID", "FGuid");
typeMapping.put("AnyType", "TSharedPtr<FJsonValue>");
importMapping = new HashMap<String, String>();
importMapping.put("HttpFileInput", "#include \"" + modelNamePrefix + "Helpers.h\"");
namespaces = new HashMap<String, String>();
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey("cppNamespace")) {
cppNamespace = (String) additionalProperties.get("cppNamespace");
}
additionalProperties.put("cppNamespaceDeclarations", cppNamespace.split("\\::"));
boolean updateSupportingFiles = false;
if (additionalProperties.containsKey("unrealModuleName")) {
unrealModuleName = (String) additionalProperties.get("unrealModuleName");
additionalProperties().put("dllapi", unrealModuleName.toUpperCase(Locale.ROOT) + "_API");
modelNamePrefix = unrealModuleName;
updateSupportingFiles = true;
}
if (additionalProperties.containsKey("modelNamePrefix")) {
modelNamePrefix = (String) additionalProperties.get("modelNamePrefix");
updateSupportingFiles = true;
}
if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_PROJECT_FILE)) {
setOptionalProjectFileFlag(convertPropertyToBooleanAndWriteBack(CodegenConstants.OPTIONAL_PROJECT_FILE));
} else {
additionalProperties.put(CodegenConstants.OPTIONAL_PROJECT_FILE, optionalProjectFileFlag);
}
if (updateSupportingFiles) {
supportingFiles.clear();
supportingFiles.add(new SupportingFile("model-base-header.mustache", publicFolder, modelNamePrefix + "BaseModel.h"));
supportingFiles.add(new SupportingFile("model-base-source.mustache", privateFolder, modelNamePrefix + "BaseModel.cpp"));
supportingFiles.add(new SupportingFile("helpers-header.mustache", publicFolder, modelNamePrefix + "Helpers.h"));
supportingFiles.add(new SupportingFile("helpers-source.mustache", privateFolder, modelNamePrefix + "Helpers.cpp"));
if (optionalProjectFileFlag) {
supportingFiles.add(new SupportingFile("Build.cs.mustache", unrealModuleName + ".Build.cs"));
supportingFiles.add(new SupportingFile("module-header.mustache", privateFolder, unrealModuleName + "Module.h"));
supportingFiles.add(new SupportingFile("module-source.mustache", privateFolder, unrealModuleName + "Module.cpp"));
}
importMapping.put("HttpFileInput", "#include \"" + modelNamePrefix + "Helpers.h\"");
}
}
public void setOptionalProjectFileFlag(boolean flag) {
this.optionalProjectFileFlag = flag;
}
/**
* Configures the type of generator.
*
* @return the CodegenType for this generator
* @see org.openapitools.codegen.CodegenType
*/
@Override
public CodegenType getTag() {
return CodegenType.CLIENT;
}
/**
* Configures a friendly name for the generator. This will be used by the generator
* to select the library with the -l flag.
*
* @return the friendly name for the generator
*/
@Override
public String getName() {
return "cpp-ue4";
}
/**
* Returns human-friendly help for the generator. Provide the consumer with help
* tips, parameters here
*
* @return A string value for the help message
*/
@Override
public String getHelp() {
return "Generates a Unreal Engine 4 C++ Module (beta).";
}
@Override
public String toModelImport(String name) {
if (namespaces.containsKey(name)) {
return "using " + namespaces.get(name) + ";";
} else if (systemIncludes.contains(name)) {
return "#include <" + name + ">";
}
String folder = modelPackage().replace("::", File.separator);
if (!folder.isEmpty())
folder += File.separator;
return "#include \"" + folder + name + ".h\"";
}
@Override
protected boolean needToImport(String type) {
boolean shouldImport = super.needToImport(type);
if (shouldImport)
return !languageSpecificPrimitives.contains(type);
else
return false;
}
/**
* Escapes a reserved word as defined in the `reservedWords` array. Handle escaping
* those terms here. This logic is only called if a variable matches the reserved words
*
* @return the escaped term
*/
@Override
public String escapeReservedWord(String name) {
if (this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
/**
* Location to write model files. You can use the modelPackage() as defined when the class is
* instantiated
*/
@Override
public String modelFileFolder() {
return outputFolder + File.separator + modelPackage().replace("::", File.separator);
}
/**
* Location to write api files. You can use the apiPackage() as defined when the class is
* instantiated
*/
@Override
public String apiFileFolder() {
return outputFolder + File.separator + apiPackage().replace("::", File.separator);
}
@Override
public String modelFilename(String templateName, String modelName) {
String suffix = modelTemplateFiles().get(templateName);
String folder = privateFolder;
if (".h".equals(suffix)) {
folder = publicFolder;
}
return modelFileFolder() + File.separator + folder + File.separator + toModelFilename(modelName) + suffix;
}
@Override
public String toModelFilename(String name) {
name = sanitizeName(name);
return modelNamePrefix + camelize(name);
}
@Override
public String apiFilename(String templateName, String tag) {
String suffix = apiTemplateFiles().get(templateName);
String folder = privateFolder;
if (".h".equals(suffix)) {
folder = publicFolder;
}
if (templateName.startsWith("api-operations")) {
return apiFileFolder() + File.separator + folder + File.separator + toApiFilename(tag) + "Operations" + suffix;
} else {
return apiFileFolder() + File.separator + folder + File.separator + toApiFilename(tag) + suffix;
}
}
@Override
public String toApiFilename(String name) {
name = sanitizeName(name);
return modelNamePrefix + camelize(name) + "Api";
}
/**
* Optional - type declaration. This is a String which is used by the templates to instantiate your
* types. There is typically special handling for different property types
*
* @return a string value used as the `dataType` field for model templates, `returnType` for api templates
*/
@Override
public String getTypeDeclaration(Schema p) {
String openAPIType = getSchemaType(p);
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
String inner = getSchemaType(ap.getItems());
return getSchemaType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (ModelUtils.isMapSchema(p)) {
String inner = getSchemaType(getAdditionalProperties(p));
return getSchemaType(p) + "<FString, " + getTypeDeclaration(inner) + ">";
}
if (pointerClasses.contains(openAPIType)) {
return openAPIType + "*";
} else if (languageSpecificPrimitives.contains(openAPIType)) {
return toModelName(openAPIType);
} else {
return openAPIType;
}
}
@Override
public String getTypeDeclaration(String name) {
return name;
}
@Override
public String toDefaultValue(Schema p) {
if (ModelUtils.isStringSchema(p)) {
if (p.getDefault() != null) {
return "TEXT(\"" + p.getDefault().toString() + "\")";
} else {
return null;
}
} else if (ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
} else {
return "false";
}
} else if (ModelUtils.isDateSchema(p)) {
return "FDateTime(0)";
} else if (ModelUtils.isDateTimeSchema(p)) {
return "FDateTime(0)";
} else if (ModelUtils.isDoubleSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
} else {
return "0.0";
}
} else if (ModelUtils.isFloatSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
} else {
return "0.0f";
}
} else if (ModelUtils.isIntegerSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
} else {
return "0";
}
} else if (ModelUtils.isLongSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
} else {
return "0";
}
}
return null;
}
/**
* Optional - OpenAPI type conversion. This is used to map OpenAPI types in a `Property` into
* either language specific types via `typeMapping` or into complex models if there is not a mapping.
*
* @return a string value of the type or complex model for this property
* @see io.swagger.v3.oas.models.media.Schema
*/
@Override
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
String type = null;
if (typeMapping.containsKey(openAPIType)) {
type = typeMapping.get(openAPIType);
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
if (pointerClasses.contains(type)) {
return type;
}
} else {
type = openAPIType;
}
return toModelName(type);
}
@Override
public String toModelName(String type) {
if (typeMapping.keySet().contains(type) ||
typeMapping.values().contains(type) ||
importMapping.values().contains(type) ||
defaultIncludes.contains(type) ||
languageSpecificPrimitives.contains(type)) {
return type;
} else {
return modelNamePrefix + camelize(sanitizeName(type), false);
}
}
@Override
public String toVarName(String name) {
// sanitize name
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// if it's all uppper case, convert to lower case
if (name.matches("^[A-Z_]*$")) {
name = name.toLowerCase(Locale.ROOT);
}
//Unreal variable names are CamelCase
String camelCaseName = camelize(name, false);
//Avoid empty variable name at all costs
if(!camelCaseName.isEmpty()) {
name = camelCaseName;
}
// for reserved word or word starting with number, append _
if (isReservedWord(name) || name.matches("^\\d.*")) {
name = escapeReservedWord(name);
}
return name;
}
@Override
public String toEnumVarName(String name, String datatype) {
return toVarName(name);
}
@Override
public String toParamName(String name) {
return toVarName(name);
}
@Override
public String toApiName(String type) {
return modelNamePrefix + camelize(type, false) + "Api";
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
@Override
public String toBooleanGetter(String name) {
return "Is" + getterAndSetterCapitalize(name);
}
@Override
public String toGetter(String name) {
return "Get" + getterAndSetterCapitalize(name);
}
@Override
public String toSetter(String name) {
return "Set" + getterAndSetterCapitalize(name);
}
}
| 38.261181
| 132
| 0.618711
|
5351f94303424eef314baf53e7b1b9b1f9771006
| 77
|
package com.gof.builder.vers3;
public enum Transmission {
MANUAL, AUTO;
}
| 12.833333
| 30
| 0.74026
|
e2c09235d32656253c524c5452fbb668d28bd3bf
| 1,427
|
// tag::sample[]
package giis.demo.descuento;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import lombok.*;
/**
* Clientes de la entidad bancaria, mapeados directamente a la tabla Cliente.
* A usar Spring Data define los atributos que seran usados para autogenerar la base de datos.
* En esta entidad y los DTOs los getters y setters se generan automaticamente con Lombok
* (http://www.baeldung.com/intro-to-project-lombok).
* Para ejecutar desde eclipse hay que instalarlo en el entorno.
* Ver https://projectlombok.org/setup/eclipse
*/
@Entity
@Getter @Setter @NoArgsConstructor @RequiredArgsConstructor
public class Cliente {
//el atributo NonNull es para que lombok genere constructor con los campos obligatorios
@Id
@Column(columnDefinition="int", nullable=false) private @NonNull Integer id;
@Column(columnDefinition="int", nullable=false) private @NonNull Integer edad;
@Column(columnDefinition="char(1)", nullable=false) private @NonNull String nuevo; // S o N (nuevo o habitual)
@Column(columnDefinition="char(1)", nullable=false) private @NonNull String cupon; // S o N (tiene cupon descuento)
@Column(columnDefinition="char(1)", nullable=false) private @NonNull String tarjeta; // S o N (tiene tarjeta fidelizacion)
@Column(columnDefinition="char(2)", nullable=true) private String pais; //anyadido para las pruebas de Mock
}
| 47.566667
| 126
| 0.757533
|
e334dde0efa475c7a203f67d8a5c7311eb0228dd
| 218
|
package io.corbel.iam.service;
import io.corbel.iam.model.User;
public interface MailService {
void sendMailResetPassword(String clientId, User user);
void sendMailValidation(String clientId, User user);
}
| 19.818182
| 59
| 0.770642
|
7c2d0acc7f9e382d19c363cec28e1241614e9fca
| 26,504
|
/*
* Copyright (C) 2017-2018 Jakob Nixdorf
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.motionsteel.emrhmrc.andotp.View;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Toast;
import org.motionsteel.emrhmrc.andotp.Database.Entry;
import org.motionsteel.emrhmrc.andotp.R;
import org.motionsteel.emrhmrc.andotp.Utilities.Constants;
import org.motionsteel.emrhmrc.andotp.Utilities.DatabaseHelper;
import org.motionsteel.emrhmrc.andotp.Utilities.EntryThumbnail;
import org.motionsteel.emrhmrc.andotp.Utilities.Settings;
import org.motionsteel.emrhmrc.andotp.Utilities.Tools;
import org.motionsteel.emrhmrc.andotp.View.ItemTouchHelper.ItemTouchHelperAdapter;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Callable;
import javax.crypto.SecretKey;
import static org.motionsteel.emrhmrc.andotp.Utilities.Constants.SortMode;
public class EntriesCardAdapter extends RecyclerView.Adapter<EntryViewHolder>
implements ItemTouchHelperAdapter, Filterable {
private Context context;
private Handler taskHandler;
private EntryFilter filter;
private ArrayList<Entry> entries;
private ArrayList<Entry> displayedEntries;
private Callback callback;
private List<String> tagsFilter = new ArrayList<>();
private SecretKey encryptionKey = null;
private SortMode sortMode = SortMode.UNSORTED;
private TagsAdapter tagsFilterAdapter;
private Settings settings;
public EntriesCardAdapter(Context context, TagsAdapter tagsFilterAdapter) {
this.context = context;
this.tagsFilterAdapter = tagsFilterAdapter;
this.settings = new Settings(context);
this.taskHandler = new Handler();
this.entries = new ArrayList<>();
}
public void setEncryptionKey(SecretKey key) {
encryptionKey = key;
}
public SecretKey getEncryptionKey() {
return encryptionKey;
}
@Override
public int getItemCount() {
return displayedEntries.size();
}
public ArrayList<Entry> getEntries() {
return entries;
}
public void addEntry(Entry e) {
if (! entries.contains(e)) {
entries.add(e);
entriesChanged();
} else {
Toast.makeText(context, R.string.toast_entry_exists, Toast.LENGTH_LONG).show();
}
}
private int getRealIndex(int displayPosition) {
return entries.indexOf(displayedEntries.get(displayPosition));
}
private void entriesChanged() {
displayedEntries = sortEntries(entries);
filterByTags(tagsFilter);
notifyDataSetChanged();
}
public void saveEntries() {
DatabaseHelper.saveDatabase(context, entries, encryptionKey);
}
public void loadEntries() {
if (encryptionKey != null) {
entries = DatabaseHelper.loadDatabase(context, encryptionKey);
entriesChanged();
}
}
public void filterByTags(List<String> tags) {
tagsFilter = tags;
List<Entry> matchingEntries = new ArrayList<>();
for(Entry e : entries) {
//Entries with no tags will always be shown
Boolean foundMatchingTag = e.getTags().isEmpty() && settings.getNoTagsToggle();
if(settings.getTagFunctionality() == Constants.TagFunctionality.AND) {
if(e.getTags().containsAll(tags)) {
foundMatchingTag = true;
}
} else {
for (String tag : tags) {
if (e.getTags().contains(tag)) {
foundMatchingTag = true;
}
}
}
if(foundMatchingTag) {
matchingEntries.add(e);
}
}
displayedEntries = sortEntries(matchingEntries);
notifyDataSetChanged();
}
public void updateTimeBasedTokens() {
boolean change = false;
for (Entry e : entries) {
if (e.isTimeBased()) {
boolean item_changed = e.updateOTP();
change = change || item_changed || e.hasNonDefaultPeriod();
}
}
if (change)
notifyDataSetChanged();
}
@Override
public void onBindViewHolder(@NonNull EntryViewHolder entryViewHolder, int i) {
Entry entry = displayedEntries.get(i);
if (!entry.isTimeBased())
entry.updateOTP();
entryViewHolder.updateValues(entry);
entryViewHolder.setLabelSize(settings.getLabelSize());
entryViewHolder.setLabelScroll(settings.getScrollLabel());
if(settings.getThumbnailVisible())
entryViewHolder.setThumbnailSize(settings.getThumbnailSize());
}
@Override @NonNull
public EntryViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.component_card, viewGroup, false);
EntryViewHolder viewHolder = new EntryViewHolder(context, itemView, settings.getTapToReveal());
viewHolder.setCallback(new EntryViewHolder.Callback() {
@Override
public void onMoveEventStart() {
if (callback != null)
callback.onMoveEventStart();
}
@Override
public void onMoveEventStop() {
if (callback != null)
callback.onMoveEventStop();
}
@Override
public void onMenuButtonClicked(View parentView, int position) {
showPopupMenu(parentView, position);
}
@Override
public void onCopyButtonClicked(String text, int position) {
copyToClipboard(text);
updateLastUsed(position, getRealIndex(position));
}
@Override
public void onCardClicked(final int position) {
if (settings.getTapToReveal()) {
final Entry entry = displayedEntries.get(position);
final int realIndex = entries.indexOf(entry);
if (entry.isVisible()) {
hideEntry(entry);
} else {
entries.get(realIndex).setHideTask(new Runnable() {
@Override
public void run() {
hideEntry(entry);
}
});
taskHandler.postDelayed(entries.get(realIndex).getHideTask(), settings.getTapToRevealTimeout() * 1000);
entry.setVisible(true);
notifyItemChanged(position);
}
}
}
@Override
public void onCounterClicked(int position) {
Entry entry = displayedEntries.get(position);
Entry realEntry = entries.get(getRealIndex(position));
long counter = entry.getCounter() + 1;
entry.setCounter(counter);
entry.updateOTP();
notifyItemChanged(position);
realEntry.setCounter(counter);
realEntry.updateOTP();
DatabaseHelper.saveDatabase(context, entries, encryptionKey);
}
@Override
public void onCounterLongPressed(int position) {
setCounter(position);
}
});
return viewHolder;
}
private void hideEntry(Entry entry) {
int pos = displayedEntries.indexOf(entry);
int realIndex = entries.indexOf(entry);
if (realIndex >= 0) {
entries.get(realIndex).setVisible(false);
taskHandler.removeCallbacks(entries.get(realIndex).getHideTask());
entries.get(realIndex).setHideTask(null);
}
boolean updateNeeded = updateLastUsed(pos, realIndex);
if (pos >= 0) {
displayedEntries.get(pos).setVisible(false);
if (updateNeeded)
notifyItemChanged(pos);
}
}
private void setCounter(final int pos) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
int marginSmall = context.getResources().getDimensionPixelSize(R.dimen.activity_margin_small);
int marginMedium = context.getResources().getDimensionPixelSize(R.dimen.activity_margin_medium);
final EditText input = new EditText(context);
input.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
input.setText(String.format(Locale.ENGLISH, "%d", displayedEntries.get(pos).getCounter()));
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setSingleLine();
FrameLayout container = new FrameLayout(context);
container.setPaddingRelative(marginMedium, marginSmall, marginMedium, 0);
container.addView(input);
builder.setTitle(R.string.dialog_title_counter)
.setView(container)
.setPositiveButton(R.string.button_save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
int realIndex = getRealIndex(pos);
long newCounter = Long.parseLong(input.getEditableText().toString());
displayedEntries.get(pos).setCounter(newCounter);
notifyItemChanged(pos);
Entry e = entries.get(realIndex);
e.setCounter(newCounter);
DatabaseHelper.saveDatabase(context, entries, encryptionKey);
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {}
})
.create()
.show();
}
private boolean updateLastUsed(int position, int realIndex) {
long timeStamp = System.currentTimeMillis();
if (position >= 0)
displayedEntries.get(position).setLastUsed(timeStamp);
entries.get(realIndex).setLastUsed(timeStamp);
DatabaseHelper.saveDatabase(context, entries, encryptionKey);
if (sortMode == SortMode.LAST_USED) {
displayedEntries = sortEntries(displayedEntries);
notifyDataSetChanged();
return false;
}
return true;
}
@Override
public boolean onItemMove(int fromPosition, int toPosition) {
if (sortMode == SortMode.UNSORTED && displayedEntries.equals(entries)) {
Collections.swap(entries, fromPosition, toPosition);
displayedEntries = new ArrayList<>(entries);
notifyItemMoved(fromPosition, toPosition);
DatabaseHelper.saveDatabase(context, entries, encryptionKey);
}
return true;
}
public void editEntryLabel(final int pos) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
int marginSmall = context.getResources().getDimensionPixelSize(R.dimen.activity_margin_small);
int marginMedium = context.getResources().getDimensionPixelSize(R.dimen.activity_margin_medium);
final EditText input = new EditText(context);
input.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
input.setText(displayedEntries.get(pos).getLabel());
input.setSingleLine();
FrameLayout container = new FrameLayout(context);
container.setPaddingRelative(marginMedium, marginSmall, marginMedium, 0);
container.addView(input);
builder.setTitle(R.string.dialog_title_rename)
.setView(container)
.setPositiveButton(R.string.button_save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
int realIndex = getRealIndex(pos);
String newLabel = input.getEditableText().toString();
displayedEntries.get(pos).setLabel(newLabel);
if (sortMode == SortMode.LABEL) {
displayedEntries = sortEntries(displayedEntries);
notifyDataSetChanged();
} else {
notifyItemChanged(pos);
}
Entry e = entries.get(realIndex);
e.setLabel(newLabel);
DatabaseHelper.saveDatabase(context, entries, encryptionKey);
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {}
})
.create()
.show();
}
public void changeThumbnail(final int pos) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
int marginSmall = context.getResources().getDimensionPixelSize(R.dimen.activity_margin_small);
int marginMedium = context.getResources().getDimensionPixelSize(R.dimen.activity_margin_medium);
int realIndex = getRealIndex(pos);
final ThumbnailSelectionAdapter thumbnailAdapter = new ThumbnailSelectionAdapter(context, entries.get(realIndex).getLabel());
final EditText input = new EditText(context);
input.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
input.setSingleLine();
input.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
@Override
public void afterTextChanged(Editable editable) {
thumbnailAdapter.filter(editable.toString());
}
});
int gridPadding = context.getResources().getDimensionPixelSize(R.dimen.activity_margin_small);
int gridBackground = Tools.getThemeColor(context, R.attr.thumbnailBackground);
GridView grid = new GridView(context);
grid.setAdapter(thumbnailAdapter);
grid.setBackgroundColor(gridBackground);
grid.setPadding(gridPadding, gridPadding, gridPadding, gridPadding);
grid.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
int thumbnailSize = settings.getThumbnailSize();
grid.setColumnWidth(thumbnailSize);
grid.setNumColumns(GridView.AUTO_FIT);
grid.setVerticalSpacing(context.getResources().getDimensionPixelSize(R.dimen.activity_margin_medium));
grid.setHorizontalSpacing(context.getResources().getDimensionPixelSize(R.dimen.activity_margin_medium));
grid.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
LinearLayout layout = new LinearLayout(context);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
layout.addView(input);
layout.addView(grid);
FrameLayout container = new FrameLayout(context);
container.setPaddingRelative(marginMedium, marginSmall, marginMedium, 0);
container.addView(layout);
final AlertDialog alert = builder.setTitle(R.string.menu_popup_change_image)
.setView(container)
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {}
})
.create();
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int realIndex = getRealIndex(pos);
EntryThumbnail.EntryThumbnails thumbnail = EntryThumbnail.EntryThumbnails.Default;
try {
int realPos = thumbnailAdapter.getRealIndex(position);
thumbnail = EntryThumbnail.EntryThumbnails.values()[realPos];
} catch (Exception e) {
e.printStackTrace();
}
Entry e = entries.get(realIndex);
e.setThumbnail(thumbnail);
DatabaseHelper.saveDatabase(context, entries, encryptionKey);
notifyItemChanged(pos);
alert.cancel();
}
});
alert.show();
}
public void editEntryTags(final int pos) {
final int realPos = getRealIndex(pos);
final Entry entry = entries.get(realPos);
HashMap<String, Boolean> tagsHashMap = new HashMap<>();
for(String tag: entry.getTags()) {
tagsHashMap.put(tag, true);
}
for(String tag: getTags()) {
if(!tagsHashMap.containsKey(tag))
tagsHashMap.put(tag, false);
}
final TagsAdapter tagsAdapter = new TagsAdapter(context, tagsHashMap);
final Callable tagsCallable = new Callable() {
@Override
public Object call() throws Exception {
entries.get(realPos).setTags(tagsAdapter.getActiveTags());
DatabaseHelper.saveDatabase(context, entries, encryptionKey);
List<String> inUseTags = getTags();
HashMap<String, Boolean> tagsHashMap = new HashMap<>();
for(String tag: tagsFilterAdapter.getTags()) {
if(inUseTags.contains(tag))
tagsHashMap.put(tag, false);
}
for(String tag: tagsFilterAdapter.getActiveTags()) {
if(inUseTags.contains(tag))
tagsHashMap.put(tag, true);
}
for(String tag: getTags()) {
if(inUseTags.contains(tag))
if(!tagsHashMap.containsKey(tag))
tagsHashMap.put(tag, true);
}
tagsFilterAdapter.setTags(tagsHashMap);
filterByTags(tagsFilterAdapter.getActiveTags());
return null;
}
};
TagsDialog.show(context, tagsAdapter, tagsCallable, tagsCallable);
}
public void removeItem(final int pos) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
String label = displayedEntries.get(pos).getLabel();
String message = context.getString(R.string.dialog_msg_confirm_delete, label);
builder.setTitle(R.string.dialog_title_remove)
.setMessage(message)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
int realIndex = getRealIndex(pos);
displayedEntries.remove(pos);
notifyItemRemoved(pos);
entries.remove(realIndex);
DatabaseHelper.saveDatabase(context, entries, encryptionKey);
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {}
})
.show();
}
private void showPopupMenu(View view, final int pos) {
View menuItemView = view.findViewById(R.id.menuButton);
PopupMenu popup = new PopupMenu(view.getContext(), menuItemView);
MenuInflater inflate = popup.getMenuInflater();
inflate.inflate(R.menu.menu_popup, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_popup_editLabel) {
editEntryLabel(pos);
return true;
} else if(id == R.id.menu_popup_changeImage) {
changeThumbnail(pos);
return true;
} else if (id == R.id.menu_popup_editTags) {
editEntryTags(pos);
return true;
} else if (id == R.id.menu_popup_remove) {
removeItem(pos);
return true;
} else {
return false;
}
}
});
popup.show();
}
private void copyToClipboard(String text) {
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(context.getString(R.string.label_clipboard_content), text);
clipboard.setPrimaryClip(clip);
Toast.makeText(context, R.string.toast_copied_to_clipboard, Toast.LENGTH_LONG).show();
}
public void setSortMode(SortMode mode) {
this.sortMode = mode;
entriesChanged();
}
public SortMode getSortMode() {
return this.sortMode;
}
private ArrayList<Entry> sortEntries(List<Entry> unsorted) {
ArrayList<Entry> sorted = new ArrayList<>(unsorted);
if (sortMode == SortMode.LABEL) {
Collections.sort(sorted, new LabelComparator());
} else if (sortMode == SortMode.LAST_USED) {
Collections.sort(sorted, new LastUsedComparator());
}
return sorted;
}
public void setCallback(Callback cb) {
this.callback = cb;
}
public EntryFilter getFilter() {
if (filter == null)
filter = new EntryFilter();
return filter;
}
public List<String> getTags() {
HashSet<String> tags = new HashSet<String>();
for(Entry entry : entries) {
tags.addAll(entry.getTags());
}
return new ArrayList<String>(tags);
}
public class EntryFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults filterResults = new FilterResults();
ArrayList<Entry> filtered = new ArrayList<>();
if (constraint != null && constraint.length() != 0){
for (int i = 0; i < entries.size(); i++) {
if (entries.get(i).getLabel().toLowerCase().contains(constraint.toString().toLowerCase())) {
filtered.add(entries.get(i));
}
}
} else {
filtered = entries;
}
filterResults.count = filtered.size();
filterResults.values = filtered;
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
displayedEntries = sortEntries((ArrayList<Entry>) results.values);
notifyDataSetChanged();
}
}
public class LabelComparator implements Comparator<Entry> {
Collator collator;
LabelComparator(){
collator = Collator.getInstance();
collator.setStrength(Collator.PRIMARY);
}
@Override
public int compare(Entry o1, Entry o2) {
return collator.compare(o1.getLabel(), o2.getLabel());
}
}
public class LastUsedComparator implements Comparator<Entry> {
@Override
public int compare(Entry o1, Entry o2) {
return Long.compare(o2.getLastUsed(), o1.getLastUsed());
}
}
public interface Callback {
void onMoveEventStart();
void onMoveEventStop();
}
}
| 37.172511
| 135
| 0.613492
|
f4f8f21ffdd301383a90854de75d8ac3bd79e59d
| 491
|
package net.openid.conformance.fapi1advancedfinal;
/**
* This class finished the test after the token endpoint call
*
* i.e. it does not go on to call the resource endpoint.
*/
public abstract class AbstractFAPI1AdvancedFinalPerformTokenEndpoint extends AbstractFAPI1AdvancedFinalServerTestModule {
@Override
protected void performPostAuthorizationFlow() {
// call the token endpoint and complete the flow
createAuthorizationCodeRequest();
requestAuthorizationCode();
}
}
| 23.380952
| 121
| 0.792261
|
c231418c5713bee7f2c5a24bb662983c0012ebb3
| 896
|
// Copyright (c) 2015-2020 Vladimir Schneider <vladimir.schneider@gmail.com> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.parser.cache.data.dependency;
/**
* Versioned dependency
* <p>
* NOTE: equals and hashCode for two versioned instances for the same underlying object should result in equivalence between the versioned instances
* <p>
* If the underlying dependency is a PsiElement then original psi element should be used for version tracking and comparisons
* <p>
* If the underlying dependency is a PsiFile then original original file should be used for version tracking and comparisons
*/
public interface DataDependency {
/**
* Get current version of this dependency or -1 if dependent is no longer valid
*
* @return version of the dependent
*/
long getVersion();
}
| 40.727273
| 177
| 0.748884
|
431a9612cb6a2c7bc5198948ba1afd2693ec7749
| 180
|
package modelo.jugador;
import modelo.herramientas.Herramienta;
public interface Orientacion {
boolean golpear(Herramienta herramientaActual);
String obtenerImagen();
}
| 18
| 51
| 0.788889
|
8db9289cd6b89795dc5792acb5233239437c6af2
| 469
|
package com.booking.replication.replicant;
import java.sql.SQLException;
/**
* Created by edmitriev on 8/2/17.
*/
public class DummyReplicantPool implements ReplicantPool {
@Override
public String getReplicantDBActiveHost() {
return "localhost";
}
@Override
public int getReplicantDBActiveHostServerID() {
return 0;
}
@Override
public int obtainServerID(String host) throws SQLException {
return 0;
}
}
| 19.541667
| 64
| 0.680171
|
feca54008da4b506b4462f38eba9b5ef1e6f3f26
| 310
|
package com.uece.questions.templateMethod;
public class Inverte extends ImprimiNaTelaTemplate {
@Override
protected String tratarString(String string) {
return new StringBuilder(string).reverse().toString();
}
@Override
protected void printarNaTela(String string) {
System.out.println(string);
}
}
| 22.142857
| 56
| 0.777419
|
b0ecf4e3c85d667f8bbfa13740fe3c5c35217dec
| 1,305
|
/**
* For copyright information see the LICENSE document.
*/
package realityshard.container;
import java.util.concurrent.ScheduledExecutorService;
/**
* This class provides access to the global executor object (a thread pool manager)
* you can trust the host application to set the executor at startup.
*
* Any exception possibly thrown by any method below is not expected to be thrown
* at any time because of the first statement.
*
* @author _rusty
*/
public class GlobalExecutor
{
private static ScheduledExecutorService executor = null;
/**
* Initialize the static executor value of this class.
*
* @param executor The global executor.
*/
public static void init(ScheduledExecutorService initExec)
{
executor = initExec;
}
/**
* Getter.
*
* @return The global executor as set by the host application.
* @throws IllegalStateException If no executor was set.
*/
public static ScheduledExecutorService get()
throws IllegalStateException
{
if (executor == null)
{
throw new IllegalStateException("The global executor was not yet set by the host application!");
}
return executor;
}
}
| 25.588235
| 108
| 0.642146
|
f501d704b0cf2d89fb85a3514f201d5c4c817b5b
| 1,220
|
import java.util.Scanner;
class BinSearch {
static int search(int arr[], int left, int right, int valToSearch) {
if (right >= left) {
int mid = left + (right - left) / 2;
if (arr[mid] == valToSearch) return mid;
if (arr[mid] > valToSearch) return search(
arr,
left,
mid - 1,
valToSearch
);
return search(arr, mid + 1, right, valToSearch);
}
return -1;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int arr[] = {
9,
6,
14,
12,
10,
8,
3,
4,
1,
2,
7,
11,
13,
5,
15,
17,
19,
18,
20,
22,
21,
24,
23,
26,
25,
29,
30,
28,
27
};
// sort the array first
for (int i = 0; i < arr.length; i++) for (
int j = i + 1;
j < arr.length;
j++
) if (arr[i] > arr[j]) {
arr[i] = arr[i] + arr[j];
arr[j] = arr[i] - arr[j];
arr[i] = arr[i] - arr[j];
}
int valToSearch = scan.nextInt();
int valIndex = search(arr, 0, arr.length - 1, valToSearch);
if (valIndex != -1) System.out.printf(
"\nSearched value %d found in index %d",
valToSearch,
valIndex
); else System.out.printf("\nSearched value %d not found", valToSearch);
}
}
| 16.266667
| 74
| 0.531148
|
5f1797f0eb9356b889df315efa901740bde81f2e
| 888
|
package leetCode.day47;
/**
* @author liqiqi_tql
* @date 2021/4/17 -16:31
*/
public class T81 {
public boolean search(int[] nums,int target){
int n = nums.length;
if (n==0){
return true;
}
if (n==1){
return nums[0]==target?true:false;
}
int l=0,r=n-1;
while (l<=r){
int mid=(r-l)/2+l;
if (nums[mid]==target){
return true;
}
if (nums[0]<=nums[mid]){
if(nums[0]<=target&&target<nums[mid]){
r=mid-1;
}else {
l=mid+1;
}
}else {
if (nums[mid]<target&&target<=nums[n-1]){
l=mid+1;
}else {
r=mid-1;
}
}
}
return false;
}
}
| 22.769231
| 57
| 0.358108
|
eebd5e952098e945e87ae648f522ad73c02bcc59
| 6,300
|
/*
* Copyright 2011-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.repository.support;
import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
import org.bson.Document;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.convert.QueryMapper;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import com.mongodb.DBRef;
import com.querydsl.core.types.Constant;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.Operation;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.PathMetadata;
import com.querydsl.core.types.PathType;
import com.querydsl.mongodb.MongodbSerializer;
import com.querydsl.mongodb.document.MongodbDocumentSerializer;
/**
* Custom {@link MongodbSerializer} to take mapping information into account when building keys for constraints.
*
* @author Oliver Gierke
* @author Christoph Strobl
* @author Mark Paluch
*/
class SpringDataMongodbSerializer extends MongodbDocumentSerializer {
private static final String ID_KEY = "_id";
private static final Set<PathType> PATH_TYPES;
static {
Set<PathType> pathTypes = new HashSet<>();
pathTypes.add(PathType.VARIABLE);
pathTypes.add(PathType.PROPERTY);
PATH_TYPES = Collections.unmodifiableSet(pathTypes);
}
private final MongoConverter converter;
private final MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> mappingContext;
private final QueryMapper mapper;
/**
* Creates a new {@link SpringDataMongodbSerializer} for the given {@link MongoConverter}.
*
* @param converter must not be {@literal null}.
*/
public SpringDataMongodbSerializer(MongoConverter converter) {
Assert.notNull(converter, "MongoConverter must not be null");
this.mappingContext = converter.getMappingContext();
this.converter = converter;
this.mapper = new QueryMapper(converter);
}
@Override
public Object visit(Constant<?> expr, Void context) {
if (!ClassUtils.isAssignable(Enum.class, expr.getType())) {
return super.visit(expr, context);
}
return converter.convertToMongoType(expr.getConstant());
}
@Override
protected String getKeyForPath(Path<?> expr, PathMetadata metadata) {
if (!metadata.getPathType().equals(PathType.PROPERTY)) {
return super.getKeyForPath(expr, metadata);
}
Path<?> parent = metadata.getParent();
MongoPersistentEntity<?> entity = mappingContext.getRequiredPersistentEntity(parent.getType());
MongoPersistentProperty property = entity.getPersistentProperty(metadata.getName());
return property == null ? super.getKeyForPath(expr, metadata) : property.getFieldName();
}
@Override
protected Document asDocument(@Nullable String key, @Nullable Object value) {
value = value instanceof Optional ? ((Optional) value).orElse(null) : value;
return super.asDocument(key, value instanceof Pattern ? value : converter.convertToMongoType(value));
}
@Override
protected boolean isReference(@Nullable Path<?> path) {
MongoPersistentProperty property = getPropertyForPotentialDbRef(path);
return property == null ? false : property.isAssociation();
}
@Override
protected DBRef asReference(@Nullable Object constant) {
return asReference(constant, null);
}
protected DBRef asReference(Object constant, Path<?> path) {
return converter.toDBRef(constant, getPropertyForPotentialDbRef(path));
}
@Override
protected String asDBKey(@Nullable Operation<?> expr, int index) {
Expression<?> arg = expr.getArg(index);
String key = super.asDBKey(expr, index);
if (!(arg instanceof Path)) {
return key;
}
Path<?> path = (Path<?>) arg;
if (!isReference(path)) {
return key;
}
MongoPersistentProperty property = getPropertyFor(path);
return property.isIdProperty() ? key.replaceAll("." + ID_KEY + "$", "") : key;
}
protected Object convert(@Nullable Path<?> path, @Nullable Constant<?> constant) {
if (!isReference(path)) {
return super.convert(path, constant);
}
MongoPersistentProperty property = getPropertyFor(path);
return property.isIdProperty() ? asReference(constant.getConstant(), path.getMetadata().getParent())
: asReference(constant.getConstant(), path);
}
@Nullable
private MongoPersistentProperty getPropertyFor(Path<?> path) {
Path<?> parent = path.getMetadata().getParent();
if (parent == null || !PATH_TYPES.contains(path.getMetadata().getPathType())) {
return null;
}
MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(parent.getType());
return entity != null ? entity.getPersistentProperty(path.getMetadata().getName()) : null;
}
/**
* Checks the given {@literal path} for referencing the {@literal id} property of a {@link DBRef} referenced object.
* If so it returns the referenced {@link MongoPersistentProperty} of the {@link DBRef} instead of the {@literal id}
* property.
*
* @param path
* @return
*/
private MongoPersistentProperty getPropertyForPotentialDbRef(Path<?> path) {
if (path == null) {
return null;
}
MongoPersistentProperty property = getPropertyFor(path);
PathMetadata metadata = path.getMetadata();
if (property != null && property.isIdProperty() && metadata != null && metadata.getParent() != null) {
return getPropertyFor(metadata.getParent());
}
return property;
}
}
| 31.188119
| 117
| 0.751587
|
9027a47c97f43231f8ef636a574a4cf3ca3f3cc7
| 4,460
|
package com.andcreations.ae.studio.plugins.ui.main.view.dialogs;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.andcreations.ae.studio.plugins.ui.common.UIColors;
import com.andcreations.ae.studio.plugins.ui.common.quickopen.QuickOpenDialog;
import com.andcreations.ae.studio.plugins.ui.common.quickopen.QuickOpenItem;
import com.andcreations.ae.studio.plugins.ui.common.quickopen.QuickOpenUtil;
import com.andcreations.ae.studio.plugins.ui.common.quickopen.SeparatorQuickOpenMatcher;
import com.andcreations.ae.studio.plugins.ui.main.MainFrame;
import com.andcreations.ae.studio.plugins.ui.main.view.View;
import com.andcreations.ae.studio.plugins.ui.main.view.ViewManager;
import com.andcreations.ae.studio.plugins.ui.main.view.ViewProvider;
import com.andcreations.resources.BundleResources;
/**
* Dialog which allows to go to a dialog in a group.
*
* @author Mikolaj Gucki
*/
public class GoToView {
/** */
private static BundleResources res = new BundleResources(GoToView.class);
/** */
private static List<QuickOpenItem> createViewItems(Collection<View> views) {
List<QuickOpenItem> items = new ArrayList<>();
// for each view
for (View view:views) {
items.add(new QuickOpenItem(view.getIcon(),
view.getTitle(),view.getTitle(),view));
}
return items;
}
private static List<QuickOpenItem> createProviderItems(
List<ViewProvider> providers) {
//
List<QuickOpenItem> items = new ArrayList<>();
String dark = UIColors.htmlDark();
// for each provider
for (ViewProvider provider:providers) {
items.add(new QuickOpenItem(provider.getIcon(),
provider.getTitle(),
res.getStr("provider.text",provider.getTitle()),
res.getStr("provider.html",provider.getTitle(),dark),
provider));
}
return items;
}
/** */
private static void goToView(List<QuickOpenItem> items) {
// sort
QuickOpenUtil.sortBySearchValue(items);
// create dialog
QuickOpenDialog dialog = new QuickOpenDialog(MainFrame.get(),
res.getStr("go.to.view"),items,true);
int height = Math.min(48,24 + items.size());
dialog.setRelativeMinimumSize(16,height);
// matcher
SeparatorQuickOpenMatcher matcher = new SeparatorQuickOpenMatcher(
" ",dialog.getMatcher(),true);
dialog.setMatcher(dialog.getMatcherLabel(),matcher);
// show
dialog.showOptionDialog();
// selected view
QuickOpenItem item = dialog.getSelectedItem();
if (item != null) {
Object object = item.getObject();
if (object instanceof View) {
MainFrame.get().getViewManager().showView((View)object);
}
if (object instanceof ViewProvider) {
ViewProvider provider = (ViewProvider)object;
provider.showView();
}
}
}
/** */
public static void go(View view) {
List<View> siblings =
MainFrame.get().getViewManager().getSiblingViews(view);
if (siblings == null) {
return;
}
goToView(createViewItems(siblings));
}
/** */
public static void go() {
ViewManager manager = MainFrame.get().getViewManager();
List<ViewProvider> providers =
new ArrayList<>(manager.getViewProviders());
// remove the providers for which view is already shown
while (true) {
ViewProvider providerToRemove = null;
for (ViewProvider provider:providers) {
if (manager.getViewByTitle(provider.getTitle()) != null) {
providerToRemove = provider;
break;
}
}
if (providerToRemove == null) {
break;
}
providers.remove(providerToRemove);
}
List<QuickOpenItem> items = createProviderItems(providers);
items.addAll(createViewItems(manager.getViews()));
goToView(items);
}
}
| 34.84375
| 89
| 0.587892
|
e5fa224a08acfcd6566ce76adf61dc0b6cb76c77
| 2,110
|
package com.xixi.sdk.utils.file;
import java.util.HashSet;
import java.util.Set;
import com.xixi.sdk.parser.LLGsonUtils;
public class LLDoorSafeUserUtils {
private final String FILENAME = "USER_DATA_FILE";
public String getFILENAME() {
return FILENAME;
}
final Set<String> subscribers = new HashSet<String>();
// private static LLDoorSafeUserUtils instance = null;
// public static LLDoorSafeUserUtils getInstance() {
// if (instance == null) {
// instance = new LLDoorSafeUserUtils();
// }
// return instance;
// }
public void getAllUserDataOverFile(final IoCompletionListener1<String> callback) {
LLFileUtils.getInstance().readFromFile(FILENAME, new IoCompletionListener1<String>() {
@Override
public void onFinish(String data, Object context) {
// TODO Auto-generated method stub
callback.onFinish(data, null);
}
});
}
public String getAllUserDataOverCatch(){
return LLGsonUtils.getInstance().toJson(subscribers);
}
public void writeUsersToFile(Set<String> users){
String userStr = LLGsonUtils.getInstance().toJson(users);
LLFileUtils.getInstance().writeToFile(FILENAME, userStr);
}
public void operateUserData(final String user, final boolean isAdd) {
// final String dataStr = LLGsonUtils.getInstance().toJson(userData);
boolean contained = subscribers.contains(user) ;
if ( isAdd && !contained) {
subscribers.add(user) ;
}else if ( !isAdd && contained ) {
subscribers.remove(user) ;
}else{
return ;
}
writeUsersToFile(subscribers);
}
public int sizeOfSubscribers() {
return subscribers.size() ;
}
public Set<String> getSubscribers() {
return subscribers;
}
public boolean isContain(String user){
return subscribers.contains(user) ;
}
public void setSubscribers(String subs,boolean isWriteToFile){
@SuppressWarnings("unchecked")
Set<String> _sub = (Set<String>)LLGsonUtils.fromJson(subs, (new HashSet<String>()).getClass());
if ( _sub != null ) {
subscribers.addAll(_sub) ;
if(isWriteToFile){
writeUsersToFile(subscribers);
}
}
}
protected LLDoorSafeUserUtils() {
}
}
| 27.051282
| 97
| 0.716588
|
83e59127b55242da9375ac8cd7ed0128dd2b5ed5
| 391
|
package none.engine.component.common.uuid;
import com.google.inject.Singleton;
import java.util.UUID;
/**
* Creates random UUID's.
*/
@Singleton
public class RandomUUID implements UUIDFactory {
@Override
public UUID createUUID() {
return UUID.randomUUID();
}
@Override
public UUID fromString(String value) {
return UUID.fromString(value);
}
}
| 16.291667
| 48
| 0.677749
|
144362644afff7baec5ffbfff5f3b0a5eca96d75
| 856
|
package controllers;
import java.io.InputStream;
import apimodels.ModelApiResponse;
import apimodels.Pet;
import play.mvc.Http;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
@SuppressWarnings("RedundantThrows")
public interface PetApiControllerImpInterface {
void addPet(Pet body) throws Exception;
void deletePet(Long petId, String apiKey) throws Exception;
List<Pet> findPetsByStatus(List<String> status) throws Exception;
List<Pet> findPetsByTags(List<String> tags) throws Exception;
Pet getPetById(Long petId) throws Exception;
void updatePet(Pet body) throws Exception;
void updatePetWithForm(Long petId, String name, String status) throws Exception;
ModelApiResponse uploadFile(Long petId, String additionalMetadata, Http.MultipartFormData.FilePart file) throws Exception;
}
| 26.75
| 126
| 0.787383
|
d8a0cb05b102bd9593802f0c27a8e31609159724
| 5,225
|
/*
* 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 warsztatsamochodowy.controllers;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import warsztatsamochodowy.Helper;
import warsztatsamochodowy.database.DatabaseConnection;
/**
* FXML Controller class
*
* @author Artur
*/
public class NewWorkersController implements Initializable {
@FXML
private Button b_zatwierdz;
@FXML
private Button b_powrot;
@FXML
private TextField tfImie;
@FXML
private TextField tfNazwisko;
@FXML
private TextField tfMiejscowosc;
@FXML
private TextField tfAdres;
@FXML
private TextField tfLogin;
@FXML
private TextField tfHaslo;
@FXML
private TextField tfTelefon;
@FXML
private TextField tfEmial;
private Helper helper = new Helper();
@FXML
private ComboBox<String> cbSpecjalizacja;
@FXML
private ComboBox<String> cbStatus;
/**
* Initializes the controller class.
*/
DatabaseConnection PolaczenieDB = new DatabaseConnection();
LoginController login = new LoginController();
String username = login.getLogin();
String aktualne_haslo = "";
Connection sesja = PolaczenieDB.connectDatabase();
@FXML
private TextField tfWynagordzenie;
@FXML
private ComboBox<?> comboSpecjalizacja;
@FXML
private RadioButton RadioMezczyzna;
@FXML
private RadioButton RadioKobieta;
public void initialize(URL url, ResourceBundle rb) {
cbStatus.getItems().addAll(
"Zatrudniony",
"Urlop",
"Zwolniony"
);
cbSpecjalizacja.getItems().addAll(
"Diagnosta",
"Mechanik",
"Pomocnik",
"Recepcjonista"
);
}
public static Boolean czyLitery(String text){
return text.matches("[A-Za-zżźćńółęąśŻŹĆĄŚĘŁÓŃ]+.*[A-Za-zżźćńółęąśŻŹĆĄŚĘŁÓŃ]");
}
private void brakZaznaczenia(String tytul, String komunikat1, String komunikat2) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle(tytul);
alert.setHeaderText(komunikat1);
alert.setContentText(komunikat2);
alert.showAndWait();
}
/*
* Tworzenie metody zatwierdzenia metody tworzenia do bazy
*
* @param event
*/
@FXML
private void ZatwierdzZm(ActionEvent event) {
Statement stmt = null;
try {
stmt = sesja.createStatement();
String wynagrodzenie = tfWynagordzenie.getText();
int wyplata = Integer.parseInt(wynagrodzenie);
// if(czyLitery(tfTelefon.getText())||czyLitery (tfWynagordzenie.getText())){
// brakZaznaczenia("Bład","Zły format wpisywania danych! ","Proszę uzupełnić pola.");
//
// }
//
String query = "INSERT INTO pracownik (PracownikId, Login, Haslo, Imie, Nazwisko, Miejscowosc, Adres, Telefon, Email, Specjalizacja, Status,Wynagrodzenie) "
+ "Values(NULL,'" + tfLogin.getText()
+ "','" + tfHaslo.getText() + "','" + tfImie.getText()
+ "','" + tfNazwisko.getText()
+ "','" + tfMiejscowosc.getText()
+ "','" + tfAdres.getText() + "','"
+ tfTelefon.getText() + "','"
+ tfEmial.getText() + "','"
+ cbSpecjalizacja.getSelectionModel().getSelectedItem().toString()
+ "','" + cbStatus.getSelectionModel().getSelectedItem().toString()
+ "','" + wyplata
+ "');";
int wynik = stmt.executeUpdate(query);
helper.message("Ustawienia zostały zapisane");
tfLogin.clear();
tfHaslo.clear();
tfImie.clear();
tfNazwisko.clear();
tfMiejscowosc.clear();
tfAdres.clear();
tfTelefon.clear();
tfEmial.clear();
tfWynagordzenie.clear();
} catch (Exception e) {
helper.message("Sprawdź dane w formularzu");
}
}
/**
* Powrot do menu
* @param event
* @throws IOException
*/
@FXML
private void PowrotTab(ActionEvent event) throws IOException {
try {
sesja.close();
} catch (Exception e) {
helper.error(e.getMessage());
}
helper.powrotDoMenu();
Stage settings = (Stage) b_powrot.getScene().getWindow();
settings.close();
}
}
| 27.941176
| 168
| 0.599426
|
f3729bfcc93667413ee922c7f9035a1f845a86de
| 1,181
|
package com.jurabek.restaurant.order.api.mappers;
import java.util.Date;
import java.util.UUID;
import java.util.stream.Collectors;
import com.jurabek.restaurant.order.api.dtos.CustomerBasketDto;
import com.jurabek.restaurant.order.api.models.Order;
import com.jurabek.restaurant.order.api.models.OrderItems;
import org.modelmapper.ModelMapper;
import org.modelmapper.PropertyMap;
/**
* CustomerBasketToOrderMap
*/
public class CustomerBasketToOrderMap extends PropertyMap<CustomerBasketDto, Order> {
private ModelMapper modelMapper;
public CustomerBasketToOrderMap(ModelMapper modelMapper) {
this.modelMapper = modelMapper;
}
@Override
protected void configure() {
using(ctx -> {
CustomerBasketDto customerBasketDto = (CustomerBasketDto) ctx.getSource();
return customerBasketDto.getItems().stream()
.map(basketItem -> modelMapper.map(basketItem, OrderItems.class)).collect(Collectors.toList());
}).map(source, destination.getOrderItems());
map().setId(UUID.randomUUID());
map().setOrderedDate(new Date());
map().setBuyerId(source.getCustomerId());
}
}
| 30.282051
| 115
| 0.719729
|
dbbae5664fdc329f83674ebcd0dc9f0ee1b0971f
| 4,429
|
/*
* Copyright 2013 Jin Kwon <onacit at gmail.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.github.jinahya.sql;
import com.github.jinahya.lang.FieldEnum;
import com.github.jinahya.lang.FieldEnumHelper;
import java.sql.Connection;
import java.sql.SQLException;
/**
*
* @author Jin Kwon <onacit at gmail.com>
*/
public enum TransactionIsolationLevel
implements FieldEnum<TransactionIsolationLevel, Integer> {
/**
* A constant for {@link Connection#TRANSACTION_NONE}.
*/
TRANSACTION_NONE(Connection.TRANSACTION_NONE), // 0
/**
* A constant for {@link Connection#TRANSACTION_READ_UNCOMMITTED}.
*/
TRANSACTION_READ_UNCOMMITTED(Connection.TRANSACTION_READ_UNCOMMITTED), // 1
/**
* A constant for {@link Connection#TRANSACTION_READ_COMMITTED}.
*/
TRANSACTION_READ_COMMITTED(Connection.TRANSACTION_READ_COMMITTED), // 2
/**
* A constant for {@link Connection#TRANSACTION_REPEATABLE_READ}.
*/
TRANSACTION_REPEATABLE_READ(Connection.TRANSACTION_REPEATABLE_READ), // 4
/**
* A constant for {@link Connection#TRANSACTION_SERIALIZABLE}.
*/
TRANSACTION_SERIALIZABLE(Connection.TRANSACTION_SERIALIZABLE); // 8
/**
* Returns the enum constant of this type with the specified transaction
* isolation level.
*
* @param fieldValue the transaction isolation level
*
* @return the enum constant with the specified transaction isolation level
*/
public static TransactionIsolationLevel fromFieldValue(
final int fieldValue) {
return FieldEnumHelper.fromFieldValue(
TransactionIsolationLevel.class, fieldValue);
}
/**
* Returns the enum constant of this type with the specified connection's
* current transaction isolation level.
*
* @param connection the connection
*
* @return the enum constant with the specified connection's current
* transaction isolation level
*
* @throws SQLException if a database access error occurs or this method is
* called on a closed connection
*
* @see Connection#getTransactionIsolation()
*/
public static TransactionIsolationLevel fromConnection(
final Connection connection)
throws SQLException {
if (connection == null) {
throw new NullPointerException("connection");
}
return fromFieldValue(connection.getTransactionIsolation());
}
/**
* Returns an array containing the field values of this enum type.
*
* @return an array containing the field values of this enum type.
*/
public static Integer[] fieldValues() {
return FieldEnumHelper.fieldValues(
TransactionIsolationLevel.class, Integer.class);
}
/**
* Creates a new instance.
*
* @param fieldValue
*/
private TransactionIsolationLevel(final int fieldValue) {
this.fieldValue = fieldValue;
}
@Override
public Integer getFieldValue() {
return fieldValue;
}
/**
* Attempts to change the transaction isolation level for given connection
* to this constant's field value.
*
* @param connection the connection
*
* @throws SQLException if a database access error occurs, this method is
* called on a closed connection
*
* @see Connection#setTransactionIsolation(int)
*/
public void set(final Connection connection) throws SQLException {
if (connection == null) {
throw new NullPointerException("connection");
}
connection.setTransactionIsolation(fieldValue);
}
/**
* field value.
*/
private final int fieldValue;
}
| 28.210191
| 80
| 0.654324
|
9b9c5e6bfece13cb4fa36b01a2722262dcc671f8
| 618
|
package seedu.address.ui;
import java.util.logging.Logger;
import javafx.scene.layout.Region;
import seedu.address.commons.core.LogsCenter;
//@@author snajef
/**
* A blank panel. The default view to show when the app starts up.
*/
public class BlankPanel extends UiPart<Region> implements Swappable {
private static final String FXML = "BlankPanel.fxml";
private final Logger logger = LogsCenter.getLogger(getClass());
private final String loggingPrefix = "[" + getClass().getName() + "]: ";
public BlankPanel() {
super(FXML);
}
@Override
public void refreshView() {
}
}
| 24.72
| 76
| 0.694175
|
b8b96d21f811c515fbffd7d4d7ba2bd628c4a814
| 256
|
package taru.easyrecruit.api.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import taru.easyrecruit.api.dao.entity.RoleEntity;
@Mapper
public interface RoleDao extends BaseMapper<RoleEntity> {
}
| 25.6
| 57
| 0.828125
|
8fec3b7dad185bd4cf649a2dfa746c0f8d455652
| 1,058
|
package pl.beda.hibernateManyToMany.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "department")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_department")
private Integer idDepartment;
@Column(name = "name")
private String name;
public Department() {
}
public Department(String name) {
this.name = name;
}
public Integer getIdDepartment() {
return idDepartment;
}
public void setIdDepartment(Integer idDepartment) {
this.idDepartment = idDepartment;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Department [idDepartment=" + idDepartment + ", name=" + name + "]";
}
}
| 20.346154
| 83
| 0.666352
|
e3308b45f2fc57a8147a5ff596c4330a1aeb8e40
| 198
|
package org.mindtrails.persistence;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ParticipantExportRepository extends JpaRepository<ParticipantExportDAO, Long> {}
| 33
| 97
| 0.863636
|
24e9ae2c41f549e5c9c241ca7427cf909e4ac042
| 1,578
|
package com.joaodartora.springcore.calculator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import com.joaodartora.springcore.operations.Division;
import com.joaodartora.springcore.operations.Exponentiation;
import com.joaodartora.springcore.operations.MathOperation;
import com.joaodartora.springcore.operations.Multiplication;
import com.joaodartora.springcore.operations.Subtraction;
import com.joaodartora.springcore.operations.Sum;
@Configuration
@ComponentScan(basePackages = "com.joaodartora.springcore.calculator")
public class ApplicationConfig {
@Bean
public Calculator calculator(ApplicationContext applicationContext) {
return new Calculator(applicationContext);
}
@Bean(name="+")
@Scope("prototype")
public MathOperation addValues(Double x, Double y) {
return new Sum(x,y);
}
@Bean(name="-")
@Scope("prototype")
public MathOperation subtractValues(Double x, Double y) {
return new Subtraction(x,y);
}
@Bean(name="/")
@Scope("prototype")
public MathOperation divideValues(Double x, Double y) {
return new Division(x,y);
}
@Bean(name="*")
@Scope("prototype")
public MathOperation multiplyValues(Double x, Double y) {
return new Multiplication(x,y);
}
@Bean(name="^")
@Scope("prototype")
public MathOperation raiseXOnYPower(Double x, Double y) {
return new Exponentiation(x,y);
}
}
| 28.690909
| 70
| 0.784537
|
b5bc9d35fa6b085bf24c17ce73878173891e7df6
| 1,539
|
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class HelloJava3 extends JComponent implements MouseMotionListener, ActionListener{
int messageX = 125, messageY = 95;
String theMessage;
JButton theButton;
int colorIndex;
static Color[] someColors = { Color.black, Color.red,
Color.green, Color.blue, Color.YELLOW };
public HelloJava3(String message){
theMessage = message;
theButton = new JButton("Change Color");
setLayout(new FlowLayout( ));
add(theButton);
theButton.addActionListener(this);
addMouseMotionListener(this);
}
public void paintComponent(Graphics g){
g.drawString(theMessage, messageX, messageY);
}
public void mouseDragged(MouseEvent e) {
messageX = e.getX( );
messageY = e.getY( );
repaint( );
}
public void mouseMoved(MouseEvent e){
}
public void actionPerformed(ActionEvent e){
if (e.getSource( ) == theButton)
changeColor();
}
synchronized private void changeColor(){
if (++colorIndex == someColors.length)
colorIndex = 0;
setForeground(currentColor( ));
repaint();
}
synchronized private Color currentColor(){
return someColors[colorIndex];
}
public static void main(String[] args){
JFrame f = new JFrame("HelloJava3");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
f.setSize(300, 300);
f.getContentPane( ).add(new HelloJava3("Hello, Java!"));
f.setVisible(true);
}
}
| 24.428571
| 91
| 0.676413
|
142af1ede6c2bc374be86b3f44260f073fb13022
| 10,716
|
package com.github.marchenkoprojects.prettyjdbc.query;
import com.github.marchenkoprojects.prettyjdbc.mapper.ResultMapper;
import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* This class represents a typed SQL query with the ability to mapping the result in a specific object type.
* Typed queries extend all the capabilities of {@link NamedParameterQuery} and allow to use {@link ResultMapper}
* to convert the {@link ResultSet} to a specific object.
* <br>
* After the query is executed the result data tuple can be transformed into a single object or a list of objects.
* To convert the result set to a single object, use the method {@link TypedQuery#unique()};
* or convert to a list of objects, use the method {@link TypedQuery#list()}.
*
* @param <T> the specific object type
*
* @author Oleg Marchenko
*
* @see NamedParameterQuery
* @see ResultMapper
*/
public class TypedQuery<T> extends NamedParameterQuery {
private final Class<T> resultType;
private ResultMapper<T> resultMapper;
public TypedQuery(PreparedStatement preparedStatement, Class<T> resultType) {
this(preparedStatement, Collections.emptyList(), resultType);
}
public TypedQuery(PreparedStatement preparedStatement, List<String> parameters, Class<T> resultType) {
super(preparedStatement, parameters);
if (resultType == null) {
throw new NullPointerException("Result type is null");
}
this.resultType = resultType;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> addBatch() {
super.addBatch();
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, boolean value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, byte value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, short value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, int value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, long value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, float value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, double value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, BigDecimal value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, String value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, byte[] value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, Date value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, LocalDate value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, Time value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, LocalTime value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, Timestamp value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, LocalDateTime value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(int paramIndex, Object value) {
super.setParameter(paramIndex, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, boolean value) {
super.setParameter(paramName, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, byte value) {
super.setParameter(paramName, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, short value) {
super.setParameter(paramName, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, int value) {
super.setParameter(paramName, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, long value) {
super.setParameter(paramName, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, float value) {
super.setParameter(paramName, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, double value) {
super.setParameter(paramName, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, BigDecimal value) {
super.setParameter(paramName, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, String value) {
super.setParameter(paramName, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, byte[] value) {
super.setParameter(paramName, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, Date value) {
super.setParameter(paramName, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, LocalDate value) {
super.setParameter(paramName, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, Time value) {
super.setParameter(paramName, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, LocalTime value) {
super.setParameter(paramName, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, Timestamp value) {
super.setParameter(paramName, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, LocalDateTime value) {
super.setParameter(paramName, value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public TypedQuery<T> setParameter(String paramName, Object value) {
super.setParameter(paramName, value);
return this;
}
/**
* Sets the result mapper for transforming to specific typed object.
*
* @param resultMapper the specific result mapper
* @return instance of this query
*/
public TypedQuery<T> setResultMapper(ResultMapper<T> resultMapper) {
if (resultMapper == null) {
throw new NullPointerException("Result mapper is null");
}
this.resultMapper = resultMapper;
return this;
}
/**
* Retrieves a single tuple from the {@link ResultSet} and transforms it into a specific object.
*
* @return a single specific object or <code>null</code>, if the result set is empty
* @throws IllegalStateException if the result mapper is null
* @throws RuntimeException if a database access error occurs
* or this method is called when the session connection is closed
*/
public T unique() {
checkMapperPresent();
try (ResultSet resultSet = preparedStatement.executeQuery()) {
if (resultSet.next()) {
return resultMapper.map(resultSet);
}
return null;
}
catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* Retrieves all tuples from the {@link ResultSet} and transforms it into a list of specific objects.
*
* @return a list of specific objects
* @throws IllegalStateException if the result mapper is null
* @throws RuntimeException if a database access error occurs
* or this method is called when the session connection is closed
*/
public List<T> list() {
checkMapperPresent();
try (ResultSet resultSet = preparedStatement.executeQuery()) {
List<T> list = new ArrayList<>(32);
while (resultSet.next()) {
list.add(resultMapper.map(resultSet));
}
return list;
}
catch (SQLException e) {
throw new RuntimeException(e);
}
}
private void checkMapperPresent() {
if (resultMapper == null) {
throw new IllegalStateException("Result mapper for type '" + resultType.getSimpleName() + "' not found");
}
}
}
| 25.037383
| 117
| 0.606943
|
29d09e66db124f43578b6f70e9c54b0d423ed291
| 7,130
|
/* DO NOT EDIT */
/* This file was generated from files.stone */
package com.dropbox.core.v2.files;
import com.dropbox.core.stone.StoneSerializers;
import com.dropbox.core.stone.StructSerializer;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import java.io.IOException;
class ListFolderLongpollArg {
// struct ListFolderLongpollArg
protected final String cursor;
protected final long timeout;
/**
*
* @param cursor A cursor as returned by {@link
* DbxUserFilesRequests#listFolder(String)} or {@link
* DbxUserFilesRequests#listFolderContinue(String)}. Cursors retrieved
* by setting {@link ListFolderArg#getIncludeMediaInfo} to {@code true}
* are not supported. Must have length of at least 1 and not be {@code
* null}.
* @param timeout A timeout in seconds. The request will block for at most
* this length of time, plus up to 90 seconds of random jitter added to
* avoid the thundering herd problem. Care should be taken when using
* this parameter, as some network infrastructure does not support long
* timeouts. Must be greater than or equal to 30 and be less than or
* equal to 480.
*
* @throws IllegalArgumentException If any argument does not meet its
* preconditions.
*/
public ListFolderLongpollArg(String cursor, long timeout) {
if (cursor == null) {
throw new IllegalArgumentException("Required value for 'cursor' is null");
}
if (cursor.length() < 1) {
throw new IllegalArgumentException("String 'cursor' is shorter than 1");
}
this.cursor = cursor;
if (timeout < 30L) {
throw new IllegalArgumentException("Number 'timeout' is smaller than 30L");
}
if (timeout > 480L) {
throw new IllegalArgumentException("Number 'timeout' is larger than 480L");
}
this.timeout = timeout;
}
/**
* The default values for unset fields will be used.
*
* @param cursor A cursor as returned by {@link
* DbxUserFilesRequests#listFolder(String)} or {@link
* DbxUserFilesRequests#listFolderContinue(String)}. Cursors retrieved
* by setting {@link ListFolderArg#getIncludeMediaInfo} to {@code true}
* are not supported. Must have length of at least 1 and not be {@code
* null}.
*
* @throws IllegalArgumentException If any argument does not meet its
* preconditions.
*/
public ListFolderLongpollArg(String cursor) {
this(cursor, 30L);
}
/**
* A cursor as returned by {@link DbxUserFilesRequests#listFolder(String)}
* or {@link DbxUserFilesRequests#listFolderContinue(String)}. Cursors
* retrieved by setting {@link ListFolderArg#getIncludeMediaInfo} to {@code
* true} are not supported.
*
* @return value for this field, never {@code null}.
*/
public String getCursor() {
return cursor;
}
/**
* A timeout in seconds. The request will block for at most this length of
* time, plus up to 90 seconds of random jitter added to avoid the
* thundering herd problem. Care should be taken when using this parameter,
* as some network infrastructure does not support long timeouts.
*
* @return value for this field, or {@code null} if not present. Defaults to
* 30L.
*/
public long getTimeout() {
return timeout;
}
@Override
public int hashCode() {
int hash = java.util.Arrays.hashCode(new Object [] {
cursor,
timeout
});
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
// be careful with inheritance
else if (obj.getClass().equals(this.getClass())) {
ListFolderLongpollArg other = (ListFolderLongpollArg) obj;
return ((this.cursor == other.cursor) || (this.cursor.equals(other.cursor)))
&& (this.timeout == other.timeout)
;
}
else {
return false;
}
}
@Override
public String toString() {
return Serializer.INSTANCE.serialize(this, false);
}
/**
* Returns a String representation of this object formatted for easier
* readability.
*
* <p> The returned String may contain newlines. </p>
*
* @return Formatted, multiline String representation of this object
*/
public String toStringMultiline() {
return Serializer.INSTANCE.serialize(this, true);
}
/**
* For internal use only.
*/
static final class Serializer extends StructSerializer<ListFolderLongpollArg> {
public static final Serializer INSTANCE = new Serializer();
@Override
public void serialize(ListFolderLongpollArg value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException {
if (!collapse) {
g.writeStartObject();
}
g.writeFieldName("cursor");
StoneSerializers.string().serialize(value.cursor, g);
g.writeFieldName("timeout");
StoneSerializers.uInt64().serialize(value.timeout, g);
if (!collapse) {
g.writeEndObject();
}
}
@Override
public ListFolderLongpollArg deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException {
ListFolderLongpollArg value;
String tag = null;
if (!collapsed) {
expectStartObject(p);
tag = readTag(p);
}
if (tag == null) {
String f_cursor = null;
Long f_timeout = 30L;
while (p.getCurrentToken() == JsonToken.FIELD_NAME) {
String field = p.getCurrentName();
p.nextToken();
if ("cursor".equals(field)) {
f_cursor = StoneSerializers.string().deserialize(p);
}
else if ("timeout".equals(field)) {
f_timeout = StoneSerializers.uInt64().deserialize(p);
}
else {
skipValue(p);
}
}
if (f_cursor == null) {
throw new JsonParseException(p, "Required field \"cursor\" missing.");
}
value = new ListFolderLongpollArg(f_cursor, f_timeout);
}
else {
throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\"");
}
if (!collapsed) {
expectEndObject(p);
}
return value;
}
}
}
| 35.29703
| 139
| 0.589481
|
de4445a8abe56862992b74ee286dee0ae161aa61
| 465
|
package solutions;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class MagicSquaresInGridTests {
@Test
public void testExample() {
// arrange
var solution = new MagicSquaresInGrid();
// act
var result = solution.numMagicSquaresInside(new int[][] {
{4,3,8,4},
{9,5,1,9},
{2,7,6,2}});
// assert
assertEquals(1, result);
}
}
| 19.375
| 65
| 0.546237
|
9149994de546e93a4cb5d8ad3c54df85598bc53e
| 3,972
|
package maze;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Random;
/**
* Implements a randomized version of Kruskal's algorithm. It is essentially
* Kruskal's algorithm with random edge weights so its result is a minimum
* spanning tree for an equally weighted graph.
*/
public class RandomizedKruskals extends Maze implements Serializable {
private static final long serialVersionUID = 612546716632291472L;
private final Random rnd;
/**
* Sets the dimensions of the maze.
*
* @param width the width of the maze
* @param height the height of the maze
* @throws IllegalArgumentException if width or height is not positive
*/
public RandomizedKruskals(int width, int height) {
super(width, height);
rnd = new Random();
}
@Override
public void generate() {
fill();
randomizedKruskals();
}
private void randomizedKruskals() {
/* Creates a list of all edges. */
int[] edges = getEdges();
/* Randomizes the order of the edge list. */
shuffle(edges);
/* Creates a disjoint set forest with a set for each node. */
DisjointSetForest dsf = new DisjointSetForest(getWidth() * getHeight());
/* Merges the nodes if they belong to different sets. */
for (int e : edges) {
Direction d = (e < 0) ? Direction.EAST : Direction.SOUTH;
int u = e & 0x7fffffff;
int v = u + d.dy * getWidth() + d.dx;
if (dsf.union(u, v)) {
removeWall(u % getWidth(), u / getWidth(), d);
}
}
}
/**
* Returns a list of all the edges in the maze. The sign bit is used to
* distinguish the horizontal edges from the vertical ones.
*/
private int[] getEdges() {
int nodes = getWidth() * getHeight();
int[] edges = new int[2 * nodes - getWidth() - getHeight()];
int index = 0;
for (int y = 0; y < getHeight() - 1; ++y) {
for (int x = 0; x < getWidth() - 1; ++x) {
int mazeIndex = y * getWidth() + x;
edges[index++] = mazeIndex;
edges[index++] = mazeIndex | 0x80000000;
}
}
for (int y = 1; y < getHeight(); ++y) {
edges[index++] = y * getWidth() - 1;
}
for (int x = nodes - getWidth(); x < nodes - 1; ++x) {
edges[index++] = x | 0x80000000;
}
return edges;
}
/** Randomly permutes the elements in an array. */
private void shuffle(int[] array) {
for (int i = array.length - 1; i >= 1; --i) {
int j = rnd.nextInt(i + 1);
int tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
}
/** Allows for efficient union/find operations. */
private static class DisjointSetForest {
int[] a;
DisjointSetForest(int n) {
a = new int[n];
Arrays.fill(a, -1);
}
int find(int x) {
int root = x;
int current = a[x];
while (current >= 0) {
root = current;
current = a[current];
}
current = x;
while (current != root) {
int old = current;
current = a[current];
a[old] = root;
}
return root;
}
boolean union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY) {
return false;
}
int rankX = a[rootX];
int rankY = a[rootY];
if (rankX > rankY) {
a[rootX] = rootY;
} else {
if (rankX == rankY) {
--a[rootX];
}
a[rootY] = rootX;
}
return true;
}
}
}
| 28.57554
| 80
| 0.492951
|
70054695760d6395f32392044e3fe1f4c3067979
| 2,935
|
/**
* Java WordNet Library (JWNL)
* See the documentation for copyright information.
*
* @version 1.1
*/
package net.didion.jwnl.princeton.file;
import net.didion.jwnl.JWNLRuntimeException;
import net.didion.jwnl.data.POS;
import net.didion.jwnl.dictionary.file.DictionaryFile;
import net.didion.jwnl.dictionary.file.DictionaryFileType;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
/**
* A <code>RandomAccessDictionaryFile</code> that accesses files named with Princeton's dictionary file naming convention.
* Uses java.nio.channels.FileChannel for file access.
*/
public class PrincetonChannelDictionaryFile extends AbstractPrincetonRandomAccessDictionaryFile {
/** The random-access file. */
private CharBuffer _buffer = null;
private FileChannel _channel = null;
public PrincetonChannelDictionaryFile() {}
public DictionaryFile newInstance(String path, POS pos, DictionaryFileType fileType) {
return new PrincetonChannelDictionaryFile(path, pos, fileType);
}
public PrincetonChannelDictionaryFile(String path, POS pos, DictionaryFileType fileType) {
super(path, pos, fileType);
}
public String readLine() throws IOException {
if (isOpen()) {
//The following lines gratuitously lifted from java.io.RandomAccessFile.readLine()
StringBuffer input = new StringBuffer();
char c = (char)-1;
boolean eol = false;
while (!eol) {
c = _buffer.get((int)getFilePointer());
_buffer.position((int)getFilePointer() + 1);
switch (c) {
case (char)-1:
case '\n':
eol = true;
break;
case '\r':
eol = true;
if ((_buffer.get((int)getFilePointer() + 1)) == '\n')
_buffer.position((int)getFilePointer() + 1);
break;
default:
input.append(c);
break;
}
}
return ((c == -1) && (input.length() == 0)) ? null : input.toString();
} else {
throw new JWNLRuntimeException("PRINCETON_EXCEPTION_001");
}
}
public void seek(long pos) throws IOException {
_buffer.position((int)pos);
}
public long getFilePointer() throws IOException {
return (long)_buffer.position();
}
public boolean isOpen() {
return _channel != null;
}
public void close() {
try {
_buffer = null;
_channel.close();
} catch (IOException ex) {
} finally {
_channel = null;
}
}
protected void openFile(File file) throws IOException {
_channel = new FileInputStream(file).getChannel();
_buffer = Charset.forName("ISO-8859-15").newDecoder().decode(
_channel.map(FileChannel.MapMode.READ_ONLY,0,_channel.size()));
}
public long length() throws IOException {
// Do not use "_buffer.length()" because it returns the
// buffer length, not the total length of the file
return _channel.size();
}
public int read() throws IOException {
return (int)_buffer.get();
}
}
| 26.926606
| 122
| 0.702555
|
bd415527a761e8fc68db6059ce935384aa759fcc
| 1,338
|
package com.xiaojukeji.kafka.manager.web.api.versionone.op;
import com.xiaojukeji.kafka.manager.common.entity.Result;
import com.xiaojukeji.kafka.manager.common.entity.ResultStatus;
import com.xiaojukeji.kafka.manager.common.utils.ValidateUtils;
import com.xiaojukeji.kafka.manager.openapi.common.dto.TopicAuthorityDTO;
import com.xiaojukeji.kafka.manager.service.service.TopicManagerService;
import com.xiaojukeji.kafka.manager.web.converters.AuthorityConverter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* Authority操作相关接口
* @author zengqiao
* @date 21/5/18
*/
@Api(tags = "OP-Authority操作相关接口(REST)")
@RestController
public class OpAuthorityController {
@Autowired
private TopicManagerService topicManagerService;
@ApiOperation(value = "权限调整",notes = "权限调整")
@PostMapping(value = "topic-authorities")
@ResponseBody
public Result addAuthority(@RequestBody TopicAuthorityDTO dto) {
//非空校验
if (ValidateUtils.isNull(dto) || !dto.paramLegal()) {
return Result.buildFrom(ResultStatus.PARAM_ILLEGAL);
}
return Result.buildFrom(topicManagerService.addAuthority(AuthorityConverter.convert2AuthorityDO(dto)));
}
}
| 37.166667
| 111
| 0.77429
|
6c74e895cb3b7ad6de10fb6a0afc53af72a8a381
| 2,222
|
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.jvm.internal.resolve;
import org.gradle.api.internal.artifacts.ArtifactDependencyResolver;
import org.gradle.api.internal.artifacts.ImmutableModuleIdentifierFactory;
import org.gradle.api.internal.artifacts.repositories.ResolutionAwareRepository;
import org.gradle.api.internal.attributes.AttributesSchemaInternal;
import org.gradle.internal.operations.BuildOperationProcessor;
import org.gradle.jvm.internal.DependencyResolvingClasspath;
import org.gradle.language.base.LanguageSourceSet;
import org.gradle.platform.base.DependencySpec;
import org.gradle.platform.base.internal.BinarySpecInternal;
import java.util.List;
public class SourceSetDependencyResolvingClasspath extends DependencyResolvingClasspath {
public SourceSetDependencyResolvingClasspath(
BinarySpecInternal binarySpec,
LanguageSourceSet sourceSet,
Iterable<DependencySpec> dependencies,
ArtifactDependencyResolver dependencyResolver,
VariantsMetaData binaryVariants,
List<ResolutionAwareRepository> remoteRepositories,
AttributesSchemaInternal attributesSchema,
ImmutableModuleIdentifierFactory moduleIdentifierFactory,
BuildOperationProcessor buildOperationProcessor) {
super(binarySpec,
"source set '" + sourceSet.getDisplayName() + "'",
dependencyResolver,
remoteRepositories,
new JvmLibraryResolveContext(binarySpec.getId(), binaryVariants, dependencies, UsageKind.API, sourceSet.getDisplayName(), moduleIdentifierFactory), attributesSchema, buildOperationProcessor);
}
}
| 44.44
| 203
| 0.782628
|
0c4e5fe13ae4de017ed37fb1f03d094e36cf360a
| 634
|
package net.younic.core.api;
public class ResourceRenderingFailedException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public ResourceRenderingFailedException(String message) {
super(message);
}
public ResourceRenderingFailedException(Throwable cause) {
super(cause);
}
public ResourceRenderingFailedException(String message, Throwable cause) {
super(message, cause);
}
public ResourceRenderingFailedException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| 21.862069
| 100
| 0.780757
|
4ed1d6ac617695a05b35b198d423a33dff005700
| 4,163
|
package org.bdgas.webproxy.services;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class EndPointService {
@Value("${endpoint.adminserver.protocol}")
private String protocol;
@Value("${endpoint.adminserver.domain}")
private String domain;
@Value("${endpoint.adminserver.port}")
private String port;
@Value("${endpoint.adminserver.basepath}")
private String basepath;
@Value("${endpoint.adminserver.version}")
private String version;
private final String HELPTEXT = "helptext";
private final String HELPTEXTFORNAME = "helptext/name";
private final String CODETYPE = "codetype";
private final String CODETABLE = "codetable";
private final String CODETABLESNR = "codetable/codetypenr";
private final String CODETYPETABLES = "codetable/codetype";
private final String TASK = "task";
private final String LOCALDATASOURCES = "localdatasource";
private final String TEAM = "team";
private final String TEAMTEAMS = "team/user";
private final String USER = "user";
private final String TEAMUSER = "teamuser";
private final String TEAMUSERUSERS = "teamuser/team";
private final String TEAMPROJECTS = "project/team";
private final String PROJECT = "project";
private final String WORKINGPAPER = "workingpaper";
private final String WPLINE = "wpline";
private final String WORKINGPAPERLINES = "wpline/workingpaper";
private final String PROJECTWORKINGPAPERS = "workingpaper/project";
private final String SIGNEDURL = "s3/signedurl";
private final String DATASOURCE = "datasource";
private final String TEAMDATASOURCE = "datasource/team";
private final String JOBSERVER = "jobserver";
public String getHelpTextEP() {
return this.merge(this.HELPTEXT);
}
public String getHelpTextForNameEP() {
return this.merge(this.HELPTEXTFORNAME);
}
public String getCodeTypeEP() {
return this.merge(this.CODETYPE);
}
public String getCodeTableEP() {
return this.merge(this.CODETABLE);
}
public String getCodeTypeTablesEP() {
return this.merge(this.CODETYPETABLES );
}
public String getCodeTablesByNrEP() {
return this.merge(this.CODETABLESNR );
}
public String getTaskEP() {
return this.merge(this.TASK);
}
public String getLocalDataSourcesEP() {
return this.merge(this.LOCALDATASOURCES);
}
public String getTeamEP() {
return this.merge(this.TEAM);
}
public String getUserEP() {
return this.merge(this.USER);
}
public String getTeamUserEP() {
return this.merge(this.TEAMUSER);
}
public String getUserTeamsEP() {
return this.merge(this.TEAMTEAMS);
}
public String getTeamUserUsersEP() {
return this.merge(this.TEAMUSERUSERS);
}
public String getProjectEP() {
return this.merge(this.PROJECT);
}
public String getTeamProjectsEP() {
return this.merge(this.TEAMPROJECTS);
}
public String getWorkingPaperEP() {
return this.merge(this.WORKINGPAPER);
}
public String getProjectWorkingPapersEP() {
return this.merge(this.PROJECTWORKINGPAPERS);
}
public String getWpLineEP() {
return this.merge(this.WPLINE);
}
public String getWorkingPaperLinesEP() {
return this.merge(this.WORKINGPAPERLINES);
}
public String getSignedUrlEP() {
return this.merge(this.SIGNEDURL);
}
public String getDataSourceEP() {
return this.merge(this.DATASOURCE);
}
public String getTeamDataSourcesEP() {
return this.merge(this.TEAMDATASOURCE);
}
public String getJobServerEP() {
return this.merge(this.JOBSERVER);
}
private String merge(String endpoint) {
String merged = protocol
+ domain + ":"
+ port + "/"
+ basepath + "/"
+ version + "/"
+ endpoint;
return merged;
}
}
| 27.569536
| 71
| 0.659861
|
f1d47dadb4c836fda87c3448eb03ba60dd57c057
| 1,254
|
package jp.co.lib.tkato.tktask;
import android.support.annotation.NonNull;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import jp.co.lib.tkato.tktask.latch.AbortableCountDownLatch;
abstract class AbstractTask {
// region count down latch
protected AbortableCountDownLatch counter;
protected final AbortableCountDownLatch getCounter() {
synchronized (this) {
return counter;
}
}
protected final void setCounter(AbortableCountDownLatch counter) {
synchronized (this) {
this.counter = counter;
}
}
// endregion count down latch
// ExecutorService について
// https://qiita.com/amay077/items/b5f4e98b50d7fbcbaaec
// https://qiita.com/mmmm/items/f33b757119fc4dbd6aa1
// https://java.keicode.com/lang/multithreading-cancel.php
ExecutorService executor;
Future future;
AbstractTask() {
// this.executor = Executors.newSingleThreadExecutor(); // シングルスレッドなので並列に処理されない
this.executor = Executors.newCachedThreadPool(); // 必要に応じて複数スレッド生成
}
AbstractTask(@NonNull final ExecutorService executor) {
this.executor = executor;
}
}
| 26.125
| 86
| 0.697767
|
160deec5f1fbb25b1fbc37ff5c19e40028680c86
| 1,850
|
package jjcard.text.game.util;
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
public class IListMapTest {
@Test
public void addTest_listHashMap() {
IListMap<String, String> map = IListMap.newListHashMap();
assertNull(map.get("5252"));
List<String> out = map.add("5252", "testValue");
assertNotNull(out);
assertEquals(1, out.size());
assertEquals("testValue", out.get(0));
assertSame(out, map.get("5252"));
}
@Test
public void addAllTest_listHashMap() {
IListMap<String, String> map = IListMap.newListHashMap();
assertNull(map.get("5252"));
List<String> inList = new ArrayList<>();
inList.add("testValue");
inList.add("testValue2");
List<String> out = map.addAll("5252", inList);
assertNotNull(out);
assertEquals(2, out.size());
assertEquals(inList, out);
assertNotSame(inList, out);
}
@Test
public void addAllTest_alreadyExists_listHashMap() {
IListMap<String, String> map = IListMap.newListHashMap();
assertNull(map.get("5252"));
List<String> alreadyList = new ArrayList<>();
alreadyList.add("testValue3");
alreadyList.add("testValue4");
map.put("5252", alreadyList);
List<String> inList = new ArrayList<>();
inList.add("testValue");
inList.add("testValue2");
List<String> out = map.addAll("5252", inList);
assertNotNull(out);
assertEquals(4, out.size());
assertTrue(out.containsAll(inList));
assertTrue(out.containsAll(alreadyList));
}
@Test
public void addTest_listTreeMap() {
IListMap<String, String> map = IListMap.newListTreeMap();
assertNull(map.get("5252"));
List<String> out = map.add("5252", "testValue");
assertNotNull(out);
assertEquals(1, out.size());
assertEquals("testValue", out.get(0));
assertSame(out, map.get("5252"));
}
}
| 25.694444
| 59
| 0.693514
|
f36ee64cb54b91baacf5da92f849702458d250b7
| 10,527
|
/*
* Copyright (c) 2011, 2018 Purdue University.
* 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 etalon.purdue.edu.base;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
/**
* Created by hussein on 5/25/16.
*/
public class ConfigManager {
private static final int DEBUG_MODE = 1;
/**
* The constant isDebug.
*/
public final static boolean isDebug =
(DEBUG_MODE | ApplicationInfo.FLAG_DEBUGGABLE) != 0;
/**
* Debug sos.
*
* @param msg the msg
*/
public static void DebugSOS(String msg) {
if(isDebug) {
Log.e("debu_msg --> ", msg);
}
}
/**
* The constant PREFS_NAME.
*/
public static final String PREFS_NAME = "app.conf";
/**
* The constant READABLE_MEM.
*/
public static final int READABLE_MEM = 1;
/**
* The constant WRITABLE_MEM.
*/
public static final int WRITABLE_MEM = 2;
/**
* The Properties.
*/
public Properties properties;
private SharedPreferences configs;
private String confFilePath;
private String appRootPath;
private String dataRootPath;
private String defaultButtonClassName;
private int storageAccess;
private Activity creatorActivity;
/**
* Gets app data path.
*
* @param foldername the foldername
* @return the app data path
*/
public String getAppDataPath(String foldername) {
return dataRootPath + File.separator + foldername;
}
/**
* Gets app conf file.
*
* @param foldername the foldername
* @return the app conf file
*/
public String getAppConfFile(String foldername) {
return dataRootPath + File.separator + foldername + File.separator +
this.properties.getProperty("app_conf_file");
}
/**
* Create config manager config manager.
*
* @param runningActivity the running activity
* @return the config manager
*/
public static ConfigManager CreateConfigManager(Activity runningActivity) {
return new ConfigManager(runningActivity);
}
private void loadFromPrivate() {
int fileNameId =
creatorActivity.getResources().getIdentifier("conf_file_name", "string",
creatorActivity.getPackageName());
confFilePath = creatorActivity.getResources().getString(fileNameId);
configs =
creatorActivity.getApplicationContext().getSharedPreferences(confFilePath,
Context.MODE_PRIVATE);
}
private void generateAppPath() {
String pkgName = creatorActivity.getPackageName();
int confDirNameId =
creatorActivity.getResources().getIdentifier("conf_dir_name",
"string", pkgName);
int extRootPathId =
creatorActivity.getResources().getIdentifier("external_root_path",
"string", pkgName);
// int appNameId =
// creatorActivity.getResources().getIdentifier("app_name", "string",
// pkgName);
String extDirPath =
creatorActivity.getResources().getString(extRootPathId);// +
//File.separator + creatorActivity.getResources().getString(appNameId);
appRootPath = Environment.getExternalStorageDirectory() + File.separator +
extDirPath;
dataRootPath = appRootPath + File.separator +
creatorActivity.getResources().getString(confDirNameId);
confFilePath = dataRootPath + File.separator + confFilePath;
}
/**
* Instantiates a new Config manager.
*
* @param runningActivity the running activity
*/
private ConfigManager(Activity runningActivity) {
this.creatorActivity = runningActivity;
storageAccess = 0;
storageAccess |= (isExternalStorageReadable() ? READABLE_MEM : 0);
storageAccess |= (isExternalStorageWritable() ? WRITABLE_MEM : 0);
loadFromPrivate();
properties = new Properties();
for (Map.Entry<String, ?> entry : configs.getAll().entrySet()) {
String key = entry.getKey();
if(key.startsWith("list_")) {
properties.put(key, entry.getValue());
} else {
String value = entry.getValue().toString();
properties.setProperty(key, value);
}
}
if (isReadableCard()) {
generateAppPath();
try {
File file = new File(confFilePath);
FileInputStream fileInput = new FileInputStream(file);
properties.loadFromXML(fileInput);
defaultButtonClassName = properties.getProperty("clzz_default_button", null);
fileInput.close();
Enumeration enuKeys = properties.keys();
SharedPreferences.Editor editor = configs.edit();
while (enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
String value = properties.getProperty(key);
if (key.startsWith("list_")) {
StringTokenizer st = new StringTokenizer(value);
HashSet<String> libList = new HashSet <String>();
while (st.hasMoreTokens()) {
libList.add(st.nextToken());
}
editor.putStringSet(key, libList);
} else {
editor.putString(key, value);
}
editor.commit();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
confFilePath = PREFS_NAME;
}
for (Map.Entry<String, ?> entry : configs.getAll().entrySet()) {
DebugSOS("config values.. ["+ entry.getKey() + "] : [" +
entry.getValue().toString() + "]");
}
}
/**
* Gets app tag.
*
* @return the app tag
*/
public String getAppTag() {
return this.properties.getProperty("tag");
}
/**
* Gets iterations count.
*
* @return the iterations count
*/
public int getIterationsCount() {
String iterationsCount = this.properties.getProperty("iterations", "1");
return Integer.parseInt(iterationsCount);
}
/**
* Gets buttons.
*
* @return the buttons
*/
public List<String> getButtons() {
String definedBtns = this.properties.getProperty("app_buttons", null);
if (definedBtns == null)
return null;
ArrayList<String> decalredBTNs = new ArrayList<String>();
decalredBTNs.addAll(Arrays.asList(definedBtns.split(",")));
return decalredBTNs;
}
/**
* Gets signal buttons.
*
* @return the signal buttons
*/
public List<String> getSignalButtons() {
String definedSigBtns = this.properties.getProperty("signal_buttons", null);
if (definedSigBtns == null)
return null;
ArrayList<String> decalredSigBtnsBTNs = new ArrayList<String>();
decalredSigBtnsBTNs.addAll(Arrays.asList(definedSigBtns.split(",")));
return decalredSigBtnsBTNs;
}
/**
* Get benchmark speed string.
*
* @return the string
*/
public String getBenchmarkLoad() {
try {
throw new Exception("Add the implementation here");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Get button action string.
*
* @param butnName the butn name
* @return the string
*/
public String GetButtonAction(String butnName) {
return this.properties.getProperty("action_" + butnName);
}
/**
* Get button label string.
*
* @param butnName the butn name
* @return the string
*/
public String GetButtonLabel(String butnName) {
String btnLabel = this.properties.getProperty("label_" + butnName);
return (btnLabel == null ? butnName : btnLabel);
}
/**
* Get button signal string.
*
* @param butnName the butn name
* @return the string
*/
public String GetButtonSignal(String butnName) {
String btnSignal = this.properties.getProperty("sig_" + butnName);
return (btnSignal == null ? butnName : btnSignal);
}
/**
* Gets benchmark iterations.
*
* @return the benchmark iterations
*/
public String getBenchmarkIterations() {
try {
throw new Exception("Add the implementation here");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Is gui enabled boolean.
*
* @return the boolean
*/
public boolean isGuiEnabled() {
String isGUIstr = this.configs.getString("use_gui", "false");
boolean isGuiB = Boolean.valueOf(isGUIstr);
return isGuiB;
}
/**
* Gets config value.
*
* @param key the key
* @return the config value
*/
public String getConfigValue(String key) {
return this.configs.getString(key, null);
}
/* Checks if external storage is available to at least read */
private boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
/**
* Is external storage writable boolean.
*
* @return the boolean
*/
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/**
* @return
*/
private boolean isReadableCard() {
return ((storageAccess & READABLE_MEM) > 0);
}
/**
* @return
*/
private boolean isWritableCard() {
return ((storageAccess & WRITABLE_MEM) > 0);
}
public Set<String> getStringList(String key) {
HashSet<String> list = new HashSet<String>();
list.addAll(this.configs.getStringSet(key, list));
return list;
}
}
| 25.366265
| 85
| 0.658687
|
8cf84a04f8b16b48f846ae93b2a76cfbbea28a14
| 1,355
|
package com.ecommerce.customer.comment;
import com.ecommerce.general.comment.CommentDaoImpl;
import com.ecommerce.general.helper.Helper;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
@WebServlet(name = "DeleteCommentControllerC", urlPatterns = {"/delete-comment"})
public class DeleteCommentController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// get commentId param from the request
String commentId = request.getParameter("commentid");
// return the commentId if number or return 0
long id = commentId != null && Helper.isNumber(commentId) ? Long.parseLong(commentId) : 0;
// delete comment By id
boolean commentDeleted
= new CommentDaoImpl(getServletContext()).deleteComment(id);
JSONObject obj = new JSONObject();
obj.put("success", commentDeleted);
response.setContentType("application/json");
response.getWriter().print(obj.toJSONString());
}
}
| 37.638889
| 99
| 0.714391
|
a8765cdcf2834c3ee8a04679d9633a161a8bb3f5
| 993
|
package com.seeini.stack.controller.rest;
import com.seeini.common.response.ResponseData;
import com.seeini.common.response.ResponseUtil;
import com.seeini.stack.entity.GuidelinesDetail;
import com.seeini.stack.service.GuidelinesDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RequestMapping("guidelines/detail")
@RestController
public class GuidelinesDetailController {
@Autowired
private GuidelinesDetailService guidelinesDetailService;
@RequestMapping("get/{id}")
public ResponseData detail(@PathVariable("id") Long id){
GuidelinesDetail detail = guidelinesDetailService.selectByPrimaryKey(id);
return ResponseUtil.success(detail);
}
}
| 31.03125
| 82
| 0.811682
|
ca2590528e0e69ddcac9369c9c717de5bb34f7b7
| 8,795
|
/**
* Copyright 2007-2015, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.k3po.driver.internal.netty.bootstrap.http;
import static java.lang.String.format;
import static org.jboss.netty.channel.Channels.fireChannelClosed;
import static org.jboss.netty.channel.Channels.fireChannelDisconnected;
import static org.jboss.netty.channel.Channels.fireChannelInterestChanged;
import static org.jboss.netty.channel.Channels.fireChannelUnbound;
import static org.jboss.netty.channel.Channels.fireExceptionCaught;
import static org.jboss.netty.channel.Channels.fireMessageReceived;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.SWITCHING_PROTOCOLS;
import static org.kaazing.k3po.driver.internal.netty.channel.Channels.abortOutput;
import static org.kaazing.k3po.driver.internal.netty.channel.Channels.fireInputAborted;
import static org.kaazing.k3po.driver.internal.netty.channel.Channels.fireInputShutdown;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpChunkTrailer;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpRequestEncoder;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.kaazing.k3po.driver.internal.netty.channel.ShutdownInputEvent;
public class HttpClientChannelSource extends HttpChannelHandler {
private HttpClientChannel httpClientChannel;
public void setHttpChannel(HttpClientChannel httpClientChannel) {
assert this.httpClientChannel == null;
this.httpClientChannel = httpClientChannel;
}
@Override
protected void httpMessageReceived(ChannelHandlerContext ctx, MessageEvent e, HttpResponse httpResponse) throws Exception {
HttpChannelConfig httpChildConfig = httpClientChannel.getConfig();
httpChildConfig.setStatus(httpResponse.getStatus());
httpChildConfig.setVersion(httpResponse.getProtocolVersion());
httpChildConfig.getReadHeaders().set(httpResponse.headers());
if (httpResponse.getStatus().getCode() == SWITCHING_PROTOCOLS.getCode()) {
Channel transport = ctx.getChannel();
ChannelPipeline pipeline = transport.getPipeline();
pipeline.remove(HttpRequestEncoder.class);
httpClientChannel.readState(HttpClientChannel.HttpReadState.UPGRADED);
boolean readable = httpClientChannel.isReadable();
if (!readable) {
httpClientChannel.setReadable(true);
fireChannelInterestChanged(httpClientChannel);
}
// propagate any remaining bytes out of replaying decoder (after channel is marked as readable)
ChannelHandlerContext httpDecoderCtx = pipeline.getContext(HttpResponseDecoder.class);
HttpResponseDecoder httpDecoder = (HttpResponseDecoder) httpDecoderCtx.getHandler();
httpDecoder.replace(format("%s.noop", httpDecoderCtx.getName()), NOOP_HANDLER);
}
else {
ChannelBuffer content = httpResponse.getContent();
boolean readable = httpClientChannel.isReadable();
if (!readable) {
httpClientChannel.setReadable(true);
fireChannelInterestChanged(httpClientChannel);
}
if (content.readable()) {
fireMessageReceived(httpClientChannel, content);
}
if (!httpResponse.isChunked()) {
HttpClientChannel httpClientChannel = this.httpClientChannel;
this.httpClientChannel = null;
fireInputShutdown(httpClientChannel);
boolean wasConnected = httpClientChannel.isConnected();
boolean wasBound = httpClientChannel.isBound();
if (httpClientChannel.setClosed()) {
if (wasConnected) {
fireChannelDisconnected(httpClientChannel);
}
if (wasBound) {
fireChannelUnbound(httpClientChannel);
}
fireChannelClosed(httpClientChannel);
}
}
}
}
@Override
protected void httpMessageReceived(ChannelHandlerContext ctx, MessageEvent e, HttpChunk httpChunk) throws Exception {
ChannelBuffer content = httpChunk.getContent();
if (content.readable()) {
fireMessageReceived(httpClientChannel, content);
}
boolean last = httpChunk.isLast();
if (last) {
HttpClientChannel httpClientChannel = this.httpClientChannel;
if (httpChunk instanceof HttpChunkTrailer) {
HttpHeaders trailingHeaders = ((HttpChunkTrailer) httpChunk).trailingHeaders();
httpClientChannel.getConfig().getReadTrailers().set(trailingHeaders);
}
this.httpClientChannel = null;
fireInputShutdown(httpClientChannel);
if (httpClientChannel.setClosed()) {
fireChannelDisconnected(httpClientChannel);
fireChannelUnbound(httpClientChannel);
fireChannelClosed(httpClientChannel);
}
}
}
@Override
protected void httpMessageReceived(ChannelHandlerContext ctx, MessageEvent e, ChannelBuffer message) throws Exception {
if (message.readable()) {
// after 101 switching protocols
fireMessageReceived(httpClientChannel, message);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
if (httpClientChannel != null) {
HttpClientChannel httpClientChannel = this.httpClientChannel;
this.httpClientChannel = null;
if (httpClientChannel.setClosed()) {
fireExceptionCaught(httpClientChannel, e.getCause());
fireChannelClosed(httpClientChannel);
}
}
Channel channel = ctx.getChannel();
channel.close();
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
HttpClientChannel httpClientChannel = this.httpClientChannel;
if (httpClientChannel != null) {
this.httpClientChannel = null;
HttpChannelConfig httpClientConfig = httpClientChannel.getConfig();
HttpResponseStatus httpStatus = httpClientConfig.getStatus();
int httpStatusCode = (httpStatus != null) ? httpStatus.getCode() : 0;
if (httpStatusCode == SWITCHING_PROTOCOLS.getCode()) {
if (httpClientChannel.setClosed()) {
fireChannelDisconnected(httpClientChannel);
fireChannelUnbound(httpClientChannel);
fireChannelClosed(httpClientChannel);
}
}
else {
fireInputAborted(httpClientChannel);
}
}
}
@Override
public void inputShutdown(ChannelHandlerContext ctx, ShutdownInputEvent e) {
HttpClientChannel httpClientChannel = this.httpClientChannel;
if (httpClientChannel != null) {
if (httpClientChannel.readState() == HttpClientChannel.HttpReadState.UPGRADED)
{
fireInputShutdown(httpClientChannel);
}
}
else {
abortOutput(ctx, Channels.future(e.getChannel()));
}
}
@Sharable
private static class NoopChannelHandler extends SimpleChannelHandler {
}
private static final ChannelHandler NOOP_HANDLER = new NoopChannelHandler();
}
| 42.283654
| 127
| 0.685617
|
2ff0cc7445964c7ffff37e24777cf707668bbaf5
| 3,257
|
/*
* Copyright 2005 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.ole.fp.document.web.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.kuali.ole.fp.businessobject.InternalBillingItem;
import org.kuali.ole.sys.OLEConstants;
import org.kuali.ole.sys.OLEPropertyConstants;
import org.kuali.ole.sys.context.SpringContext;
import org.kuali.rice.kns.service.DictionaryValidationService;
/**
* This class handles Actions for InternalBilling.
*/
public class InternalBillingAction extends CapitalAccountingLinesActionBase {
/**
* Adds a new InternalBillingItem from the Form to the Document if valid. This method is called reflectively from KualiAction.
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws Exception
*/
public ActionForward insertItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
InternalBillingForm internalBillingForm = (InternalBillingForm) form;
if (validateNewItem(internalBillingForm)) {
internalBillingForm.getInternalBillingDocument().addItem(internalBillingForm.getNewItem());
internalBillingForm.setNewItem(new InternalBillingItem());
}
return mapping.findForward(OLEConstants.MAPPING_BASIC);
}
/**
* Validates the new InternalBillingItem on the Form, adding a global error if invalid.
*
* @param internalBillingForm
* @return whether the new item is valid
*/
protected static boolean validateNewItem(InternalBillingForm internalBillingForm) {
return SpringContext.getBean(DictionaryValidationService.class).isBusinessObjectValid(internalBillingForm.getNewItem(), OLEPropertyConstants.NEW_ITEM);
}
/**
* Deletes an InternalBillingItem from the Document. This method is called reflectively from KualiAction.
*
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
* @throws Exception
*/
public ActionForward deleteItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
InternalBillingForm internalBillingForm = (InternalBillingForm) form;
internalBillingForm.getInternalBillingDocument().getItems().remove(getLineToDelete(request));
return mapping.findForward(OLEConstants.MAPPING_BASIC);
}
}
| 40.7125
| 159
| 0.750384
|
da1df6f4fc5ddb45cec29e114272ca862a229f70
| 1,376
|
package de.bmoth.parser;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.atn.ATNConfigSet;
import org.antlr.v4.runtime.dfa.DFA;
public class ErrorListener extends BaseErrorListener {
class VisitorException extends RuntimeException {
private static final long serialVersionUID = -3388334148890725470L;
private final ParseErrorException parseErrorException;
VisitorException(ParseErrorException parseErrorException) {
this.parseErrorException = parseErrorException;
}
public ParseErrorException getParseErrorException() {
return this.parseErrorException;
}
}
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine,
String msg, RecognitionException e) {
CommonToken token = (CommonToken) offendingSymbol;
throw new VisitorException(new ParseErrorException(token, msg));
}
@Override
public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex,
java.util.BitSet conflictingAlts, ATNConfigSet configs) {
// log ambiguity
}
}
| 34.4
| 114
| 0.736919
|
ca3ea424e41586ae474fc9e84f82fd3e12b1b4e1
| 6,096
|
package com.misterpemodder.shulkerboxtooltip.impl.renderer;
import java.util.Arrays;
import com.misterpemodder.shulkerboxtooltip.api.PreviewType;
import com.misterpemodder.shulkerboxtooltip.api.provider.PreviewProvider;
import com.misterpemodder.shulkerboxtooltip.impl.ShulkerBoxTooltip;
import com.misterpemodder.shulkerboxtooltip.impl.ShulkerBoxTooltipClient;
import com.misterpemodder.shulkerboxtooltip.impl.config.Configuration.Theme;
import com.misterpemodder.shulkerboxtooltip.impl.util.MergedItemStack;
import com.mojang.blaze3d.systems.RenderSystem;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.font.TextRenderer;
import net.minecraft.client.gui.DrawableHelper;
import net.minecraft.client.render.item.ItemRenderer;
import net.minecraft.client.texture.TextureManager;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.util.DyeColor;
import net.minecraft.util.Identifier;
@Environment(EnvType.CLIENT)
public class ModPreviewRenderer extends BasePreviewRenderer {
private static final Identifier DEFAULT_TEXTURE_LIGHT =
new Identifier("shulkerboxtooltip", "textures/gui/shulker_box_tooltip.png");
private static final Identifier DEFAULT_TEXTURE_DARK =
new Identifier("shulkerboxtooltip", "textures/gui/shulker_box_tooltip_dark.png");
public static final ModPreviewRenderer INSTANCE = new ModPreviewRenderer();
@Override
public int getWidth() {
return 14 + Math.min(this.getMaxRowSize(), this.getInvSize()) * 18;
}
@Override
public int getHeight() {
return 14 + (int) Math.ceil(this.getInvSize() / (double) this.getMaxRowSize()) * 18;
}
/**
* Sets the color of the preview window.
*
* @return the color that was used.
*/
private float[] setColor() {
float[] color;
if (ShulkerBoxTooltip.config.preview.coloredPreview) {
color = this.provider.getWindowColor(this.previewContext);
if (color == null || color.length < 3) {
color = PreviewProvider.DEFAULT_COLOR;
}
} else {
color = PreviewProvider.DEFAULT_COLOR;
}
RenderSystem.setShaderColor(color[0], color[1], color[2], 1.0f);
return color;
}
/**
* Sets the texture to be used.
*
* @param color An array of three floats.
*/
private void setTexture(float[] color) {
Identifier texture = this.textureOverride;
if (texture == null) {
Theme theme = ShulkerBoxTooltip.config.preview.theme;
if (theme == Theme.MOD_AUTO)
theme = ShulkerBoxTooltipClient.isDarkModeEnabled() ? Theme.MOD_DARK : Theme.MOD_LIGHT;
if (theme == Theme.MOD_DARK && (Arrays.equals(color, PreviewProvider.DEFAULT_COLOR)
|| Arrays.equals(color, DyeColor.WHITE.getColorComponents()))) {
texture = DEFAULT_TEXTURE_DARK;
} else {
texture = DEFAULT_TEXTURE_LIGHT;
}
}
RenderSystem.setShaderTexture(0, texture);
}
private void drawBackground(int x, int y, int z, MatrixStack matrices) {
int zOffset = z + 100;
int invSize = this.getInvSize();
int xOffset = 7;
int yOffset = 7;
int rowTexYPos = 7;
int rowSize = Math.min(this.getMaxRowSize(), invSize);
int rowWidth = rowSize * 18;
setTexture(this.setColor());
// top side
for (int size = rowSize; size > 0; size -= 9) {
int s = Math.min(size, 9);
DrawableHelper.drawTexture(matrices, x + xOffset, y, zOffset, 7, 0, s * 18, 7, 256, 256);
xOffset += s * 18;
}
while (invSize > 0) {
xOffset = 7;
// left side
DrawableHelper.drawTexture(matrices, x, y + yOffset, zOffset, 0, rowTexYPos, 7, 18, 256, 256);
for (int rSize = rowSize; rSize > 0; rSize -= 9) {
int s = Math.min(rSize, 9);
// center
DrawableHelper.drawTexture(matrices, x + xOffset, y + yOffset, zOffset, 7, rowTexYPos,
s * 18, 18, 256, 256);
xOffset += s * 18;
}
// right side
DrawableHelper.drawTexture(matrices, x + xOffset, y + yOffset, zOffset, 169, rowTexYPos, 7,
18, 256, 256);
yOffset += 18;
invSize -= rowSize;
rowTexYPos = rowTexYPos >= 43 ? 7 : rowTexYPos + 18;
}
xOffset = 7;
for (int size = rowSize; size > 0; size -= 9) {
int s = Math.min(size, 9);
// bottom side
DrawableHelper.drawTexture(matrices, x + xOffset, y + yOffset, zOffset, 7, 61, s * 18, 7, 256,
256);
xOffset += s * 18;
}
// top-left corner
DrawableHelper.drawTexture(matrices, x, y, zOffset, 0, 0, 7, 7, 256, 256);
// top-right corner
DrawableHelper.drawTexture(matrices, x + rowWidth + 7, y, zOffset, 169, 0, 7, 7, 256, 256);
// bottom-right corner
DrawableHelper.drawTexture(matrices, x + rowWidth + 7, y + yOffset, zOffset, 169, 61, 7, 7, 256,
256);
// bottom-left corner
DrawableHelper.drawTexture(matrices, x, y + yOffset, zOffset, 0, 61, 7, 7, 256, 256);
}
@Override
public void draw(int x, int y, int z, MatrixStack matrices, TextRenderer textRenderer,
ItemRenderer itemRenderer, TextureManager textureManager) {
if (this.items.isEmpty() || this.previewType == PreviewType.NO_PREVIEW)
return;
this.drawBackground(x, y, z, matrices);
this.drawItems(x, y, z, textRenderer, itemRenderer);
}
public void drawItems(int x, int y, int z, TextRenderer textRenderer, ItemRenderer itemRenderer) {
int maxRowSize = this.getMaxRowSize();
itemRenderer.zOffset = z;
if (this.previewType == PreviewType.COMPACT) {
for (int i = 0, s = this.items.size(); i < s; ++i)
renderMergedStack(this.items.get(i).get(), itemRenderer, textRenderer,
8 + x + 18 * (i % maxRowSize), 8 + y + 18 * (i / maxRowSize));
} else {
for (MergedItemStack compactor : this.items)
for (int slot = 0, size = compactor.size(); slot < size; ++slot)
renderSubStack(compactor.getSubStack(slot), itemRenderer, textRenderer,
8 + x + 18 * (slot % maxRowSize), 8 + y + 18 * (slot / maxRowSize), slot);
}
itemRenderer.zOffset = 0.0f;
}
}
| 36.285714
| 100
| 0.666995
|
e7893cce62dea1365c09ffb77c0e0cd1eea4107b
| 1,983
|
/*
* Copyright 2017 Idaho State Police.
*
* 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 gov.idaho.isp.saktrack.report;
import gov.idaho.isp.saktrack.domain.SexualAssaultKit;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
public class StatutoryRequirementReportGroup {
private String requirement;
private List<StatutoryRequirementReportRow> rows;
public StatutoryRequirementReportGroup(List<SexualAssaultKit> kits, StatutoryRequirementType type) {
this.requirement = type.getLabel();
this.rows = kits.stream().map(k -> new StatutoryRequirementReportRow(k, type)).collect(Collectors.toList());
}
public String getGroupId() {
return requirement.replaceAll("[^a-zA-Z0-9]+", "");
}
public String getRequirement() {
return requirement;
}
public void setRequirement(String requirement) {
this.requirement = requirement;
}
public List<StatutoryRequirementReportRow> getRows() {
return rows;
}
public void setRows(List<StatutoryRequirementReportRow> rows) {
this.rows = rows;
}
public BigDecimal getAverageDays() {
List<Long> days = rows.stream().filter(r -> r.getDays() != null).map(StatutoryRequirementReportRow::getDays).collect(Collectors.toList());
if (!days.isEmpty()) {
return BigDecimal.valueOf(days.stream().mapToLong(l -> l).average().getAsDouble()).setScale(2, BigDecimal.ROUND_HALF_UP);
}
return null;
}
}
| 32.508197
| 142
| 0.726677
|
5eaf1e28acbbf9e6c30c48e1b79b8c551299c2c2
| 2,715
|
package org.skroll.reactor.pool;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import reactor.core.Disposable;
import reactor.core.Exceptions;
import reactor.util.Logger;
import reactor.util.Loggers;
import reactor.util.annotation.Nullable;
final class DecoratingMember<T> implements Member<T>, Runnable {
private static final Logger log = Loggers.getLogger(DecoratingMember.class);
private volatile T value;
private final MemberMono<T> memberMono;
private final BiFunction<? super T, ? super CheckIn, ? extends T> checkInDecorator;
private Disposable scheduled;
private boolean releasing;
private boolean checking;
private long lastCheckTime;
DecoratingMember(@Nullable final T value,
final BiFunction<? super T, ? super CheckIn, ? extends T> checkInDecorator,
final MemberMono<T> memberMono) {
this.checkInDecorator = checkInDecorator;
this.memberMono = memberMono;
this.value = value;
}
@Override
public T value() {
return checkInDecorator.apply(value, this);
}
@Override
public void checkIn() {
memberMono.pool.checkIn(this);
}
public void markAsReleasing() {
this.releasing = true;
}
public boolean isReleasing() {
return releasing;
}
public void markAsChecking() {
this.checking = true;
}
public boolean isChecking() {
return checking;
}
@Override
public void disposeValue() {
try {
if (scheduled != null) {
scheduled.dispose();
scheduled = null;
}
log.debug("disposing value {}", value);
memberMono.pool.disposer.accept(value);
} catch (Throwable e) {
// make action configurable
Exceptions.throwIfFatal(e);
} finally {
value = null;
checking = false;
}
}
public void setValueAndClearReleasingFlag(final T value) {
this.value = value;
this.releasing = false;
this.lastCheckTime = now();
}
void scheduleRelease() {
if (scheduled != null) {
scheduled.dispose();
log.debug("cancelled scheduled release of {}", this);
}
long maxIdleTimeMs = memberMono.pool.maxIdleTimeMs;
if (maxIdleTimeMs > 0) {
scheduled = memberMono.pool.scheduler.schedule(
this, maxIdleTimeMs, TimeUnit.MILLISECONDS);
log.debug("scheduled release in {}ms of {}", maxIdleTimeMs, this);
}
}
@Override
public void run() {
memberMono.addToBeReleased(this);
}
public void markAsChecked() {
checking = false;
lastCheckTime = now();
}
private long now() {
return memberMono.pool.scheduler.now(TimeUnit.MILLISECONDS);
}
public long lastCheckTime() {
return lastCheckTime;
}
}
| 23.405172
| 94
| 0.671455
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.