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
|
---|---|---|---|---|---|
c753ef27d5f3afe82064151441c6a87eb15583c2
| 332 |
package com.opuscapita.peppol.commons.queue.consume;
import com.opuscapita.peppol.commons.container.ContainerMessage;
import org.jetbrains.annotations.NotNull;
public interface ContainerMessageProcessor {
void process(@NotNull ContainerMessage cm);
void setContainerMessageConsumer(ContainerMessageConsumer consumer);
}
| 27.666667 | 72 | 0.834337 |
07217a5d104070bb81ee6d97fbf1852e93740b92
| 5,726 |
package com.jskillcloud.authsvc.it.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jskillcloud.authsvc.dto.*;
import com.jskillcloud.authsvc.mapper.UserMapper;
import com.jskillcloud.authsvc.model.RoleName;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
MockMvc mockMvc;
@Autowired
UserMapper userMapper;
SignUpRequest signUpRequest;
@Autowired
ObjectMapper objectMapper;
@Before
public void setUp() {
userMapper.deleteAll();
signUpRequest = SignUpRequest.builder()
.username("testUsername")
.password("testPassword")
.build();
}
@Test
public void testCheckUsernameAvailability() throws Exception {
this.signUpSuccess();
// not available case
MvcResult mvcResult = mockMvc.perform(get("/user/checkUsernameAvailability")
.param("username", "testUsername"))
.andExpect(status().isOk())
.andReturn();
UserIdentityAvailability userIdentityAvailability =
objectMapper.readValue(mvcResult.getResponse().getContentAsString(), UserIdentityAvailability.class);
assertThat(userIdentityAvailability.isAvailable()).isFalse();
// available case
mvcResult = mockMvc.perform(get("/user/checkUsernameAvailability")
.param("username", "availableUsername"))
.andExpect(status().isOk())
.andReturn();
userIdentityAvailability =
objectMapper.readValue(mvcResult.getResponse().getContentAsString(), UserIdentityAvailability.class);
assertThat(userIdentityAvailability.isAvailable());
}
@Test
public void testGetUserNoToken() throws Exception {
this.signUpSuccess();
MvcResult mvcResult = mockMvc.perform(get("/user/me"))
.andExpect(status().isUnauthorized())
.andReturn();
}
@Test
public void testGetUserWithCorrectToken() throws Exception {
// signUp
this.signUpSuccess();
// signIn
String token = this.signInThenGetToken();
// getUser
MvcResult mvcResult = mockMvc.perform(get("/user/me")
.header("Authorization", "Bearer " + token))
.andExpect(status().isOk())
.andReturn();
UserInfo userInfo =
objectMapper.readValue(mvcResult.getResponse().getContentAsString(), UserInfo.class);
assertThat(userInfo.getId()).isNotNull();
assertThat(userInfo.getUsername()).isEqualTo(signUpRequest.getUsername());
assertThat(userInfo.getRoles().size()).isEqualTo(1);
assertThat(userInfo.getRoles().get(0)).isEqualTo(RoleName.ROLE_USER.name());
}
@Test
public void testGetUserWithWrongToken() throws Exception {
// signUp
this.signUpSuccess();
// signIn
String token = signInThenGetToken();
// getUser
mockMvc.perform(get("/user/me")
.header("Authorization", "Bearer xxx" + token))
.andExpect(status().isUnauthorized())
.andReturn();
}
private String signInThenGetToken() throws Exception {
// signIn
LoginRequest loginRequest = LoginRequest.builder()
.username("testUsername")
.password("testPassword")
.build();
MvcResult mvcResult = mockMvc.perform(post("/auth/signin")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsBytes(loginRequest)))
.andExpect(status().isOk())
.andReturn();
JwtAuthenticationResponse jwtAuthenticationResponse =
objectMapper.readValue(mvcResult.getResponse().getContentAsString(), JwtAuthenticationResponse.class);
assertThat(jwtAuthenticationResponse.getAccessToken()).isNotBlank();
assertThat(jwtAuthenticationResponse.getTokenType()).isEqualTo("Bearer");
return jwtAuthenticationResponse.getAccessToken();
}
private void signUpSuccess() throws Exception {
MvcResult mvcResult = mockMvc.perform(post("/auth/signup")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsBytes(signUpRequest)))
.andExpect(status().isOk())
.andReturn();
ApiResponse apiResponse = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), ApiResponse.class);
assertThat(apiResponse.getSuccess()).isTrue();
assertThat(apiResponse.getMessage()).isEqualTo("User registered successfully");
}
@After
public void destroy() {
userMapper.deleteAll();
}
}
| 36.012579 | 122 | 0.670276 |
d9941cd09be48ef4fa52297dae863c9d9892697c
| 145 |
package org.delusion.elgame.utils;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public interface SimpleRenderable {
void render();
}
| 16.111111 | 49 | 0.772414 |
c4b0f80f4f891d42dcfab19fddf5180e410c6fa3
| 306 |
package pattern.structural.composite;
/**
* Componente principal
*/
public class Window extends Component {
private String name;
public Window(String name) {
this.name = name;
}
@Override
public void draw() {
System.out.println(name);
super.draw();
}
}
| 16.105263 | 39 | 0.611111 |
feca27894aa011ae621d29721872e566d56095db
| 157 |
package com.wakaleo.myflix.movies.model;
/**
* Created by john on 11/06/2015.
*/
public enum Genre {
Drama, Comedy, Action, ScienceFiction, Fantasy
}
| 17.444444 | 50 | 0.700637 |
cfcc2c35c5fb7b7bf4741265de19ad147f0d913b
| 190 |
package com.databasir.core.domain.group.event;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class GroupDeleted {
private Integer groupId;
}
| 14.615385 | 46 | 0.794737 |
1466e063230be5489a775aadb116c348d8c397d5
| 1,627 |
package com.restfiddle.util.apicreator;
import com.restfiddle.controller.rest.ConversationController;
import com.restfiddle.controller.rest.NodeController;
import com.restfiddle.dto.NodeDTO;
import com.restfiddle.dto.RfRequestDTO;
import com.restfiddle.dto.ConversationDTO;
import com.restfiddle.entity.BaseNode;
import com.restfiddle.entity.GenericEntity;
import org.json.JSONObject;
public class CreateApiCreator extends ApiCreator {
public CreateApiCreator(BaseNode entityNode, ConversationController conversationController, NodeController nodeController, String hostUri){
super(entityNode, conversationController, nodeController, hostUri);
}
public NodeDTO create(){
String projectId = entityNode.getProjectId();
// API to GENERATE >> Create Entity Data
ConversationDTO conversationDTO = new ConversationDTO();
RfRequestDTO rfRequestDTO = new RfRequestDTO();
rfRequestDTO.setApiUrl(hostUri + "/api/" + projectId + "/entities/" + entityNode.getName());
rfRequestDTO.setMethodType("POST");
JSONObject jsonObject = getFieldJSON(genericEntity);
// Make a pretty-printed JSON text of this JSONObject.
rfRequestDTO.setApiBody(jsonObject.toString(4));
conversationDTO.setRfRequestDTO(rfRequestDTO);
ConversationDTO createdConversation = conversationController.create(conversationDTO);
conversationDTO.setId(createdConversation.getId());
String nodeName = "Create " + entityNode.getName();
NodeDTO createdNode = new NodeBuilder(nodeName)
.setProjectId(projectId)
.setConversationDTO(conversationDTO)
.build();
return createdNode;
}
}
| 38.738095 | 141 | 0.778734 |
ead8d9e1a0faec081e1c09508c521f6df584e916
| 829 |
/*
* ResponseType.java
*
* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar.
* See http://sam.zoy.org/wtfpl/COPYING for more details.
*
* @author shaika-dzari
* @since 2012-09-17
*/
package net.nakama.duckquery.net.response.api;
public enum ResponseType {
A("Article"), D("Disambiguation"), C("Category"), N("Name"), E("Exclusive");
private String desc;
ResponseType(String desc) {
this.desc = desc;
}
public String getDescription() {
return this.desc;
}
public static ResponseType fromString(String v) {
if (v.equals(""))
return null;
return ResponseType.valueOf(v);
}
}
| 23.685714 | 77 | 0.693607 |
6ef03dd97e2f44dd8728133e8fbf887dec6a9773
| 1,928 |
/*
* Copyright (C) 2014 Indeed Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.indeed.imhotep.web;
import javax.annotation.Nonnull;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Sets header
* Cache-control: no-cache, must-revalidate
*/
public class NoCacheFilter implements Filter {
@Override
public void init(@Nonnull final FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(@Nonnull final ServletRequest servletRequest,
@Nonnull final ServletResponse servletResponse,
@Nonnull final FilterChain filterChain) throws IOException, ServletException {
if (servletRequest instanceof HttpServletRequest && servletResponse instanceof HttpServletResponse) {
final HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Cache-control", "no-cache, must-revalidate");
}
filterChain.doFilter(servletRequest, servletResponse);
}
/**
* Noop
*/
@Override
public void destroy() {
// noop
}
}
| 33.824561 | 109 | 0.727178 |
0a2641ca082b3fd58cf552b694d12ebb6ef6dbf0
| 504 |
public class TokenCatalogBean {
private int termId;
private long startOffset;
private long endOffset;
public int getTermId() {
return termId;
}
public void setTermId(int termId) {
this.termId = termId;
}
public long getStartOffset() {
return startOffset;
}
public void setStartOffset(long startOffset) {
this.startOffset = startOffset;
}
public long getEndOffset() {
return endOffset;
}
public void setEndOffset(long endOffset) {
this.endOffset = endOffset;
}
}
| 15.272727 | 47 | 0.712302 |
b27347b7d2ae170a08889d37ff9ac0312a2ed41f
| 989 |
package net.lizistired.animationoverhaul.mixin;
import net.lizistired.animationoverhaul.AnimationOverhaulMain;
import gg.moonflower.pollen.pinwheel.api.client.geometry.GeometryModel;
import gg.moonflower.pollen.pinwheel.api.client.geometry.GeometryModelManager;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.Map;
import net.minecraft.util.Identifier;
@Mixin(GeometryModelManager.class)
public class MixinGeometryLoader {
@Shadow @Final private static Map<Identifier, GeometryModel> MODELS;
@Inject(method = "getModel", at = @At("HEAD"))
private static void bbbb(Identifier location, CallbackInfoReturnable<GeometryModel> cir){
AnimationOverhaulMain.LOGGER.warn(MODELS.keySet());
}
}
| 39.56 | 93 | 0.812942 |
f83bd7b721eccc61659c62c15374008d7d30bff3
| 448 |
package com.thinkgem.jeesite.modules.sign.dao;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.thinkgem.jeesite.modules.sign.entity.Client;
import org.springframework.stereotype.Component;
/**
* DAO 接口类
* Created by bb on 2017-11-11.
*/
@MyBatisDao
public interface ClientTestDao {
int insert(Client client);
Client isPass(Client client);
}
| 23.578947 | 69 | 0.776786 |
79a6ae5868542280055fea9057d10c2b92734d0d
| 988 |
package LeetCodePractice;
import java.util.Stack;
public class _143ReorderList {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public static void main(String[] args) {
ListNode ln=new ListNode(1);
ln.next=new ListNode(2);
ln.next.next=new ListNode(3);
ln.next.next.next=new ListNode(4);
reorderList(ln);
}
public static void reorderList(ListNode ln) {
Stack<ListNode> stack=new Stack<>();
ListNode headPointer=ln;
int length=0;
while(ln!=null)
{
stack.push(ln);
length++;
ln=ln.next;
}
if(length<=2){
ln=headPointer;
return;
}
ln=headPointer;
int counter=0;
while(ln!=null && counter<length)
{
ListNode ln1=stack.pop();
ListNode nextNode=ln.next;
ln.next=ln1;
counter++;
if(counter<length)
ln1.next=nextNode;
else
ln1.next=null;
counter++;
ln=ln.next;
if(ln!=null)
ln=ln.next;
}
if(ln!=null)
{
ln.next=null;
}
ln=headPointer;
}
}
| 17.034483 | 46 | 0.635628 |
a4e4385f7ec0c888116c9b5a62b2f2a3da004f23
| 4,708 |
package nl.weeaboo.vn.impl.sound;
import java.io.IOException;
import java.util.Collection;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableSet;
import nl.weeaboo.filesystem.FilePath;
import nl.weeaboo.prefsstore.IPreferenceStore;
import nl.weeaboo.vn.core.IEnvironment;
import nl.weeaboo.vn.core.NovelPrefs;
import nl.weeaboo.vn.core.ResourceId;
import nl.weeaboo.vn.core.ResourceLoadInfo;
import nl.weeaboo.vn.impl.core.AbstractModule;
import nl.weeaboo.vn.signal.ISignal;
import nl.weeaboo.vn.signal.PrefsChangeSignal;
import nl.weeaboo.vn.sound.ISound;
import nl.weeaboo.vn.sound.ISoundController;
import nl.weeaboo.vn.sound.ISoundModule;
import nl.weeaboo.vn.sound.SoundType;
import nl.weeaboo.vn.sound.desc.ISoundDefinition;
/**
* Sub-module for audio.
*/
public final class SoundModule extends AbstractModule implements ISoundModule {
private static final long serialVersionUID = SoundImpl.serialVersionUID;
private static final Logger LOG = LoggerFactory.getLogger(SoundModule.class);
private final SoundResourceLoader resourceLoader;
private final ISoundController soundController;
private final INativeAudioFactory nativeAudioFactory;
public SoundModule(IEnvironment env) {
this(new SoundResourceLoader(env), new SoundController());
}
public SoundModule(SoundResourceLoader resourceLoader, ISoundController soundController) {
this.resourceLoader = resourceLoader;
this.soundController = soundController;
nativeAudioFactory = new NativeAudioFactory(resourceLoader);
resourceLoader.setPreloadHandler(nativeAudioFactory);
}
/**
* Returns the set of file extensions (without the '.' prefix) supported by the load methods of this
* class.
*/
public static ImmutableSet<String> getSupportedFileExts() {
return ImmutableSet.of("ogg", "mp3");
}
@Override
public void destroy() {
super.destroy();
soundController.stopAll();
}
@Override
public void update() {
super.update();
soundController.update();
}
@Override
public @Nullable ResourceId resolveResource(FilePath filename) {
return resourceLoader.resolveResource(filename);
}
@Override
public @Nullable ISound createSound(SoundType stype, ResourceLoadInfo loadInfo) {
FilePath path = loadInfo.getPath();
resourceLoader.checkRedundantFileExt(path);
ResourceId resourceId = resolveResource(path);
if (resourceId == null) {
LOG.debug("Unable to find audio file: {}", path);
return null;
}
FilePath absolutePath = resourceLoader.getAbsolutePath(resourceId.getFilePath());
INativeAudio nativeAudio;
try {
nativeAudio = nativeAudioFactory.createNativeAudio(absolutePath);
} catch (IOException e) {
LOG.warn("Error loading audio file: {}", path);
return null;
}
resourceLoader.logLoad(resourceId, loadInfo);
return new Sound(soundController, stype, resourceId.getFilePath(), nativeAudio);
}
/**
* @param filename Path to an audio file
*/
@Override
public @Nullable String getDisplayName(FilePath filename) {
ResourceId resourceId = resolveResource(filename);
if (resourceId == null) {
return null;
}
ISoundDefinition def = resourceLoader.getSoundDef(resourceId.getFilePath());
if (def == null) {
return null;
}
return def.getDisplayName();
}
@Override
public Collection<FilePath> getSoundFiles(FilePath folder) {
return resourceLoader.getMediaFiles(folder);
}
@Override
public ISoundController getSoundController() {
return soundController;
}
@Override
public void preload(FilePath path) {
resourceLoader.preload(path);
}
@Override
public void handleSignal(ISignal signal) {
super.handleSignal(signal);
if (signal.isUnhandled(PrefsChangeSignal.class)) {
IPreferenceStore prefsStore = ((PrefsChangeSignal)signal).getPrefsStore();
soundController.setMasterVolume(SoundType.MUSIC, prefsStore.get(NovelPrefs.MUSIC_VOLUME));
soundController.setMasterVolume(SoundType.SOUND, prefsStore.get(NovelPrefs.SOUND_EFFECT_VOLUME));
soundController.setMasterVolume(SoundType.VOICE, prefsStore.get(NovelPrefs.VOICE_VOLUME));
}
}
@Override
public void clearCaches() {
super.clearCaches();
nativeAudioFactory.clearCaches();
}
}
| 30.179487 | 109 | 0.695624 |
e39df1620ea7504667cf17b1ff1ec4e3893c8bde
| 5,413 |
package com.sourcey.materiallogindemo;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.github.mikephil.charting.charts.HorizontalBarChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.utils.ColorTemplate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import az.plainpie.animation.PieAngleAnimation;
import butterknife.BindView;
import butterknife.ButterKnife;
public class SubjectAtt extends AppCompatActivity {
@BindView(R.id.barchart)
HorizontalBarChart barchart;
SharedPreferences sf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subject_att);
ButterKnife.bind(this);
String url = "https://kaustubhk.com/ecollege/attendance.php";
Map<String, String> params = new HashMap<String, String>();
sf = getSharedPreferences("access_token", MODE_PRIVATE);
String token = sf.getString("value", null);
if (token == null) {
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(i);
finish();
}
params.put("access_token", token);
final ProgressDialog progressDialog = new ProgressDialog(SubjectAtt.this,
R.style.AppTheme);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Loading");
progressDialog.show();
JsonObjectRequest jsonRequest = new JsonObjectRequest
(Request.Method.POST, url, new JSONObject(params), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// the response is already constructed as a JSONObject!
Log.i("response", response.toString());
try {
Boolean success = response.getBoolean("success");
ArrayList<String> labels = new ArrayList<String>();
ArrayList<BarEntry> bt = new ArrayList<BarEntry>();
JSONArray keys = response.names ();
for (int i = 0,j=0; i < keys.length (); ++i) {
String key = keys.getString (i); // Here's your key
if(!key.equals("success")) {
JSONObject value = response.getJSONObject(key); // Here's your value
labels.add(key);
int attended = value.getInt("attended");
int conducted = value.getInt("conducted");
bt.add(new BarEntry(((float)(attended*100)/conducted),j++));
}
}
BarDataSet bardataset = new BarDataSet(bt, "Attendance");
BarData data = new BarData(labels, bardataset);
bardataset.setColors(ColorTemplate.COLORFUL_COLORS);
barchart.animateY(1500);
barchart.setData(data);
barchart.setDescription("Subject Wise Attendence");
progressDialog.dismiss();
return;
} catch (JSONException e) {
Toast.makeText(getBaseContext(), "Loading failed", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
return;
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getBaseContext(), "Loading failed", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
// Log.i("error",error.getMessage());
return;
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
return params;
}
// @Override
// public String getBodyContentType() {
// return "application/x-www-form-urlencoded; charset=UTF-8";
// }
};
Volley.newRequestQueue(SubjectAtt.this).add(jsonRequest);
//onSignupSuccess();
// onSignupFailed();
progressDialog.dismiss();
}
}
| 40.096296 | 105 | 0.55533 |
322f4448238e8e68b63670218fbf3839a6b1113c
| 1,799 |
package com.hrym.wechat.mapper;
import com.hrym.wechat.entity.MeditationRecord;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;
/**
* Created by hrym13 on 2018/4/14.
*/
@Repository
public interface MeditationRecordMapper {
/**
* 查找本活动有多少人参加
*
* @param scheduleId
* @return
*/
@Select(" SELECT COUNT(1) FROM x_meditation_record WHERE schedule_id = #{scheduleId}")
Integer selectUserCount(Integer scheduleId);
// /**
// * 加入共修活动
// * @param record
// */
// @Insert(" insert into x_meditation_record(schedule_id,status,created_time,user_id)values(#{scheduleId},#{status},#{createdTime},#{userId})")
// void insertMeditationRecord(MeditationRecord record);
/**
* 查看用户是否在此共修中
*
* @param userId
* @param meditationTypeId
* @return
*/
@Select(" select * from x_meditation_record where user_id = #{userId} AND meditation_type_id= #{meditationTypeId}")
MeditationRecord findMeditationRecord(@Param("userId") Integer userId, @Param("meditationTypeId") Integer meditationTypeId);
//新版加入活动
/**
* 加入共修活动
*
* @param record
*/
@Insert(" insert into x_meditation_record (meditation_type_id,user_id,created_time,is_top)values(#{meditationTypeId},#{userId},#{createdTime},#{isTop})")
void insertMeditationTypeRecord(MeditationRecord record);
/**
* 改变置顶的状态
*
* @param med
*/
@Update("update x_meditation_record set is_top = #{isTop} where meditation_type_id = #{meditationTypeId} and user_id = #{userId}")
void updateMedRecordIsTop(MeditationRecord med);
}
| 29.016129 | 157 | 0.691495 |
0326ed15bd83272bd0f7a45ccbbd204e65855b76
| 1,384 |
package org.thoughtcrime.securesms.glide.cache;
import androidx.annotation.NonNull;
import org.thoughtcrime.securesms.logging.Log;
import com.bumptech.glide.load.EncodeStrategy;
import com.bumptech.glide.load.Options;
import com.bumptech.glide.load.ResourceEncoder;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.util.ByteBufferUtil;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
public class EncryptedGifDrawableResourceEncoder extends EncryptedCoder implements ResourceEncoder<GifDrawable> {
private static final String TAG = EncryptedGifDrawableResourceEncoder.class.getSimpleName();
private final byte[] secret;
public EncryptedGifDrawableResourceEncoder(@NonNull byte[] secret) {
this.secret = secret;
}
@Override
public EncodeStrategy getEncodeStrategy(@NonNull Options options) {
return EncodeStrategy.TRANSFORMED;
}
@Override
public boolean encode(@NonNull Resource<GifDrawable> data, @NonNull File file, @NonNull Options options) {
GifDrawable drawable = data.get();
try (OutputStream outputStream = createEncryptedOutputStream(secret, file)) {
ByteBufferUtil.toStream(drawable.getBuffer(), outputStream);
return true;
} catch (IOException e) {
Log.w(TAG, e);
return false;
}
}
}
| 30.086957 | 113 | 0.775289 |
f387013b4351fbcb93f4ef8ee51c36069af34cfa
| 996 |
package me.hvkcoder.java_basic.juc.aqs;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* CyclicBarrier 指定线程数执行完成,再执行后续操作,它的计数器可通过 reset() 方法重置
*
* @author h-vk
* @since 2020/11/20
*/
@Slf4j
public class AQS02_CyclicBarrier {
public static void main(String[] args) {
final int count = 7;
final CyclicBarrier cyclicBarrier = new CyclicBarrier(count, () -> log.info("召唤神龙~~"));
ExecutorService executor = Executors.newFixedThreadPool(count);
for (int i = 1; i <= count; i++) {
final int number = i;
executor.execute(
() -> {
log.info("收集第 {} 个龙珠", number);
try {
System.out.println(cyclicBarrier.getNumberWaiting());
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
});
}
executor.shutdown();
}
}
| 25.538462 | 89 | 0.693775 |
8ec73a169008136736d713a2565f86108d848a22
| 6,632 |
/*
* Copyright © 2015-2019 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.db.batch.source;
import com.google.common.base.Throwables;
import io.cdap.plugin.ConnectionConfig;
import io.cdap.plugin.DBUtils;
import io.cdap.plugin.JDBCDriverShim;
import io.cdap.plugin.db.batch.NoOpCommitConnection;
import io.cdap.plugin.db.batch.TransactionIsolationLevel;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
import org.apache.hadoop.mapreduce.lib.db.DBInputFormat;
import org.apache.hadoop.mapreduce.lib.db.DBWritable;
import org.apache.hadoop.mapreduce.lib.db.DataDrivenDBInputFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
/**
* Class that extends {@link DBInputFormat} to load the database driver class correctly.
*/
public class DataDrivenETLDBInputFormat extends DataDrivenDBInputFormat {
public static final String AUTO_COMMIT_ENABLED = "io.cdap.hydrator.db.autocommit.enabled";
private static final Logger LOG = LoggerFactory.getLogger(DataDrivenETLDBInputFormat.class);
private Driver driver;
private JDBCDriverShim driverShim;
static void setInput(Configuration conf,
Class<? extends DBWritable> inputClass,
String inputQuery,
String inputBoundingQuery,
boolean enableAutoCommit) {
DBConfiguration dbConf = new DBConfiguration(conf);
dbConf.setInputClass(inputClass);
dbConf.setInputQuery(inputQuery);
dbConf.setInputBoundingQuery(inputBoundingQuery);
conf.setBoolean(AUTO_COMMIT_ENABLED, enableAutoCommit);
}
@Override
public Connection getConnection() {
if (this.connection == null) {
Configuration conf = getConf();
try {
String url = conf.get(DBConfiguration.URL_PROPERTY);
try {
// throws SQLException if no suitable driver is found
DriverManager.getDriver(url);
} catch (SQLException e) {
if (driverShim == null) {
if (driver == null) {
ClassLoader classLoader = conf.getClassLoader();
@SuppressWarnings("unchecked")
Class<? extends Driver> driverClass =
(Class<? extends Driver>) classLoader.loadClass(conf.get(DBConfiguration.DRIVER_CLASS_PROPERTY));
driver = driverClass.newInstance();
// De-register the default driver that gets registered when driver class is loaded.
DBUtils.deregisterAllDrivers(driverClass);
}
driverShim = new JDBCDriverShim(driver);
DriverManager.registerDriver(driverShim);
LOG.debug("Registered JDBC driver via shim {}. Actual Driver {}.", driverShim, driver);
}
}
Properties properties =
ConnectionConfig.getConnectionArguments(conf.get(DBUtils.CONNECTION_ARGUMENTS),
conf.get(DBConfiguration.USERNAME_PROPERTY),
conf.get(DBConfiguration.PASSWORD_PROPERTY));
connection = DriverManager.getConnection(url, properties);
boolean autoCommitEnabled = conf.getBoolean(AUTO_COMMIT_ENABLED, false);
if (autoCommitEnabled) {
// hack to work around jdbc drivers like the hive driver that throw exceptions on commit
this.connection = new NoOpCommitConnection(this.connection);
} else {
this.connection.setAutoCommit(false);
}
int fetchSize = conf.getInt(DBUtils.FETCH_SIZE, 0);
if (fetchSize > 0) {
this.connection = new ConnectionWithFetchSize(this.connection, fetchSize);
}
String level = conf.get(TransactionIsolationLevel.CONF_KEY);
LOG.debug("Transaction isolation level: {}", level);
connection.setTransactionIsolation(TransactionIsolationLevel.getLevel(level));
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
return this.connection;
}
// versions > HDP-2.3.4 started using createConnection instead of getConnection,
// this is added for compatibility, more information at (HYDRATOR-791)
public Connection createConnection() {
return getConnection();
}
@Override
protected RecordReader createDBRecordReader(DBInputSplit split, Configuration conf) throws IOException {
final RecordReader dbRecordReader = super.createDBRecordReader(split, conf);
return new RecordReader() {
@Override
public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
dbRecordReader.initialize(split, context);
}
@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
return dbRecordReader.nextKeyValue();
}
@Override
public Object getCurrentKey() throws IOException, InterruptedException {
return dbRecordReader.getCurrentKey();
}
@Override
public Object getCurrentValue() throws IOException, InterruptedException {
return dbRecordReader.getCurrentValue();
}
@Override
public float getProgress() throws IOException, InterruptedException {
return dbRecordReader.getProgress();
}
@Override
public void close() throws IOException {
dbRecordReader.close();
try {
DriverManager.deregisterDriver(driverShim);
} catch (SQLException e) {
throw new IOException(e);
}
}
};
}
@Override
protected void closeConnection() {
super.closeConnection();
try {
DriverManager.deregisterDriver(driverShim);
} catch (SQLException e) {
throw Throwables.propagate(e);
}
}
}
| 37.468927 | 117 | 0.691345 |
4cd7573d25e380d686b6b4b906614e8959a30255
| 4,074 |
package eu.spitfire_project.ld4s.resource.actuator_decision;
import java.io.Serializable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import eu.spitfire_project.ld4s.lod_cloud.Context;
import eu.spitfire_project.ld4s.resource.LD4SDataResource;
import eu.spitfire_project.ld4s.resource.LD4SObject;
import eu.spitfire_project.ld4s.vocabulary.LD4SConstants;
public class ActuatorDecision extends LD4SObject implements Serializable{
/** Property that is the focus of an Actuator. **/
private String actuatorProperty = null;
/** Application Domain of an Actuator. **/
private String applicationDomain = null;
/** Optional actions that the actuator can apply on the property of focus. **/
private String[] decisionOptions = null;
/** Latitude for the actuator */
private String latitude = null;
/** Longitude for the actuator */
private String longitude = null;
/**
*
*/
private static final long serialVersionUID = 5222281425211809256L;
public ActuatorDecision(JSONObject json) throws JSONException {
super(json);
if (json.has("actuator"+LD4SConstants.JSON_SEPARATOR+"property")){
this.setActuatorProperty(LD4SDataResource.removeBrackets(
json.getString("actuator"+LD4SConstants.JSON_SEPARATOR+"property")));
}
if (json.has("application"+LD4SConstants.JSON_SEPARATOR+"domain")){
this.setApplicationDomain(LD4SDataResource.removeBrackets(
json.getString("application"+LD4SConstants.JSON_SEPARATOR+"domain")));
}
if (json.has("latitude")){
this.setLatitude(LD4SDataResource.removeBrackets(
json.getString("latitude")));
}
if (json.has("longitude")){
this.setLongitude(LD4SDataResource.removeBrackets(
json.getString("longitude")));
}
if (json.has("decision"+LD4SConstants.JSON_SEPARATOR+"options")){
this.setDecisionOptions(
json.getJSONArray("decision"+LD4SConstants.JSON_SEPARATOR+"options"));
}
}
@Override
protected void initDefaultType() {
// TODO Auto-generated method stub
}
@Override
protected void initAcceptedTypes() {
// TODO Auto-generated method stub
}
@Override
public String getRemote_uri() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setRemote_uri(String resourceHost) {
// TODO Auto-generated method stub
}
@Override
public void setStoredRemotely(boolean storedRemotely) {
// TODO Auto-generated method stub
}
@Override
public boolean isStoredRemotely() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isStoredRemotely(String localUri) {
// TODO Auto-generated method stub
return false;
}
@Override
public void setLink_criteria(Context link_criteria) {
// TODO Auto-generated method stub
}
@Override
public Context getLink_criteria() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setLink_criteria(String link_criteria, String localhost)
throws Exception {
// TODO Auto-generated method stub
}
public String getActuatorProperty() {
return this.actuatorProperty;
}
public String getApplicationDomain() {
return applicationDomain;
}
public void setApplicationDomain(String applicationDomain) {
this.applicationDomain = applicationDomain;
}
public void setDecisionOptions (JSONArray jvalues) throws JSONException {
String[] values = new String[jvalues.length()];
for (int i=0; i< jvalues.length(); i++){
values[i] = jvalues.get(i).toString();
}
setDecisionOptions(values);
}
public String[] getDecisionOptions() {
return decisionOptions;
}
public void setDecisionOptions(String[] decisionOptions) {
this.decisionOptions = decisionOptions;
}
public void setActuatorProperty(String actuatorProperty) {
this.actuatorProperty = actuatorProperty;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
| 23.549133 | 79 | 0.746441 |
52aa22ad4beb8cee6486c97e7c105ef62d382af9
| 2,987 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// 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: 2017.11.30 at 08:24:17 PM JST
//
package eu.datex2.schema._2_0rc1._2_0;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for RoadsideAssistance complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="RoadsideAssistance">
* <complexContent>
* <extension base="{http://datex2.eu/schema/2_0RC1/2_0}OperatorAction">
* <sequence>
* <element name="roadsideAssistanceType" type="{http://datex2.eu/schema/2_0RC1/2_0}RoadsideAssistanceTypeEnum"/>
* <element name="roadsideAssistanceExtension" type="{http://datex2.eu/schema/2_0RC1/2_0}ExtensionType" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RoadsideAssistance", propOrder = {
"roadsideAssistanceType",
"roadsideAssistanceExtension"
})
public class RoadsideAssistance
extends OperatorAction
{
@XmlElement(required = true)
@XmlSchemaType(name = "string")
protected RoadsideAssistanceTypeEnum roadsideAssistanceType;
protected ExtensionType roadsideAssistanceExtension;
/**
* Gets the value of the roadsideAssistanceType property.
*
* @return
* possible object is
* {@link RoadsideAssistanceTypeEnum }
*
*/
public RoadsideAssistanceTypeEnum getRoadsideAssistanceType() {
return roadsideAssistanceType;
}
/**
* Sets the value of the roadsideAssistanceType property.
*
* @param value
* allowed object is
* {@link RoadsideAssistanceTypeEnum }
*
*/
public void setRoadsideAssistanceType(RoadsideAssistanceTypeEnum value) {
this.roadsideAssistanceType = value;
}
/**
* Gets the value of the roadsideAssistanceExtension property.
*
* @return
* possible object is
* {@link ExtensionType }
*
*/
public ExtensionType getRoadsideAssistanceExtension() {
return roadsideAssistanceExtension;
}
/**
* Sets the value of the roadsideAssistanceExtension property.
*
* @param value
* allowed object is
* {@link ExtensionType }
*
*/
public void setRoadsideAssistanceExtension(ExtensionType value) {
this.roadsideAssistanceExtension = value;
}
}
| 29.574257 | 130 | 0.677938 |
38ecc8c41fdfd7b699c7edd898e2aeab605e001b
| 2,954 |
package libs;
import java.util.Random;
public final class RandomNumGen {
/** Generate a random integers in the range 1 to 4. */
public static int d4(int numberOfDice){
Random randomGenerator = new Random();
int randomInt = 0;
int calculatedInt = 0;
for (int i = 0; i < numberOfDice; i++){
randomInt = randomGenerator.nextInt(4) + 1;
calculatedInt += randomInt;
}
return calculatedInt;
}
/** Generate a random integers in the range 1 to 6. */
public static int d6(int numberOfDice){
Random randomGenerator = new Random();
int randomInt = 0;
int calculatedInt = 0;
for (int i = 0; i < numberOfDice; i++){
randomInt = randomGenerator.nextInt(6) + 1;
calculatedInt = 0;
}
return calculatedInt;
}
/** Generate a random integers in the range 1 to 8. */
public static int d8(int numberOfDice){
Random randomGenerator = new Random();
int randomInt = 0;
int calculatedInt = 0;
for (int i = 0; i < numberOfDice; i++){
randomInt = randomGenerator.nextInt(8) + 1;
calculatedInt += randomInt;
}
return calculatedInt;
}
/** Generate a random integers in the range 1 to 10. */
public static int d10(int numberOfDice){
Random randomGenerator = new Random();
int randomInt = 0;
int calculatedInt = 0;
for (int i = 0; i < numberOfDice; i++){
randomInt = randomGenerator.nextInt(10) + 1;
calculatedInt += randomInt;
}
return calculatedInt;
}
/** Generate a random integers in the range 1 to 12. */
public static int d12(int numberOfDice){
Random randomGenerator = new Random();
int randomInt = 0;
int calculatedInt = 0;
for (int i = 0; i < numberOfDice; i++){
randomInt = randomGenerator.nextInt(12) + 1;
calculatedInt += randomInt;
}
return calculatedInt;
}
/** Generate a random integers in the range 1 to 20. */
public static int d20(int numberOfDice){
Random randomGenerator = new Random();
int randomInt = 0;
int calculatedInt = 0;
for (int i = 0; i < numberOfDice; i++){
randomInt = randomGenerator.nextInt(20) + 1;
calculatedInt += randomInt;
}
return calculatedInt;
}
/** Generate a random integers in the range 1 to 100. */
public static int d100(int numberOfDice){
Random randomGenerator = new Random();
int randomInt = 0;
int calculatedInt = 0;
for (int i = 0; i < numberOfDice; i++){
randomInt = randomGenerator.nextInt(100) + 1;
calculatedInt += randomInt;
}
return calculatedInt;
}
}
| 23.444444 | 58 | 0.555518 |
214901232fe3276360e176d98b29fc36d957fcdd
| 110 |
package com.pigeon.sundermusic.queue;
public interface Queueable {
public long getIdentifier();
}
| 12.222222 | 37 | 0.718182 |
0459f07fd98454e2a83abfcaf7ca6a407efc82d3
| 3,779 |
/**
*/
package aadl2.impl;
import aadl2.Aadl2Package;
import aadl2.DataClassifier;
import aadl2.EventDataSource;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Event Data Source</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link aadl2.impl.EventDataSourceImpl#getDataClassifier <em>Data Classifier</em>}</li>
* </ul>
*
* @generated
*/
public class EventDataSourceImpl extends InternalFeatureImpl implements EventDataSource {
/**
* The cached value of the '{@link #getDataClassifier() <em>Data Classifier</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDataClassifier()
* @generated
* @ordered
*/
protected DataClassifier dataClassifier;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EventDataSourceImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Aadl2Package.eINSTANCE.getEventDataSource();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DataClassifier getDataClassifier() {
if (dataClassifier != null && dataClassifier.eIsProxy()) {
InternalEObject oldDataClassifier = (InternalEObject)dataClassifier;
dataClassifier = (DataClassifier)eResolveProxy(oldDataClassifier);
if (dataClassifier != oldDataClassifier) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, Aadl2Package.EVENT_DATA_SOURCE__DATA_CLASSIFIER, oldDataClassifier, dataClassifier));
}
}
return dataClassifier;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DataClassifier basicGetDataClassifier() {
return dataClassifier;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDataClassifier(DataClassifier newDataClassifier) {
DataClassifier oldDataClassifier = dataClassifier;
dataClassifier = newDataClassifier;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Aadl2Package.EVENT_DATA_SOURCE__DATA_CLASSIFIER, oldDataClassifier, dataClassifier));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Aadl2Package.EVENT_DATA_SOURCE__DATA_CLASSIFIER:
if (resolve) return getDataClassifier();
return basicGetDataClassifier();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Aadl2Package.EVENT_DATA_SOURCE__DATA_CLASSIFIER:
setDataClassifier((DataClassifier)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Aadl2Package.EVENT_DATA_SOURCE__DATA_CLASSIFIER:
setDataClassifier((DataClassifier)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Aadl2Package.EVENT_DATA_SOURCE__DATA_CLASSIFIER:
return dataClassifier != null;
}
return super.eIsSet(featureID);
}
} //EventDataSourceImpl
| 24.070064 | 148 | 0.679545 |
4d2c9a7be640c04778f3843ea02f6188b22c023d
| 2,967 |
package com.xsw.neo.service.controller;
import com.google.common.collect.Lists;
import com.xsw.neo.service.common.annotation.ExportAnnotation;
import com.xsw.neo.service.common.annotation.I18nAnnotation;
import com.xsw.neo.service.common.annotation.LogAnnotation;
import com.xsw.neo.service.common.result.ResultBody;
import com.xsw.neo.service.model.bo.StudentBO;
import com.xsw.neo.service.model.dto.StudentDTO;
import com.xsw.neo.service.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.lang.reflect.Field;
import java.util.List;
/**
* 学生控制器
*
* @author xueshengwen
* @since 2020/12/17 13:50
*/
@Api(tags = "学生相关接口")
@RestController
@RequestMapping(value = "/student")
public class StudentController {
@Autowired
private StudentService studentService;
@ApiOperation(value = "学生列表")
@GetMapping(value = "/listStudent")
@LogAnnotation
public ResultBody listStudent() {
return ResultBody.SUCCESS(studentService.listStudent());
}
@ApiOperation(value = "新增学生")
@PostMapping(value = "/saveStudent")
public ResultBody saveStudent(@RequestBody StudentDTO studentDTO) {
return ResultBody.SUCCESS(studentService.saveStudent(studentDTO));
}
@ApiOperation(value = "获取学生信息")
@GetMapping(value = "/findStudentInfo")
public ResultBody findStudentInfo(@RequestParam(value = "id") Integer id) {
return ResultBody.SUCCESS(studentService.findStudentInfo(id));
}
@ApiOperation(value = "导出Excel 测试多语言切换")
@GetMapping(value = "/export")
@ExportAnnotation
public void export() throws Exception {
// 模拟查询的学生列表
List<StudentBO> studentBOList = Lists.newArrayList();
studentBOList.add(new StudentBO("薛胜文", "申城佳苑", "男"));
studentBOList.add(new StudentBO("罗彦凯", "开天公寓", "男"));
studentBOList.add(new StudentBO("王彬", "浦江镇", "男"));
studentBOList.add(new StudentBO("关羽", "荆州", "男"));
studentBOList.add(new StudentBO("大乔", "铜雀台", "女"));
studentBOList.add(new StudentBO("小乔", "铜雀台", "女"));
//EasyExcel.write(new File("D:\\my-doc\\export.xlsx"),StudentBO.class).sheet("学生花名册").doWrite(studentBOList);
// Class<?> clazz = Class.forName("com.xsw.neo.service.model.bo.StudentBO");
// Field[] declaredFields = clazz.getDeclaredFields();
// for (Field declaredField : declaredFields) {
// I18nFieldAnnotation annotation = declaredField.getAnnotation(I18nFieldAnnotation.class);
// if(annotation != null){
// String title = annotation.title();
// if(title.equals(LanguageEnum.CHINESE.getValue())){
// String value = annotation.value();
// System.out.println(value);
// }
//
// }
// }
}
}
| 34.103448 | 117 | 0.674419 |
d8ca87127503ae3a82ff29e4f55e2b81e30aca28
| 1,823 |
package net.blay09.mods.cookingforblockheads.client.model;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.vertex.IVertexBuilder;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.model.Model;
import net.minecraft.client.renderer.model.ModelRenderer;
public class FridgeLargeDoorModel extends Model {
private final ModelRenderer main;
private final ModelRenderer handle;
public FridgeLargeDoorModel(boolean flipped) {
super(RenderType::getEntitySolid);
textureWidth = 64;
textureHeight = 32;
if (flipped) {
main = new ModelRenderer(this, 4, 0);
main.addBox(-14f, 0f, 0f, 14, 29, 1);
main.setRotationPoint(7f, -5f, -7f);
main.setTextureSize(64, 32);
handle = new ModelRenderer(this, 0, 0);
handle.addBox(-13f, 3f, -1f, 1, 23, 1);
handle.setRotationPoint(7f, -5f, -7f);
handle.setTextureSize(64, 32);
} else {
main = new ModelRenderer(this, 4, 0);
main.addBox(0f, 0f, 0f, 14, 29, 1);
main.setRotationPoint(-7f, -5f, -7f);
main.setTextureSize(64, 32);
handle = new ModelRenderer(this, 0, 0);
handle.addBox(12f, 3f, -1f, 1, 23, 1);
handle.setRotationPoint(-7f, -5f, -7f);
handle.setTextureSize(64, 32);
}
}
@Override
public void render(MatrixStack matrixStackIn, IVertexBuilder bufferIn, int packedLightIn, int packedOverlayIn, float red, float green, float blue, float alpha) {
main.render(matrixStackIn, bufferIn, packedLightIn, packedOverlayIn, red, green, blue, alpha);
handle.render(matrixStackIn, bufferIn, packedLightIn, packedOverlayIn, red, green, blue, alpha);
}
}
| 37.979167 | 165 | 0.642896 |
653921be46f675932b3390fef9947b1091bb3518
| 7,294 |
package io.github.batizhao.service.iml;
import cn.hutool.core.io.IoUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.batizhao.constant.GenConstants;
import io.github.batizhao.exception.NotFoundException;
import io.github.batizhao.domain.Code;
import io.github.batizhao.domain.CodeMeta;
import io.github.batizhao.mapper.CodeMapper;
import io.github.batizhao.service.CodeMetaService;
import io.github.batizhao.service.CodeService;
import io.github.batizhao.util.CodeGenUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.ByteArrayOutputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipOutputStream;
/**
* 在这里要注意,在事务开启的情况下,动态数据源会无效。
* 无论是上级方法,还是当前方法,都不能开启事务。
*
* @author batizhao
* @date 2020/10/10
*/
@Service
public class CodeServiceImpl extends ServiceImpl<CodeMapper, Code> implements CodeService {
@Autowired
private CodeMapper codeMapper;
@Autowired
private CodeMetaService codeMetaService;
@Override
public IPage<Code> findCodes(Page<Code> page, Code code) {
LambdaQueryWrapper<Code> wrapper = Wrappers.lambdaQuery();
if (StringUtils.isNotBlank(code.getTableName())) {
wrapper.like(Code::getTableName, code.getTableName());
}
return codeMapper.selectPage(page, wrapper);
}
@Override
public Code findById(Long id) {
Code code = codeMapper.selectById(id);
if (code == null) {
throw new NotFoundException(String.format("没有该记录 '%s'。" , id));
}
return code;
}
/**
* 当前方法开启事务,会导致动态数据源无法切换。
* 为了解决这个问题,单独封装了 saveCode 方法处理事务。
* 但是这种方式,只适合这个方法,并不适合所有的事务+动态数据源的场景。
* @see <a href="SpringBoot+Mybatis配置多数据源及事务方案">https://juejin.cn/post/6844904159074844685</a>
*
* @param code 生成代码
* @return
*/
@Override
public Code saveOrUpdateCode(Code code) {
if (code.getId() == null) {
code.setCreateTime(LocalDateTime.now());
code.setUpdateTime(LocalDateTime.now());
List<CodeMeta> codeMetas = codeMetaService.findColumnsByTableName(code.getTableName(), code.getDsName());
saveCode(code, codeMetas);
} else {
code.setUpdateTime(LocalDateTime.now());
this.updateById(code);
if (CollectionUtils.isNotEmpty(code.getCodeMetaList())) {
codeMetaService.updateBatchById(code.getCodeMetaList());
}
}
return code;
}
@Override
@Transactional
public Code saveCode(Code code, List<CodeMeta> codeMetas) {
this.save(code);
codeMetas.forEach(cm -> {
cm.setCodeId(code.getId());
CodeGenUtils.initColumnField(cm);
});
codeMetaService.saveBatch(codeMetas);
return code;
}
@Override
@Transactional
public Boolean deleteByIds(List<Long> ids) {
this.removeByIds(ids);
ids.forEach(i -> codeMetaService.remove(Wrappers.<CodeMeta>lambdaQuery().eq(CodeMeta::getCodeId, i)));
return true;
}
@Override
@DS("#last")
public IPage<Code> findTables(Page<Code> page, Code code, String dsName) {
IPage<Code> p = codeMapper.selectTablePageByDs(page, code);
List<Code> c = p.getRecords();
if (StringUtils.isBlank(dsName)) {
dsName = "master";
}
String finalDsName = dsName;
c.forEach(ll -> ll.setDsName(finalDsName));
return p;
}
/**
* 这里不能开启事务,会导致动态数据源失效。
*
* @param codes
* @return
*/
@Override
public Boolean importTables(List<Code> codes) {
if (codes == null) return false;
for (Code c : codes) {
CodeGenUtils.initData(c);
saveOrUpdateCode(c);
}
return true;
}
@Override
public byte[] downloadCode(List<Long> ids) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
for (Long i : ids) {
CodeGenUtils.generateCode(prepareCodeMeta(i), zip);
}
IoUtil.close(zip);
return outputStream.toByteArray();
}
@Override
public Boolean generateCode(Long id) {
CodeGenUtils.generateCode(prepareCodeMeta(id));
return true;
}
@Override
public Map<String, String> previewCode(Long id) {
return CodeGenUtils.previewCode(prepareCodeMeta(id));
}
@Override
public Boolean syncCodeMeta(Long id) {
Code code = this.findById(id);
List<CodeMeta> codeMetas = codeMetaService.findByCodeId(code.getId());
List<CodeMeta> dbTableColumns = codeMetaService.findColumnsByTableName(code.getTableName(), code.getDsName());
return syncColumn(id, codeMetas, dbTableColumns);
}
@Override
@Transactional
public Boolean syncColumn(Long id, List<CodeMeta> codeMetas, List<CodeMeta> dbTableColumns) {
if (CollectionUtils.isEmpty(dbTableColumns)) {
throw new RuntimeException("同步数据失败,原表结构不存在");
}
List<String> tableColumnNames = codeMetas.stream().map(CodeMeta::getColumnName).collect(Collectors.toList());
List<String> dbTableColumnNames = dbTableColumns.stream().map(CodeMeta::getColumnName).collect(Collectors.toList());
dbTableColumns.forEach(column -> {
if (!tableColumnNames.contains(column.getColumnName())) {
column.setCodeId(id);
CodeGenUtils.initColumnField(column);
codeMetaService.save(column);
}
});
List<CodeMeta> delColumns = codeMetas.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(delColumns)) {
List<Long> ids = delColumns.stream().map(CodeMeta::getId).collect(Collectors.toList());
codeMetaService.removeByIds(ids);
}
return true;
}
private Code prepareCodeMeta(Long id) {
Code code = findById(id);
List<CodeMeta> codeMetas = codeMetaService.findByCodeId(code.getId());
code.setCodeMetaList(codeMetas);
if (code.getTemplate().equals(GenConstants.TPL_ONE_TO_MANY) && code.getSubTableId() != null) {
Code subCode = findById(code.getSubTableId());
// subCode.setCodeMetaList(codeMetaService.findByCodeId(subCode.getId()));
code.setSubCode(subCode);
}
code.setRelationCode(codeMapper.selectList(Wrappers.<Code>query().lambda().eq(Code::getSubTableId, code.getId())));
return code;
}
}
| 33.004525 | 155 | 0.665204 |
c1a4e601ee0a38d3fff14eee687f3403973f8c74
| 157 |
package redradishes.encoder;
public interface EncoderBase<E extends EncoderBase<E>> {
E prepend(ConstExpr c);
E append(ConstExpr c);
E compact();
}
| 15.7 | 56 | 0.726115 |
265145b6ac47fef3e5723f1dde49066742390834
| 419 |
package com.xinyu.hashMapDemo;
import java.util.HashMap;
import java.util.Map;
/**
* @Description
* @Author xinyu4
* @Date 2021/4/6/0006 15:35
*/
public class Demo {
public static void main(String[] args) {
Map<PObject, String> hashMap = new HashMap<>();
PObject a = new PObject("A");
PObject b = new PObject("A");
hashMap.put(a, "hello");
String s = hashMap.get(b);
System.out.println(s);
}
}
| 16.115385 | 49 | 0.649165 |
3c7be929702c87489640693a521cf04719263268
| 3,703 |
package com.html5parser.classes.token;
import java.util.ArrayList;
import java.util.List;
import com.html5parser.classes.Token;
public class TagToken extends Token {
boolean flagSelfClosingTag = false;
boolean flagAcknowledgeSelfClosingTag = false;
List<Attribute> attributes = new ArrayList<TagToken.Attribute>();
Attribute lasttAttribute;
public TagToken(TokenType _type, int _value) {
super(_type, _value);
}
public TagToken(TokenType _type, String _value) {
super(_type, _value);
}
public boolean isFlagSelfClosingTag() {
return flagSelfClosingTag;
}
public void setFlagSelfClosingTag(boolean value) {
this.flagSelfClosingTag = value;
}
public boolean isFlagAcknowledgeSelfClosingTag() {
return flagAcknowledgeSelfClosingTag;
}
public void setFlagAcknowledgeSelfClosingTag(boolean value) {
this.flagAcknowledgeSelfClosingTag = value;
}
public Boolean hasAttribute(String[] attributeNames) {
for (Attribute att : this.attributes)
for (String s : attributeNames)
if (att.getName().equals(s))
return true;
return false;
}
public Attribute getAttribute(String attributeName) {
for (Attribute att : this.attributes)
if (att.getName().equals(attributeName))
return att;
return null;
}
public List<Attribute> getAttributes() {
return attributes;
}
public void setAttributes(List<Attribute> attributes) {
this.attributes = attributes;
}
public void addAttribute(String name, String value) {
this.attributes.add(new Attribute(name, value));
}
public Attribute createAttribute(String name) {
lasttAttribute = new Attribute(name, "");
attributes.add(lasttAttribute);
return lasttAttribute;
}
public Attribute createAttribute(int name) {
return createAttribute(String.valueOf(Character.toChars(name)));
}
public void appendCharacterInNameInLastAttribute(String character) {
appendCharacterInName(lasttAttribute, character);
}
public void appendCharacterInNameInLastAttribute(int character) {
appendCharacterInName(lasttAttribute,
String.valueOf(Character.toChars(character)));
}
public void appendCharacterInName(Attribute attribute, String character) {
attribute.appendCharacterToName(character);
}
public void appendCharacterInValueInLastAttribute(String character) {
appendCharacterInValue(lasttAttribute, character);
}
public void appendCharacterInValueInLastAttribute(int character) {
appendCharacterInValue(lasttAttribute,
String.valueOf(Character.toChars(character)));
}
public void appendCharacterInValue(Attribute attribute, String character) {
attribute.appendCharacterToValue(character);
}
public class Attribute {
String name;
String value;
String localName;
String prefix;
String namespace;
public Attribute(String name, String value) {
super();
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public void appendCharacterToName(String character) {
this.name = name.concat(character);
}
public void appendCharacterToValue(String character) {
this.value = value.concat(character);
}
public String getLocalName() {
return localName;
}
public void setLocalName(String localName) {
this.localName = localName;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
}
}
| 22.442424 | 76 | 0.745612 |
c4e74d5e31551dbacecce18943eaf640c54c135c
| 1,777 |
/*
* Copyright 2014 - 2017 Cognizant Technology Solutions
*
* 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.cognizant.cognizantits.engine.util.data.fx;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;
/**
*
*
*/
public class FunctionsLib {
public Object getDate(int dx) {
return getDate(dx, "dd/MM/yyyy");
}
public Object getDate(int dx, String format) {
SimpleDateFormat date = new SimpleDateFormat(format);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, dx);
return date.format(cal.getTime());
}
public Object getRound(Double val) {
return Math.round(val);
}
public Object getRandom(Double from, Double to) {
Random rn = new Random(System.currentTimeMillis());
return from + (rn.nextDouble() * (to - from));
}
public Object getRandom(Double len) {
return getRandom(Math.pow(10d, len - 1), Math.pow(10d, len) - 1);
}
public Object getPow(Double a, Double b) {
return Math.pow(a, b);
}
public Object getMin(Double a, Double b) {
return Math.min(a, b);
}
public Object getMax(Double a, Double b) {
return Math.max(a, b);
}
}
| 27.338462 | 75 | 0.661227 |
69fc92db52bd1995eb90236f2d3aa31cc3d6c0f9
| 1,424 |
import java.util.*;
public class Q_1 {
public static void main(String args[]) {
System.out.println("Please enter 3 numbers to find greatest among them");
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number : ");
int a = sc.nextInt();
System.out.print("Enter second number : ");
int b = sc.nextInt();
System.out.print("Enter third number : ");
int c = sc.nextInt();
int large = largest(a, b, c);
System.out.println("The greatest among three numbers is : " + large);
int small = smallest(a, b, c);
System.out.println("The smallest among three numbers is : " + small);
}
public static int largest(int a, int b, int c) {
if (a>b) {
if (a>c) {
return a;
}
else{
return c;
}
}
else {
if (b>c) {
return b;
}
else {
return c;
}
}
}
public static int smallest(int a, int b, int c) {
if (a<b) {
if (a<c) {
return a;
}
else{
return c;
}
}
else {
if (b<c) {
return b;
}
else {
return c;
}
}
}
}
| 23.344262 | 79 | 0.410815 |
74c162b77bc4aa6492b115e5140bafbed54150c2
| 1,877 |
package src;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
/*
* https://github.com/xerial/sqlite-jdbc/blob/master/Usage.md
*
* DB tables on a per-ticker bases
* historical data for a ticker
* date,
* prices (open, close, etc),
* indicators (macd, etc)
* user info
* fields in user obj
* open positions
* trade history
* all trades made by user
* open positions
*
*/
public class Database {
int timeout;
Connection conn = null;
Database() {
String path = "temp.db";
//String path = "memory"; //DEBUG: dont write to disk
this.timeout = 5;
try {
this.conn = DriverManager.getConnection("jdbc:sqlite:" + path);
}
catch (SQLException e) {
//out of mem error = db not found
System.out.println(e);
}
}
public ResultSet query(String statement) {
//System.out.println(statement);
try {
Statement s = this.conn.createStatement();
s.setQueryTimeout(this.timeout);
ResultSet rs = s.executeQuery(statement);
return rs;
}
catch (SQLException e) {
System.out.println(e);
}
return null;
}
public void update(String statement) {
//System.out.println(statement);
try {
Statement s = this.conn.createStatement();
s.executeUpdate(statement);
s.close();
}
catch (SQLException e) {
System.out.println(e);
}
}
public void disconnect() {
try {
this.conn.close();
}
catch (SQLException e) {
System.out.println(e);
}
}
}
| 22.890244 | 75 | 0.536494 |
a6f38113ff0f0c2040bef91fcbfbe2afdd031202
| 662 |
package ru.job4j.search;
import java.util.LinkedList;
/**
*
* Class Класс очереди задач с приоритетом
* @athor Buryachenko
* @since 09.02.19
* @version 1
*/
public class PriorityQueue {
private LinkedList<Task> tasks = new LinkedList<>();
public void put(Task task) {
var size = tasks.size();
for (var i = 0; i < size; i++) {
if (task.getPriority() <= tasks.get(i).getPriority()) {
tasks.add(i, task);
break;
}
}
if (size == tasks.size()) {
tasks.addLast(task);
}
}
public Task take() {
return this.tasks.poll();
}
}
| 21.354839 | 67 | 0.522659 |
185eff03d74cab0c4e57af16e5ef25af973c87cf
| 1,984 |
package io.hashimati.repository;
import io.hashimati.domains.Fruit;
import io.hashimati.microstream.Data;
import io.micronaut.microstream.RootProvider;
import io.micronaut.microstream.annotations.StoreParams;
import io.micronaut.microstream.annotations.StoreReturn;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import javax.validation.constraints.PastOrPresent;
import java.util.HashMap;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Stream;
@Singleton
public class FruitRepositoryImpl implements FruitRepository{
@Inject
RootProvider<Data> rootProvider;
@Override
public Fruit save(Fruit fruit) {
return save(rootProvider.root().getFruits(), fruit);
}
@Override
public void update(String id, Fruit update) {
updateFruit(id, update);
}
@Override
public Optional<Fruit> findById(String id) {
return Optional.ofNullable(rootProvider.root().getFruits().get(id));
}
@Override
public void deleteById(String id) {
removeFruit(id);
}
public Stream<Fruit> findAll()
{
return rootProvider.root().getFruits().values().stream();
}
@StoreParams("fruits")
protected void removeFruit(String id) {
rootProvider.root().getFruits().remove(id);
}
@StoreParams("fruits")
protected Fruit save(HashMap<String, Fruit> map , Fruit fruit)
{
fruit.setId(UUID.randomUUID().toString());
map.putIfAbsent(fruit.getId(), fruit);
return fruit;
}
@StoreReturn
protected Fruit updateFruit(String id, Fruit update)
{
HashMap<String, Fruit> map = rootProvider.root().getFruits();
Fruit fruit = map.get(update.getId());
if(fruit != null)
{
fruit.setName(update.getName());
fruit.setLetter(update.getLetter());
map.put(fruit.getName(), fruit);
return fruit;
}
return null;
}
}
| 25.113924 | 76 | 0.66381 |
5635885d128fef3c6dd04582fb7adf59b239c72d
| 1,161 |
package phone.validation.server.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.springframework.lang.Nullable;
@Entity
@Table(name = "Customer")
public class Customer{
@Id
private int id;
@Column(name="name")
private String name;
@Column(name="phone")
private String phone;
@Nullable
@OneToOne
@JoinColumn(name = "country_id")
private Country country;
@Nullable
@Column(name="valid")
private Integer valid;
public Customer(){
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public String getPhone() {
return phone;
}
public Country getCountry() {
return country;
}
public int getValid() {
return valid;
}
public void setValid(int valid) {
this.valid = valid;
}
public void setCountry(Country country) {
this.country = country;
}
@Override
public String toString() {
return "Customer [id=" + id + " , name=" + name +" , phone=" + phone +" , country=" + country.getName() + "]";
}
}
| 19.677966 | 112 | 0.6882 |
64bade4d5f798ddb07c461658e077bda1413853c
| 1,396 |
/*
Copyright 2017 Stratumn SAS. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.stratumn.sdk.model.responseModels;
public class FragmentTraceStateResponse {
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public Object getState() {
return state;
}
public void setState(Object state) {
this.state = state;
}
public HeadResponse getHead() {
return head;
}
public void setHead(HeadResponse head) {
this.head = head;
}
private String updatedAt;
private Object state;
private HeadResponse head;
}
class HeadResponse {
public Object getRaw() {
return raw;
}
public void setRaw(Object raw) {
this.raw = raw;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
private Object raw;
private Object data;
}
| 19.942857 | 72 | 0.737106 |
3bcf167e698a6b3aa9b48f59cc41e667b615f093
| 306 |
package com.ps.services;
import com.ps.base.ReviewGrade;
import com.ps.ents.Review;
import com.ps.ents.User;
import java.util.Set;
public interface ReviewService extends AbstractService<Review>{
Review createReview(ReviewGrade grade, String details);
Set<Review> findAllByUser(User user);
}
| 19.125 | 64 | 0.771242 |
58a9160e7e72ba9e53b6e91010340659ea4070e7
| 2,864 |
package com.onarandombox.multiverseinventories;
import com.dumptruckman.minecraft.util.Logging;
import com.onarandombox.multiverseinventories.profile.ProfileType;
import com.onarandombox.multiverseinventories.profile.ProfileTypes;
import com.onarandombox.multiverseinventories.profile.container.ProfileContainer;
import com.onarandombox.multiverseinventories.share.Sharables;
import com.onarandombox.multiverseinventories.event.MVInventoryHandlingEvent.Cause;
import com.onarandombox.multiverseinventories.util.Perm;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import java.util.List;
/**
* GameMode change implementation of ShareHandler.
*/
final class GameModeShareHandler extends ShareHandler {
public GameModeShareHandler(MultiverseInventories inventories, Player player,
GameMode fromGameMode, GameMode toGameMode) {
super(inventories, player, Cause.GAME_MODE_CHANGE, player.getWorld().getName(),
player.getWorld().getName(), fromGameMode, toGameMode);
}
@Override
public void handle() {
Player player = event.getPlayer();
ProfileType fromType = ProfileTypes.forGameMode(event.getFromGameMode());
ProfileType toType = ProfileTypes.forGameMode(event.getToGameMode());
String world = event.getPlayer().getWorld().getName();
Logging.finer("=== " + player.getName() + " changing game mode from: " + fromType
+ " to: " + toType + " for world: " + world + " ===");
// Grab the player from the world they're coming from to save their stuff to every time.
ProfileContainer worldProfileContainer = this.inventories.getWorldProfileContainerStore().getContainer(world);
addFromProfile(worldProfileContainer, Sharables.allOf(), worldProfileContainer.getPlayerData(fromType, player));
if (Perm.BYPASS_WORLD.hasBypass(player, world)) {
this.hasBypass = true;
return;
} else if (Perm.BYPASS_GAME_MODE.hasBypass(player, event.getToGameMode().name().toLowerCase())) {
this.hasBypass = true;
return;
}
List<WorldGroup> worldGroups = this.inventories.getGroupManager().getGroupsForWorld(world);
for (WorldGroup worldGroup : worldGroups) {
ProfileContainer container = worldGroup.getGroupProfileContainer();
addFromProfile(container, Sharables.allOf(), container.getPlayerData(fromType, player));
addToProfile(container, Sharables.allOf(), container.getPlayerData(toType, player));
}
if (worldGroups.isEmpty()) {
Logging.finer("No groups for world.");
addToProfile(worldProfileContainer, Sharables.allOf(), worldProfileContainer.getPlayerData(toType, player));
}
}
}
| 48.542373 | 121 | 0.69588 |
54aceabb84986fb0e6cc182c8290af786614262d
| 6,956 |
package com.pcy.movierecommendation.controller;
import com.github.pagehelper.PageInfo;
import com.pcy.movierecommendation.core.constants.ErrorMessages;
import com.pcy.movierecommendation.core.model.ApiResponse;
import com.pcy.movierecommendation.entity.movieDetail.MovieDetail;
import com.pcy.movierecommendation.entity.movieDetail.MovieDetailSearchRequest;
import com.pcy.movierecommendation.es.ElasticSearchVo;
import com.pcy.movierecommendation.service.MovieDetailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Map;
/**
* (MovieDetail)表控制层
*
* @author PengChenyu
* @since 2020-12-21 21:41:53
*/
@Api(value = "/movieDetail", tags = "movieDetail")
@RestController
@RequestMapping("api/recommendation/movieDetail")
public class MovieDetailController extends BaseController {
/**
* 服务对象
*/
@Resource
private MovieDetailService movieDetailService;
/**
* 通过主键查询单条数据
*
* @param doubanId 主键
* @return 单条数据
*/
@ApiOperation(value = "主键查询", notes = "通过主键查询单条数据")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "doubanId", value = "豆瓣id", required = true, dataType = "Integer")
})
@GetMapping("/{doubanId}")
public ApiResponse<MovieDetail> selectOne(@PathVariable("doubanId") Integer doubanId) {
MovieDetail movieDetail = this.movieDetailService.queryById(doubanId);
if (movieDetail == null) {
return new ApiResponse<>(Boolean.FALSE, ErrorMessages.QUERY_NULL, null);
}
return new ApiResponse<>(Boolean.TRUE, ErrorMessages.REQUEST_SUCCESS, movieDetail);
}
/**
* 分页获取电影详情
*
* @param pageNum 当前页
* @param pageSize 每页多少数据
* @return 分页数据
*/
@ApiOperation(value = "分页获取电影详情")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "pageNum", value = "当前页", required = true, dataType = "int"),
@ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页的数量", required = true, dataType = "int")
})
@GetMapping("/page/{pageNum}/{pageSize}")
public ApiResponse<PageInfo<MovieDetail>> queryPageMovie(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize) {
PageInfo<MovieDetail> movieDetailPageInfo = movieDetailService.queryPageMovie(pageNum, pageSize);
if (movieDetailPageInfo.getTotal() == 0L) {
return new ApiResponse<>(Boolean.FALSE, ErrorMessages.QUERY_NULL, null);
}
return new ApiResponse<>(Boolean.TRUE, ErrorMessages.REQUEST_SUCCESS, movieDetailPageInfo);
}
/**
* 分页查询
*
* @param pageNum 当前页
* @param pageSize 每页多少数据
* @param movieDetail 查询条件
* @return 分页数据
*/
@ApiOperation(value = "分页查询")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "pageNum", value = "当前页", required = true, dataType = "int"),
@ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页的数量", required = true, dataType = "int"),
@ApiImplicitParam(paramType = "query", name = "movieDetail", value = "查询条件", required = true, dataType = "MovieDetail")
})
@PostMapping("/page/{pageNum}/{pageSize}")
public ApiResponse<PageInfo<MovieDetail>> queryPage(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize, @RequestBody MovieDetail movieDetail) {
PageInfo<MovieDetail> movieDetailPageInfo = movieDetailService.queryPage(pageNum, pageSize, movieDetail);
if (movieDetailPageInfo.getTotal() == 0L) {
return new ApiResponse<>(Boolean.FALSE, ErrorMessages.QUERY_NULL, null);
}
return new ApiResponse<>(Boolean.TRUE, ErrorMessages.REQUEST_SUCCESS, movieDetailPageInfo);
}
/**
* 搜索,电影名/导演/演员
*
* @param pageNum 当前页
* @param pageSize 每页多少数据
* @param map keyword 用户搜索的关键字
* @return 分页数据
*/
@ApiOperation(value = "分页查询")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "pageNum", value = "当前页", required = true, dataType = "int"),
@ApiImplicitParam(paramType = "query", name = "pageSize", value = "每页的数量", required = true, dataType = "int"),
@ApiImplicitParam(paramType = "query", name = "map", value = "用户搜索的关键字", required = true, dataType = "Map")
})
@PostMapping("/search/{pageNum}/{pageSize}")
public ApiResponse<ElasticSearchVo<MovieDetail>> searchMovie(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize, @RequestBody Map<String, String> map) {
String keyword = map.get("keyword");
ElasticSearchVo<MovieDetail> movieDetailElasticSearchVo = movieDetailService.searchMovie(keyword, pageNum, pageSize);
if (movieDetailElasticSearchVo.getTotal() == 0) {
return new ApiResponse<>(Boolean.FALSE, ErrorMessages.QUERY_NULL, null);
}
return new ApiResponse<>(Boolean.TRUE, ErrorMessages.REQUEST_SUCCESS, movieDetailElasticSearchVo);
}
/**
* 根据 douban_id 精准搜索
* 基于ES
*
* @param doubanId 豆瓣id
* @return ES内电影数据
*/
@ApiOperation(value = "douban_id精准搜索")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "doubanId", value = "doubanId", required = true, dataType = "int")
})
@GetMapping("/search/{doubanId}")
public ApiResponse<MovieDetail> searchMovieByDoubanId(@PathVariable("doubanId") int doubanId) {
MovieDetail movieDetail = movieDetailService.searchMovieByDoubanId(doubanId);
if (movieDetail == null) {
return new ApiResponse<>(Boolean.FALSE, ErrorMessages.QUERY_NULL, null);
}
return new ApiResponse<>(Boolean.TRUE, ErrorMessages.REQUEST_SUCCESS, movieDetail);
}
/**
* 类豆瓣标签搜索
* 基于ES
*
* @param movieDetailSearchRequest 请求条件实体
* @return ES内电影数据
*/
@ApiOperation(value = "类豆瓣标签搜索")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "body", name = "movieDetailSearchRequest", value = "doubanId", required = true, dataType = "MovieDetailSearchRequest")
})
@PostMapping("/searchByTags")
public ApiResponse<ElasticSearchVo<MovieDetail>> searchByTags(@RequestBody MovieDetailSearchRequest movieDetailSearchRequest) {
ElasticSearchVo<MovieDetail> result = movieDetailService.searchByTags(movieDetailSearchRequest);
if (CollectionUtils.isEmpty(result.getResultList())) {
return new ApiResponse<>(Boolean.FALSE, ErrorMessages.QUERY_NULL, null);
}
return new ApiResponse<>(Boolean.TRUE, ErrorMessages.REQUEST_SUCCESS, result);
}
}
| 41.652695 | 182 | 0.679988 |
53fddc4f60a66d34b3d0fc1e40cc4b410afe46e6
| 6,572 |
package seedu.address.model.lesson;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.address.logic.commands.CommandTestUtil.VALID_LESSON_TAG_EASY;
import static seedu.address.testutil.Assert.assertThrows;
import static seedu.address.testutil.TypicalLessons.CS2106;
import static seedu.address.testutil.TypicalLessons.GES1028;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import seedu.address.model.lesson.exceptions.DuplicateLessonException;
import seedu.address.model.lesson.exceptions.LessonNotFoundException;
import seedu.address.testutil.LessonBuilder;
public class UniqueLessonListTest {
private final UniqueLessonList uniqueLessonList = new UniqueLessonList();
@Test
public void contains_nullLesson_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> uniqueLessonList.contains(null));
}
@Test
public void contains_lessonNotInList_returnsFalse() {
assertFalse(uniqueLessonList.contains(GES1028));
}
@Test
public void contains_lessonInList_returnsTrue() {
uniqueLessonList.add(GES1028);
assertTrue(uniqueLessonList.contains(GES1028));
}
@Test
public void contains_lessonWithSameIdentityFieldsInList_returnsTrue() {
uniqueLessonList.add(GES1028);
Lesson editedGes1028 = new LessonBuilder(GES1028).withTags(VALID_LESSON_TAG_EASY).build();
assertTrue(uniqueLessonList.contains(editedGes1028));
}
@Test
public void add_nullLesson_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> uniqueLessonList.add(null));
}
@Test
public void add_duplicateLesson_throwsDuplicateLessonException() {
uniqueLessonList.add(GES1028);
assertThrows(DuplicateLessonException.class, () -> uniqueLessonList.add(GES1028));
}
@Test
public void setLesson_nullTargetLesson_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> uniqueLessonList.setLesson(null, GES1028));
}
@Test
public void setLesson_nullEditedLesson_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> uniqueLessonList.setLesson(GES1028, null));
}
@Test
public void setLesson_targetLessonNotInList_throwsLessonNotFoundException() {
assertThrows(LessonNotFoundException.class, () -> uniqueLessonList.setLesson(GES1028, GES1028));
}
@Test
public void setLesson_editedLessonIsSameLesson_success() {
uniqueLessonList.add(GES1028);
uniqueLessonList.setLesson(GES1028, GES1028);
UniqueLessonList expectedUniqueLessonList = new UniqueLessonList();
expectedUniqueLessonList.add(GES1028);
assertEquals(expectedUniqueLessonList, uniqueLessonList);
}
@Test
public void setLesson_editedLessonHasSameIdentity_success() {
uniqueLessonList.add(GES1028);
Lesson editedGes1028 = new LessonBuilder(GES1028).withTags(VALID_LESSON_TAG_EASY)
.build();
uniqueLessonList.setLesson(GES1028, editedGes1028);
UniqueLessonList expectedUniqueLessonList = new UniqueLessonList();
expectedUniqueLessonList.add(editedGes1028);
assertEquals(expectedUniqueLessonList, uniqueLessonList);
}
@Test
public void setLesson_editedLessonHasDifferentIdentity_success() {
uniqueLessonList.add(GES1028);
uniqueLessonList.setLesson(GES1028, CS2106);
UniqueLessonList expectedUniqueLessonList = new UniqueLessonList();
expectedUniqueLessonList.add(CS2106);
assertEquals(expectedUniqueLessonList, uniqueLessonList);
}
@Test
public void setLesson_editedLessonHasNonUniqueIdentity_throwsDuplicateLessonException() {
uniqueLessonList.add(GES1028);
uniqueLessonList.add(CS2106);
assertThrows(DuplicateLessonException.class, () -> uniqueLessonList.setLesson(GES1028, CS2106));
}
@Test
public void remove_nullLesson_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> uniqueLessonList.remove(null));
}
@Test
public void remove_lessonDoesNotExist_throwsLessonNotFoundException() {
assertThrows(LessonNotFoundException.class, () -> uniqueLessonList.remove(GES1028));
}
@Test
public void remove_existingLesson_removesLesson() {
uniqueLessonList.add(GES1028);
uniqueLessonList.remove(GES1028);
UniqueLessonList expectedUniqueLessonList = new UniqueLessonList();
assertEquals(expectedUniqueLessonList, uniqueLessonList);
}
@Test
public void setLessons_nullUniqueLessonList_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> uniqueLessonList.setLessons((UniqueLessonList) null));
}
@Test
public void setLessons_uniqueLessonList_replacesOwnListWithProvidedUniqueLessonList() {
uniqueLessonList.add(GES1028);
UniqueLessonList expectedUniqueLessonList = new UniqueLessonList();
expectedUniqueLessonList.add(CS2106);
uniqueLessonList.setLessons(expectedUniqueLessonList);
assertEquals(expectedUniqueLessonList, uniqueLessonList);
}
@Test
public void setLessons_nullList_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> uniqueLessonList.setLessons((List<Lesson>) null));
}
@Test
public void setLessons_list_replacesOwnListWithProvidedList() {
uniqueLessonList.add(GES1028);
List<Lesson> lessonList = Collections.singletonList(CS2106);
uniqueLessonList.setLessons(lessonList);
UniqueLessonList expectedUniqueLessonList = new UniqueLessonList();
expectedUniqueLessonList.add(CS2106);
assertEquals(expectedUniqueLessonList, uniqueLessonList);
}
@Test
public void setLessons_listWithDuplicateLessons_throwsDuplicateLessonException() {
List<Lesson> listWithDuplicateLessons = Arrays.asList(GES1028, GES1028);
assertThrows(DuplicateLessonException.class, () -> uniqueLessonList.setLessons(listWithDuplicateLessons));
}
@Test
public void asUnmodifiableObservableList_modifyList_throwsUnsupportedOperationException() {
assertThrows(UnsupportedOperationException.class, () ->
uniqueLessonList.asUnmodifiableObservableList().remove(0));
}
}
| 38.887574 | 114 | 0.750609 |
2f54adef3d3339b1a4356408d8be394e303483b8
| 5,972 |
/*
* Copyright (c) 2010-2017, sikuli.org, sikulix.com - MIT license
*/
package org.sikuli.syntaxhighlight.style;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.sikuli.syntaxhighlight.Jygments;
import org.sikuli.syntaxhighlight.NestedDef;
import org.sikuli.syntaxhighlight.ResolutionException;
import org.sikuli.syntaxhighlight.Util;
import org.sikuli.syntaxhighlight.grammar.TokenType;
import org.sikuli.syntaxhighlight.style.def.StyleElementDef;
/**
* @author Tal Liron
*/
public class Style extends NestedDef<Style>
{
static String extJSON = ".jso";
//
// Static operations
//
public static Style getByName( String name ) throws ResolutionException
{
if( Character.isLowerCase( name.charAt( 0 ) ) )
name = Character.toUpperCase( name.charAt( 0 ) ) + name.substring( 1 ) + "Style";
Style style = getByFullName( name );
if( style != null )
return style;
else
{
// Try contrib package
String pack = Jygments.class.getPackage().getName();
return getByFullName( pack, "contrib", name );
}
}
public static Style getByFullName( String name ) throws ResolutionException {
return getByFullName("", "", name);
}
@SuppressWarnings("unchecked")
public static Style getByFullName( String pack, String sub, String name ) throws ResolutionException
{
String fullname = name;
if (!pack.isEmpty()) {
if (!sub.isEmpty()) {
fullname = pack + "." + sub + "." + fullname;
} else {
fullname = pack + "." + fullname;
}
}
// Try cache
Style style = styles.get( fullname );
if( style != null )
return style;
try
{
return (Style) Jygments.class.getClassLoader().loadClass( fullname ).newInstance();
}
catch( InstantiationException x )
{
}
catch( IllegalAccessException x )
{
}
catch( ClassNotFoundException x )
{
}
InputStream stream = Util.getJsonFile(pack, sub, name, fullname);
if( stream != null )
{
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.getFactory().configure( JsonParser.Feature.ALLOW_COMMENTS, true );
try
{
Map<String, Object> json = objectMapper.readValue( stream, HashMap.class );
style = new Style();
style.addJson( json );
style.resolve();
// Cache it
Style existing = styles.putIfAbsent( fullname, style );
if( existing != null )
style = existing;
return style;
}
catch( JsonParseException x )
{
throw new ResolutionException( x );
}
catch( JsonMappingException x )
{
throw new ResolutionException( x );
}
catch( IOException x )
{
throw new ResolutionException( x );
}
}
return null;
}
//
// Attributes
//
public Map<TokenType, List<StyleElement>> getStyleElements()
{
return styleElements;
}
//
// Operations
//
public void addStyleElement( TokenType tokenType, StyleElement styleElement )
{
List<StyleElement> styleElementsForTokenType = styleElements.get( tokenType );
if( styleElementsForTokenType == null )
{
styleElementsForTokenType = new ArrayList<StyleElement>();
styleElements.put( tokenType, styleElementsForTokenType );
}
styleElementsForTokenType.add( styleElement );
}
public void resolve() throws ResolutionException
{
resolve( this );
}
//
// Def
//
@Override
public boolean resolve( Style style ) throws ResolutionException
{
if( super.resolve( style ) )
{
boolean done = false;
while( !done )
{
done = true;
for( TokenType tokenType : TokenType.getTokenTypes() )
{
if( tokenType != TokenType.Token )
{
if( !styleElements.containsKey( tokenType ) )
{
boolean doneOne = false;
TokenType parent = tokenType.getParent();
while( parent != null )
{
if( parent == TokenType.Token )
{
doneOne = true;
break;
}
List<StyleElement> parentElements = styleElements.get( parent );
if( parentElements != null )
{
styleElements.put( tokenType, parentElements );
doneOne = true;
break;
}
parent = parent.getParent();
}
if( !doneOne )
done = false;
}
}
}
}
return true;
}
else
return false;
}
// //////////////////////////////////////////////////////////////////////////
// Protected
protected void add( String tokenTypeName, String... styleElementNames )
{
ArrayList<String> list = new ArrayList<String>( styleElementNames.length );
for( String styleElementName : styleElementNames )
list.add( styleElementName );
addDef( new StyleElementDef( tokenTypeName, list ) );
}
@SuppressWarnings("unchecked")
protected void addJson( Map<String, Object> json ) throws ResolutionException
{
for( Map.Entry<String, Object> entry : json.entrySet() )
{
String tokenTypeName = entry.getKey();
if( entry.getValue() instanceof Iterable<?> )
{
for( String styleElementName : (Iterable<String>) entry.getValue() )
add( tokenTypeName, styleElementName );
}
else if( entry.getValue() instanceof String )
add( tokenTypeName, (String) entry.getValue() );
else
throw new ResolutionException( "Unexpected value in style definition: " + entry.getValue() );
}
}
// //////////////////////////////////////////////////////////////////////////
// Private
private static final ConcurrentMap<String, Style> styles = new ConcurrentHashMap<String, Style>();
private final Map<TokenType, List<StyleElement>> styleElements = new HashMap<TokenType, List<StyleElement>>();
}
| 24.780083 | 111 | 0.655894 |
6af5932c36000e4a2be5e58d137704b9e5a3d460
| 670 |
package com.shekhargulati.java8_tutorial.ch09;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
public class CompletableFutureExample {
public static void main(String[] args) {
CompletableFuture.completedFuture("hello");
CompletableFuture.runAsync(() -> System.out.println("hello"));
CompletableFuture.runAsync(() -> System.out.println("hello"), Executors.newSingleThreadExecutor());
CompletableFuture.supplyAsync(() -> UUID.randomUUID().toString());
CompletableFuture.supplyAsync(() -> UUID.randomUUID().toString(), Executors.newSingleThreadExecutor());
}
}
| 39.411765 | 111 | 0.732836 |
f4c4e11842cb64ceb47296458a0f122de15da2f4
| 8,201 |
/*******************************************************************************
* Copyright (c) 2015-2016, WSO2.Telco Inc. (http://www.wso2telco.com) All Rights Reserved.
*
* WSO2.Telco Inc. licences this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.wso2telco.dep.mediator.impl.smsmessaging;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.MessageContext;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.wso2telco.dep.mediator.MSISDNConstants;
import com.wso2telco.dep.mediator.OperatorEndpoint;
import com.wso2telco.dep.mediator.ResponseHandler;
import com.wso2telco.dep.mediator.entity.OparatorEndPointSearchDTO;
import com.wso2telco.dep.mediator.entity.smsmessaging.QuerySMSStatusResponse;
import com.wso2telco.dep.mediator.internal.UID;
import com.wso2telco.dep.mediator.internal.Util;
import com.wso2telco.dep.mediator.mediationrule.OriginatingCountryCalculatorIDD;
import com.wso2telco.dep.mediator.service.SMSMessagingService;
import com.wso2telco.dep.mediator.util.APIType;
import com.wso2telco.dep.mediator.util.DataPublisherConstants;
import com.wso2telco.dep.oneapivalidation.exceptions.CustomException;
import com.wso2telco.dep.oneapivalidation.service.IServiceValidate;
import com.wso2telco.dep.oneapivalidation.service.impl.smsmessaging.ValidateDeliveryStatus;
import com.wso2telco.dep.subscriptionvalidator.util.ValidatorUtils;
// TODO: Auto-generated Javadoc
/**
* The Class QuerySMSStatusHandler.
*/
public class QuerySMSStatusHandler implements SMSHandler {
/** The log. */
private Log log = LogFactory.getLog(QuerySMSStatusHandler.class);
/** The Constant API_TYPE. */
private static final String API_TYPE = "sms";
/** The occi. */
private OriginatingCountryCalculatorIDD occi;
/** The executor. */
private SMSExecutor executor;
/** The smsMessagingDAO. */
private SMSMessagingService smsMessagingService;
/** The response handler. */
private ResponseHandler responseHandler;
/** The sender address. */
private String senderAddress = null;
/** The request id. */
private String requestId = null;
/**
* Instantiates a new query sms status handler.
*
* @param executor
* the executor
*/
public QuerySMSStatusHandler(SMSExecutor executor) {
occi = new OriginatingCountryCalculatorIDD();
this.executor = executor;
smsMessagingService = new SMSMessagingService();
responseHandler = new ResponseHandler();
}
/*
* (non-Javadoc)
*
* @see
* com.wso2telco.mediator.impl.sms.SMSHandler#validate(java.lang.String,
* java.lang.String, org.json.JSONObject, org.apache.synapse.MessageContext)
*/
@Override
public boolean validate(String httpMethod, String requestPath, JSONObject jsonBody, MessageContext context)
throws Exception {
context.setProperty(DataPublisherConstants.OPERATION_TYPE, 202);
if (!httpMethod.equalsIgnoreCase("GET")) {
((Axis2MessageContext) context).getAxis2MessageContext().setProperty("HTTP_SC", 405);
throw new Exception("Method not allowed");
}
IServiceValidate validator = new ValidateDeliveryStatus();
validator.validateUrl(requestPath);
loadRequestParams();
validator.validate(new String[] { senderAddress, requestId });
return true;
}
/*
* (non-Javadoc)
*
* @see
* com.wso2telco.mediator.impl.sms.SMSHandler#handle(org.apache.synapse.
* MessageContext)
*/
@Override
public boolean handle(MessageContext context) throws Exception {
Map<String, String> requestIdMap = smsMessagingService.getSMSRequestIds(requestId, senderAddress);
Map<String, QuerySMSStatusResponse> responseMap = sendStatusQueries(context, requestIdMap, senderAddress);
if (Util.isAllNull(responseMap.values())) {
throw new CustomException("SVC0001", "", new String[] { "Could not complete querying SMS statuses" });
}
executor.removeHeaders(context);
String responsePayload = responseHandler.makeQuerySmsStatusResponse(context, senderAddress, requestId,
responseMap);
executor.setResponse(context, responsePayload);
return true;
}
/**
* Send status queries.
*
* @param context
* the context
* @param requestIdMap
* the request id map
* @param senderAddr
* the sender addr
* @return the map
* @throws Exception
* the exception
*/
private Map<String, QuerySMSStatusResponse> sendStatusQueries(MessageContext context,
Map<String, String> requestIdMap, String senderAddr) throws Exception {
String resourcePathPrefix = "/outbound/" + URLEncoder.encode(senderAddr, "UTF-8") + "/requests/";
Map<String, QuerySMSStatusResponse> statusResponses = new HashMap<String, QuerySMSStatusResponse>();
for (Map.Entry<String, String> entry : requestIdMap.entrySet()) {
String address = entry.getKey();
String reqId = entry.getValue();
if (reqId != null) {
context.setProperty(MSISDNConstants.USER_MSISDN, address.substring(5));
OperatorEndpoint endpoint = null;
String resourcePath = resourcePathPrefix + reqId + "/deliveryInfos";
if (ValidatorUtils.getValidatorForSubscription(context)
.validate(context)) {
OparatorEndPointSearchDTO searchDTO = new OparatorEndPointSearchDTO();
searchDTO.setApi(APIType.SMS);
searchDTO.setContext(context);
searchDTO.setIsredirect(true);
searchDTO.setMSISDN(address);
searchDTO.setOperators(executor.getValidoperators());
searchDTO.setRequestPathURL(resourcePath);
endpoint = occi.getOperatorEndpoint(searchDTO);
/*
* occi.getAPIEndpointsByMSISDN(address.replace("tel:", ""),
* API_TYPE, resourcePath, true,
* executor.getValidoperators());
*/
}
String sending_add = endpoint.getEndpointref().getAddress();
log.info("sending endpoint found: " + sending_add + " Request ID: " + UID.getRequestID(context));
String responseStr = executor.makeGetRequest(endpoint, sending_add, resourcePath, true, context,false);
QuerySMSStatusResponse statusResponse = parseJsonResponse(responseStr);
statusResponses.put(address, statusResponse);
} else {
statusResponses.put(address, null);
}
}
return statusResponses;
}
/**
* Parses the json response.
*
* @param responseString
* the response string
* @return the query sms status response
*/
private QuerySMSStatusResponse parseJsonResponse(String responseString) {
Gson gson = new GsonBuilder().create();
QuerySMSStatusResponse response;
try {
response = gson.fromJson(responseString, QuerySMSStatusResponse.class);
if (response.getDeliveryInfoList() == null) {
return null;
}
} catch (JsonSyntaxException e) {
return null;
}
return response;
}
/**
* Load request params.
*
* @throws UnsupportedEncodingException
* the unsupported encoding exception
*/
private void loadRequestParams() throws UnsupportedEncodingException {
String reqPath = URLDecoder.decode(executor.getSubResourcePath().replace("+", "%2B"), "UTF-8");
Pattern pattern = Pattern.compile("outbound/(.+?)/requests/(.+?)/");
Matcher matcher = pattern.matcher(reqPath);
while (matcher.find()) {
senderAddress = matcher.group(1);
requestId = matcher.group(2);
}
}
}
| 34.75 | 108 | 0.730277 |
90598f8ea8524bdcd1f37942a67b70b04fbf7fa9
| 1,081 |
package mybase;
import myLinkedList.Iterator;
import myLinkedList.LinkedList;
/**
* Created by thoma on 11-Mar-17.
*/
public class MoveBehavior implements Movable {
private Entity entity;
private Game game;
public MoveBehavior(Entity entity, Game game) {
this.entity = entity;
this.game = game;
}
public void move() {
LinkedList<Location> body = entity.getBody();
Direction direction = entity.getDirection();
Location head = body.first();
Point nextPoint = Navigation.getNextPoint(new Point(head), direction);
Iterator<Location> iterator = body.iterator();
while (iterator.hasNext()) {
Location location = iterator.next();
Point copyOfOldCoordinates = new Point(location);
location.set(nextPoint);
nextPoint = copyOfOldCoordinates;
}
Point warpedPoint = Navigation.warp(new Point(head), game.getBounds());
head.set(warpedPoint);
}
public void setEntity(Entity entity) {
this.entity = entity;
}
}
| 27.025 | 79 | 0.635523 |
2b9b6fda3e9d0ef36cdeeeefecbda1e879947755
| 786 |
package io.fastjson.bnsf.holders.basic;
import io.fastjson.bnsf.WireValueType;
import io.fastjson.bnsf.holders.WireValueHolder;
/**
* Created by Richard on 9/25/14.
*/
public class UintHolder extends Number implements WireValueHolder {
private char value;
public char getValue() {
return value;
}
public void setValue(char value) {
this.value = value;
}
@Override
public WireValueType type() {
return WireValueType.UINT;
}
@Override
public int intValue() {
return value;
}
@Override
public long longValue() {
return value;
}
@Override
public float floatValue() {
return value;
}
@Override
public double doubleValue() {
return value;
}
}
| 17.086957 | 68 | 0.618321 |
9a0a7835f9ee15c33828e1fb4689fedd3b4cd881
| 660 |
package slide1Ex03;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.swing.JLabel;
public class Song {
private String title;
private String artist;
public void setTitle(String title) {
this.title = title;
}
public void setArtist(String artist) {
this.artist = artist;
}
public void play(){
JLabel c = new JLabel();
final DateFormat formato = new SimpleDateFormat("HH:mm:ss");
System.out.println(formato);
char[] a;
String b = "aaaaaaaaa";
a = b.toCharArray();
for (int i = 0; i < a.length; i++) {
System.out.println("Posicao " + i + " Letra " + a[i]);
}
}
}
| 20.625 | 65 | 0.631818 |
5f02c629c358048b17e56e9879c866cefe311301
| 320 |
package security.ex1.screen.customerdetail;
import io.jmix.ui.screen.*;
import security.ex1.entity.CustomerDetail;
@UiController("sample_CustomerDetail.edit")
@UiDescriptor("customer-detail-edit.xml")
@EditedEntityContainer("customerDetailDc")
public class CustomerDetailEdit extends StandardEditor<CustomerDetail> {
}
| 32 | 72 | 0.83125 |
c2d9f85d68fc06dee882588437fb5b821eb83496
| 455 |
package betterquesting.api2.utils;
import net.minecraft.util.Tuple;
// Purely so I don't have to do casting every damn time I want to use a Tuple
public class Tuple2<T, K> extends Tuple
{
public Tuple2(T first, K second)
{
super(first, second);
}
@Override
public T getFirst()
{
return (T)super.getFirst();
}
@Override
public K getSecond()
{
return (K)super.getSecond();
}
}
| 18.2 | 77 | 0.602198 |
b91b20ce021c9beb81e432a7ff4198f7ebd32f1b
| 3,376 |
/*
* Copyright 2018 iserge.
*
* 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.cesiumjs.cs.core;
import jsinterop.annotations.JsConstructor;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
/**
* @author Serge Silaev aka iSergio
*/
@JsType(isNative = true, namespace = "Cesium", name = "HeadingPitchRange")
public class HeadingPitchRange {
/**
* Heading is the rotation from the local north direction where a positive angle
* is increasing eastward.
*/
@JsProperty
public double heading;
/**
* Pitch is the rotation from the local xy-plane. Positive pitch angles are
* above the plane. Negative pitch angles are below the plane.
*/
@JsProperty
public double pitch;
/**
* Range is the distance from the center of the local frame.
*/
@JsProperty
public double range;
/**
* Defines a heading angle, pitch angle, and range in a local frame. Heading is
* the rotation from the local north direction where a positive angle is
* increasing eastward. Pitch is the rotation from the local xy-plane. Positive
* pitch angles are above the plane. Negative pitch angles are below the plane.
* Range is the distance from the center of the frame.
*/
@JsConstructor
public HeadingPitchRange() {
}
/**
* Defines a heading angle, pitch angle, and range in a local frame. Heading is
* the rotation from the local north direction where a positive angle is
* increasing eastward. Pitch is the rotation from the local xy-plane. Positive
* pitch angles are above the plane. Negative pitch angles are below the plane.
* Range is the distance from the center of the frame.
*
* @param heading The heading angle in radians. Default: 0.0
* @param pitch The pitch angle in radians. Default: 0.0
* @param range The distance from the center in meters. Default: 0.0
*/
@JsConstructor
public HeadingPitchRange(double heading, double pitch, double range) {
}
/**
* Duplicates a HeadingPitchRange instance.
*
* @param hpr The HeadingPitchRange to duplicate.
* @return The modified result parameter or a new HeadingPitchRange instance if
* one was not provided. (Returns undefined if hpr is undefined)
*/
public static native HeadingPitchRange clone(HeadingPitchRange hpr);
/**
* Duplicates a HeadingPitchRange instance.
*
* @param hpr The HeadingPitchRange to duplicate.
* @param result The object onto which to store the result.
* @return The modified result parameter or a new HeadingPitchRange instance if
* one was not provided. (Returns undefined if hpr is undefined)
*/
public static native HeadingPitchRange clone(HeadingPitchRange hpr, HeadingPitchRange result);
}
| 37.098901 | 98 | 0.703199 |
22626d64cce606b687af33a6ffe8980190c0aa1e
| 1,402 |
package com.miu360.taxi_check.ui;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.miu360.inspect.FaZhiBanQueayActivity;
import com.miu360.inspect.R;
import com.miu360.inspect.ZhiFaJianChaJiLutableActivity;
import com.miu360.legworkwrit.mvp.data.CacheManager;
import com.miu360.taxi_check.BaseActivity;
import com.miu360.taxi_check.view.HeaderHolder;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class OtherActivity extends BaseActivity implements OnClickListener {
@ViewInject(R.id.fagui_query)
private TextView fagui_query;
@ViewInject(R.id.fazhiban_query)
private TextView fazhiban_query;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_others);
initView();
}
private void initView() {
ViewUtils.inject(self);
new HeaderHolder().init(self, "其它");
fagui_query.setOnClickListener(this);
fazhiban_query.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == fagui_query) {
Intent intent = new Intent(self, FaGuiActivity.class);
startActivity(intent);
}else if(fazhiban_query==v){
Intent intent = new Intent(self, FaZhiBanQueayActivity.class);
startActivity(intent);
}
}
}
| 27.490196 | 76 | 0.789586 |
865f46627f25631aedd4496b9e305c30dd9cb3d9
| 3,719 |
package cn.xfyun.service.lfasr;
import cn.xfyun.model.response.lfasr.LfasrMessage;
import cn.xfyun.service.lfasr.task.Task;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* TODO
*
* @author : jun
* @date : 2021年03月31日
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({LfasrExecutorService.class})
@PowerMockIgnore("cn.xfyun.util.HttpConnector")
public class LfasrExecutorServiceTest {
@Test
public void execTest() throws Exception {
LfasrExecutorService lfasrExecutorService = LfasrExecutorService.build(10, 30, 1000, 300, 22);
Task task = PowerMockito.mock(Task.class);
LfasrMessage message = new LfasrMessage();
message.setOk(1);
Future<LfasrMessage> future = PowerMockito.mock(Future.class);
PowerMockito.when(future.get(10322, TimeUnit.MILLISECONDS)).thenReturn(message);
lfasrExecutorService.exec(task);
assertEquals(1, message.getOk());
}
@Test
public void getFutureTest() throws Exception {
LfasrExecutorService lfasrExecutorService = LfasrExecutorService.build(10, 30, 1000, 300, 22);
LfasrMessage message = new LfasrMessage();
message.setOk(1);
Future<LfasrMessage> future = PowerMockito.mock(Future.class);
PowerMockito.when(future.get(10322, TimeUnit.MILLISECONDS)).thenReturn(message);
message = Whitebox.invokeMethod(lfasrExecutorService, "getFuture", future, Mockito.mock(Task.class));
assertEquals(1, message.getOk());
}
@Test
public void getFutureTest_ExecutionException() throws Exception {
LfasrExecutorService lfasrExecutorService = LfasrExecutorService.build(10, 30, 1000, 300, 22);
Future<LfasrMessage> future = PowerMockito.mock(Future.class);
PowerMockito.when(future.get(10322, TimeUnit.MILLISECONDS)).thenThrow(ExecutionException.class);
LfasrMessage message = Whitebox.invokeMethod(lfasrExecutorService, "getFuture", future, Mockito.mock(Task.class));
assertTrue(message.getFailed().contains("服务调用异常"));
}
@Test
public void getFutureTest_TimeoutException() throws Exception {
LfasrExecutorService lfasrExecutorService = LfasrExecutorService.build(10, 30, 1000, 300, 22);
Future<LfasrMessage> future = PowerMockito.mock(Future.class);
PowerMockito.when(future.get(10322, TimeUnit.MILLISECONDS)).thenThrow(TimeoutException.class);
LfasrMessage message = Whitebox.invokeMethod(lfasrExecutorService, "getFuture", future, Mockito.mock(Task.class));
assertTrue(message.getFailed().contains("连接超时"));
}
@Test
public void getFutureTest_InterruptedException() throws Exception {
LfasrExecutorService lfasrExecutorService = LfasrExecutorService.build(10, 30, 1000, 300, 22);
Future<LfasrMessage> future = PowerMockito.mock(Future.class);
PowerMockito.when(future.get(10322, TimeUnit.MILLISECONDS)).thenThrow(InterruptedException.class);
LfasrMessage message = Whitebox.invokeMethod(lfasrExecutorService, "getFuture", future, Mockito.mock(Task.class));
assertTrue(message.getFailed().contains("服务调用异常"));
}
}
| 39.989247 | 122 | 0.743748 |
af67f9908f51a7d679318c4ed3479621c26fea6a
| 4,676 |
/*
* 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.druid.indexing.common.task;
import com.google.common.collect.ImmutableMap;
import org.apache.druid.data.input.impl.DimensionsSpec;
import org.apache.druid.data.input.impl.NoopFirehoseFactory;
import org.apache.druid.data.input.impl.NoopInputFormat;
import org.apache.druid.data.input.impl.NoopInputSource;
import org.apache.druid.data.input.impl.TimestampSpec;
import org.apache.druid.indexing.common.task.IndexTask.IndexIOConfig;
import org.apache.druid.indexing.common.task.IndexTask.IndexIngestionSpec;
import org.apache.druid.java.util.common.granularity.Granularities;
import org.apache.druid.query.aggregation.AggregatorFactory;
import org.apache.druid.segment.indexing.DataSchema;
import org.apache.druid.segment.indexing.granularity.ArbitraryGranularitySpec;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class IndexIngestionSpecTest
{
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void testParserAndInputFormat()
{
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(
"Cannot use parser and inputSource together. Try using inputFormat instead of parser."
);
final IndexIngestionSpec spec = new IndexIngestionSpec(
new DataSchema(
"dataSource",
ImmutableMap.of("fake", "parser map"),
new AggregatorFactory[0],
new ArbitraryGranularitySpec(Granularities.NONE, null),
null,
null
),
new IndexIOConfig(
null,
new NoopInputSource(),
new NoopInputFormat(),
null
),
null
);
}
@Test
public void testParserAndInputSource()
{
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Cannot use parser and inputSource together.");
final IndexIngestionSpec spec = new IndexIngestionSpec(
new DataSchema(
"dataSource",
ImmutableMap.of("fake", "parser map"),
new AggregatorFactory[0],
new ArbitraryGranularitySpec(Granularities.NONE, null),
null,
null
),
new IndexIOConfig(
null,
new NoopInputSource(),
null,
null
),
null
);
}
@Test
public void testFirehoseAndInputSource()
{
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage(
"At most one of [Property{name='firehose', value=NoopFirehoseFactory{}}, Property{name='inputSource'"
);
final IndexIngestionSpec spec = new IndexIngestionSpec(
new DataSchema(
"dataSource",
new TimestampSpec(null, null, null),
DimensionsSpec.EMPTY,
new AggregatorFactory[0],
new ArbitraryGranularitySpec(Granularities.NONE, null),
null
),
new IndexIOConfig(
new NoopFirehoseFactory(),
new NoopInputSource(),
null,
null
),
null
);
}
@Test
public void testFirehoseAndInputFormat()
{
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Cannot use firehose and inputFormat together.");
final IndexIngestionSpec spec = new IndexIngestionSpec(
new DataSchema(
"dataSource",
new TimestampSpec(null, null, null),
DimensionsSpec.EMPTY,
new AggregatorFactory[0],
new ArbitraryGranularitySpec(Granularities.NONE, null),
null
),
new IndexIOConfig(
new NoopFirehoseFactory(),
null,
new NoopInputFormat(),
null
),
null
);
}
}
| 32.699301 | 109 | 0.6713 |
6f7698f39e001978140dd868f7ebf5ee598a8135
| 729 |
package ru.job4j.lock;
/**
* testing of the class UserLock.
*/
public class UserLockTest {
/**
* method main.
* @param arRgs - String[]
* @throws InterruptedException - exception
*/
public static void main(String[] arRgs) throws InterruptedException {
UserLock userLock = new UserLock();
Thread threadLock = new Thread(new Block(userLock));
Thread threadUnlock = new Thread(new UnBlock(userLock));
threadLock.start();
threadUnlock.start();
Thread.sleep(5000);
userLock.lock();
Thread.sleep(3000);
userLock.unblock();
Thread.sleep(5000);
threadLock.interrupt();
threadUnlock.interrupt();
}
}
| 21.441176 | 73 | 0.604938 |
58ae948ad08be1563fbc2ddf4521d02d25d60442
| 261 |
package ru.job4j.auto.repository;
import org.springframework.stereotype.Repository;
import ru.job4j.auto.model.Body;
@Repository
public class BodyRepository extends BaseEntityRepository<Body> {
public BodyRepository() {
super(Body.class);
}
}
| 21.75 | 64 | 0.758621 |
22bbeacfe300c208d77659e148c418f147162ee7
| 1,528 |
package com.raizlabs.android.dbflow.config;
import com.raizlabs.android.dbflow.converter.BigDecimalConverter;
import com.raizlabs.android.dbflow.converter.BooleanConverter;
import com.raizlabs.android.dbflow.converter.CalendarConverter;
import com.raizlabs.android.dbflow.converter.CharConverter;
import com.raizlabs.android.dbflow.converter.DateConverter;
import com.raizlabs.android.dbflow.converter.SqlDateConverter;
import com.raizlabs.android.dbflow.converter.UUIDConverter;
import java.lang.Boolean;
import java.lang.Character;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.UUID;
public final class GeneratedDatabaseHolder extends DatabaseHolder {
public GeneratedDatabaseHolder() {
typeConverters.put(Boolean.class, new BooleanConverter());
typeConverters.put(Character.class, new CharConverter());
typeConverters.put(BigDecimal.class, new BigDecimalConverter());
typeConverters.put(Date.class, new SqlDateConverter());
typeConverters.put(Time.class, new SqlDateConverter());
typeConverters.put(Timestamp.class, new SqlDateConverter());
typeConverters.put(Calendar.class, new CalendarConverter());
typeConverters.put(GregorianCalendar.class, new CalendarConverter());
typeConverters.put(java.util.Date.class, new DateConverter());
typeConverters.put(UUID.class, new UUIDConverter());
new MyDatabaseRestClientDatabase_Database(this);
}
}
| 43.657143 | 73 | 0.808246 |
b3decade223488aebfa211c2808aa3c26a006020
| 1,992 |
package ch.fhnw.wodss.tippspiel.builder;
import ch.fhnw.wodss.tippspiel.domain.Role;
import ch.fhnw.wodss.tippspiel.dto.BetDTO;
import ch.fhnw.wodss.tippspiel.dto.BetGroupDTO;
import ch.fhnw.wodss.tippspiel.dto.UserDTO;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class UserDTOBuilder {
Set<String> roles = new HashSet<>();
List<BetDTO> bets = new ArrayList<>();
List<BetGroupDTO> betGroups = new ArrayList<>();
UserDTO user;
public UserDTOBuilder(){
user = new UserDTO();
}
public UserDTOBuilder withId(long id){
user.setId(id);
return this;
}
public UserDTOBuilder withName(String username) {
user.setName(username);
return this;
}
public UserDTOBuilder withRole(String role) {
roles.add(role);
return this;
}
public UserDTOBuilder withPassword(String password) {
user.setPassword(password);
return this;
}
public UserDTOBuilder withEmail(String email){
user.setEmail(email);
return this;
}
public UserDTOBuilder withBet(BetDTO bet){
bets.add(bet);
return this;
}
public UserDTOBuilder withBetGroup(BetGroupDTO betGroup){
betGroups.add(betGroup);
return this;
}
public UserDTOBuilder withReminders(boolean reminders){
user.setReminders(reminders);
return this;
}
public UserDTOBuilder withDailyResults(boolean dailyResults){
user.setDailyResults(dailyResults);
return this;
}
public UserDTO build() {
Set<Role> roles = this.roles.stream().map(roleName -> {
Role role = new Role();
role.setName(roleName);
return role;
}).collect(Collectors.toSet());
user.setRole(roles);
user.setBetGroups(betGroups);
user.setBets(bets);
return user;
}
}
| 24.592593 | 65 | 0.643072 |
d46683046b17a36275b91d638089383cd3b8de63
| 3,789 |
/**
* Copyright 2008-2010 Digital Enterprise Research Institute (DERI)
*
* 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.deri.any23.extractor.rdfa;
import org.deri.any23.extractor.ErrorReporter;
import org.deri.any23.extractor.ExtractionContext;
import org.deri.any23.extractor.ExtractionException;
import org.deri.any23.extractor.ExtractionResult;
import org.deri.any23.extractor.ExtractionResultImpl;
import org.deri.any23.extractor.Extractor;
import org.deri.any23.extractor.ExtractorDescription;
import org.deri.any23.writer.TripleHandler;
import org.junit.Assert;
import org.junit.Test;
import org.openrdf.model.impl.URIImpl;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Test case for {@link org.deri.any23.extractor.ExtractionException}.
*
* @author Michele Mostarda (mostarda@fbk.eu)
*/
public class ExtractionExceptionTest {
@Test
public void testPrintStackTrace() throws ExtractionException, IOException {
final String FAKE_EXTRACTOR_NAME = "fake-extractor-name";
final Extractor extractor = mock(Extractor.class);
final ExtractorDescription ed = mock(ExtractorDescription.class);
when(ed.getExtractorName()).thenReturn(FAKE_EXTRACTOR_NAME);
when(extractor.getDescription()).thenReturn(ed);
final TripleHandler th = mock(TripleHandler.class);
final ExtractionContext extractionContext = new ExtractionContext(
extractor.getDescription().getExtractorName(),
new URIImpl("http://fake.document.uri")
);
final ExtractionResult er = new ExtractionResultImpl(extractionContext, extractor, th);
er.notifyError(ErrorReporter.ErrorLevel.FATAL, "Fake fatal error.", 1, 2);
er.notifyError(ErrorReporter.ErrorLevel.ERROR, "Fake error." , 3, 4);
er.notifyError(ErrorReporter.ErrorLevel.WARN , "Fake warning." , 5, 6);
ExtractionException ee = new ExtractionException("Fake message.", new RuntimeException("Fake cause"), er);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ee.printStackTrace(new PrintWriter(baos));
final String bufferContent = baos.toString();
Assert.assertTrue("Unexpected message content.", bufferContent.contains(FAKE_EXTRACTOR_NAME));
Assert.assertTrue("Unexpected message content.", bufferContent.contains("http://fake.document.uri"));
Assert.assertTrue("Unexpected message content.", bufferContent.contains(
ExtractionContext.ROOT_EXTRACTION_RESULT_ID
));
Assert.assertTrue("Unexpected message content.", bufferContent.contains("Fake fatal error."));
Assert.assertTrue("Unexpected message content.", bufferContent.contains("(1,2)"));
Assert.assertTrue("Unexpected message content.", bufferContent.contains("Fake error."));
Assert.assertTrue("Unexpected message content.", bufferContent.contains("(3,4)"));
Assert.assertTrue("Unexpected message content.", bufferContent.contains("Fake warning."));
Assert.assertTrue("Unexpected message content.", bufferContent.contains("(5,6)"));
baos.close();
}
}
| 45.650602 | 114 | 0.731328 |
31a38b4b87a402e0e23903cc15ec75e0213733fd
| 23,916 |
/*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxauth.session.ws.rs;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang.StringUtils;
import org.gluu.model.security.Identity;
import org.gluu.oxauth.audit.ApplicationAuditLogger;
import org.gluu.oxauth.model.audit.Action;
import org.gluu.oxauth.model.audit.OAuth2AuditLog;
import org.gluu.oxauth.model.authorize.AuthorizeRequestParam;
import org.gluu.oxauth.model.common.AuthorizationGrant;
import org.gluu.oxauth.model.common.AuthorizationGrantList;
import org.gluu.oxauth.model.common.SessionId;
import org.gluu.oxauth.model.config.Constants;
import org.gluu.oxauth.model.configuration.AppConfiguration;
import org.gluu.oxauth.model.error.ErrorHandlingMethod;
import org.gluu.oxauth.model.error.ErrorResponseFactory;
import org.gluu.oxauth.model.exception.InvalidJwtException;
import org.gluu.oxauth.model.gluu.GluuErrorResponseType;
import org.gluu.oxauth.model.jwt.Jwt;
import org.gluu.oxauth.model.registration.Client;
import org.gluu.oxauth.model.session.EndSessionErrorResponseType;
import org.gluu.oxauth.model.session.EndSessionRequestParam;
import org.gluu.oxauth.model.token.JsonWebResponse;
import org.gluu.oxauth.model.util.URLPatternList;
import org.gluu.oxauth.model.util.Util;
import org.gluu.oxauth.service.*;
import org.gluu.oxauth.service.external.ExternalApplicationSessionService;
import org.gluu.oxauth.service.external.ExternalEndSessionService;
import org.gluu.oxauth.service.external.context.EndSessionContext;
import org.gluu.oxauth.util.ServerUtil;
import org.gluu.util.Pair;
import org.gluu.util.StringHelper;
import org.slf4j.Logger;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @author Javier Rojas Blum
* @author Yuriy Movchan
* @author Yuriy Zabrovarnyy
* @version December 8, 2018
*/
@Path("/")
public class EndSessionRestWebServiceImpl implements EndSessionRestWebService {
@Inject
private Logger log;
@Inject
private ErrorResponseFactory errorResponseFactory;
@Inject
private RedirectionUriService redirectionUriService;
@Inject
private AuthorizationGrantList authorizationGrantList;
@Inject
private ExternalApplicationSessionService externalApplicationSessionService;
@Inject
private ExternalEndSessionService externalEndSessionService;
@Inject
private SessionIdService sessionIdService;
@Inject
private CookieService cookieService;
@Inject
private ClientService clientService;
@Inject
private GrantService grantService;
@Inject
private Identity identity;
@Inject
private ApplicationAuditLogger applicationAuditLogger;
@Inject
private AppConfiguration appConfiguration;
@Inject
private LogoutTokenFactory logoutTokenFactory;
@Override
public Response requestEndSession(String idTokenHint, String postLogoutRedirectUri, String state, String sessionId,
HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext sec) {
try {
log.debug("Attempting to end session, idTokenHint: {}, postLogoutRedirectUri: {}, sessionId: {}, Is Secure = {}",
idTokenHint, postLogoutRedirectUri, sessionId, sec.isSecure());
Jwt idToken = validateIdTokenHint(idTokenHint, postLogoutRedirectUri);
validateSessionIdRequestParameter(sessionId, postLogoutRedirectUri);
final Pair<SessionId, AuthorizationGrant> pair = getPair(idTokenHint, sessionId, httpRequest);
if (pair.getFirst() == null) {
final String reason = "Failed to identify session by session_id query parameter or by session_id cookie.";
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.INVALID_GRANT_AND_SESSION, reason));
}
postLogoutRedirectUri = validatePostLogoutRedirectUri(postLogoutRedirectUri, pair);
validateSid(postLogoutRedirectUri, idToken, pair.getFirst());
endSession(pair, httpRequest, httpResponse);
auditLogging(httpRequest, pair);
Set<Client> clients = getSsoClients(pair);
Set<String> frontchannelUris = Sets.newHashSet();
Map<String, Client> backchannelUris = Maps.newHashMap();
for (Client client : clients) {
boolean hasBackchannel = false;
for (String logoutUri : client.getAttributes().getBackchannelLogoutUri()) {
if (Util.isNullOrEmpty(logoutUri)) {
continue; // skip if logout_uri is blank
}
backchannelUris.put(logoutUri, client);
hasBackchannel = true;
}
if (hasBackchannel) { // client has backchannel_logout_uri
continue;
}
if(StringUtils.isNotBlank(client.getFrontChannelLogoutUri())) {
String logoutUri = client.getFrontChannelLogoutUri();
if (client.getFrontChannelLogoutSessionRequired()) {
logoutUri = EndSessionUtils.appendSid(logoutUri, pair.getFirst().getOutsideSid(), appConfiguration.getIssuer());
}
frontchannelUris.add(logoutUri);
}
}
backChannel(backchannelUris, pair.getSecond(), pair.getFirst().getOutsideSid());
postLogoutRedirectUri = addStateInPostLogoutRedirectUri(postLogoutRedirectUri, state);
if (frontchannelUris.isEmpty() && StringUtils.isNotBlank(postLogoutRedirectUri)) { // no front-channel
log.trace("No frontchannel_redirect_uri's found in clients involved in SSO.");
try {
log.trace("Redirect to postlogout_redirect_uri: " + postLogoutRedirectUri);
return Response.status(Response.Status.FOUND).location(new URI(postLogoutRedirectUri)).build();
} catch (URISyntaxException e) {
final String message = "Failed to create URI for " + postLogoutRedirectUri + " postlogout_redirect_uri.";
log.error(message);
return Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.errorAsJson(EndSessionErrorResponseType.INVALID_REQUEST, message)).build();
}
}
return httpBased(frontchannelUris, postLogoutRedirectUri, state, pair, httpRequest);
} catch (WebApplicationException e) {
if (e.getResponse() != null) {
return e.getResponse();
}
throw e;
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new WebApplicationException(Response
.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(errorResponseFactory.getJsonErrorResponse(GluuErrorResponseType.SERVER_ERROR))
.build());
}
}
/**
* Adds state param in the post_logout_redirect_uri whether it exists.
*/
private String addStateInPostLogoutRedirectUri(String postLogoutRedirectUri, String state) {
if (StringUtils.isBlank(postLogoutRedirectUri) || StringUtils.isBlank(state)) {
return postLogoutRedirectUri;
}
return UriBuilder.fromUri(postLogoutRedirectUri)
.queryParam(EndSessionRequestParam.STATE, state)
.build()
.toString();
}
private void validateSid(String postLogoutRedirectUri, Jwt idToken, SessionId session) {
if (idToken == null) {
return;
}
final String sid = idToken.getClaims().getClaimAsString("sid");
if (StringUtils.isNotBlank(sid) && !sid.equals(session.getOutsideSid())) {
log.error("sid in id_token_hint does not match sid of the session. id_token_hint sid: {}, session sid: {}", sid, session.getOutsideSid());
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.INVALID_REQUEST, "sid in id_token_hint does not match sid of the session"));
}
}
private void backChannel(Map<String, Client> backchannelUris, AuthorizationGrant grant, String outsideSid) throws InterruptedException {
if (backchannelUris.isEmpty()) {
return;
}
log.trace("backchannel_redirect_uri's: " + backchannelUris);
final ExecutorService executorService = EndSessionUtils.getExecutorService();
for (final Map.Entry<String, Client> entry : backchannelUris.entrySet()) {
final JsonWebResponse logoutToken = logoutTokenFactory.createLogoutToken(entry.getValue(), outsideSid, grant.getUser());
if (logoutToken == null) {
log.error("Failed to create logout_token for client: " + entry.getValue().getClientId());
return;
}
executorService.execute(() -> EndSessionUtils.callRpWithBackchannelUri(entry.getKey(), logoutToken.toString()));
}
executorService.shutdown();
executorService.awaitTermination(30, TimeUnit.SECONDS);
log.trace("Finished backchannel calls.");
}
private Response createErrorResponse(String postLogoutRedirectUri, EndSessionErrorResponseType error, String reason) {
log.debug(reason);
try {
if (allowPostLogoutRedirect(postLogoutRedirectUri)) {
if (ErrorHandlingMethod.REMOTE == appConfiguration.getErrorHandlingMethod()) {
String separator = postLogoutRedirectUri.contains("?") ? "&" : "?";
postLogoutRedirectUri = postLogoutRedirectUri + separator + errorResponseFactory.getErrorAsQueryString(error, "", reason);
}
return Response.status(Response.Status.FOUND).location(new URI(postLogoutRedirectUri)).build();
}
} catch (URISyntaxException e) {
log.error("Can't perform redirect", e);
}
return Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.errorAsJson(error, reason)).build();
}
/**
* Allow post logout redirect without validation only if:
* allowPostLogoutRedirectWithoutValidation = true and post_logout_redirect_uri is white listed
*/
private boolean allowPostLogoutRedirect(String postLogoutRedirectUri) {
if (StringUtils.isBlank(postLogoutRedirectUri)) {
return false;
}
final Boolean allowPostLogoutRedirectWithoutValidation = appConfiguration.getAllowPostLogoutRedirectWithoutValidation();
return allowPostLogoutRedirectWithoutValidation != null &&
allowPostLogoutRedirectWithoutValidation &&
new URLPatternList(appConfiguration.getClientWhiteList()).isUrlListed(postLogoutRedirectUri);
}
private void validateSessionIdRequestParameter(String sessionId, String postLogoutRedirectUri) {
// session_id is not required but if it is present then we must validate it #831
if (StringUtils.isNotBlank(sessionId)) {
SessionId sessionIdObject = sessionIdService.getSessionId(sessionId);
if (sessionIdObject == null) {
final String reason = "session_id parameter in request is not valid. Logout is rejected. session_id parameter in request can be skipped or otherwise valid value must be provided.";
log.error(reason);
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.INVALID_GRANT_AND_SESSION, reason));
}
}
}
private Jwt validateIdTokenHint(String idTokenHint, String postLogoutRedirectUri) {
if (appConfiguration.getForceIdTokenHintPrecense() && StringUtils.isBlank(idTokenHint)) { // must be present for logout tests #1279
final String reason = "id_token_hint is not set";
log.trace(reason);
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.INVALID_REQUEST, reason));
}
final AuthorizationGrant tokenHintGrant = getTokenHintGrant(idTokenHint);
if (appConfiguration.getForceIdTokenHintPrecense() && tokenHintGrant == null) { // must be present for logout tests #1279
final String reason = "id_token_hint is not set";
log.trace(reason);
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.INVALID_REQUEST, reason));
}
// id_token_hint is not required but if it is present then we must validate it #831
if (StringUtils.isNotBlank(idTokenHint)) {
if (tokenHintGrant == null) {
final String reason = "id_token_hint is not valid. Logout is rejected. id_token_hint can be skipped or otherwise valid value must be provided.";
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.INVALID_GRANT_AND_SESSION, reason));
}
try {
return Jwt.parse(idTokenHint);
} catch (InvalidJwtException e) {
log.error("Unable to parse id_token_hint as JWT.", e);
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.INVALID_GRANT_AND_SESSION, "Unable to parse id_token_hint as JWT."));
}
}
return null;
}
private AuthorizationGrant getTokenHintGrant(String idTokenHint) {
if (StringUtils.isBlank(idTokenHint)) {
return null;
}
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
if (authorizationGrant != null) {
return authorizationGrant;
}
Boolean endSessionWithAccessToken = appConfiguration.getEndSessionWithAccessToken();
if ((endSessionWithAccessToken != null) && endSessionWithAccessToken) {
return authorizationGrantList.getAuthorizationGrantByAccessToken(idTokenHint);
}
return null;
}
private String validatePostLogoutRedirectUri(String postLogoutRedirectUri, Pair<SessionId, AuthorizationGrant> pair) {
try {
if (StringUtils.isBlank(postLogoutRedirectUri)) {
return "";
}
if (appConfiguration.getAllowPostLogoutRedirectWithoutValidation()) {
log.trace("Skipped post_logout_redirect_uri validation (because allowPostLogoutRedirectWithoutValidation=true)");
return postLogoutRedirectUri;
}
final String result;
if (pair.getSecond() == null) {
result = redirectionUriService.validatePostLogoutRedirectUri(pair.getFirst(), postLogoutRedirectUri);
} else {
result = redirectionUriService.validatePostLogoutRedirectUri(pair.getSecond().getClient().getClientId(), postLogoutRedirectUri);
}
if (StringUtils.isBlank(result)) {
log.trace("Failed to validate post_logout_redirect_uri.");
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.POST_LOGOUT_URI_NOT_ASSOCIATED_WITH_CLIENT, ""));
}
if (StringUtils.isNotBlank(result)) {
return result;
}
log.trace("Unable to validate post_logout_redirect_uri.");
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.POST_LOGOUT_URI_NOT_ASSOCIATED_WITH_CLIENT, ""));
} catch (WebApplicationException e) {
if (pair.getFirst() != null) {
log.error(e.getMessage(), e);
throw new WebApplicationException(createErrorResponse(postLogoutRedirectUri, EndSessionErrorResponseType.POST_LOGOUT_URI_NOT_ASSOCIATED_WITH_CLIENT, ""));
} else {
throw e;
}
}
}
private Response httpBased(Set<String> frontchannelUris, String postLogoutRedirectUri, String state, Pair<SessionId, AuthorizationGrant> pair, HttpServletRequest httpRequest) {
try {
final EndSessionContext context = new EndSessionContext(httpRequest, frontchannelUris, postLogoutRedirectUri, pair.getFirst());
final String htmlFromScript = externalEndSessionService.getFrontchannelHtml(context);
if (StringUtils.isNotBlank(htmlFromScript)) {
log.debug("HTML from `getFrontchannelHtml` external script: " + htmlFromScript);
return okResponse(htmlFromScript);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
// default handling
final String html = EndSessionUtils.createFronthannelHtml(frontchannelUris, postLogoutRedirectUri, state);
log.debug("Constructed html logout page: " + html);
return okResponse(html);
}
private Response okResponse(String html) {
return Response.ok().
cacheControl(ServerUtil.cacheControl(true, true)).
header("Pragma", "no-cache").
type(MediaType.TEXT_HTML_TYPE).entity(html).
build();
}
private Pair<SessionId, AuthorizationGrant> getPair(String idTokenHint, String sessionId, HttpServletRequest httpRequest) {
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
if (authorizationGrant == null) {
Boolean endSessionWithAccessToken = appConfiguration.getEndSessionWithAccessToken();
if ((endSessionWithAccessToken != null) && endSessionWithAccessToken) {
authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(idTokenHint);
}
}
SessionId ldapSessionId = null;
try {
String id = sessionId;
if (StringHelper.isEmpty(id)) {
id = cookieService.getSessionIdFromCookie(httpRequest);
}
if (StringHelper.isNotEmpty(id)) {
ldapSessionId = sessionIdService.getSessionId(id);
}
} catch (Exception e) {
log.error("Failed to current session id.", e);
}
return new Pair<>(ldapSessionId, authorizationGrant);
}
private void endSession(Pair<SessionId, AuthorizationGrant> pair, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
// Clean up authorization session
removeConsentSessionId(httpRequest, httpResponse);
removeSessionId(pair, httpResponse);
boolean isExternalLogoutPresent;
boolean externalLogoutResult = false;
isExternalLogoutPresent = externalApplicationSessionService.isEnabled();
if (isExternalLogoutPresent) {
String userName = pair.getFirst().getSessionAttributes().get(Constants.AUTHENTICATED_USER);
externalLogoutResult = externalApplicationSessionService.executeExternalEndSessionMethods(httpRequest, pair.getFirst());
log.info("End session result for '{}': '{}'", userName, "logout", externalLogoutResult);
}
boolean isGrantAndExternalLogoutSuccessful = isExternalLogoutPresent && externalLogoutResult;
if (isExternalLogoutPresent && !isGrantAndExternalLogoutSuccessful) {
throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, EndSessionErrorResponseType.INVALID_GRANT, "External logout is present but executed external logout script returned failed result.");
}
grantService.logout(pair.getFirst().getDn());
if (identity != null) {
identity.logout();
}
}
private Set<Client> getSsoClients(Pair<SessionId, AuthorizationGrant> pair) {
SessionId sessionId = pair.getFirst();
AuthorizationGrant authorizationGrant = pair.getSecond();
if (sessionId == null) {
log.error("session_id is not passed to endpoint (as cookie or manually). Therefore unable to match clients for session_id.");
return Sets.newHashSet();
}
final Set<Client> clients = sessionId.getPermissionGrantedMap() != null ?
clientService.getClient(sessionId.getPermissionGrantedMap().getClientIds(true), true) :
Sets.newHashSet();
if (authorizationGrant != null) {
clients.add(authorizationGrant.getClient());
}
return clients;
}
private void removeSessionId(Pair<SessionId, AuthorizationGrant> pair, HttpServletResponse httpResponse) {
try {
boolean result = sessionIdService.remove(pair.getFirst());
if (!result) {
log.error("Failed to remove session_id '{}'", pair.getFirst().getId());
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
cookieService.removeSessionIdCookie(httpResponse);
cookieService.removeOPBrowserStateCookie(httpResponse);
}
}
private void removeConsentSessionId(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
try {
String id = cookieService.getConsentSessionIdFromCookie(httpRequest);
if (StringHelper.isNotEmpty(id)) {
SessionId ldapSessionId = sessionIdService.getSessionId(id);
if (ldapSessionId != null) {
boolean result = sessionIdService.remove(ldapSessionId);
if (!result) {
log.error("Failed to remove consent_session_id '{}'", id);
}
} else {
log.error("Failed to load session by consent_session_id: '{}'", id);
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
cookieService.removeConsentSessionIdCookie(httpResponse);
}
}
private void auditLogging(HttpServletRequest request, Pair<SessionId, AuthorizationGrant> pair) {
SessionId sessionId = pair.getFirst();
AuthorizationGrant authorizationGrant = pair.getSecond();
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.SESSION_DESTROYED);
oAuth2AuditLog.setSuccess(true);
if (authorizationGrant != null) {
oAuth2AuditLog.setClientId(authorizationGrant.getClientId());
oAuth2AuditLog.setScope(StringUtils.join(authorizationGrant.getScopes(), " "));
oAuth2AuditLog.setUsername(authorizationGrant.getUserId());
} else if (sessionId != null) {
oAuth2AuditLog.setClientId(sessionId.getPermissionGrantedMap().getClientIds(true).toString());
oAuth2AuditLog.setScope(sessionId.getSessionAttributes().get(AuthorizeRequestParam.SCOPE));
oAuth2AuditLog.setUsername(sessionId.getUserDn());
}
applicationAuditLogger.sendMessage(oAuth2AuditLog);
}
}
| 46.529183 | 232 | 0.677454 |
56908ec41b06ad2f53e3111fa58692ba06c08b5f
| 930 |
package net.viralpatel.jsp.custom.taglib;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class SubstrTagHandler extends TagSupport {
private String input;
private int start;
private int end;
@Override
public int doStartTag() throws JspException {
try {
//Get the writer object for output.
JspWriter out = pageContext.getOut();
//Perform substr operation on string.
out.println(input.substring(start, end));
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
}
| 19.375 | 50 | 0.709677 |
9d150691cc1926fd6320ed6120f17aa7fc1488a6
| 6,932 |
package controllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import displayScholarship.*;
import objects.*;
import myJStuff.MyController;
public class ScholarshipController extends MyController{
/**
* Instance Variables
*/
private JPanel viewScholarshipPanel;
private JPanel allScholarshipsPanel;
private JPanel editScholarshipPanel;
private JPanel viewStudentsAppliedPanel;
private JPanel viewStudentsAcceptedPanel;
private JPanel viewStudentsWonPanel;
/**
* This is all of the panels that are in the displaySchoalrship
*/
private ViewScholarshipPanel vsp;
private AllScholarshipsPanel asp;
private EditScholarshipPanel esp;
private ViewStudentsAppliedPanel vsapp;
private ViewStudentsAcceptedPanel vsacp;
private ViewStudentsWonPanel vswp;
private List<Student> students;
/**
* HashMap of all of the scholarships
*/
private HashMap<Integer, Scholarship> scMap;
private Scholarship currentScholarship;
/**
* If the scholarship controller is started as an admin or a student
*/
private boolean isAdmin = false;
/**
* Constructor
* @param globalListener - ActionListener
* @param frame - the JFrame
*/
public ScholarshipController(ActionListener globalListener,JFrame frame) {
super(globalListener, frame);
}
/**
* Start the scholarshipController and switch to ViewAllScholarshipsPanel
* @param isAdmin - boolean
* @param scMap - the HashMap of the scholarships
*/
public void start(boolean isAdmin, HashMap<Integer, Scholarship> scMap) {
this.isAdmin = isAdmin;
this.scMap = scMap;
// Initialize all of the panels
vsp = new ViewScholarshipPanel(this,globalListener,this.isAdmin);
asp = new AllScholarshipsPanel(this,globalListener,this.isAdmin);
esp = new EditScholarshipPanel(this,globalListener);
vsapp = new ViewStudentsAppliedPanel(this, globalListener);
vsacp = new ViewStudentsAcceptedPanel(this, globalListener);
vswp = new ViewStudentsWonPanel(this,globalListener);
// Get the content panes
viewScholarshipPanel = vsp.getContentPane();
allScholarshipsPanel = asp.getContentPane();
editScholarshipPanel = esp.getContentPane();
viewStudentsAppliedPanel = vsapp.getContentPane();
viewStudentsAcceptedPanel = vsacp.getContentPane();
viewStudentsWonPanel = vswp.getContentPane();
// Add all the scholarships to the allScholarshipsPanel
scholarshipLoop(scMap);
// Switch the current JPanel
switchPanel(allScholarshipsPanel);
}
/**
* Set list of students only if admin
* @param students
*/
public void setStudents(List<Student> students) {
this.students=students;
}
/**
* Loop through the list of scholarships and add them to the screen
* @param scMap
*/
public void scholarshipLoop(HashMap<Integer, Scholarship> scMap) {
for(Integer ID: scMap.keySet()) {
Scholarship value = scMap.get(ID);
asp.displayScholarship(value);
}
}
/**
* Find a scholarship by its name
* @param name - String
* @return - Scholarship
*/
private void searchForScholarship(String name) {
HashMap<Integer, Scholarship> filteredMap = new HashMap<Integer, Scholarship>();
for(Integer ID: scMap.keySet()) {
//if what the user entered, regardless of case, matches then put it into the filtered map
if(scMap.get(ID).getName().toLowerCase().contains(name.toLowerCase())) {
filteredMap.put(ID,scMap.get(ID));
}
}
asp.resetScholarships();
//display the filtered matches in a new panel
scholarshipLoop(filteredMap);
switchPanel(allScholarshipsPanel);
}
/**
* Switch the JPaenl to the ViewScholarshipPanel
* @param scholarship - the scholarship to view
*/
public void switchToViewScholarshipPanel(Scholarship scholarship) {
// Display the scholarship
vsp.displayScholarship(scholarship);
// IF the current user is an admin display all students that have applied
switchPanel(viewScholarshipPanel);
}
private void switchToViewStudentsAppliedPanel(Scholarship scholar) {
vsapp.resetStudents();
vsapp.setScholarship(currentScholarship);
for(Student s: students) {
if(scholar.getStudentsApplied().contains(s.getUCID())) {
vsapp.addStudent(s);
}
}
switchPanel(viewStudentsAppliedPanel);
}
private void switchToViewStudentsAcceptedPanel(Scholarship scholar) {
vsacp.resetStudents();
vsacp.setScholarship(currentScholarship);
for(Student s: students) {
if(scholar.getStudentsAccepted().contains(s.getUCID())) {
vsacp.addStudent(s);
}
}
switchPanel(viewStudentsAcceptedPanel);
}
private void switchToViewStudentsWonPanel(Scholarship scholar) {
vswp.resetStudents();
vswp.setScholarship(currentScholarship);
for(Student s: students) {
if(scholar.getStudentsWon().contains(s.getUCID())) {
vswp.addStudent(s);
}
}
switchPanel(viewStudentsWonPanel);
}
/**
* Get edit panel
* Used to get the info for editing a panel
* @return - JPanel
*/
public EditScholarshipPanel getEdits() {
return esp;
}
/**
* ALl buttons presses in the dispalyScholarship Package that have been given the packageListener actionListener
*/
@Override
public void actionPerformed(ActionEvent e) {
// Get the name of the button that was pressed
JButton source = (JButton)e.getSource();
String name = source.getName();
switch(name){
case"ViewScholarship_AllScholarshipsPanel":
// Get the id of the scholarship to view
int id = Integer.parseInt(source.getActionCommand());
// Find the scholarship
currentScholarship = scMap.get(id);
switchToViewScholarshipPanel(currentScholarship);
break;
case"Back_ViewScholarshipPanel":
switchPanel(allScholarshipsPanel);
break;
case"Back_EditScholarshipPanel":
switchPanel(allScholarshipsPanel);
break;
case "EditScholarship_ViewScholarshipPanel":
esp.setScholarship(currentScholarship);
// Switch the panel
switchPanel(editScholarshipPanel);
break;
case "ViewStudentsApplied_ViewScholarshipPanel":
switchToViewStudentsAppliedPanel(currentScholarship);
break;
case "ViewStudentsAccepted_ViewScholarshipPanel":
switchToViewStudentsAcceptedPanel(currentScholarship);
break;
case "ViewStudentsWon_ViewScholarshipPanel":
switchToViewStudentsWonPanel(currentScholarship);
break;
case "Back_ViewStudentsAppliedPanel":
switchPanel(viewScholarshipPanel);
break;
case "Back_ViewStudentsWonPanel":
switchPanel(viewScholarshipPanel);
break;
case "Back_ViewStudentsAcceptedPanel":
switchPanel(viewScholarshipPanel);
break;
case"Search_AllScholarshipsPanel":
// Get the text of the search bar
String x = asp.getSearchResult();
// Search for scholarships with the search string and display only those on the page
searchForScholarship(x);
break;
default:
break;
}
}
}
| 28.644628 | 114 | 0.75202 |
886fd5f771f282bc7df4dc0830f5742392bb235f
| 980 |
package com.umutburdur.urlshortener.core;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpStatus;
@Getter
@Setter
public class UrlShortenerResponseHolder<T> {
@JsonInclude(JsonInclude.Include.NON_NULL)
private T responseData;
@JsonInclude(JsonInclude.Include.NON_NULL)
private HttpStatus httpStatus;
@JsonInclude(JsonInclude.Include.NON_NULL)
private UrlShortenerResponseError error;
public UrlShortenerResponseHolder(HttpStatus httpStatus) {
this.httpStatus = httpStatus;
}
public UrlShortenerResponseHolder(T responseData, HttpStatus httpStatus) {
this.responseData = responseData;
this.httpStatus = httpStatus;
}
public UrlShortenerResponseHolder(HttpStatus httpStatus,
UrlShortenerResponseError error) {
this.httpStatus = httpStatus;
this.error = error;
}
}
| 28 | 78 | 0.728571 |
48dba380ef314e35a59c58aa343b6bfa4c4f2c5e
| 616 |
package io.simplesource.saga.model.specs;
import io.simplesource.saga.model.serdes.SagaClientSerdes;
import lombok.Value;
/**
* Represents the details required to create a saga client instance
*
* @param <A> a representation of an action command that is shared across all actions in the saga. This is typically a generic type, such as Json, or if using Avro serialization, SpecificRecord or GenericRecord
*/
@Value(staticConstructor = "of")
public class SagaClientSpec<A> {
/**
* The serdes required for all the saga request and response topics.
*/
public final SagaClientSerdes<A> serdes;
}
| 34.222222 | 210 | 0.751623 |
8834cbcb22745a388ebe886ebcddae032140128a
| 2,458 |
package io.github.cweijan.mock.jupiter.inject;
import io.github.cweijan.mock.jupiter.MockInstanceContext;
import io.github.cweijan.mock.jupiter.environment.BootEnvironmentReader;
import org.springframework.beans.TypeConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanExpressionContext;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.convert.ApplicationConversionService;
import org.springframework.context.expression.StandardBeanExpressionResolver;
import org.springframework.util.PropertyPlaceholderHelper;
import java.lang.reflect.Field;
/**
* Value anntaion resolver.
* @author cweijan
* @since 2020/06/04 16:20
*/
public class ValueFieldResolver implements FieldResolver {
private final PropertyPlaceholderHelper propertyPlaceholderHelper;
private final BootEnvironmentReader bootwEnvironmentReader;
private final StandardBeanExpressionResolver standardBeanExpressionResolver;
private TypeConverter typeConverter;
private BeanExpressionContext beanExpressionContext;
public ValueFieldResolver(MockInstanceContext mockInstanceContext) {
this.standardBeanExpressionResolver = new StandardBeanExpressionResolver();
this.bootwEnvironmentReader = mockInstanceContext.getBootwEnvironmentReader();
this.propertyPlaceholderHelper = new PropertyPlaceholderHelper("${", "}", ":", true);
initConverter();
}
private void initConverter() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.setConversionService(ApplicationConversionService.getSharedInstance());
this.typeConverter = beanFactory.getTypeConverter();
this.beanExpressionContext=new BeanExpressionContext(beanFactory,null);
}
@Override
public Object resolve(Field field) {
Value value = field.getDeclaredAnnotation(Value.class);
if (value != null) {
String resolvedText = propertyPlaceholderHelper.replacePlaceholders(value.value(), bootwEnvironmentReader::get);
Object execute = execute(resolvedText);
return typeConverter.convertIfNecessary(execute, field.getType(), field);
}
return null;
}
private Object execute(String expression) {
return standardBeanExpressionResolver.evaluate(expression, beanExpressionContext);
}
}
| 42.37931 | 124 | 0.780309 |
89443ea7d487a84b4e71e22138f2c87f7d8cfdaf
| 913 |
package com.cwjcsu.projecteuler.p1_50;
import java.util.ArrayList;
public class Problem23 {
public static boolean isAbundant(int n) {
int sum = 0;
for (int i = 1; i < n; i++) {
if (n % i == 0) {
sum += i;
}
}
if (sum > n) {
return true;
}
return false;
}
public static void main(String[] args) {
int result = 0;
int[] numbers = new int[28123];
ArrayList abundants = new ArrayList();
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i + 1;
result += numbers[i];
if (isAbundant(numbers[i])) {
abundants.add(numbers[i]);
}
}
for (int i = 0; i < abundants.size(); i++) {
for (int j = i; j < abundants.size(); j++) {
int index = (Integer) abundants.get(i)
+ (Integer) abundants.get(j) - 1;
if (index < numbers.length) {
result -= numbers[index];
numbers[index] = 0;
}
}
}
System.out.println(result);
}
}
| 17.557692 | 47 | 0.557503 |
a81b39b06ed936198959b87340b0f972ff5e4761
| 409 |
// automatically generated by the FlatBuffers compiler, do not modify
import java.nio.*;
import java.lang.*;
import java.util.*;
import com.google.flatbuffers.*;
public class TableAT {
private MyGame.OtherNameSpace.TableBT b;
public MyGame.OtherNameSpace.TableBT getB() { return b; }
public void setB(MyGame.OtherNameSpace.TableBT b) { this.b = b; }
public TableAT() {
this.b = null;
}
}
| 19.47619 | 69 | 0.711491 |
1c5a159175f5a640680b4e5d3b7e562dcd66ad21
| 2,500 |
/**
* 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.jena.commonsrdf.impl;
import java.util.Objects;
import java.util.Optional;
import org.apache.commons.rdf.api.IRI;
import org.apache.commons.rdf.api.Literal;
import org.apache.jena.graph.Node;
public class JCR_Literal extends JCR_Term implements Literal {
/*package*/ JCR_Literal(Node node) {
super(node);
}
@Override
public String getLexicalForm() {
return getNode().getLiteralLexicalForm();
}
@Override
public IRI getDatatype() {
return JCR_Factory.createIRI(getNode().getLiteralDatatype().getURI());
}
@Override
public Optional<String> getLanguageTag() {
String x = getNode().getLiteralLanguage();
if ( x == null || x.isEmpty() )
return Optional.empty();
return Optional.of(x);
}
@Override
public int hashCode() {
return Objects.hash(getLexicalForm(), getDatatype(), getLanguageTag());
}
private static boolean equalsIgnoreCase(Optional<String> s1, Optional<String> s2) {
if ( Objects.equals(s1, s2) )
return true;
if ( ! s1.isPresent() || ! s2.isPresent() )
return false;
return s1.get().equalsIgnoreCase(s2.get());
}
@Override
public boolean equals(Object other) {
if ( other == this ) return true;
if ( other == null ) return false;
if ( ! ( other instanceof Literal ) ) return false;
Literal literal = (Literal)other;
return getLexicalForm().equals(literal.getLexicalForm()) &&
equalsIgnoreCase(getLanguageTag(), literal.getLanguageTag()) &&
getDatatype().equals(literal.getDatatype());
}
}
| 32.467532 | 87 | 0.666 |
11ef08ca270219edc9dcecf0f44a675523decd5e
| 2,882 |
package LeetCode;
/*
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
示例:
s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".
*/
public class Solution394 {
public String decodeString(String s) {
StringBuilder stringBuilder = new StringBuilder();
StringBuilder stringBuilderTemp = new StringBuilder();
int time = 0, repetition = 0;
for (char ch : s.toCharArray()) {
if (ch > '0' && ch <= '9') {
time = time *10 + (ch - '0');
if (stringBuilderTemp.length() != 0) {
stringBuilder.append(stringBuilderTemp);
stringBuilderTemp.setLength(0);
}
} else if (ch == '[') {
repetition = time;
stringBuilderTemp.setLength(0);
time = 0;
} else if (ch == ']') {
for (int i = 0; i < repetition; i ++) {
stringBuilder.append(stringBuilderTemp);
}
stringBuilderTemp.setLength(0);
} else {
stringBuilderTemp.append(ch);
}
}
return stringBuilder.toString();
}
}
class Solution394_ {
public String decodeString(String s) {
StringBuilder stringBuilder = new StringBuilder();
StringBuilder stringBuilderTemp = new StringBuilder();
int time = 0, repetition = 0;
for (char ch : s.toCharArray()) {
if (ch > '0' && ch <= '9') {
time = time *10 + (ch - '0');
if (stringBuilderTemp.length() != 0) {
stringBuilder.append(stringBuilderTemp);
stringBuilderTemp.setLength(0);
}
} else if (ch == '[') {
repetition = time;
stringBuilderTemp.setLength(0);
time = 0;
} else if (ch == ']') {
for (int i = 0; i < repetition; i ++) {
stringBuilder.append(stringBuilderTemp);
}
stringBuilderTemp.setLength(0);
} else {
stringBuilderTemp.append(ch);
}
}
return stringBuilder.toString();
}
public StringBuilder SolveFunction(String string) {
int time = 0;
StringBuilder stringBuilder = new StringBuilder();
for (char ch : string.toCharArray()) {
if (ch > '0' && ch <= '9') {
time = time * 10 + (ch - '0');
continue;
}
}
return stringBuilder;
}
}
| 33.126437 | 73 | 0.482651 |
5e8f8ce349984adc62d07520b7fc7e9ecd14f4c2
| 7,262 |
package jhaturanga.model.match.online;
import java.util.Optional;
import java.util.Set;
import org.eclipse.paho.client.mqttv3.MqttException;
import jhaturanga.model.board.Board;
import jhaturanga.model.board.BoardPosition;
import jhaturanga.model.game.Game;
import jhaturanga.model.game.type.GameType;
import jhaturanga.model.history.History;
import jhaturanga.model.match.Match;
import jhaturanga.model.match.MatchEndType;
import jhaturanga.model.match.MatchImpl;
import jhaturanga.model.match.MatchStatus;
import jhaturanga.model.match.online.network.MqttNetworkMatchManager;
import jhaturanga.model.match.online.network.NetworkMatchData;
import jhaturanga.model.match.online.network.NetworkMatchManager;
import jhaturanga.model.movement.BasicMovement;
import jhaturanga.model.movement.MovementResult;
import jhaturanga.model.movement.PieceMovement;
import jhaturanga.model.movement.PieceMovementImpl;
import jhaturanga.model.piece.Piece;
import jhaturanga.model.player.Player;
import jhaturanga.model.player.PlayerColor;
import jhaturanga.model.player.PlayerImpl;
import jhaturanga.model.player.pair.PlayerPair;
import jhaturanga.model.player.pair.PlayerPairImpl;
import jhaturanga.model.timer.DefaultTimers;
import jhaturanga.model.timer.Timer;
import jhaturanga.model.user.User;
public final class OnlineMatchImpl implements OnlineMatch {
private final NetworkMatchManager network;
private String matchID;
private final User localUser;
private Player localPlayer;
private Player otherPlayer;
private NetworkMatchData data;
private final Runnable onReady;
private Runnable onResign;
private MovementHandler onMovementHandler;
private Match match;
private final DefaultTimers timer = DefaultTimers.NO_LIMIT;
/**
* Setup a NetworkMatch.
*
* @param user - the user
* @param onReady - the callback to call when the game is ready
* @throws MqttException
*/
public OnlineMatchImpl(final User user, final Runnable onReady) throws MqttException {
this.localUser = user;
this.onReady = onReady;
this.network = new MqttNetworkMatchManager(this::onMovement, this::onResignHandler);
}
/**
* {@inheritDoc}
*/
@Override
public void setOnMovementHandler(final MovementHandler onMovementHandler) {
this.onMovementHandler = onMovementHandler;
}
/**
* {@inheritDoc}
*/
@Override
public void exit() {
this.network.disconnect();
}
/**
* {@inheritDoc}
*/
@Override
public void join(final String matchID) {
// For now the player which join is the black player.
this.localPlayer = new PlayerImpl(PlayerColor.BLACK, this.localUser);
this.matchID = matchID;
this.network.joinMatch(matchID, this.localPlayer, this::onDataReceived);
}
/**
* {@inheritDoc}
*/
@Override
public String create(final GameType gameType) {
// For now the player which create is the white player.
this.localPlayer = new PlayerImpl(PlayerColor.WHITE, this.localUser);
this.data = new NetworkMatchData(gameType, this.timer, this.localPlayer);
this.matchID = this.network.createMatch(this.data, this::onUserJoined);
return this.matchID;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isWhitePlayer() {
return Optional.ofNullable(this.localPlayer).map(x -> x.getColor().equals(PlayerColor.WHITE)).orElse(false);
}
private void onDataReceived() {
this.data = this.network.getMatchData();
this.otherPlayer = this.data.getPlayer();
final PlayerPair players = new PlayerPairImpl(this.otherPlayer, this.localPlayer);
this.match = new MatchImpl(this.data.getGameType().getGameInstance(players),
this.data.getTimer().getTimer(players));
Optional.ofNullable(this.onReady).ifPresent(Runnable::run);
}
private void onUserJoined() {
this.otherPlayer = this.network.getJoinedPlayer();
final PlayerPair players = new PlayerPairImpl(this.localPlayer, this.otherPlayer);
this.match = new MatchImpl(this.data.getGameType().getGameInstance(players),
this.data.getTimer().getTimer(players));
Optional.ofNullable(this.onReady).ifPresent(Runnable::run);
}
private void onMovement(final BasicMovement movement) {
final PieceMovement realMovement = new PieceMovementImpl(
this.getBoard().getPieceAtPosition(movement.getOrigin()).get(), movement.getDestination());
final MovementResult res = this.match.move(realMovement);
if (!res.equals(MovementResult.INVALID_MOVE)) {
Optional.ofNullable(this.onMovementHandler).ifPresent(x -> x.handleMovement(realMovement, res));
}
}
/**
* {@inheritDoc}
*/
@Override
public void setOnResign(final Runnable onResign) {
this.onResign = onResign;
}
private void onResignHandler() {
this.match.resign(this.otherPlayer);
Optional.ofNullable(this.onResign).ifPresent(Runnable::run);
}
/**
* {@inheritDoc}
*/
@Override
public MovementResult move(final PieceMovement movement) {
final MovementResult res = this.match.move(movement);
if (!res.equals(MovementResult.INVALID_MOVE)) {
this.network.sendMove(movement);
}
return res;
}
/**
* {@inheritDoc}
*/
@Override
public String getMatchID() {
return this.matchID;
}
/**
* {@inheritDoc}
*/
@Override
public PlayerPair getPlayers() {
return this.match.getPlayers();
}
/**
* {@inheritDoc}
*/
@Override
public Game getGame() {
return this.match.getGame();
}
/**
* {@inheritDoc}
*/
@Override
public Timer getTimer() {
return this.match.getTimer();
}
/**
* {@inheritDoc}
*/
@Override
public History getHistory() {
return this.match.getHistory();
}
/**
* {@inheritDoc}
*/
@Override
public Board getBoard() {
return this.match.getBoard();
}
/**
* {@inheritDoc}
*/
@Override
public void start() {
this.match.start();
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Player> getWinner() {
return this.match.getWinner();
}
/**
* {@inheritDoc}
*/
@Override
public Set<BoardPosition> getPiecePossibleMoves(final Piece piece) {
return this.match.getPiecePossibleMoves(piece);
}
/**
* {@inheritDoc}
*/
@Override
public MatchStatus getMatchStatus() {
return this.match.getMatchStatus();
}
/**
* {@inheritDoc}
*/
@Override
public Optional<MatchEndType> getEndType() {
return this.match.getEndType();
}
/**
* {@inheritDoc}
*/
@Override
public void resign(final Player player) {
this.network.sendResign();
this.match.resign(player);
}
/**
* {@inheritDoc}
*/
@Override
public Player getLocalPlayer() {
return this.localPlayer;
}
}
| 26.896296 | 116 | 0.655467 |
0197453d21e8cc0021d998b460a8d617dfbd6dba
| 230 |
package com.nazmul.ftp.common.exception;
public class InvalidArgException extends DatagramException {
private static final long serialVersionUID = 1L;
public InvalidArgException(String message) {
super(message);
}
}
| 19.166667 | 60 | 0.773913 |
b7142b42369b28a7561f06646dd4ec0570e2b540
| 2,975 |
package userinterface;
import java.util.List;
import java.util.Arrays;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Series;
import algorithm.Measurement;
import algorithm.ToolMeasure;
@SuppressWarnings("unused")
public class Coordinatesystem {
// @SupressWarnings({"unchecked", "rawtypes"})
/*
* The individual parameters from the class Diagramm (drawAchsen is called
* there) are transferred to the method. "Choice" defines which level is to
* be selected and shown.The individual x, y and z values are transferred
* from the list "List<Measurement>". The chart series and the axes are also
* handed over.
*/
public static void drawAchsen(String choice, List<Measurement> l, XYChart.Series s, NumberAxis xAxis,
NumberAxis yAxis) {
// Create variables from type double x,y and z //
double x;
double y;
double z;
/*
* Selection is transferred
*
*/
switch (choice) {
/*
* If "xy" is passed, the axes for the x-y-plane will be drawn and the
* values transferred.
*/
case "xy":
xAxis.setLabel("X-axis");
yAxis.setLabel("Y-axis");
/*
* The loop goes through the list and gets all values. With the
* getPoint method, the x-value and y-value are explicitly picked
* from the list
*
*/
for (int i = 0, j = 1; i < l.size() && j < l.size(); i += 3, j += 3) {
x = l.get(i).getPoint().getX();
// System.out.println(x);
y = l.get(i).getPoint().getY();
s.getData().add(new XYChart.Data(x, y));
// new Thread(() -> {
// while (!Thread.currentThread().isInterrupted())
//
// //repaint();
// s.getChart().getData().clear();
// s.getChart().getData().addAll();
//
//
// try {
// Thread.sleep(500);
// } catch (InterruptedException ex) {
// Thread.currentThread().interrupt();
// //break;
// }
// }
// //}
// ).start();
}
/*
* Program takes a break here and then it goes on with the next case
*/
break;
case "xz":
xAxis.setLabel("X-axis");
yAxis.setLabel("Z-axis");
/*
* The loop goes through the list and gets all values. With the
* getPoint method, the x-value and z-value are explicitly picked
* from the list
*/
for (int i = 0, j = 2; i < l.size() && j < l.size(); i += 3, j += 3) {
x = l.get(i).getPoint().getX();
z = l.get(i).getPoint().getZ();
// System.out.println(x);
s.getData().add(new XYChart.Data(x, z));
}
break;
case "zy":
/*
* Set label for the axes
*/
xAxis.setLabel("Z-axis");
yAxis.setLabel("Y-axis");
for (int i =2 , j = 1; i < l.size() && j < l.size(); i += 3, j += 3) {
z = l.get(i).getPoint().getZ();
y = l.get(i).getPoint().getY();
// System.out.println(y);
/*
* The chart is drawn on the series with the axes z and y
*/
s.getData().add(new XYChart.Data(z, y));
}
break;
}
}
}
| 23.242188 | 102 | 0.588908 |
518dd5b9f4177fdf6619f2fbaf59c2090744f758
| 348 |
package mage.interfaces.plugin;
import mage.interfaces.PluginException;
import net.xeoh.plugins.base.Plugin;
/**
* Interface for counter plugins
*
* @version 0.1 14.112010
* @author nantuko
*/
public interface CounterPlugin extends Plugin {
void addGamePlayed() throws PluginException;
int getGamePlayed() throws PluginException;
}
| 21.75 | 48 | 0.758621 |
f7eb9b62c48c0e55c642279800c68a9f481cc95d
| 883 |
package de.hpi.datastreams.messages;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import de.hpi.datastreams.serialization.JSONSerdeCompatible;
import lombok.Getter;
import lombok.Setter;
import java.util.HashMap;
import java.util.Map;
public class LabeledData implements JSONSerdeCompatible {
@JsonProperty("label")
@Getter
@Setter
Integer label;
@JsonProperty("inputData")
@Getter
@Setter
Map<Integer, Float> inputData = new HashMap<>();
@JsonCreator
public LabeledData(@JsonProperty("inputData") Map<Integer, Float> inputData, @JsonProperty("label") Integer label) {
this.inputData = inputData;
this.label = label;
}
@Override
public String toString() {
return String.format("LabeledData(%s, %d)", inputData.toString(), label);
}
}
| 25.228571 | 120 | 0.713477 |
c8f01642b6aa8cfd1467f9f0642ae5594a341e43
| 315 |
package pl.dicedev.kakebo.security.exceptions;
import static pl.dicedev.kakebo.security.exceptions.ExceptionMessages.INCORRECT_USER_OR_PASSWORD;
public class BadKakeboCredentialsException extends RuntimeException {
public BadKakeboCredentialsException() {
super(INCORRECT_USER_OR_PASSWORD);
}
}
| 26.25 | 97 | 0.815873 |
1c6946d328d065eeba7b179aee1d602bc3ff044b
| 2,878 |
package org.jesperancinha.std.flash19.transactional.services;
import org.jesperancinha.std.flash19.transactional.converters.AlbumConverter;
import org.jesperancinha.std.flash19.transactional.domain.Album;
import org.jesperancinha.std.flash19.transactional.dto.AlbumDto;
import org.jesperancinha.std.flash19.transactional.repos.AlbumRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.Collectors;
import static org.jesperancinha.console.consolerizer.common.ConsolerizerColor.RED;
import static org.springframework.transaction.annotation.Propagation.REQUIRES_NEW;
@Service
public class AlbumServiceImpl implements AlbumService {
private final AlbumRepository albumRepository;
private Album lastTry;
public AlbumServiceImpl(AlbumRepository albumRepository) {
this.albumRepository = albumRepository;
}
/**
* Creates the album
*
* @param album {@link Album}
* @return The created album {@link Album}
*/
private Album createAlbum(Album album) {
return albumRepository.save(album);
}
/**
* Removes an album by its Id
*
* @param id {@link Long}
* @return True if album has been deleted
*/
@Override
public boolean deleteAlbumByIdI(Long id) {
albumRepository.deleteById(id);
return true;
}
/**
* Updates the album that has already been created
*
* @param album {@link Album}
* @return Updated album {@link Album}
*/
@Override
public AlbumDto updateAlbum(AlbumDto album) {
return AlbumConverter.toDto(albumRepository.save(AlbumConverter.toData(album)));
}
@Override
public AlbumDto createAlbum(String name, String artist, String publisher, Long year) {
final var album = new Album();
album.setName(name);
album.setArtist(artist);
album.setPublisher(publisher);
album.setYear(year);
return AlbumConverter.toDto(createAlbum(album));
}
@Override
@Transactional(propagation = REQUIRES_NEW,
rollbackFor = RuntimeException.class)
public AlbumDto createAlbumRollBack(String name, String artist, String publisher, Long year) {
final var album = new Album();
album.setName(name);
album.setArtist(artist);
album.setPublisher(publisher);
album.setYear(year);
createAlbum(album);
this.lastTry = album;
throw new RuntimeException(RED.getPBText("Your album %s was not saved!", album));
}
@Override
public List<AlbumDto> getAllAlbums() {
return this.albumRepository.findAll().stream().map(AlbumConverter::toDto).collect(Collectors.toList());
}
@Override
public Album getLastTry() {
return lastTry;
}
}
| 30.294737 | 111 | 0.694927 |
6c1ac98d2b5f0636a4b4571aa38ba62fb54f5d86
| 410 |
package org.researchsuite.omhclient.Exception;
import org.json.JSONObject;
/**
* Created by jameskizer on 2/5/17.
*/
public class OMHClientMalformedResponse extends OMHClientException {
private String responseBody;
public OMHClientMalformedResponse(String responseBody) {
this.responseBody = responseBody;
}
public String getResponseBody() {
return responseBody;
}
}
| 20.5 | 68 | 0.729268 |
760f3efefa76cd1f6beee9b3adc9d389c3a13adf
| 10,852 |
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.irobot.home.model;
import android.os.Parcel;
import android.os.Parcelable;
// Referenced classes of package com.irobot.home.model:
// y
public class WifiConfig
implements Parcelable
{
public WifiConfig()
{
// 0 0:aload_0
// 1 1:invokespecial #33 <Method void Object()>
// 2 4:return
}
public WifiConfig(Parcel parcel)
{
// 0 0:aload_0
// 1 1:invokespecial #33 <Method void Object()>
a = parcel.readString();
// 2 4:aload_0
// 3 5:aload_1
// 4 6:invokevirtual #40 <Method String Parcel.readString()>
// 5 9:putfield #42 <Field String a>
c = parcel.readString();
// 6 12:aload_0
// 7 13:aload_1
// 8 14:invokevirtual #40 <Method String Parcel.readString()>
// 9 17:putfield #44 <Field String c>
b = (y)parcel.readSerializable();
// 10 20:aload_0
// 11 21:aload_1
// 12 22:invokevirtual #48 <Method java.io.Serializable Parcel.readSerializable()>
// 13 25:checkcast #50 <Class y>
// 14 28:putfield #52 <Field y b>
d = parcel.readInt();
// 15 31:aload_0
// 16 32:aload_1
// 17 33:invokevirtual #56 <Method int Parcel.readInt()>
// 18 36:putfield #58 <Field int d>
e = parcel.readLong();
// 19 39:aload_0
// 20 40:aload_1
// 21 41:invokevirtual #62 <Method long Parcel.readLong()>
// 22 44:putfield #64 <Field long e>
f = parcel.readLong();
// 23 47:aload_0
// 24 48:aload_1
// 25 49:invokevirtual #62 <Method long Parcel.readLong()>
// 26 52:putfield #66 <Field long f>
g = parcel.readLong();
// 27 55:aload_0
// 28 56:aload_1
// 29 57:invokevirtual #62 <Method long Parcel.readLong()>
// 30 60:putfield #68 <Field long g>
h = parcel.readLong();
// 31 63:aload_0
// 32 64:aload_1
// 33 65:invokevirtual #62 <Method long Parcel.readLong()>
// 34 68:putfield #70 <Field long h>
i = parcel.readLong();
// 35 71:aload_0
// 36 72:aload_1
// 37 73:invokevirtual #62 <Method long Parcel.readLong()>
// 38 76:putfield #72 <Field long i>
// 39 79:return
}
public WifiConfig(String s, y y1, String s1, int j, long l, long l1, long l2, long l3, long l4)
{
// 0 0:aload_0
// 1 1:invokespecial #33 <Method void Object()>
a = s;
// 2 4:aload_0
// 3 5:aload_1
// 4 6:putfield #42 <Field String a>
b = y1;
// 5 9:aload_0
// 6 10:aload_2
// 7 11:putfield #52 <Field y b>
c = s1;
// 8 14:aload_0
// 9 15:aload_3
// 10 16:putfield #44 <Field String c>
d = j;
// 11 19:aload_0
// 12 20:iload 4
// 13 22:putfield #58 <Field int d>
e = l;
// 14 25:aload_0
// 15 26:lload 5
// 16 28:putfield #64 <Field long e>
f = l1;
// 17 31:aload_0
// 18 32:lload 7
// 19 34:putfield #66 <Field long f>
g = l2;
// 20 37:aload_0
// 21 38:lload 9
// 22 40:putfield #68 <Field long g>
h = l3;
// 23 43:aload_0
// 24 44:lload 11
// 25 46:putfield #70 <Field long h>
i = l4;
// 26 49:aload_0
// 27 50:lload 13
// 28 52:putfield #72 <Field long i>
// 29 55:return
}
public void a(int j)
{
d = j;
// 0 0:aload_0
// 1 1:iload_1
// 2 2:putfield #58 <Field int d>
// 3 5:return
}
public void a(y y1)
{
b = y1;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #52 <Field y b>
// 3 5:return
}
public void a(String s)
{
a = s;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #42 <Field String a>
// 3 5:return
}
public boolean a()
{
return d == 1;
// 0 0:aload_0
// 1 1:getfield #58 <Field int d>
// 2 4:iconst_1
// 3 5:icmpne 10
// 4 8:iconst_1
// 5 9:ireturn
// 6 10:iconst_0
// 7 11:ireturn
}
public String b()
{
return a;
// 0 0:aload_0
// 1 1:getfield #42 <Field String a>
// 2 4:areturn
}
public void b(int j)
{
e = j;
// 0 0:aload_0
// 1 1:iload_1
// 2 2:i2l
// 3 3:putfield #64 <Field long e>
// 4 6:return
}
public void b(String s)
{
c = s;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #44 <Field String c>
// 3 5:return
}
public y c()
{
return b;
// 0 0:aload_0
// 1 1:getfield #52 <Field y b>
// 2 4:areturn
}
public void c(int j)
{
f = j;
// 0 0:aload_0
// 1 1:iload_1
// 2 2:i2l
// 3 3:putfield #66 <Field long f>
// 4 6:return
}
public String d()
{
return c;
// 0 0:aload_0
// 1 1:getfield #44 <Field String c>
// 2 4:areturn
}
public void d(int j)
{
g = j;
// 0 0:aload_0
// 1 1:iload_1
// 2 2:i2l
// 3 3:putfield #68 <Field long g>
// 4 6:return
}
public int describeContents()
{
return 0;
// 0 0:iconst_0
// 1 1:ireturn
}
public long e()
{
return e;
// 0 0:aload_0
// 1 1:getfield #64 <Field long e>
// 2 4:lreturn
}
public void e(int j)
{
h = j;
// 0 0:aload_0
// 1 1:iload_1
// 2 2:i2l
// 3 3:putfield #70 <Field long h>
// 4 6:return
}
public long f()
{
return f;
// 0 0:aload_0
// 1 1:getfield #66 <Field long f>
// 2 4:lreturn
}
public void f(int j)
{
i = j;
// 0 0:aload_0
// 1 1:iload_1
// 2 2:i2l
// 3 3:putfield #72 <Field long i>
// 4 6:return
}
public long g()
{
return g;
// 0 0:aload_0
// 1 1:getfield #68 <Field long g>
// 2 4:lreturn
}
public long h()
{
return h;
// 0 0:aload_0
// 1 1:getfield #70 <Field long h>
// 2 4:lreturn
}
public long i()
{
return i;
// 0 0:aload_0
// 1 1:getfield #72 <Field long i>
// 2 4:lreturn
}
public void writeToParcel(Parcel parcel, int j)
{
parcel.writeString(a);
// 0 0:aload_1
// 1 1:aload_0
// 2 2:getfield #42 <Field String a>
// 3 5:invokevirtual #84 <Method void Parcel.writeString(String)>
parcel.writeString(c);
// 4 8:aload_1
// 5 9:aload_0
// 6 10:getfield #44 <Field String c>
// 7 13:invokevirtual #84 <Method void Parcel.writeString(String)>
parcel.writeSerializable(((java.io.Serializable) (b)));
// 8 16:aload_1
// 9 17:aload_0
// 10 18:getfield #52 <Field y b>
// 11 21:invokevirtual #88 <Method void Parcel.writeSerializable(java.io.Serializable)>
parcel.writeInt(d);
// 12 24:aload_1
// 13 25:aload_0
// 14 26:getfield #58 <Field int d>
// 15 29:invokevirtual #91 <Method void Parcel.writeInt(int)>
parcel.writeLong(e);
// 16 32:aload_1
// 17 33:aload_0
// 18 34:getfield #64 <Field long e>
// 19 37:invokevirtual #95 <Method void Parcel.writeLong(long)>
parcel.writeLong(f);
// 20 40:aload_1
// 21 41:aload_0
// 22 42:getfield #66 <Field long f>
// 23 45:invokevirtual #95 <Method void Parcel.writeLong(long)>
parcel.writeLong(g);
// 24 48:aload_1
// 25 49:aload_0
// 26 50:getfield #68 <Field long g>
// 27 53:invokevirtual #95 <Method void Parcel.writeLong(long)>
parcel.writeLong(h);
// 28 56:aload_1
// 29 57:aload_0
// 30 58:getfield #70 <Field long h>
// 31 61:invokevirtual #95 <Method void Parcel.writeLong(long)>
parcel.writeLong(i);
// 32 64:aload_1
// 33 65:aload_0
// 34 66:getfield #72 <Field long i>
// 35 69:invokevirtual #95 <Method void Parcel.writeLong(long)>
// 36 72:return
}
public static final android.os.Parcelable.Creator CREATOR = new android.os.Parcelable.Creator() {
public WifiConfig a(Parcel parcel)
{
return new WifiConfig(parcel);
// 0 0:new #9 <Class WifiConfig>
// 1 3:dup
// 2 4:aload_1
// 3 5:invokespecial #19 <Method void WifiConfig(Parcel)>
// 4 8:areturn
}
public WifiConfig[] a(int j)
{
return new WifiConfig[j];
// 0 0:iload_1
// 1 1:anewarray WifiConfig[]
// 2 4:areturn
}
public Object createFromParcel(Parcel parcel)
{
return ((Object) (a(parcel)));
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokevirtual #24 <Method WifiConfig a(Parcel)>
// 3 5:areturn
}
public Object[] newArray(int j)
{
return ((Object []) (a(j)));
// 0 0:aload_0
// 1 1:iload_1
// 2 2:invokevirtual #28 <Method WifiConfig[] a(int)>
// 3 5:areturn
}
}
;
private String a;
private y b;
private String c;
private int d;
private long e;
private long f;
private long g;
private long h;
private long i;
static
{
// 0 0:new #8 <Class WifiConfig$1>
// 1 3:dup
// 2 4:invokespecial #29 <Method void WifiConfig$1()>
// 3 7:putstatic #31 <Field android.os.Parcelable$Creator CREATOR>
//* 4 10:return
}
}
| 27.197995 | 98 | 0.464707 |
9f2158e26fee45a0ad632736554d42946a92adf9
| 10,965 |
package org.jivesoftware.spark.ui.login;
import org.jivesoftware.resource.Default;
import org.jivesoftware.resource.Res;
import org.jivesoftware.spark.util.ModelUtil;
import org.jivesoftware.spark.util.ResourceUtils;
import org.jivesoftware.sparkimpl.settings.local.LocalPreferences;
import org.jivesoftware.sparkimpl.settings.local.SettingsManager;
import javax.swing.*;
import java.awt.*;
import java.util.Properties;
import static java.awt.GridBagConstraints.*;
/**
* Internal class to allow setting of proxies within Spark.
*/
class ProxyLoginSettingsPanel extends JPanel
{
private final static Insets DEFAULT_INSETS = new Insets( 5, 5, 5, 5 );
private final LocalPreferences localPreferences;
private final JCheckBox useProxyBox = new JCheckBox();
private final JComboBox<String> protocolBox = new JComboBox<>();
private final JTextField hostField = new JTextField();
private final JTextField portField = new JTextField();
private final JTextField usernameField = new JTextField();
private final JPasswordField passwordField = new JPasswordField();
private final JDialog optionsDialog;
public ProxyLoginSettingsPanel( LocalPreferences localPreferences, JDialog optionsDialog )
{
this.localPreferences = localPreferences;
this.optionsDialog = optionsDialog;
final JLabel protocolLabel = new JLabel();
final JLabel hostLabel = new JLabel();
final JLabel portLabel = new JLabel();
final JLabel usernameLabel = new JLabel();
final JLabel passwordLabel = new JLabel();
protocolBox.addItem( "SOCKS" );
protocolBox.addItem( "HTTP" );
ResourceUtils.resButton( useProxyBox, Res.getString( "checkbox.use.proxy.server" ) );
ResourceUtils.resLabel( protocolLabel, protocolBox, Res.getString( "label.protocol" ) );
ResourceUtils.resLabel( hostLabel, hostField, Res.getString( "label.host" ) );
ResourceUtils.resLabel( portLabel, portField, Res.getString( "label.port" ) );
ResourceUtils.resLabel( usernameLabel, usernameField, Res.getString( "label.username" ) );
ResourceUtils.resLabel( passwordLabel, passwordField, Res.getString( "label.password" ) );
setLayout( new GridBagLayout() );
add( useProxyBox, new GridBagConstraints( 0, 0, 2, 1, 1.0, 0.0, NORTHWEST, NONE, DEFAULT_INSETS, 0, 0 ) );
add( protocolLabel, new GridBagConstraints( 0, 1, 1, 1, 0.0, 0.0, NORTHWEST, NONE, DEFAULT_INSETS, 0, 0 ) );
add( protocolBox, new GridBagConstraints( 1, 1, 1, 1, 1.0, 0.0, NORTHWEST, HORIZONTAL, DEFAULT_INSETS, 0, 0 ) );
add( hostLabel, new GridBagConstraints( 0, 2, 1, 1, 0.0, 0.0, NORTHWEST, NONE, DEFAULT_INSETS, 0, 0 ) );
add( hostField, new GridBagConstraints( 1, 2, 1, 1, 1.0, 0.0, NORTHWEST, HORIZONTAL, DEFAULT_INSETS, 0, 0 ) );
add( portLabel, new GridBagConstraints( 0, 3, 1, 1, 0.0, 0.0, NORTHWEST, NONE, DEFAULT_INSETS, 0, 0 ) );
add( portField, new GridBagConstraints( 1, 3, 1, 1, 1.0, 0.0, NORTHWEST, HORIZONTAL, DEFAULT_INSETS, 0, 0 ) );
add( usernameLabel, new GridBagConstraints( 0, 4, 1, 1, 0.0, 0.0, NORTHWEST, NONE, DEFAULT_INSETS, 0, 0 ) );
add( usernameField, new GridBagConstraints( 1, 4, 1, 1, 1.0, 0.0, NORTHWEST, HORIZONTAL, DEFAULT_INSETS, 0, 0 ) );
add( passwordLabel, new GridBagConstraints( 0, 5, 1, 1, 0.0, 0.0, NORTHWEST, NONE, DEFAULT_INSETS, 0, 0 ) );
add( passwordField, new GridBagConstraints( 1, 5, 1, 1, 1.0, 1.0, NORTHWEST, HORIZONTAL, DEFAULT_INSETS, 0, 0 ) );
useProxyBox.addActionListener( e -> enableFields( useProxyBox.isSelected() ) );
// Check localSettings
if ( localPreferences.isProxyEnabled() )
{
useProxyBox.setSelected( true );
}
enableFields( useProxyBox.isSelected() );
if ( ModelUtil.hasLength( localPreferences.getHost() ) )
{
hostField.setText( localPreferences.getHost() );
}
if ( ModelUtil.hasLength( localPreferences.getPort() ) )
{
portField.setText( localPreferences.getPort() );
}
if ( ModelUtil.hasLength( localPreferences.getProxyPassword() ) )
{
passwordField.setText( localPreferences.getProxyPassword() );
}
if ( ModelUtil.hasLength( localPreferences.getProxyUsername() ) )
{
usernameField.setText( localPreferences.getProxyUsername() );
}
if ( ModelUtil.hasLength( localPreferences.getProtocol() ) )
{
protocolBox.setSelectedItem( localPreferences.getProtocol() );
}
if ( Default.getString( Default.PROXY_PROTOCOL ).length() > 0 )
{
protocolBox.setSelectedItem( Default.getString( Default.PROXY_PROTOCOL ) );
protocolBox.setEnabled( false );
useProxyBox.setSelected( true );
useProxyBox.setVisible( false );
}
if ( Default.getString( Default.PROXY_HOST ).length() > 0 )
{
hostField.setText( Default.getString( Default.PROXY_HOST ) );
hostField.setEnabled( false );
useProxyBox.setSelected( true );
useProxyBox.setVisible( false );
}
if ( Default.getString( Default.PROXY_PORT ).length() > 0 )
{
portField.setText( Default.getString( Default.PROXY_PORT ) );
portField.setEnabled( false );
}
}
/**
* Enables the fields of the proxy panel.
*
* @param enable true if all fields should be enabled, otherwise false.
*/
private void enableFields( boolean enable )
{
Component[] comps = getComponents();
for ( Component comp1 : comps )
{
if ( comp1 instanceof JTextField || comp1 instanceof JComboBox )
{
JComponent comp = (JComponent) comp1;
comp.setEnabled( enable );
}
}
}
/**
* Returns the protocol to use for this proxy.
*
* @return the protocol.
*/
public String getProtocol()
{
return (String) protocolBox.getSelectedItem();
}
/**
* Returns the host to use for this proxy.
*
* @return the host.
*/
public String getHost()
{
return hostField.getText();
}
/**
* Returns the port to use with this proxy.
*
* @return the port to use.
*/
public String getPort()
{
return portField.getText();
}
/**
* Returns the username to use with this proxy.
*
* @return the username.
*/
public String getUsername()
{
return usernameField.getText();
}
/**
* Returns the password to use with this proxy.
*
* @return the password.
*/
public String getPassword()
{
return new String( passwordField.getPassword() );
}
public boolean validate_settings()
{
boolean valid = true;
UIManager.put( "OptionPane.okButtonText", Res.getString( "ok" ) );
if ( useProxyBox.isSelected() )
{
try
{
Integer.valueOf( portField.getText() );
}
catch ( NumberFormatException numberFormatException )
{
JOptionPane.showMessageDialog( optionsDialog,
Res.getString( "message.supply.valid.port" ),
Res.getString( "title.error" ),
JOptionPane.ERROR_MESSAGE );
portField.requestFocus();
valid = false;
}
if ( !ModelUtil.hasLength( hostField.getText() ) )
{
JOptionPane.showMessageDialog( optionsDialog,
Res.getString( "message.supply.valid.host" ),
Res.getString( "title.error" ),
JOptionPane.ERROR_MESSAGE );
hostField.requestFocus();
valid = false;
}
}
return valid;
}
public void useDefault() {
useProxyBox.setSelected(Default.getBoolean(Default.PROXY_ENABLED));
enableFields(useProxyBox.isSelected());
}
/**
* Persist the proxy settings to local preferences.
*/
public void saveSettings()
{
localPreferences.setProxyEnabled( useProxyBox.isSelected() );
if ( ModelUtil.hasLength( getProtocol() ) )
{
localPreferences.setProtocol( getProtocol() );
}
if ( ModelUtil.hasLength( getHost() ) )
{
localPreferences.setHost( getHost() );
}
if ( ModelUtil.hasLength( getPort() ) )
{
localPreferences.setPort( getPort() );
}
if ( getUsername().equals( "" ) || getUsername() == null )
{
localPreferences.setProxyUsername( "" );
}
if ( ModelUtil.hasLength( getUsername() ) )
{
localPreferences.setProxyUsername( getUsername() );
}
if ( getPassword().equals( "" ) || getPassword() == null )
{
localPreferences.setProxyPassword( "" );
}
if ( ModelUtil.hasLength( getPassword() ) )
{
localPreferences.setProxyPassword( getPassword() );
}
if ( !localPreferences.isProxyEnabled() )
{
Properties props = System.getProperties();
props.remove( "socksProxyHost" );
props.remove( "socksProxyPort" );
props.remove( "http.proxyHost" );
props.remove( "http.proxyPort" );
props.remove( "http.proxySet" );
}
else
{
String host = localPreferences.getHost();
String port = localPreferences.getPort();
String protocol = localPreferences.getProtocol();
boolean isValid = ModelUtil.hasLength( host ) && ModelUtil.hasLength( port );
if ( isValid )
{
if ( protocol.equals( "SOCKS" ) )
{
System.setProperty( "socksProxyHost", host );
System.setProperty( "socksProxyPort", port );
}
else
{
System.setProperty( "http.proxySet", "true" );
// Set https settings
System.setProperty( "https.proxyHost", host );
System.setProperty( "https.proxyPort", port );
// Set http settings
System.setProperty( "http.proxyHost", host );
System.setProperty( "http.proxyPort", port );
}
}
else
{
localPreferences.setProxyEnabled( false );
}
}
SettingsManager.saveSettings();
}
}
| 34.699367 | 122 | 0.578842 |
bd7e0ad27a13686ead22f210e136741cc6b4c666
| 6,215 |
package com.samirkhan.apps.citymenu;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import custom.OptionMenuItemListner;
import custom.PreferencesFile;
import datalayer.LocalDataManager;
public class CityListActivity extends AppCompatActivity {
private final String SET_DEFAULT_CITY = "setDefaultCity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_list);
getSupportActionBar().setTitle("Cities");
ListView list = (ListView) findViewById(R.id.list_activity_city_list);
Boolean selectDefaultCity = getIntent().getBooleanExtra("setDefaultCity", false);
CityListAdapter adapter;
adapter = new CityListAdapter(this, new LocalDataManager(this).getCity(null, true), selectDefaultCity);
list.setAdapter(adapter);
/*
if (selectDefaultCity) {
Snackbar.make(findViewById(android.R.id.content), "Select Default City", Snackbar.LENGTH_SHORT).show();
}*/
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.option_menu_without_search, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
OptionMenuItemListner optionMenuItemListner = new OptionMenuItemListner(this, id);
optionMenuItemListner.performAction();
return super.onOptionsItemSelected(item);
}
}
/*
* CITY CUSTOM ADAPTER..
* */
class CityListAdapter extends BaseAdapter {
private Context context;
private ArrayList<Object[]> data;
Boolean selectDefaultCity;
public CityListAdapter(Context context, ArrayList<Object[]> list, Boolean selectDefaultCity) {
this.context = context;
this.data = (ArrayList<Object[]>) list.clone();
this.selectDefaultCity = selectDefaultCity;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return data.indexOf(position);
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getViewTypeCount() {
return getCount();
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.item_city_list, parent, false);
TextView textViewName = (TextView) view.findViewById(R.id.text_item_city_list_name);
TextView textViewState = (TextView) view.findViewById(R.id.text_item_city_list_state);
TextView textViewRestSize = (TextView) view.findViewById(R.id.text_item_city_list_rest_size);
TextView textViewRestLabel = (TextView) view.findViewById(R.id.text_item_city_list_rest_label);
ImageView imgView = (ImageView) view.findViewById(R.id.img_item_city_list_img);
textViewName.setText(((String) data.get(position)[1] != null) ? (String) data.get(position)[1] : "City");
textViewState.setText(((String) data.get(position)[2] != null) ? (String) data.get(position)[2] : "Address");
textViewRestSize.setText((String) data.get(position)[4]);
if(textViewRestSize.getText().toString().equals("0")){
textViewRestLabel.setText("restaurant");
} else {
textViewRestLabel.setText("restaurants");
textViewRestLabel.setTextColor(Color.parseColor("#D33A34"));
textViewRestSize.setTextColor(Color.parseColor("#D33A34"));
}
StringBuilder logo;
logo = ((StringBuilder) data.get(position)[3]);
byte[] byteArray = Base64.decode(logo.toString(), Base64.DEFAULT);
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length, options);
imgView.setImageBitmap(bitmap);
}
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// find city Id..
TextView textView = (TextView) v.findViewById(R.id.text_item_city_list_name);
int cityId = -1;
for (int i = 0; i < data.size(); i++) {
if (data.get(i)[1].equals(textView.getText().toString())) {
cityId = Integer.parseInt((String) data.get(i)[0]);
break;
}
}
if (selectDefaultCity) {
PreferencesFile preferencesFile = new PreferencesFile(context);
preferencesFile.setDefaultCityId(cityId);
/* Toast.makeText(context, textView.getText().toString() + " has been Selected as Default City."
, Toast.LENGTH_SHORT).show();*/
}
Intent intent = new Intent(context, RestaurantListActivity.class);
intent.putExtra("cityId", cityId);
context.startActivity(intent);
((Activity) context).finish();
}
});
return view;
}
}
| 35.112994 | 121 | 0.651006 |
e5154a43c3c7211f1094aee4daca315a801c9e3a
| 448 |
package net.dblsaiko.qcommon.cfg.keys;
import net.dblsaiko.qcommon.cfg.core.api.ConfigApi;
import net.dblsaiko.qcommon.cfg.keys.binding.BindManager;
import net.fabricmc.api.ModInitializer;
public class Main implements ModInitializer {
@Override
public void onInitialize() {
ConfigApi.Mutable api = ConfigApi.getInstanceMut();
BindManager.INSTANCE.register(api);
VanillaKeyWrapper.INSTANCE.register(api);
}
}
| 26.352941 | 59 | 0.747768 |
c20b638fadc95daea754066555b4c37ee15312cf
| 3,933 |
/*-------------------------------------------------------------------------+
| |
| Copyright 2005-2011 The ConQAT 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 org.conqat.engine.commons.findings;
import org.conqat.engine.commons.ConQATParamDoc;
import org.conqat.engine.commons.node.IConQATNode;
import org.conqat.engine.commons.node.NodeUtils;
import org.conqat.engine.commons.traversal.ETargetNodes;
import org.conqat.engine.commons.traversal.TargetExposedNodeTraversingProcessorBase;
import org.conqat.engine.core.core.AConQATFieldParameter;
import org.conqat.engine.core.core.AConQATProcessor;
import org.conqat.engine.core.core.ConQATException;
import org.conqat.lib.commons.string.StringUtils;
/**
* {@ConQAT.Doc}
*
* @author hummelb
* @author $Author: streitel $
* @version $Rev: 50576 $
* @ConQAT.Rating RED Hash: 7D2BC2C936286934DB6B507D05532886
*/
@AConQATProcessor(description = "Processor that takes all findings of a report, concatenates their messages and writes these messages to a ConQAT key.")
public class FindingMessageAnnotator extends
TargetExposedNodeTraversingProcessorBase<IConQATNode> {
/** {@ConQAT.Doc} */
@AConQATFieldParameter(parameter = ConQATParamDoc.FINDING_PARAM_NAME, attribute = ConQATParamDoc.FINDING_KEY_NAME, optional = false, description = ConQATParamDoc.FINDING_KEY_DESC)
public String findingKey;
/** {@ConQAT.Doc} */
@AConQATFieldParameter(parameter = ConQATParamDoc.WRITEKEY_NAME, attribute = ConQATParamDoc.WRITEKEY_KEY_NAME, optional = false, description = ConQATParamDoc.WRITEKEY_KEY_DESC)
public String writeKey;
/** {@inheritDoc} */
@Override
protected ETargetNodes getDefaultTargetNodes() {
return ETargetNodes.LEAVES;
}
/** {@inheritDoc} */
@Override
protected void setUp(IConQATNode root) throws ConQATException {
super.setUp(root);
NodeUtils.addToDisplayList(root, writeKey);
}
/** {@inheritDoc} */
@Override
public void visit(IConQATNode node) {
StringBuilder findingMessages = new StringBuilder();
FindingsList findings = NodeUtils.getFindingsList(node, findingKey);
// TODO (FS) sorry, but my comment that caused you to add this if
// statement was not well thought through: previously, the processor
// would write the empty string to writeKey if findings == null. now
// nothing is stored there. please check which version is desired. if
// storing nothing is OK, you can just remove this comment and make the
// file green. otherwise, please revert to the old version of this
// method before my half-baked review and make the file green as well
// :-)
if (findings == null) {
return;
}
for (Finding finding : findings) {
if (findingMessages.length() > 0) {
findingMessages.append(StringUtils.CR);
}
findingMessages.append(finding.getMessage());
}
node.setValue(writeKey, findingMessages.toString());
}
}
| 44.191011 | 180 | 0.640224 |
76960bbacda39b09f320d8d868062c124ffaecde
| 14,323 |
/*
* Copyright 2019 Arcus Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iris.platform.scene.catalog;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.stream.Collectors;
import com.iris.messages.MessageBody;
import com.iris.platform.scene.resolver.ThermostatResolver;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.iris.capability.registry.CapabilityRegistry;
import com.iris.capability.registry.CapabilityRegistryModule;
import com.iris.common.rule.action.Action;
import com.iris.io.xml.JAXBUtil;
import com.iris.messages.MessagesModule;
import com.iris.messages.PlatformMessage;
import com.iris.messages.capability.CameraCapability;
import com.iris.messages.capability.DimmerCapability;
import com.iris.messages.capability.FanCapability;
import com.iris.messages.capability.SecuritySubsystemCapability;
import com.iris.messages.capability.Somfyv1Capability;
import com.iris.messages.capability.SwitchCapability;
import com.iris.messages.capability.ThermostatCapability;
import com.iris.messages.model.Model;
import com.iris.messages.type.ActionSelector;
import com.iris.messages.type.ThermostatAction;
import com.iris.platform.scene.catalog.serializer.ActionTemplateType;
import com.iris.platform.scene.catalog.serializer.SceneCatalog;
import com.iris.platform.scene.resolver.CatalogActionTemplateResolver;
import com.iris.platform.scene.resolver.ShadeResolver;
import com.iris.resource.Resources;
import com.iris.test.Modules;
import static com.iris.Utils.assertTrue;
import static com.iris.messages.MessageBody.buildMessage;
@Modules({ CapabilityRegistryModule.class, MessagesModule.class })
public class TestCatalogResolver extends SceneCatalogBaseTest {
private Map<String,CatalogActionTemplateResolver>resolverMap;
private CatalogActionTemplateResolver resolver;
private CatalogActionTemplateResolver fanResolver;
@Inject CapabilityRegistry registry;
SceneCatalog sc;
Model testSwitch;
Model testFan;
@Before
public void setUp() throws Exception {
super.setUp();
testSwitch = addDevice(SwitchCapability.NAMESPACE,DimmerCapability.NAMESPACE);
testFan = addDevice(SwitchCapability.NAMESPACE,FanCapability.NAMESPACE);
testFan.setAttribute(FanCapability.ATTR_MAXSPEED, 5);
sc = JAXBUtil.fromXml(Resources.getResource("classpath:/com/iris/conf/scene-catalog.xml"), SceneCatalog.class);
resolverMap=sc.getActionTemplates().getActionTemplate().stream().collect(
Collectors.toMap(ActionTemplateType::getTypeHint, (p) -> new CatalogActionTemplateResolver(registry, p)));
resolver = resolverMap.get("lights");
fanResolver = resolverMap.get("fan");
}
@After
public void tearDown() throws Exception {
}
@Test
public void testDimmerSwitch() {
List<ActionSelector>actionSelectors=resolver.resolve(context,testSwitch);
assertEquals(1, actionSelectors.size());
ActionSelector selector1 = actionSelectors.get(0);
assertEquals("switch", selector1.getName());
assertEquals(ActionSelector.TYPE_GROUP, selector1.getType().toUpperCase());
List<List<Object>> values = (List<List<Object>>)selector1.getValue();
ActionSelector subselector = new ActionSelector(ImmutableMap.of(ActionSelector.ATTR_TYPE,ActionSelector.TYPE_PERCENT,ActionSelector.ATTR_NAME,"dim"));
List<List<Object>> expecting = ImmutableList.of(ImmutableList.of("ON",ImmutableList.of(subselector.toMap())),ImmutableList.of("OFF",ImmutableList.of()));
assertEquals(expecting, values);
Action action = resolver.generate(context, testSwitch.getAddress(), ImmutableMap.<String,Object>of("switch", "ON","dim","50"));
action.execute(context);
BlockingQueue<PlatformMessage> messages = context.getMessages();
PlatformMessage message = messages.remove();
assertEquals("base:SetAttributes", message.getValue().getMessageType());
// turned to a long via json serialization
assertEquals(50L, message.getValue().getAttributes().get(DimmerCapability.ATTR_BRIGHTNESS));
assertEquals("ON", message.getValue().getAttributes().get(SwitchCapability.ATTR_STATE));
}
@Test
public void testTurnOnFan() {
List<ActionSelector>actionSelectors=fanResolver.resolve(context,testFan);
assertEquals(1, actionSelectors.size());
ActionSelector selector1 = actionSelectors.get(0);
assertEquals("switch", selector1.getName());
assertEquals(ActionSelector.TYPE_GROUP, selector1.getType().toUpperCase());
List<List<Object>> values = (List<List<Object>>)selector1.getValue();
ActionSelector expedctingSubselector = new ActionSelector(ImmutableMap.of(ActionSelector.ATTR_TYPE,ActionSelector.TYPE_LIST,ActionSelector.ATTR_NAME,"fanspeed"));
expedctingSubselector.setValue(ImmutableList.of(ImmutableList.of("LOW",1),ImmutableList.of("MEDIUM",3),ImmutableList.of("HIGH",5)));
List<List<Object>> expecting = ImmutableList.of(ImmutableList.of("ON",ImmutableList.of(expedctingSubselector.toMap())),ImmutableList.of("OFF",ImmutableList.of()));
assertEquals(expecting, values);
Action action = fanResolver.generate(context, testFan.getAddress(), ImmutableMap.<String,Object>of("switch", "ON","fanspeed","1"));
action.execute(context);
BlockingQueue<PlatformMessage> messages = context.getMessages();
PlatformMessage message = messages.remove();
assertEquals("base:SetAttributes", message.getValue().getMessageType());
assertEquals("ON", message.getValue().getAttributes().get(SwitchCapability.ATTR_STATE));
assertEquals(1L, message.getValue().getAttributes().get(FanCapability.ATTR_SPEED));
}
@Test
public void testTurnOffFan() {
List<ActionSelector>actionSelectors=fanResolver.resolve(context,testFan);
assertEquals(1, actionSelectors.size());
ActionSelector selector1 = actionSelectors.get(0);
assertEquals("switch", selector1.getName());
assertEquals(ActionSelector.TYPE_GROUP, selector1.getType().toUpperCase());
List<List<Object>> values = (List<List<Object>>)selector1.getValue();
ActionSelector expectedSubselector = new ActionSelector(ImmutableMap.of(ActionSelector.ATTR_TYPE,ActionSelector.TYPE_LIST,ActionSelector.ATTR_NAME,"fanspeed"));
expectedSubselector.setValue(ImmutableList.of(ImmutableList.of("LOW",1),ImmutableList.of("MEDIUM",3),ImmutableList.of("HIGH",5)));
List<List<Object>> expecting = ImmutableList.of(ImmutableList.of("ON",ImmutableList.of(expectedSubselector.toMap())),ImmutableList.of("OFF",ImmutableList.of()));
assertEquals(expecting, values);
Action action = fanResolver.generate(context, testFan.getAddress(), ImmutableMap.<String,Object>of("switch", "OFF"));
action.execute(context);
BlockingQueue<PlatformMessage> messages = context.getMessages();
PlatformMessage message = messages.remove();
assertEquals("base:SetAttributes", message.getValue().getMessageType());
assertEquals("OFF", message.getValue().getAttributes().get(SwitchCapability.ATTR_STATE));
assertEquals(null, message.getValue().getAttributes().get(FanCapability.ATTR_SPEED));
}
@Test
public void testFanmodeOn() {
ThermostatResolver test = new ThermostatResolver();
Model testThermostat = createThermostat(1.67, 35.0, 1.67);
ThermostatAction taction = createThermostatAction(30.0, 15.0, ThermostatAction.MODE_AUTO, false);
taction.setFanmode(1);
Map<String,Object>variables=ImmutableMap.of("thermostat",taction.toMap());
Action holder = test.generate(context, testThermostat.getAddress(), variables);
holder.execute(context);
BlockingQueue<PlatformMessage> messages = context.getMessages();
PlatformMessage message = messages.remove();
assertEquals("subclimate:DisableScheduler", message.getValue().getMessageType());
message = messages.remove();
assertTrue(Long.valueOf("1") == message.getValue().getAttributes().get("therm:fanmode"));
}
@Test
public void testThermostatResolver() {
resolver=resolverMap.get("thermostat");
Model testThermostat = createThermostat(1.67, 35.0, 1.67);
ThermostatAction taction = createThermostatAction(30.0, 15.0, ThermostatAction.MODE_AUTO, false);
doExecuteThermostatActionOK(taction, testThermostat);
}
//Preconditions.checkArgument(Precision.compareTo(action.getHeatSetPoint(), minSetPoint, PRECISION) > 0 , "The heatsetpoint can't be set below minSetPoint");
@Test
public void testThermostatResolver_OK_1() {
resolver=resolverMap.get("thermostat");
Model testThermostat = createThermostat(1.67, 35.0, 1.67);
//HeatSetPoint 1.661 is lower than min minSetPoint 1.67, but still within 0.01 tolerance
ThermostatAction taction = createThermostatAction(30.0, 1.661, ThermostatAction.MODE_AUTO, false);
doExecuteThermostatActionOK(taction, testThermostat);
}
@Test
public void testThermostatResolver_Error_1() {
resolver=resolverMap.get("thermostat");
Model testThermostat = createThermostat(1.67, 35.0, 1.67);
//HeatSetPoint 1.655 is lower than minSetPoint 1.67, and not within 0.01 tolerance
ThermostatAction taction = createThermostatAction(30.0, 1.655, ThermostatAction.MODE_AUTO, false);
try{
doExecuteThermostatActionOK(taction, testThermostat);
fail("should have failed");
}catch(Exception e) {
//ok
}
}
@Test
public void testThermostatResolver_OK_2() {
resolver=resolverMap.get("thermostat");
Model testThermostat = createThermostat(1.67, 35.0, 1.67);
//HeatSetPoint 1.67 is same as minSetPoint 1.67, ok
ThermostatAction taction = createThermostatAction(30.0, 1.67, ThermostatAction.MODE_AUTO, false);
doExecuteThermostatActionOK(taction, testThermostat);
}
private void doExecuteThermostatActionOK(ThermostatAction taction, Model testThermostat) {
Map<String,Object>variables=ImmutableMap.of("thermostat",taction.toMap());
Action action = resolver.generate(context, testThermostat.getAddress(),variables);
action.execute(context);
BlockingQueue<PlatformMessage> messages = context.getMessages();
PlatformMessage message = messages.remove();
assertNotNull(message);
}
private Model createThermostat(Double minSetPoint, Double maxSetPoint, Double setPointSeperation) {
return addDevice(ImmutableMap.<String, Object>of(
ThermostatCapability.ATTR_MINSETPOINT, minSetPoint,
ThermostatCapability.ATTR_MAXSETPOINT, maxSetPoint,
ThermostatCapability.ATTR_SETPOINTSEPARATION, setPointSeperation),
ThermostatCapability.NAMESPACE);
}
private ThermostatAction createThermostatAction(Double coolSetPoint, Double heatSetPoint, String mode, boolean scheduleEnabled) {
ThermostatAction taction = new ThermostatAction();
taction.setCoolSetPoint(coolSetPoint);
taction.setHeatSetPoint(heatSetPoint);
taction.setMode(mode);
taction.setScheduleEnabled(scheduleEnabled);
return taction;
}
@Test
public void testSecurityResolver() {
resolver=resolverMap.get("security");
Model testSecurity = addDevice(SecuritySubsystemCapability.NAMESPACE);
List<ActionSelector>selectors = resolver.resolve(context, testSecurity);
ActionSelector selector1 = selectors.get(0);
List<List<Object>> values = (List<List<Object>>)selector1.getValue();
assertEquals("alarm-state", selector1.getName());
assertEquals(ActionSelector.TYPE_LIST, selector1.getType().toUpperCase());
assertEquals("Arm On", values.get(0).get(0));
assertEquals("ON", values.get(0).get(1));
assertEquals("Arm Partial", values.get(1).get(0));
assertEquals("PARTIAL", values.get(1).get(1));
assertEquals("Disarm", values.get(2).get(0));
assertEquals("OFF", values.get(2).get(1));
Map<String,Object>variables=ImmutableMap.of("alarm-state","ON");
Action action = resolver.generate(context, testSecurity.getAddress(),variables);
action.execute(context);
BlockingQueue<PlatformMessage> messages = context.getMessages();
PlatformMessage message = messages.remove();
assertEquals("subsecurity:ArmBypassed",message.getMessageType());
}
@Test
public void testCameraResolver() {
resolver=resolverMap.get("camera");
Model testSecurity = addDevice(CameraCapability.NAMESPACE);
Map<String,Object>variables=ImmutableMap.of("duration","30");
Action action = resolver.generate(context, testSecurity.getAddress(),variables);
action.execute(context);
BlockingQueue<PlatformMessage> messages = context.getMessages();
PlatformMessage message = messages.remove();
assertEquals("video:StartRecording",message.getMessageType());
}
@Test
public void testSomfyBlindsResolver() {
resolver=resolverMap.get("blind");
Model testBlinds = addDevice(Somfyv1Capability.NAMESPACE);
Map<String,Object>variables=ImmutableMap.of(ShadeResolver.SOMFY_SELECTOR_NAME,Somfyv1Capability.CURRENTSTATE_OPEN);
Action action = resolver.generate(context, testBlinds.getAddress(),variables);
action.execute(context);
BlockingQueue<PlatformMessage> messages = context.getMessages();
PlatformMessage message = messages.remove();
assertEquals("somfyv1:GoToOpen",message.getMessageType());
}
}
| 47.270627 | 169 | 0.736927 |
95238f4db10da547b5e5ccd5590bb62eab298c39
| 8,401 |
package com.syncano.android.test.modules.collections;
import android.test.AndroidTestCase;
import com.syncano.android.lib.Syncano;
import com.syncano.android.lib.modules.Response;
import com.syncano.android.lib.modules.apikeys.ParamsApiKeyDelete;
import com.syncano.android.lib.modules.apikeys.ParamsApiKeyNew;
import com.syncano.android.lib.modules.apikeys.ResponseApiKeyNew;
import com.syncano.android.lib.modules.collections.ParamsCollectionActivate;
import com.syncano.android.lib.modules.collections.ParamsCollectionAddTag;
import com.syncano.android.lib.modules.collections.ParamsCollectionAuthorize;
import com.syncano.android.lib.modules.collections.ParamsCollectionDeactivate;
import com.syncano.android.lib.modules.collections.ParamsCollectionDeauthorize;
import com.syncano.android.lib.modules.collections.ParamsCollectionDelete;
import com.syncano.android.lib.modules.collections.ParamsCollectionDeleteTag;
import com.syncano.android.lib.modules.collections.ParamsCollectionGet;
import com.syncano.android.lib.modules.collections.ParamsCollectionGetOne;
import com.syncano.android.lib.modules.collections.ParamsCollectionNew;
import com.syncano.android.lib.modules.collections.ParamsCollectionUpdate;
import com.syncano.android.lib.modules.collections.ResponseCollectionGet;
import com.syncano.android.lib.modules.collections.ResponseCollectionGetOne;
import com.syncano.android.lib.modules.collections.ResponseCollectionNew;
import com.syncano.android.lib.modules.collections.ResponseCollectionUpdate;
import com.syncano.android.lib.modules.projects.ParamsProjectDelete;
import com.syncano.android.lib.modules.projects.ParamsProjectNew;
import com.syncano.android.lib.modules.projects.ResponseProjectNew;
import com.syncano.android.lib.objects.ApiKey;
import com.syncano.android.lib.utils.DownloadTool;
import com.syncano.android.test.config.Constants;
public class CollectionsTest extends AndroidTestCase {
private static final String API_KEY_ROLE_USER = "user";
private static final String COLLECTION_DESCRIPTION_UPDATED = "Updated Description";
private static final String PERMISSION_READ_DATA = "read_data";
private static final String COLLECTION_TAG = "news";
private Syncano syncano = null;
private String projectId = null;
private String collectionId = null;
private ApiKey apiKey = null;
@Override
protected void setUp() throws Exception {
super.setUp();
syncano = new Syncano(mContext, Constants.INSTANCE_NAME, Constants.API_KEY);
assertTrue("Device should be connected to internet before test", DownloadTool.connectionAvailable(mContext));
// Create test project
ParamsProjectNew paramsProjectNew = new ParamsProjectNew("CI Test Project");
ResponseProjectNew responseProjectNew = syncano.projectNew(paramsProjectNew);
assertEquals("Failed to create test project", Response.CODE_SUCCESS, (int) responseProjectNew.getResultCode());
projectId = responseProjectNew.getProject().getId();
// Create API Key
ParamsApiKeyNew paramsApiKeyNew = new ParamsApiKeyNew("test description", API_KEY_ROLE_USER);
ResponseApiKeyNew responseApiKeyNew = syncano.apikeyNew(paramsApiKeyNew);
assertEquals("Failed to create new Api Key", Response.CODE_SUCCESS, (int) responseApiKeyNew.getResultCode());
apiKey = responseApiKeyNew.getApiKey();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
// Clean test project
ParamsProjectDelete paramsProjectDelete = new ParamsProjectDelete(projectId);
Response responseProjectDelete = syncano.projectDelete(paramsProjectDelete);
assertEquals("Failed to clean test project", Response.CODE_SUCCESS, (int) responseProjectDelete.getResultCode());
// Clean Api Key
ParamsApiKeyDelete paramsApiKeyDelete = new ParamsApiKeyDelete(apiKey.getId());
Response responseApiKeyDelete = syncano.apikeyDelete(paramsApiKeyDelete);
assertEquals("Failed to clean Api Key", Response.CODE_SUCCESS, (int) responseApiKeyDelete.getResultCode());
}
public void testCollections() {
// Collection New
ParamsCollectionNew paramsCollectionNew = new ParamsCollectionNew(projectId, "CI Test Collection");
ResponseCollectionNew responseCollectionNew = syncano.collectionNew(paramsCollectionNew);
assertEquals(Response.CODE_SUCCESS, (int) responseCollectionNew.getResultCode());
collectionId = responseCollectionNew.getCollection().getId();
// Collection Get
ParamsCollectionGet paramsCollectionGet = new ParamsCollectionGet(projectId);
ResponseCollectionGet responseCollectionGet = syncano.collectionGet(paramsCollectionGet);
assertEquals(Response.CODE_SUCCESS, (int) responseCollectionGet.getResultCode());
assertTrue(responseCollectionGet.getCollection().length > 0);
// Collection Get One
ParamsCollectionGetOne paramsCollectionGetOne = new ParamsCollectionGetOne(projectId, collectionId);
ResponseCollectionGetOne responseCollectionGetOne = syncano.collectionGetOne(paramsCollectionGetOne);
assertEquals(Response.CODE_SUCCESS, (int) responseCollectionGetOne.getResultCode());
// Collection Activate
ParamsCollectionActivate paramsCollectionActivate = new ParamsCollectionActivate(projectId, collectionId);
Response responseCollectionActivate = syncano.collectionActivate(paramsCollectionActivate);
assertEquals(Response.CODE_SUCCESS, (int) responseCollectionActivate.getResultCode());
// Collection Deactivate
ParamsCollectionDeactivate paramsCollectionDeactivate = new ParamsCollectionDeactivate(projectId, collectionId);
Response responseCollectionDeactivate = syncano.collectionDeactivate(paramsCollectionDeactivate);
assertEquals(Response.CODE_SUCCESS, (int) responseCollectionDeactivate.getResultCode());
// Collection Update
ParamsCollectionUpdate paramsCollectionUpdate = new ParamsCollectionUpdate(projectId, collectionId);
paramsCollectionUpdate.setDescription(COLLECTION_DESCRIPTION_UPDATED);
ResponseCollectionUpdate responseCollectionUpdate = syncano.collectionUpdate(paramsCollectionUpdate);
assertEquals(Response.CODE_SUCCESS, (int) responseCollectionUpdate.getResultCode());
assertEquals(COLLECTION_DESCRIPTION_UPDATED, responseCollectionUpdate.getCollection().getDescription());
// Collection Authorize
ParamsCollectionAuthorize paramsCollectionAuthorize = new ParamsCollectionAuthorize(apiKey.getId(), PERMISSION_READ_DATA, projectId, collectionId, null);
Response responseCollectionAuthorize = syncano.collectionAuthorize(paramsCollectionAuthorize);
assertEquals(Response.CODE_SUCCESS, (int) responseCollectionAuthorize.getResultCode());
// Collection Deauthorize
ParamsCollectionDeauthorize paramsCollectionDeauthorize = new ParamsCollectionDeauthorize(apiKey.getId(), PERMISSION_READ_DATA, projectId, collectionId, null);
Response responseCollectionDeauthorize = syncano.collectionDeauthorize(paramsCollectionDeauthorize);
assertEquals(Response.CODE_SUCCESS, (int) responseCollectionDeauthorize.getResultCode());
// Collection Add Tag
ParamsCollectionAddTag paramsCollectionAddTag = new ParamsCollectionAddTag(projectId, collectionId, null, new String[] {COLLECTION_TAG});
Response responseCollectionAddTag = syncano.collectionAddTag(paramsCollectionAddTag);
assertEquals(Response.CODE_SUCCESS, (int) responseCollectionAddTag.getResultCode());
// Collection Delete Tag
ParamsCollectionDeleteTag paramsCollectionDeleteTag = new ParamsCollectionDeleteTag(projectId, collectionId, null, new String[] {COLLECTION_TAG});
Response responseCollectionDeleteTag = syncano.collectionDeleteTag(paramsCollectionDeleteTag);
assertEquals(Response.CODE_SUCCESS, (int) responseCollectionDeleteTag.getResultCode());
// Collection Delete
ParamsCollectionDelete paramsCollectionDelete = new ParamsCollectionDelete(projectId, collectionId);
Response responseCollectionDelete = syncano.collectionDelete(paramsCollectionDelete);
assertEquals(Response.CODE_SUCCESS, (int)responseCollectionDelete.getResultCode());
}
}
| 60.007143 | 167 | 0.790501 |
b179fe04f612e00d1444b5e4852069801145aca4
| 3,083 |
package com.akshatjain.codepath.tweeter.data;
import com.google.gson.annotations.SerializedName;
import org.parceler.Parcel;
/**
* Created by akshatjain on 8/4/16.
*/
@Parcel
public class Tweet{
@SerializedName("id")
public long id;
@SerializedName("created_at")
public String created_at;
@SerializedName("text")
public String text; // actual tweet
@SerializedName("retweet_count")
public int retweet_count;
@SerializedName("favorited")
public boolean isFavorite;
@SerializedName("retweeted")
public boolean isRetweeted;
@SerializedName("user")
public User userDetails;
@SerializedName("favorite_count")
public int favoriteCount;
@SerializedName("entities")
public Entities entities;
public Tweet() {
}
public Tweet(long id, String created_at, String text, int retweet_count, boolean isFavorite, boolean isRetweeted, User userDetails, int favoriteCount) {
this.id = id;
this.created_at = created_at;
this.text = text;
this.retweet_count = retweet_count;
this.isFavorite = isFavorite;
this.isRetweeted = isRetweeted;
this.userDetails = userDetails;
this.favoriteCount = favoriteCount;
}
public Tweet(long id, String created_at, String text, int retweet_count, boolean isFavorite, boolean isRetweeted, User userDetails, int favoriteCount,Entities entities) {
this.id = id;
this.created_at = created_at;
this.text = text;
this.retweet_count = retweet_count;
this.isFavorite = isFavorite;
this.isRetweeted = isRetweeted;
this.userDetails = userDetails;
this.favoriteCount = favoriteCount;
this.entities = entities;
}
public boolean isRetweeted() {
return isRetweeted;
}
public int getFavoriteCount() {
return favoriteCount;
}
public User getUserDetails() {
return userDetails;
}
public boolean isFavorite() {
return isFavorite;
}
public int getRetweet_count() {
return retweet_count;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getCreated_at() {
return created_at;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Entities getEntities() {
return entities;
}
@Override
public String toString() {
return "Tweet{" +
", id=" + id +
", created_at='" + created_at + '\'' +
", retweet_count=" + retweet_count +
", isFavorite=" + isFavorite +
", isRetweeted=" + isRetweeted +
", userDetails=" + userDetails.toString() +
", favoriteCount=" + favoriteCount +
", entities = " + ((entities != null ) ? entities.toString() : "") +
", text='" + text + '\'' +
'}';
}
}
| 24.664 | 174 | 0.598119 |
8fb3b4b1166452ea4d4aa08577e9037c39688e92
| 2,392 |
package com.example.robot;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements GetDataListener,OnItemLongClickListener
{
private ListView listView;
private List<ContentBean> list;
private ContentBean bean;
private EditText editText;
private MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lv);
editText = (EditText) findViewById(R.id.edittext);
list = new ArrayList<ContentBean>();
adapter = new MyAdapter(list, MainActivity.this);
bean = new ContentBean();
bean.content = getRandomWelcome();
bean.FLAG = 2;
list.add(bean);
listView.setAdapter(adapter);
}
private String getRandomWelcome()
{
String[] arrary;
arrary = this.getResources().getStringArray(R.array.arrary);
int index = (int) (Math.random() * (arrary.length));
return arrary[index];
}
public void click(View v)
{
if(editText.getText().toString().equals(""))
return;
bean = new ContentBean();
String str = editText.getText().toString();
editText.setText("");
bean.content = str;
bean.FLAG = 1;
list.add(bean);
adapter.notifyDataSetChanged();
String nospace = str.replace(" ", "");
String noenter = nospace.replace("\n", "");
new MyAsyncTask(this).execute(noenter);
}
@Override
public void getData(String str)
{
bean = new ContentBean();
bean.content = str;
bean.FLAG = 2;
list.add(bean);
adapter.notifyDataSetChanged();
}
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3)
{
ClipboardManager cmb = (ClipboardManager)this.getSystemService(Context.CLIPBOARD_SERVICE);
TextView tv = (TextView) arg1.findViewById(R.id.tv);
cmb.setText(tv.getText().toString());
//ToastUtil.show("已复制");
return false;
}
}
| 26.876404 | 93 | 0.736622 |
b7dd24460caa42ed1271a366d432bc3be2f60893
| 816 |
package com.mps.deepviolet.api.samples;
import java.net.URL;
import com.mps.deepviolet.api.DVFactory;
import com.mps.deepviolet.api.IDVEng;
import com.mps.deepviolet.api.IDVSession;
import com.mps.deepviolet.api.IDVX509Certificate;
public class PrintRawX509Certificate {
public PrintRawX509Certificate() throws Exception {
URL url = new URL("https://github.com/");
IDVSession session = DVFactory.initializeSession(url);
IDVEng eng = DVFactory.getDVEng(session);
IDVX509Certificate cert = eng.getCertificate();
// Print out the certificate or whatever you want
System.out.println("Raw X509 certificate");
System.out.println(cert.toString());
}
public static final void main(String[] args) {
try {
new PrintRawX509Certificate();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
| 24.727273 | 56 | 0.747549 |
70034b6984a31403917d4e8b60ee8162e1bcc1ea
| 279 |
package application.entities;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Person {
private int id;
private String firstName;
private String lastName;
}
| 15.5 | 34 | 0.759857 |
872324e98d0ed49b711d6a705c76bf505771b610
| 1,737 |
package com.mishinyura.university.services.impl;
import com.mishinyura.university.dao.GroupDAO;
import com.mishinyura.university.domain.Group;
import com.mishinyura.university.services.GroupService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
/**
* Class GroupServiceImpl.
* Implements Group service.
*
* @author Mishin Yura (mishin.inbox@gmail.com)
* @since 07.09.2021
*/
@Service
public class GroupServiceImpl implements GroupService {
/**
* GroupDAO.
*/
private final GroupDAO groupDAO;
/**
* Constructor.
*
* @param groupDAO groupDAO
*/
public GroupServiceImpl(final GroupDAO groupDAO) {
this.groupDAO = groupDAO;
}
/**
* Method finds all groups.
*
* @return List<Group>
*/
@Override
@Transactional(readOnly = true)
public List<Group> findAll() {
return this.groupDAO.findAll();
}
/**
* Method finds group by id.
*
* @param id Id
* @return Optional<Group>
*/
@Override
@Transactional(readOnly = true)
public Optional<Group> findById(final Long id) {
return this.groupDAO.findById(id);
}
/**
* Method saves group.
*
* @param group group
* @return group
*/
@Override
@Transactional
public Group save(final Group group) {
return this.groupDAO.save(group);
}
/**
* Method deletes group by id.
*
* @param id Id
* @return boolean
*/
@Override
@Transactional
public boolean deleteById(final Long id) {
return this.groupDAO.deleteById(id);
}
}
| 21.182927 | 64 | 0.6327 |
35348897547abff32733b1e4a985937c0dffb16e
| 894 |
package com.gobatis.demo;
import java.util.HashMap;
import java.util.Map;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.gobatis.plugins.ExamplePlugin;
/**
* @author wanggang
* @date 2018年4月12日 下午1:52:59
*
*/
public class ClientBatis {
public static void main(String[] args) {
try {
String resource = "mybatis/mybatis-config.xml"; //获取mybatis配置文件路径
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));
SqlSession sqlSession = sqlSessionFactory.openSession();
Map map = new HashMap();
map = (Map)new ExamplePlugin().plugin(map);
System.out.println(map.get(""));
} catch(Exception e) {
}
}
}
| 25.542857 | 120 | 0.713647 |
8b2b1e638720bf9f55ca2e1ef3a4fa24089b910a
| 1,582 |
package com.shangbaishuyao.connectors.rabbitmq;
import com.shangbaishuyao.common.model.MetricEvent;
import com.shangbaishuyao.common.schemas.MetricSchema;
import com.shangbaishuyao.common.utils.ExecutionEnvUtil;
import com.shangbaishuyao.common.utils.KafkaConfigUtil;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.rabbitmq.RMQSink;
import org.apache.flink.streaming.connectors.rabbitmq.common.RMQConnectionConfig;
/**
* Desc: 从 kafka 读取数据 sink 到 rabbitmq <br/>
* create by shangbaishuyao on 2021/2/1
* @Author: 上白书妖
* @Date: 13:39 2021/2/1
*/
public class Main1 {
public static void main(String[] args) throws Exception{
final ParameterTool parameterTool = ExecutionEnvUtil.createParameterTool(args);
StreamExecutionEnvironment env = ExecutionEnvUtil.prepare(parameterTool);
DataStreamSource<MetricEvent> dataSource = KafkaConfigUtil.buildSource(env);
final RMQConnectionConfig connectionConfig = new RMQConnectionConfig.Builder()
.setHost("localhost")
.setVirtualHost("/")
.setPort(5672)
.setUserName("admin")
.setPassword("admin")
.build();
//注意,换一个新的 queue,否则也会报错
dataSource.addSink(new RMQSink<>(connectionConfig,"shangbaishuyao001",new MetricSchema()));
env.execute("flink learning connectors rabbitmq");
}
}
| 40.564103 | 99 | 0.731985 |
d8f6e8059081f5a580a5e445ebbc04e16f276243
| 882 |
package startsharp.task.Login;
import net.serenitybdd.core.steps.Instrumented;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Click;
import net.serenitybdd.screenplay.actions.Enter;
import static startsharp.navigation.StartSharp.*;
public class IniciarSesion implements Task{
String user;
String password;
public IniciarSesion (String user, String password) {
this.user = user;
this.password = password;
}
@Override
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(
Enter.theValue(user).into(INPUT_USER),
Enter.theValue(password).into(INPUT_PASSWORD),
Click.on(BTN_SIGNIN)
);
}
public static IniciarSesion conCredenciales(String user, String password) {
return Instrumented.instanceOf(IniciarSesion.class).withProperties(user,password);
}
}
| 23.837838 | 84 | 0.774376 |
37fcfc3177ed6080a039eecc0fbf60b2b975cbc0
| 567 |
package programaidade;
import java.util.Scanner;
/**
*
* @author Yasmin
*/
public class ProgramaIdade {
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
System.out.print("Digite o ano que você nasceu: ");
int nasc = teclado.nextInt();
int idade = 2021 - nasc;
System.out.println("Sua idade é: "+idade);
if(idade >= 18){
System.out.println("Você é maior de idade.");
} else {
System.out.println("Você é menor de idade.");
}
}
}
| 23.625 | 59 | 0.567901 |
6dda6c838c84cba37c81ec126b070e1efad124aa
| 712 |
package com.ruoyi.common.utils;
import com.ruoyi.common.constant.UserConstants;
/**
* 校验工具类
* @author lsy
*
*/
public class ValidateUtil {
/**
* 字符串是否是email格式
* @param value
* @return true 是email格式,反之false
*/
public static boolean maybeEmail(String value)
{
if (!value.matches(UserConstants.EMAIL_PATTERN))
{
return false;
}
return true;
}
/**
* 字符串是否是电话格式
* @param value
* @return true是电话格式,反之false
*/
public static boolean maybeMobilePhoneNumber(String value)
{
if (!value.matches(UserConstants.MOBILE_PHONE_NUMBER_PATTERN))
{
return false;
}
return true;
}
}
| 18.25641 | 70 | 0.592697 |
523406b256e3d2e0066f02135c7e68476ac2c381
| 1,564 |
package com.tiscon.dto;
public class PriceRefernceDto {
private Integer priceInt;
private double distance;
private Integer pricePerDistance;
private Integer priceForDistance;
private Integer pricePerTruck;
private Integer priceForOptionalService;
private double N;
public Integer getPriceInt() {
return priceInt;
}
public void setPriceInt(Integer priceInt) {
this.priceInt = priceInt;
}
public double getDistance() {
return distance;
}
public void setDistance(double distance) {
this.distance = distance;
}
public Integer getPricePerDistance() {
return pricePerDistance;
}
public void setPricePerDistance(Integer pricePerDistance) {
this.pricePerDistance = pricePerDistance;
}
public Integer getPriceForDistance() {
return priceForDistance;
}
public void setPriceForDistance(Integer priceForDistance) {
this.priceForDistance = priceForDistance;
}
public Integer getPricePerTruck() {
return pricePerTruck;
}
public void setPricePerTruck(Integer pricePerTruck) {
this.pricePerTruck = pricePerTruck;
}
public Integer getPriceForOptionalService() {
return priceForOptionalService;
}
public void setPriceForOptionalService(Integer priceForOptionalService) {
this.priceForOptionalService = priceForOptionalService;
}
public double getN() {
return N;
}
public void setN(double N) {
this.N = N;
}
}
| 21.135135 | 77 | 0.674552 |
0caf8a33ad40b3916eb524659e82b9fedc4ce4c3
| 15,821 |
/*
* 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.sis.metadata;
import java.util.Map;
import javax.xml.bind.annotation.XmlTransient;
import org.apache.sis.util.Emptiable;
import org.apache.sis.util.ComparisonMode;
import org.apache.sis.util.LenientComparable;
import org.apache.sis.util.collection.TreeTable;
/**
* Provides basic operations using Java reflection for metadata implementations.
* All {@code AbstractMetadata} instances shall be associated to a {@link MetadataStandard}.
* The metadata standard is given by the {@link #getStandard()} method and is typically a
* constant fixed by the subclass.
*
* <p>There is a large number of {@code AbstractMetadata} subclasses (not necessarily as direct children)
* for the same standard, where each subclass implement one Java interface defined by the metadata standard.
* This base class reduces the effort required to implement those metadata interfaces by providing
* {@link #equals(Object)}, {@link #hashCode()} and {@link #toString()} implementations.
* Those methods are implemented using Java reflection for invoking the getter methods
* defined by the {@code MetadataStandard}.</p>
*
* {@code AbstractMetadata} subclasses may be read-only or read/write, at implementation choice.
* The methods that modify the metadata may throw {@link UnmodifiableMetadataException} if the
* metadata does not support the operation. Those methods are:
*
* <table class="sis">
* <caption>Metadata operations</caption>
* <tr>
* <th>Read-only operations</th>
* <th class="sep">Read/write operations</th>
* </tr>
* <tr>
* <td><ul>
* <li>{@link #isEmpty()}</li>
* <li>{@link #asMap()} with {@code get} operations</li>
* <li>{@link #asTreeTable()} with {@code getValue} operations</li>
* <li>{@link #equals(Object, ComparisonMode)}</li>
* </ul></td>
* <td class="sep"><ul>
* <li>{@link #prune()}</li>
* <li>{@link #asMap()} with {@code put} operations</li>
* <li>{@link #asTreeTable()} with {@code setValue} operations</li>
* </ul></td>
* </tr>
* </table>
*
* <h2>Thread safety</h2>
* Instances of this class are <strong>not</strong> synchronized for multi-threading.
* Synchronization, if needed, is caller's responsibility. Note that synchronization locks
* are not necessarily the metadata instances. For example an other common approach is to
* use a single lock for the whole metadata tree (including children).
*
* @author Martin Desruisseaux (Geomatys)
* @version 1.0
*
* @see MetadataStandard
*
* @since 0.3
* @module
*/
@XmlTransient
public abstract class AbstractMetadata implements LenientComparable, Emptiable {
/**
* Creates an initially empty metadata.
*/
protected AbstractMetadata() {
}
/**
* Returns the metadata standard implemented by subclasses.
* Subclasses will typically return a hard-coded constant such as
* {@link MetadataStandard#ISO_19115}.
*
* <h4>Note for implementers</h4>
* Implementation of this method shall not depend on the object state,
* since this method may be indirectly invoked by copy constructors.
*
* @return the metadata standard implemented.
*/
public abstract MetadataStandard getStandard();
/**
* Returns the metadata interface implemented by this class. It should be one of the interfaces
* defined in the {@linkplain #getStandard() metadata standard} implemented by this class.
*
* @return the standard interface implemented by this implementation class.
*
* @see MetadataStandard#getInterface(Class)
*/
public Class<?> getInterface() {
return getStandard().getInterface(getClass());
}
/**
* Returns {@code true} if this metadata contains only {@code null},
* {@linkplain org.apache.sis.xml.NilObject nil} or empty properties.
* A non-null and non-nil property is considered empty in any of the following cases:
*
* <ul>
* <li>An empty {@linkplain CharSequence character sequences}.</li>
* <li>An {@linkplain java.util.Collection#isEmpty() empty collection} or an empty array.</li>
* <li>A collection or array containing only {@code null}, nil or empty elements.</li>
* <li>An other metadata object containing only {@code null}, nil or empty properties.</li>
* </ul>
*
* Note that empty properties can be removed by calling the {@link ModifiableMetadata#prune()} method.
*
* <h4>Note for implementers</h4>
* The default implementation uses Java reflection indirectly, by iterating over all entries
* returned by {@link MetadataStandard#asValueMap(Object, Class, KeyNamePolicy, ValueExistencePolicy)}.
* Subclasses that override this method should usually not invoke {@code super.isEmpty()},
* because the Java reflection will discover and process the properties defined in the
* subclasses - which is usually not the intent when overriding a method.
*
* @return {@code true} if this metadata is empty.
*
* @see org.apache.sis.metadata.iso.extent.DefaultGeographicBoundingBox#isEmpty()
*/
@Override
public boolean isEmpty() {
return Pruner.isEmpty(this, false);
}
/**
* Removes all references to empty properties. The default implementation iterates over all
* {@linkplain ValueExistencePolicy#NON_NULL non null} properties, and sets to {@code null}
* the properties for which {@link #isEmpty()} returned {@code true}.
*
* @throws UnmodifiableMetadataException if this metadata is not modifiable.
*/
public void prune() {
Pruner.isEmpty(this, true);
}
/**
* Returns a view of the property values in a {@link Map}. The map is backed by this metadata
* object, so changes in the underlying metadata object are immediately reflected in the map
* and conversely.
*
* <h4>Supported operations</h4>
* The map supports the {@link Map#put(Object, Object) put(…)} and {@link Map#remove(Object)
* remove(…)} operations if the underlying metadata object contains setter methods.
* The {@code remove(…)} method is implemented by a call to {@code put(…, null)}.
*
* <h4>Keys and values</h4>
* The keys are case-insensitive and can be either the JavaBeans property name, the getter method name
* or the {@linkplain org.opengis.annotation.UML#identifier() UML identifier}. The value given to a call
* to the {@code put(…)} method shall be an instance of the type expected by the corresponding setter method,
* or an instance of a type {@linkplain org.apache.sis.util.ObjectConverters#find(Class, Class) convertible}
* to the expected type.
*
* <h4>Multi-values entries</h4>
* Calls to {@code put(…)} replace the previous value, with one noticeable exception: if the metadata
* property associated to the given key is a {@link java.util.Collection} but the given value is a single
* element (not a collection), then the given value is {@linkplain java.util.Collection#add(Object) added}
* to the existing collection. In other words, the returned map behaves as a <cite>multi-values map</cite>
* for the properties that allow multiple values. If the intent is to unconditionally discard all previous
* values, then make sure that the given value is a collection when the associated metadata property expects
* such collection.
*
* <h4>Default implementation</h4>
* The default implementation is equivalent to the following method call:
*
* {@preformat java
* return getStandard().asValueMap(this, null, KeyNamePolicy.JAVABEANS_PROPERTY, ValueExistencePolicy.NON_EMPTY);
* }
*
* @return a view of this metadata object as a map.
*
* @see MetadataStandard#asValueMap(Object, Class, KeyNamePolicy, ValueExistencePolicy)
*/
public Map<String,Object> asMap() {
return getStandard().asValueMap(this, null, KeyNamePolicy.JAVABEANS_PROPERTY, ValueExistencePolicy.NON_EMPTY);
}
/**
* Returns the property types and values as a tree table.
* The tree table is backed by the metadata object using Java reflection, so changes in the
* underlying metadata object are immediately reflected in the tree table and conversely.
*
* <p>The returned {@code TreeTable} instance contains the following columns:</p>
* <ul class="verbose">
* <li>{@link org.apache.sis.util.collection.TableColumn#IDENTIFIER}<br>
* The {@linkplain org.opengis.annotation.UML#identifier() UML identifier} if any,
* or the Java Beans property name otherwise, of a metadata property. For example
* in a tree table view of {@link org.apache.sis.metadata.iso.citation.DefaultCitation},
* there is a node having the {@code "title"} identifier.</li>
*
* <li>{@link org.apache.sis.util.collection.TableColumn#INDEX}<br>
* If the metadata property is a collection, then the zero-based index of the element in that collection.
* Otherwise {@code null}. For example in a tree table view of {@code DefaultCitation}, if the
* {@code "alternateTitle"} collection contains two elements, then there is a node with index 0
* for the first element and an other node with index 1 for the second element.
*
* <div class="note"><b>Note:</b>
* The {@code (IDENTIFIER, INDEX)} pair can be used as a primary key for uniquely identifying a node
* in a list of children. That uniqueness is guaranteed only for the children of a given node;
* the same keys may appear in the children of any other nodes.</div></li>
*
* <li>{@link org.apache.sis.util.collection.TableColumn#NAME}<br>
* A human-readable name for the node, derived from the identifier and the index.
* This is the column shown in the default {@link #toString()} implementation and
* may be localizable.</li>
*
* <li>{@link org.apache.sis.util.collection.TableColumn#TYPE}<br>
* The base type of the value (usually an interface).</li>
*
* <li>{@link org.apache.sis.util.collection.TableColumn#VALUE}<br>
* The metadata value for the node. Values in this column are writable if the underlying
* metadata class have a setter method for the property represented by the node.</li>
*
* <li>{@link org.apache.sis.util.collection.TableColumn#REMARKS}<br>
* Remarks or warning on the property value. This is rarely present.
* It is provided when the value may look surprising, for example the longitude values
* in a geographic bounding box spanning the anti-meridian.</li>
* </ul>
*
* <h4>Write operations</h4>
* Only the {@code VALUE} column may be writable, with one exception: newly created children need
* to have their {@code IDENTIFIER} set before any other operation. For example the following code
* adds a title to a citation:
*
* {@preformat java
* TreeTable.Node node = ...; // The node for a DefaultCitation.
* TreeTable.Node child = node.newChild();
* child.setValue(TableColumn.IDENTIFIER, "title");
* child.setValue(TableColumn.VALUE, "Le petit prince");
* // Nothing else to do - the child node has been added.
* }
*
* Nodes can be removed by invoking the {@link java.util.Iterator#remove()} method on the
* {@linkplain org.apache.sis.util.collection.TreeTable.Node#getChildren() children} iterator.
*
* <h4>Default implementation</h4>
* The default implementation is equivalent to the following method call:
*
* {@preformat java
* return getStandard().asTreeTable(this, null, ValueExistencePolicy.COMPACT);
* }
*
* @return a tree table representation of the specified metadata.
*
* @see MetadataStandard#asTreeTable(Object, Class, ValueExistencePolicy)
*/
public TreeTable asTreeTable() {
return getStandard().asTreeTable(this, null, ValueExistencePolicy.COMPACT);
}
/**
* Compares this metadata with the specified object for equality. The default
* implementation uses Java reflection. Subclasses may override this method
* for better performances, or for comparing "hidden" properties not specified
* by the GeoAPI (or other standard) interface.
*
* @param object the object to compare with this metadata.
* @param mode the strictness level of the comparison.
* @return {@code true} if the given object is equal to this metadata.
*/
@Override
public boolean equals(final Object object, final ComparisonMode mode) {
return getStandard().equals(this, object, mode);
}
/**
* Performs a {@linkplain ComparisonMode#STRICT strict} comparison of this metadata with
* the given object. This method is implemented as below:
*
* {@preformat java
* public final boolean equals(final Object object) {
* return equals(object, ComparisonMode.STRICT);
* }
* }
*
* If a subclass needs to override the behavior of this method, then
* override {@link #equals(Object, ComparisonMode)} instead.
*
* @param object the object to compare with this metadata for equality.
* @return {@code true} if the given object is strictly equals to this metadata.
*/
@Override
public final boolean equals(final Object object) {
return equals(object, ComparisonMode.STRICT);
}
/**
* Computes a hash code value for this metadata using Java reflection. The hash code
* is defined as the sum of hash code values of all non-empty properties, excluding
* cyclic dependencies. For acyclic metadata, this method contract is compatible with
* the {@link java.util.Set#hashCode()} one and ensures that the hash code value is
* insensitive to the ordering of properties.
*
* <div class="note"><b>Implementation note:</b>
* This method does not cache the value because current implementation has no notification mechanism
* for tracking changes in children properties. If this metadata is known to be immutable,
* then subclasses may consider caching the hash code value if performance is important.</div>
*
* @see MetadataStandard#hashCode(Object)
*/
@Override
public int hashCode() {
return getStandard().hashCode(this);
}
/**
* Returns a string representation of this metadata.
* The default implementation is as below:
*
* {@preformat java
* return asTreeTable().toString();
* }
*
* Note that this make extensive use of Unicode characters
* and is better rendered with a monospaced font.
*/
@Override
public String toString() {
return asTreeTable().toString();
}
}
| 46.807692 | 119 | 0.681436 |
31b12f49d3ac7354be65f85e40750cbbcf5d6f91
| 190 |
package team.gif.friendscheduler.exception;
public class IncorrectCredentialsException extends RuntimeException {
public IncorrectCredentialsException(String msg) {
super(msg);
}
}
| 19 | 69 | 0.805263 |
e1380bb802262e78a34670ed3950816b5a15b24c
| 1,566 |
package JavaFramework.SnapdealTests;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import pageObjects.SnapdealObjects.SnapdealSearchPage;
import pageObjects.SnapdealObjects.snapdealHomePage;
import resources.BrowserFactory;
public class snapdealScenarioTest extends BrowserFactory{
public static Logger log = LogManager.getLogger(BrowserFactory.class.getName());
@BeforeTest
public void setup() throws IOException{
driver = invokeBrowser();
driver.get("https://www.snapdeal.com");
log.info("Opened homepage");
}
@Test
public void testPriceSlider(){
System.out.println("Test Running");
snapdealHomePage home = new snapdealHomePage(driver);
home.getSearchField().sendKeys(prop.getProperty("snapdealSearchProduct"));
log.debug("Searched the product");
home.getSearchButton().click();
SnapdealSearchPage searchPage = new SnapdealSearchPage(driver);
Actions action = new Actions(driver);
action.dragAndDropBy(searchPage.getLeftSlider(), 0, 199).build().perform();
action.dragAndDropBy(searchPage.getRightSlider(), 0, 225).build().perform();
System.out.println("Left is "+searchPage.getFromText().getText());
System.out.println("Right is "+searchPage.getToText().getText());
}
@AfterTest
public void tearDown(){
driver.close();
driver=null;
}
}
| 31.32 | 81 | 0.777139 |
57194f6710948ffe22211cedcf20c080cf453d61
| 12,962 |
/*
* Copyright 2019 Ortis (ortis@ortis.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.ortis.jsafebox.gui;
import io.ortis.jsafebox.gui.tasks.CreateTask;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
/**
* @author Ortis
*/
public class NewSafeFrame extends javax.swing.JDialog implements MouseListener, ActionListener
{
private static final DateTimeFormatter FILENAME_DATETIME_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel createLabel;
private javax.swing.JPanel mainPanel;
private javax.swing.JLabel password1MetaLabel;
private javax.swing.JPasswordField password1TextField;
private javax.swing.JLabel password2MetaLabel;
private javax.swing.JPasswordField password2TextField;
private javax.swing.JLabel pbkdf2MetaLabel;
private javax.swing.JSpinner pbkdf2Spinner;
// End of variables declaration//GEN-END:variables
private File created = null;
/**
* Creates new form LoginFrame
*/
public NewSafeFrame(final Window parent)
{
super(parent);
initComponents();
final Settings settings = Settings.getSettings();
mainPanel.setBackground(settings.getUITheme().getBackgroundColor());
settings.applyMetaDataFieldLabelStyle(this.pbkdf2MetaLabel);
final JSpinner.NumberEditor editor = new JSpinner.NumberEditor(this.pbkdf2Spinner, "#");
this.pbkdf2Spinner.setEditor(editor);
this.pbkdf2Spinner.setValue(Integer.valueOf(1000000));
settings.applyMetaDataFieldLabelStyle(this.password1MetaLabel);
this.password1TextField.setText("");
this.password1TextField.addActionListener(this);
settings.applyMetaDataFieldLabelStyle(this.password2MetaLabel);
this.password2TextField.setText("");
this.password2TextField.addActionListener(this);
settings.applyFirstButtonStyle(this.createLabel);
this.createLabel.addMouseListener(this);
setIconImages(settings.getFrameIcons());
setModal(true);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
//setSize(Toolkit.getDefaultToolkit().getScreenSize().width * 1 / 3, Toolkit.getDefaultToolkit().getScreenSize().height * 1 / 3);
setResizable(false);
setLocationRelativeTo(parent);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents()
{
mainPanel = new javax.swing.JPanel();
createLabel = new javax.swing.JLabel();
pbkdf2Spinner = new javax.swing.JSpinner();
pbkdf2MetaLabel = new javax.swing.JLabel();
password1MetaLabel = new javax.swing.JLabel();
password2MetaLabel = new javax.swing.JLabel();
password1TextField = new javax.swing.JPasswordField();
password2TextField = new javax.swing.JPasswordField();
createLabel.setBackground(new java.awt.Color(255, 102, 0));
createLabel.setFont(new java.awt.Font("Segoe UI", 1, 16)); // NOI18N
createLabel.setForeground(new java.awt.Color(255, 255, 255));
createLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
createLabel.setText("Create");
createLabel.setOpaque(true);
pbkdf2Spinner.setFont(new java.awt.Font("Consolas", 0, 12)); // NOI18N
pbkdf2Spinner.setModel(new javax.swing.SpinnerNumberModel(1000000, 10000, null, 1000));
pbkdf2MetaLabel.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
pbkdf2MetaLabel.setForeground(new java.awt.Color(76, 69, 69));
pbkdf2MetaLabel.setText("PBKDF2");
password1MetaLabel.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
password1MetaLabel.setForeground(new java.awt.Color(76, 69, 69));
password1MetaLabel.setText("Password");
password2MetaLabel.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
password2MetaLabel.setForeground(new java.awt.Color(76, 69, 69));
password2MetaLabel.setText("Confirm Password");
password1TextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
password1TextField.setText("jPasswordField1");
password2TextField.setHorizontalAlignment(javax.swing.JTextField.CENTER);
password2TextField.setText("jPasswordField1");
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
mainPanelLayout.createSequentialGroup().addContainerGap().addGroup(mainPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING).addGroup(mainPanelLayout.createSequentialGroup().addComponent(pbkdf2MetaLabel,
javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(pbkdf2Spinner, javax.swing.GroupLayout.PREFERRED_SIZE, 130,
javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)).addGroup(
mainPanelLayout.createSequentialGroup().addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
mainPanelLayout.createSequentialGroup().addComponent(password2MetaLabel).addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(password2TextField, javax.swing.GroupLayout.DEFAULT_SIZE, 363,
Short.MAX_VALUE)).addGroup(mainPanelLayout.createSequentialGroup().addComponent(password1MetaLabel,
javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(password1TextField))).addGap(15, 15, 15)))).addGroup(
javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup().addGap(77, 77, 77).addComponent(createLabel,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addGap(80, 80, 80)));
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
mainPanelLayout.createSequentialGroup().addGap(22, 22, 22).addGroup(mainPanelLayout.createParallelGroup(
javax.swing.GroupLayout.Alignment.LEADING).addComponent(pbkdf2MetaLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 31,
javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(pbkdf2Spinner, javax.swing.GroupLayout.PREFERRED_SIZE, 31,
javax.swing.GroupLayout.PREFERRED_SIZE)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(password1MetaLabel,
javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(password1TextField,
javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(password2MetaLabel,
javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(password2TextField,
javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 51,
Short.MAX_VALUE).addComponent(createLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE).addGap(21,
21, 21)));
getContentPane().add(mainPanel, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
public File getCreated()
{
return created;
}
@Override
public void mouseClicked(final MouseEvent mouseEvent)
{
final Object source = mouseEvent.getSource();
if(source == null)
return;
if(source == this.createLabel)
{
final JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
fileChooser.setSelectedFile(new File("safe-" + FILENAME_DATETIME_FORMAT.format(LocalDateTime.now()) + ".jsb"));
fileChooser.setFileFilter(new FileNameExtensionFilter("JSafebox file", "jsb"));
fileChooser.setCurrentDirectory(Settings.getDefaultDirectory());
String filename = null;
if(fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
{
filename = fileChooser.getSelectedFile().toString();
if(!filename.toUpperCase(Locale.ENGLISH).endsWith(".JSB"))
filename += ".jsb";
}
if(filename == null)
return;
Settings.setDefaultDirectory(filename);
final String pbkdf2IterationString = ((JSpinner.DefaultEditor) pbkdf2Spinner.getEditor()).getTextField().getText();
final char[] pwd1 = password1TextField.getPassword();
final char[] pwd2 = password2TextField.getPassword();
final File destination = new File(filename);
final CreateTask task = new CreateTask(destination, pbkdf2IterationString, pwd1, pwd2, GUI.getLogger());
final ProgressFrame progressFrame = new ProgressFrame(this);
progressFrame.execute(task);
if(task.getException() == null)
{
GUI.getSettings().addSafeFilePath(filename);
this.created = destination;
dispose();
}
}
}
@Override
public void mousePressed(final MouseEvent mouseEvent)
{
}
@Override
public void mouseReleased(final MouseEvent mouseEvent)
{
}
@Override
public void mouseEntered(final MouseEvent e)
{
if(e.getSource() == null)
return;
if(e.getSource() == this.createLabel)
{
GUI.getSettings().applyFirstButtonMouseOverStyle(this.createLabel);
}
}
@Override
public void mouseExited(final MouseEvent e)
{
if(e.getSource() == null)
return;
if(e.getSource() == createLabel)
{
GUI.getSettings().applyFirstButtonStyle(this.createLabel);
}
}
@Override
public void actionPerformed(final ActionEvent e)
{
final Component component = (Component) e.getSource();
if(component == null)
return;
if(component == this.password1TextField)
{
this.password2TextField.requestFocus();
}
else if(component == this.password2TextField)
{
final MouseEvent me = new MouseEvent(createLabel, 0, 0, 0, 0, 0, 0, 0, 0, false, 0);
mouseClicked(me);// simulate click
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[])
{
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try
{
for(javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
{
if("Nimbus".equals(info.getName()))
{
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch(ClassNotFoundException ex)
{
java.util.logging.Logger.getLogger(NewSafeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch(InstantiationException ex)
{
java.util.logging.Logger.getLogger(NewSafeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch(IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(NewSafeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch(javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(NewSafeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new NewSafeFrame(null).setVisible(true);
}
});
}
}
| 39.160121 | 145 | 0.764157 |
3c5759fab9465e125c7d609913975070ff6cb152
| 272 |
package com.jab.streams.sources;
import java.util.Arrays;
public class Example2 {
public static void main(String[] args) {
Arrays.asList("a1", "a2", "a3")
.stream()
.findFirst()
.ifPresent(System.out::println);
}
}
| 17 | 44 | 0.566176 |
6d8846ca630094e8f67a8fa45631b2d0ca58402b
| 2,975 |
/**
* Copyright 2015 IBM Corp. All Rights Reserved.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.ibm.watson.developer_cloud.text_to_speech.v1;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.util.List;
import com.ibm.watson.developer_cloud.text_to_speech.v1.model.AudioFormat;
import com.ibm.watson.developer_cloud.text_to_speech.v1.model.CustomTranslation;
import com.ibm.watson.developer_cloud.text_to_speech.v1.model.CustomVoiceModel;
import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voice;
import com.ibm.watson.developer_cloud.text_to_speech.v1.util.WaveUtils;
public class CustomizationExample {
public static void main(String[] args) throws IOException {
TextToSpeech service = new TextToSpeech("<username>", "<password>");
//create custom voice model.
CustomVoiceModel model = new CustomVoiceModel();
model.setName("my model");
model.setLanguage("en-us");
model.setDescription("the model for testing");
CustomVoiceModel customVoiceModel = service.saveCustomVoiceModel(model).execute();
System.out.println(customVoiceModel);
//list custom voice models
List<CustomVoiceModel> customVoiceModels = service.getCustomVoiceModels("en-us").execute();
System.out.println(customVoiceModels);
//create custom word translations
CustomTranslation customTranslation1 = new CustomTranslation("hodor", "hold the door");
CustomTranslation customTranslation2 = new CustomTranslation("plz", "please");
service.saveWords(customVoiceModel, customTranslation1, customTranslation2).execute();
//get custom word translations
List<CustomTranslation> words = service.getWords(customVoiceModel).execute();
System.out.println(words);
//synthesize with custom voice model
String text = "plz hodor";
InputStream in = service.synthesize(text, Voice.EN_MICHAEL, AudioFormat.WAV, customVoiceModel.getId()).execute();
writeToFile(WaveUtils.reWriteWaveHeader(in), new File("output.wav"));
}
private static void writeToFile(InputStream in, File file) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 39.144737 | 117 | 0.738824 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.