code
stringlengths 3
1.04M
| repo_name
stringlengths 5
109
| path
stringlengths 6
306
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 3
1.04M
|
---|---|---|---|---|---|
package org.innovateuk.ifs.assessment.invite.controller;
import org.innovateuk.ifs.BaseControllerMockMVCTest;
import org.innovateuk.ifs.assessment.invite.form.ReviewInviteForm;
import org.innovateuk.ifs.assessment.invite.populator.ReviewInviteModelPopulator;
import org.innovateuk.ifs.assessment.invite.viewmodel.ReviewInviteViewModel;
import org.innovateuk.ifs.invite.resource.RejectionReasonResource;
import org.innovateuk.ifs.invite.resource.ReviewInviteResource;
import org.innovateuk.ifs.invite.service.RejectionReasonRestService;
import org.innovateuk.ifs.review.service.ReviewInviteRestService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.validation.BindingResult;
import java.time.ZonedDateTime;
import java.util.List;
import static java.lang.Boolean.TRUE;
import static java.util.Collections.nCopies;
import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError;
import static org.innovateuk.ifs.commons.error.CommonFailureKeys.GENERAL_NOT_FOUND;
import static org.innovateuk.ifs.commons.rest.RestResult.restFailure;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.innovateuk.ifs.invite.builder.RejectionReasonResourceBuilder.newRejectionReasonResource;
import static org.innovateuk.ifs.review.builder.ReviewInviteResourceBuilder.newReviewInviteResource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
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.*;
@RunWith(MockitoJUnitRunner.Silent.class)
@TestPropertySource(locations = { "classpath:application.properties", "classpath:/application-web-core.properties"} )
public class ReviewInviteControllerTest extends BaseControllerMockMVCTest<ReviewInviteController> {
@Spy
@InjectMocks
private ReviewInviteModelPopulator reviewInviteModelPopulator;
@Mock
private RejectionReasonRestService rejectionReasonRestService;
@Mock
private ReviewInviteRestService reviewInviteRestService;
private List<RejectionReasonResource> rejectionReasons = newRejectionReasonResource()
.withReason("Reason 1", "Reason 2")
.build(2);
private static final String restUrl = "/invite/panel/";
@Override
protected ReviewInviteController supplyControllerUnderTest() {
return new ReviewInviteController();
}
@Before
public void setUp() {
when(rejectionReasonRestService.findAllActive()).thenReturn(restSuccess(rejectionReasons));
}
@Test
public void acceptInvite_loggedIn() throws Exception {
Boolean accept = true;
mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("acceptInvitation", accept.toString()))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/invite-accept/panel/hash/accept"));
verifyZeroInteractions(reviewInviteRestService);
}
@Test
public void acceptInvite_notLoggedInAndExistingUser() throws Exception {
setLoggedInUser(null);
ZonedDateTime panelDate = ZonedDateTime.now();
Boolean accept = true;
ReviewInviteResource inviteResource = newReviewInviteResource()
.withCompetitionName("my competition")
.withPanelDate(panelDate)
.build();
ReviewInviteViewModel expectedViewModel = new ReviewInviteViewModel("hash", inviteResource, false);
when(reviewInviteRestService.checkExistingUser("hash")).thenReturn(restSuccess(TRUE));
when(reviewInviteRestService.openInvite("hash")).thenReturn(restSuccess(inviteResource));
mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("acceptInvitation", accept.toString()))
.andExpect(status().isOk())
.andExpect(model().attribute("model", expectedViewModel))
.andExpect(view().name("assessor-panel-accept-user-exists-but-not-logged-in"));
InOrder inOrder = inOrder(reviewInviteRestService);
inOrder.verify(reviewInviteRestService).checkExistingUser("hash");
inOrder.verify(reviewInviteRestService).openInvite("hash");
inOrder.verifyNoMoreInteractions();
}
@Test
public void confirmAcceptInvite() throws Exception {
when(reviewInviteRestService.acceptInvite("hash")).thenReturn(restSuccess());
mockMvc.perform(get("/invite-accept/panel/{inviteHash}/accept", "hash"))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/assessor/dashboard"));
verify(reviewInviteRestService).acceptInvite("hash");
}
@Test
public void confirmAcceptInvite_hashNotExists() throws Exception {
when(reviewInviteRestService.acceptInvite("notExistHash")).thenReturn(restFailure(GENERAL_NOT_FOUND));
mockMvc.perform(get("/invite-accept/panel/{inviteHash}/accept", "notExistHash"))
.andExpect(status().isNotFound());
verify(reviewInviteRestService).acceptInvite("notExistHash");
}
@Test
public void openInvite() throws Exception {
ZonedDateTime panelDate = ZonedDateTime.now();
ReviewInviteResource inviteResource = newReviewInviteResource().withCompetitionName("my competition")
.withPanelDate(panelDate)
.build();
ReviewInviteViewModel expectedViewModel = new ReviewInviteViewModel("hash", inviteResource, true);
when(reviewInviteRestService.openInvite("hash")).thenReturn(restSuccess(inviteResource));
mockMvc.perform(get(restUrl + "{inviteHash}", "hash"))
.andExpect(status().isOk())
.andExpect(view().name("assessor-panel-invite"))
.andExpect(model().attribute("model", expectedViewModel));
verify(reviewInviteRestService).openInvite("hash");
}
@Test
public void openInvite_hashNotExists() throws Exception {
when(reviewInviteRestService.openInvite("notExistHash")).thenReturn(restFailure(notFoundError(ReviewInviteResource.class, "notExistHash")));
mockMvc.perform(get(restUrl + "{inviteHash}", "notExistHash"))
.andExpect(model().attributeDoesNotExist("model"))
.andExpect(status().isNotFound());
verify(reviewInviteRestService).openInvite("notExistHash");
}
@Test
public void noDecisionMade() throws Exception {
ReviewInviteResource inviteResource = newReviewInviteResource().withCompetitionName("my competition").build();
when(reviewInviteRestService.openInvite("hash")).thenReturn(restSuccess(inviteResource));
ReviewInviteForm expectedForm = new ReviewInviteForm();
MvcResult result = mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash"))
.andExpect(status().isOk())
.andExpect(model().hasErrors())
.andExpect(model().attributeHasFieldErrors("form", "acceptInvitation"))
.andExpect(model().attribute("form", expectedForm))
.andExpect(model().attribute("rejectionReasons", rejectionReasons))
.andExpect(model().attributeExists("model"))
.andExpect(view().name("assessor-panel-invite")).andReturn();
ReviewInviteViewModel model = (ReviewInviteViewModel) result.getModelAndView().getModel().get("model");
assertEquals("hash", model.getPanelInviteHash());
assertEquals("my competition", model.getCompetitionName());
ReviewInviteForm form = (ReviewInviteForm) result.getModelAndView().getModel().get("form");
BindingResult bindingResult = form.getBindingResult();
assertTrue(bindingResult.hasErrors());
assertEquals(0, bindingResult.getGlobalErrorCount());
assertEquals(1, bindingResult.getFieldErrorCount());
assertTrue(bindingResult.hasFieldErrors("acceptInvitation"));
assertEquals("Please indicate your decision.", bindingResult.getFieldError("acceptInvitation").getDefaultMessage());
verify(reviewInviteRestService).openInvite("hash");
verifyNoMoreInteractions(reviewInviteRestService);
}
@Test
public void rejectInvite() throws Exception {
Boolean accept = false;
when(reviewInviteRestService.rejectInvite("hash")).thenReturn(restSuccess());
mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("acceptInvitation", accept.toString()))
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/invite/panel/hash/reject/thank-you"));
verify(reviewInviteRestService).rejectInvite("hash");
verifyNoMoreInteractions(reviewInviteRestService);
}
@Test
public void rejectInvite_hashNotExists() throws Exception {
String comment = String.join(" ", nCopies(100, "comment"));
Boolean accept = false;
when(reviewInviteRestService.rejectInvite("notExistHash")).thenReturn(restFailure(notFoundError(ReviewInviteResource.class, "notExistHash")));
when(reviewInviteRestService.openInvite("notExistHash")).thenReturn(restFailure(notFoundError(ReviewInviteResource.class, "notExistHash")));
mockMvc.perform(post(restUrl + "{inviteHash}/decision", "notExistHash")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("acceptInvitation", accept.toString()))
.andExpect(status().isNotFound());
InOrder inOrder = inOrder(reviewInviteRestService);
inOrder.verify(reviewInviteRestService).rejectInvite("notExistHash");
inOrder.verify(reviewInviteRestService).openInvite("notExistHash");
inOrder.verifyNoMoreInteractions();
}
@Test
public void rejectThankYou() throws Exception {
mockMvc.perform(get(restUrl + "{inviteHash}/reject/thank-you", "hash"))
.andExpect(status().isOk())
.andExpect(view().name("assessor-panel-reject"))
.andReturn();
}
}
|
InnovateUKGitHub/innovation-funding-service
|
ifs-web-service/ifs-assessment-service/src/test/java/org/innovateuk/ifs/assessment/invite/controller/ReviewInviteControllerTest.java
|
Java
|
mit
| 10,855 |
package org.innovateuk.ifs.registration.service;
import org.springframework.web.context.request.RequestAttributes;
import java.util.HashMap;
import java.util.Map;
/**
* This solves the java.lang.IllegalStateException: Cannot ask for request attribute - request is not active anymore!
* Error, Request attributes are reset before the organisation is updates and removed afterwards.
* @see https://stackoverflow.com/questions/44121654/inherited-servletrquestattributes-is-marked-completed-before-child-thread-finish
* @see https://medium.com/@pranav_maniar/spring-accessing-request-scope-beans-outside-of-web-request-faad27b5ed57
*
*/
public class CustomRequestScopeAttr implements RequestAttributes {
private Map<String, Object> requestAttributeMap = new HashMap<>();
@Override
public Object getAttribute(String name, int scope) {
if (scope == RequestAttributes.SCOPE_REQUEST) {
return this.requestAttributeMap.get(name);
}
return null;
}
@Override
public void setAttribute(String name, Object value, int scope) {
if (scope == RequestAttributes.SCOPE_REQUEST) {
this.requestAttributeMap.put(name, value);
}
}
@Override
public void removeAttribute(String name, int scope) {
if (scope == RequestAttributes.SCOPE_REQUEST) {
this.requestAttributeMap.remove(name);
}
}
@Override
public String[] getAttributeNames(int scope) {
if (scope == RequestAttributes.SCOPE_REQUEST) {
return this.requestAttributeMap.keySet().toArray(new String[0]);
}
return new String[0];
}
@Override
public void registerDestructionCallback(String name, Runnable callback, int scope) {
// Not Supported
}
@Override
public Object resolveReference(String key) {
// Not supported
return null;
}
@Override
public String getSessionId() {
return null;
}
@Override
public Object getSessionMutex() {
return null;
}
}
|
InnovateUKGitHub/innovation-funding-service
|
ifs-web-service/ifs-web-core/src/main/java/org/innovateuk/ifs/registration/service/CustomRequestScopeAttr.java
|
Java
|
mit
| 2,061 |
/*
* Wegas
* http://wegas.albasim.ch
*
* Copyright (c) 2013, 2014, 2015 School of Business and Engineering Vaud, Comem
* Licensed under the MIT License
*/
package com.wegas.core.security.persistence;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.JsonView;
import com.wegas.core.persistence.AbstractEntity;
import com.wegas.core.persistence.game.Player;
import com.wegas.core.rest.util.Views;
import javax.persistence.*;
import java.util.*;
////import javax.xml.bind.annotation.XmlTransient;
/**
* @author Francois-Xavier Aeberhard (fx at red-agent.com)
*/
@Entity
@Table(name = "users")
@NamedQueries({
@NamedQuery(name = "User.findUserPermissions", query = "SELECT DISTINCT users FROM User users JOIN users.permissions p WHERE p.value LIKE :instance")
,
@NamedQuery(name = "User.findUsersWithRole", query = "SELECT DISTINCT users FROM User users JOIN users.roles r WHERE r.id = :role_id")
,
@NamedQuery(name = "User.findUserWithPermission", query = "SELECT DISTINCT users FROM User users JOIN users.permissions p WHERE p.value LIKE :permission AND p.user.id =:userId")
})
public class User extends AbstractEntity implements Comparable<User> {
private static final long serialVersionUID = 1L;
/**
*
*/
@Id
@GeneratedValue
private Long id;
/**
*
*/
@OneToMany(mappedBy = "user", cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH} /*, orphanRemoval = true */)
@JsonManagedReference(value = "player-user")
private List<Player> players = new ArrayList<>();
/**
*
*/
@OneToMany(mappedBy = "user", cascade = {CascadeType.ALL}, orphanRemoval = true)
@JsonManagedReference(value = "user-account")
private List<AbstractAccount> accounts = new ArrayList<>();
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user")
@JsonIgnore
private List<Permission> permissions = new ArrayList<>();
@ManyToMany
@JsonView(Views.ExtendedI.class)
@JoinTable(name = "users_roles",
joinColumns = {
@JoinColumn(name = "users_id", referencedColumnName = "id")},
inverseJoinColumns = {
@JoinColumn(name = "roles_id", referencedColumnName = "id")})
private Set<Role> roles = new HashSet<>();
/**
*
*/
public User() {
}
/**
* @param acc
*/
public User(AbstractAccount acc) {
this.addAccount(acc);
}
@Override
public Long getId() {
return id;
}
@Override
public void merge(AbstractEntity a) {
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* @return all user's players
*/
//@XmlTransient
@JsonIgnore
@JsonManagedReference(value = "player-user")
public List<Player> getPlayers() {
return players;
}
/**
* @param players the players to set
*/
@JsonManagedReference(value = "player-user")
public void setPlayers(List<Player> players) {
this.players = players;
}
/**
* @return the accounts
*/
public List<AbstractAccount> getAccounts() {
return accounts;
}
/**
* @param accounts the accounts to set
*/
public void setAccounts(List<AbstractAccount> accounts) {
this.accounts = accounts;
}
/**
* @param account
*/
public final void addAccount(AbstractAccount account) {
this.accounts.add(account);
account.setUser(this);
}
/**
* @return first user account
*/
//@XmlTransient
@JsonIgnore
public final AbstractAccount getMainAccount() {
if (!this.accounts.isEmpty()) {
return this.accounts.get(0);
} else {
return null;
}
}
/**
* Shortcut for getMainAccount().getName();
*
* @return main account name or unnamed if user doesn't have any account
*/
public String getName() {
if (this.getMainAccount() != null) {
return this.getMainAccount().getName();
} else {
return "unnamed";
}
}
/**
* @return the permissions
*/
public List<Permission> getPermissions() {
return this.permissions;
}
/**
* @param permissions the permissions to set
*/
public void setPermissions(List<Permission> permissions) {
this.permissions = permissions;
for (Permission p : this.permissions) {
p.setUser(this);
}
}
public boolean removePermission(Permission permission) {
return this.permissions.remove(permission);
}
/**
* @param permission
* @return true id the permission has successfully been added
*/
public boolean addPermission(Permission permission) {
if (!this.permissions.contains(permission)) {
permission.setUser(this);
return this.permissions.add(permission);
} else {
return false;
}
}
/**
* @return the roles
*/
public Set<Role> getRoles() {
return roles;
}
/**
* @param roles the roles to set
*/
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
/**
* @param role
*/
public void addRole(Role role) {
this.roles.add(role);
}
/**
* strike out this account from the role
*
* @param role
*/
public void removeRole(Role role) {
this.roles.remove(role);
}
@Override
public int compareTo(User o) {
return this.getName().toLowerCase(Locale.ENGLISH).compareTo(o.getName().toLowerCase(Locale.ENGLISH));
}
}
|
ghiringh/Wegas
|
wegas-core/src/main/java/com/wegas/core/security/persistence/User.java
|
Java
|
mit
| 5,838 |
package ninja.egg82.concurrent;
import java.util.Set;
public interface IConcurrentSet<T> extends Set<T> {
//functions
int getRemainingCapacity();
int getCapacity();
}
|
egg82/Java-Lib
|
Collections-Lib/src/ninja/egg82/concurrent/IConcurrentSet.java
|
Java
|
mit
| 172 |
package com.xiaofeng;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringcloudConfigClientApplicationTests {
@Test
public void contextLoads() {
}
}
|
nellochen/springboot-start
|
springcloud-config-client/src/test/java/com/xiaofeng/SpringcloudConfigClientApplicationTests.java
|
Java
|
mit
| 346 |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
package multiverse.server.engine;
import java.util.Collection;
import java.util.Map;
import java.util.HashMap;
import java.util.LinkedList;
import multiverse.server.util.Log;
import multiverse.server.objects.ObjectType;
import multiverse.server.engine.Searchable;
import multiverse.server.messages.SearchMessageFilter;
import multiverse.server.messages.SearchMessage;
import multiverse.msgsys.*;
/** Object search framework. You can search for objects matching your
criteria.
<p>
The platform provides the following searchable collections:
<ul>
<li>Markers - Search for markers in an instance by marker properties. Use
SearchClause {@link multiverse.server.objects.Marker.Search Marker.Search}
<li>Regions - Search for regions in an instance by region properties. Use
SearchClause {@link multiverse.server.objects.Region.Search Region.Search}
<li>Instances - Search for instances by instance properties. Use
SearchClass {@link multiverse.server.engine.PropertySearch PropertySearch}
</ul>
<p>
Plugins can register searchable object collections using
{@link #registerSearchable registerSearchable()}.
*/
public class SearchManager
{
private SearchManager() {
}
/** Search for matching objects and get selected information.
Search occurs for a single ObjectType. Information indicated
in the 'SearchSelection' is returned for objects matching
the 'SearchClause'.
<p>
The search clause is a SearchClass sub-class designed specifically
for an object type (or class of object types).
@param objectType Search for this object type
@param searchClause Object matching criteria
@param selection Information selection; only the indicated
information will be returned.
@return Collection of matching objects.
*/
public static Collection searchObjects(ObjectType objectType,
SearchClause searchClause, SearchSelection selection)
{
SearchMessage message = new SearchMessage(objectType,
searchClause, selection);
Collector collector = new Collector(message);
return collector.getResults();
}
static class Collector implements ResponseCallback
{
public Collector(SearchMessage message)
{
searchMessage = message;
}
public Collection getResults()
{
int expectedResponses = Engine.getAgent().sendBroadcastRPC(searchMessage, this);
synchronized (this) {
responders += expectedResponses;
while (responders != 0) {
try {
this.wait();
} catch (InterruptedException e) {
}
}
}
return results;
}
public synchronized void handleResponse(ResponseMessage rr)
{
responders --;
GenericResponseMessage response = (GenericResponseMessage) rr;
Collection list = (Collection)response.getData();
if (list != null)
results.addAll(list);
if (responders == 0)
this.notify();
}
Collection results = new LinkedList();
SearchMessage searchMessage;
int responders = 0;
}
/** Register a new searchable object collection.
@param objectType Collection object type.
@param searchable Object search implementation.
*/
public static void registerSearchable(ObjectType objectType,
Searchable searchable)
{
SearchMessageFilter filter = new SearchMessageFilter(objectType);
Engine.getAgent().createSubscription(filter,
new SearchMessageCallback(searchable), MessageAgent.RESPONDER);
}
/** Register object match factory. A MatcherFactory returns a
Matcher object that works for the given search clause and
object class.
@param searchClauseClass A SearchClause sub-class.
@param instanceClass Instance object class.
@param matcherFactory Can return a Matcher object capable of
running the SearchClause against the instance object.
*/
public static void registerMatcher(Class searchClauseClass,
Class instanceClass, MatcherFactory matcherFactory)
{
matchers.put(new MatcherKey(searchClauseClass,instanceClass),
matcherFactory);
}
/** Get object matcher that can apply 'searchClause' to objects of
'instanceClass'.
@param searchClause The matching criteria.
@param instanceClass Instance object class.
*/
public static Matcher getMatcher(SearchClause searchClause,
Class instanceClass)
{
MatcherFactory matcherFactory;
matcherFactory = matchers.get(new MatcherKey(searchClause.getClass(),
instanceClass));
if (matcherFactory == null) {
Log.error("runSearch: No matcher for "+searchClause.getClass()+" "+instanceClass);
return null;
}
return matcherFactory.createMatcher(searchClause);
}
static class MatcherKey {
public MatcherKey(Class qt, Class it)
{
queryType = qt;
instanceType = it;
}
public Class queryType;
public Class instanceType;
public boolean equals(Object key)
{
return (((MatcherKey)key).queryType == queryType) &&
(((MatcherKey)key).instanceType == instanceType);
}
public int hashCode()
{
return queryType.hashCode() + instanceType.hashCode();
}
}
static class SearchMessageCallback implements MessageCallback
{
public SearchMessageCallback(Searchable searchable)
{
this.searchable = searchable;
}
public void handleMessage(Message msg, int flags)
{
SearchMessage message = (SearchMessage) msg;
Collection result = null;
try {
result = searchable.runSearch(
message.getSearchClause(), message.getSearchSelection());
}
catch (Exception e) {
Log.exception("runSearch failed", e);
}
Engine.getAgent().sendObjectResponse(message, result);
}
Searchable searchable;
}
static Map<MatcherKey,MatcherFactory> matchers =
new HashMap<MatcherKey,MatcherFactory>();
}
|
longde123/MultiversePlatform
|
server/src/multiverse/server/engine/SearchManager.java
|
Java
|
mit
| 7,815 |
package crawler.impl;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import main.Constants;
import model.News;
import org.horrabin.horrorss.RssFeed;
import org.horrabin.horrorss.RssItemBean;
import org.horrabin.horrorss.RssParser;
import utils.MiscUtils;
import utils.USDateParser;
import com.google.common.collect.Lists;
import crawler.Crawler;
import dao.KeywordDAO;
import dao.NewsDAO;
import dao.mysql.MySQLKeywordDAO;
import dao.mysql.MySQLNewsDAO;
public class BaiduNewsCrawler implements Crawler{
// private static NewsDAO newsDao = new MongoNewsDAO();
// private static KeywordDAO wordDao = new MongoKeywordDAO();
private NewsDAO newsDao = new MySQLNewsDAO();
private KeywordDAO wordDao = new MySQLKeywordDAO();
@Override
public List<String> getKeywords() {
return MiscUtils.mergeKeywordList(wordDao.query());
// return wordDao.query();
}
@Override
public String buildURL(String keyword) {
// Baidu新闻采用RSS爬虫的形式
String baseURL = "http://news.baidu.com/ns?word=%s&tn=newsrss&sr=0&cl=2&rn=100&ct=0";
String queryURL = null;
try {
queryURL = String.format(baseURL, URLEncoder.encode(keyword, "GB2312"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return queryURL;
}
@Override
public String fetch(String newsURL) {
// do nothing
return null;
}
@Override
public List<News> parse(String str) {
Date now = new Date();
List<News> list = Lists.newArrayList();
RssParser rss = new RssParser();
rss.setCharset("gb2312");
rss.setDateParser(new USDateParser());
try{
RssFeed feed = null;
feed = rss.load(str);
// Gets and iterate the items of the feed
List<RssItemBean> items = feed.getItems();
for(RssItemBean item : items) {
News news = new News();
news.setTitle(item.getTitle());
news.setDescription(item.getDescription());
news.setPubFrom(item.getAuthor());
news.setNewsUrl(item.getLink());
news.setDateTime(item.getPubDate().getTime());
long timeDiff = now.getTime() - item.getPubDate().getTime();
if(timeDiff <= Constants.MSEC_PER_DAY)
list.add(news);
}
}catch(Exception e){
e.printStackTrace();
}
return list;
}
@Override
public Boolean save(List<News> list) {
if(list.size() > 0 && newsDao.save(list) >= 0) {
return true;
} else
return false;
}
public static void main(String[] args) throws UnknownHostException {
}
}
|
RangerWolf/Finance-News-Helper
|
src/crawler/impl/BaiduNewsCrawler.java
|
Java
|
mit
| 2,712 |
package com.reason.ide.console;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.DumbAwareAction;
import org.jetbrains.annotations.NotNull;
class ClearLogAction extends DumbAwareAction {
private final ConsoleView m_console;
ClearLogAction(ConsoleView console) {
super("Clear All", "Clear the contents of the logs", AllIcons.Actions.GC);
m_console = console;
}
@Override
public void update(@NotNull AnActionEvent e) {
Editor editor = e.getData(CommonDataKeys.EDITOR);
e.getPresentation().setEnabled(editor != null && editor.getDocument().getTextLength() > 0);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
m_console.clear();
}
}
|
reasonml-editor/reasonml-idea-plugin
|
src/com/reason/ide/console/ClearLogAction.java
|
Java
|
mit
| 918 |
import org.junit.Test;
import java.util.Stack;
import static junit.framework.Assert.assertEquals;
/**
* https://leetcode.com/problems/min-stack/
*/
public class MinStack {
class StackItem {
int value;
int min;
StackItem(int value, int min) {
this.value = value;
this.min = min;
}
}
Stack<StackItem> stack = new Stack<>();
public void push(int x) {
if (stack.isEmpty()) {
stack.push(new StackItem(x, x));
} else {
int min = stack.peek().min;
if (x < min) {
min = x;
}
stack.push(new StackItem(x, min));
}
}
public void pop() {
stack.pop();
}
public int top() {
return stack.peek().value;
}
public int getMin() {
return stack.peek().min;
}
@Test
public void test() {
MinStack minStack = new MinStack();
minStack.push(10);
assertEquals(10, minStack.getMin());
assertEquals(10, minStack.top());
minStack.push(20);
assertEquals(10, minStack.getMin());
assertEquals(20, minStack.top());
minStack.push(5);
assertEquals(5, minStack.getMin());
assertEquals(5, minStack.top());
}
}
|
bunnyc1986/leetcode
|
min-stack/src/MinStack.java
|
Java
|
mit
| 1,302 |
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
} else {
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
}
|
caizixian/algorithm_exercise
|
LeetCode/104.Maximum Depth of Binary Tree.java
|
Java
|
mit
| 225 |
/**
*
*/
package com.velocity.enums;
/**
* This Enum defines the values for ApplicationLocation
*
* @author Vimal Kumar
* @date 12-March-2015
*/
public enum ApplicationLocation {
HomeInternet, NotSet, OffPremises, OnPremises, Unknown
}
|
nab-velocity/java-sdk
|
velocity-sdk/velocity-services/src/main/java/com/velocity/enums/ApplicationLocation.java
|
Java
|
mit
| 249 |
/*
*
*/
package umlClassMetaModel.diagram.navigator;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.emf.common.ui.URIEditorInput;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.workspace.util.WorkspaceSynchronizer;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.navigator.CommonActionProvider;
import org.eclipse.ui.navigator.ICommonActionConstants;
import org.eclipse.ui.navigator.ICommonActionExtensionSite;
import org.eclipse.ui.navigator.ICommonViewerWorkbenchSite;
import org.eclipse.ui.part.FileEditorInput;
/**
* @generated
*/
public class UmlClassMetaModelNavigatorActionProvider extends
CommonActionProvider {
/**
* @generated
*/
private boolean myContribute;
/**
* @generated
*/
private OpenDiagramAction myOpenDiagramAction;
/**
* @generated
*/
public void init(ICommonActionExtensionSite aSite) {
super.init(aSite);
if (aSite.getViewSite() instanceof ICommonViewerWorkbenchSite) {
myContribute = true;
makeActions((ICommonViewerWorkbenchSite) aSite.getViewSite());
} else {
myContribute = false;
}
}
/**
* @generated
*/
private void makeActions(ICommonViewerWorkbenchSite viewerSite) {
myOpenDiagramAction = new OpenDiagramAction(viewerSite);
}
/**
* @generated
*/
public void fillActionBars(IActionBars actionBars) {
if (!myContribute) {
return;
}
IStructuredSelection selection = (IStructuredSelection) getContext()
.getSelection();
myOpenDiagramAction.selectionChanged(selection);
if (myOpenDiagramAction.isEnabled()) {
actionBars.setGlobalActionHandler(ICommonActionConstants.OPEN,
myOpenDiagramAction);
}
}
/**
* @generated
*/
public void fillContextMenu(IMenuManager menu) {
}
/**
* @generated
*/
private static class OpenDiagramAction extends Action {
/**
* @generated
*/
private Diagram myDiagram;
/**
* @generated
*/
private ICommonViewerWorkbenchSite myViewerSite;
/**
* @generated
*/
public OpenDiagramAction(ICommonViewerWorkbenchSite viewerSite) {
super(
umlClassMetaModel.diagram.part.Messages.NavigatorActionProvider_OpenDiagramActionName);
myViewerSite = viewerSite;
}
/**
* @generated
*/
public final void selectionChanged(IStructuredSelection selection) {
myDiagram = null;
if (selection.size() == 1) {
Object selectedElement = selection.getFirstElement();
if (selectedElement instanceof umlClassMetaModel.diagram.navigator.UmlClassMetaModelNavigatorItem) {
selectedElement = ((umlClassMetaModel.diagram.navigator.UmlClassMetaModelNavigatorItem) selectedElement)
.getView();
} else if (selectedElement instanceof IAdaptable) {
selectedElement = ((IAdaptable) selectedElement)
.getAdapter(View.class);
}
if (selectedElement instanceof Diagram) {
Diagram diagram = (Diagram) selectedElement;
if (umlClassMetaModel.diagram.edit.parts.UmlPackageEditPart.MODEL_ID
.equals(umlClassMetaModel.diagram.part.UmlClassMetaModelVisualIDRegistry
.getModelID(diagram))) {
myDiagram = diagram;
}
}
}
setEnabled(myDiagram != null);
}
/**
* @generated
*/
public void run() {
if (myDiagram == null || myDiagram.eResource() == null) {
return;
}
IEditorInput editorInput = getEditorInput(myDiagram);
IWorkbenchPage page = myViewerSite.getPage();
try {
page.openEditor(
editorInput,
umlClassMetaModel.diagram.part.UmlClassMetaModelDiagramEditor.ID);
} catch (PartInitException e) {
umlClassMetaModel.diagram.part.UmlClassMetaModelDiagramEditorPlugin
.getInstance().logError(
"Exception while openning diagram", e); //$NON-NLS-1$
}
}
/**
* @generated
*/
private static IEditorInput getEditorInput(Diagram diagram) {
Resource diagramResource = diagram.eResource();
for (EObject nextEObject : diagramResource.getContents()) {
if (nextEObject == diagram) {
return new FileEditorInput(
WorkspaceSynchronizer.getFile(diagramResource));
}
if (nextEObject instanceof Diagram) {
break;
}
}
URI uri = EcoreUtil.getURI(diagram);
String editorName = uri.lastSegment() + '#'
+ diagram.eResource().getContents().indexOf(diagram);
IEditorInput editorInput = new URIEditorInput(uri, editorName);
return editorInput;
}
}
}
|
KuehneThomas/model-to-model-transformation-generator
|
src/MetaModels.UmlClass.diagram/src/umlClassMetaModel/diagram/navigator/UmlClassMetaModelNavigatorActionProvider.java
|
Java
|
mit
| 4,850 |
/*
* This file is part of TechReborn, licensed under the MIT License (MIT).
*
* Copyright (c) 2018 TechReborn
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package techreborn.tiles;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import reborncore.api.IToolDrop;
import reborncore.api.recipe.IRecipeCrafterProvider;
import reborncore.api.tile.IInventoryProvider;
import reborncore.common.powerSystem.TilePowerAcceptor;
import reborncore.common.recipes.RecipeCrafter;
import reborncore.common.util.Inventory;
/**
* @author drcrazy
*
*/
public abstract class TileGenericMachine extends TilePowerAcceptor
implements IToolDrop, IInventoryProvider, IRecipeCrafterProvider{
public String name;
public int maxInput;
public int maxEnergy;
public Block toolDrop;
public int energySlot;
public Inventory inventory;
public RecipeCrafter crafter;
/**
* @param name String Name for a tile. Do we need it at all?
* @param maxInput int Maximum energy input, value in EU
* @param maxEnergy int Maximum energy buffer, value in EU
* @param toolDrop Block Block to drop with wrench
* @param energySlot int Energy slot to use to charge machine from battery
*/
public TileGenericMachine(String name, int maxInput, int maxEnergy, Block toolDrop, int energySlot) {
this.name = "Tile" + name;
this.maxInput = maxInput;
this.maxEnergy = maxEnergy;
this.toolDrop = toolDrop;
this.energySlot = energySlot;
checkTeir();
}
public int getProgressScaled(final int scale) {
if (crafter != null && crafter.currentTickTime != 0) {
return crafter.currentTickTime * scale / crafter.currentNeededTicks;
}
return 0;
}
// TilePowerAcceptor
@Override
public void update() {
super.update();
if (!world.isRemote) {
charge(energySlot);
}
}
@Override
public double getBaseMaxPower() {
return maxEnergy;
}
@Override
public boolean canAcceptEnergy(final EnumFacing direction) {
return true;
}
@Override
public boolean canProvideEnergy(final EnumFacing direction) {
return false;
}
@Override
public double getBaseMaxOutput() {
return 0;
}
@Override
public double getBaseMaxInput() {
return maxInput;
}
// IToolDrop
@Override
public ItemStack getToolDrop(EntityPlayer p0) {
return new ItemStack(toolDrop, 1);
}
// IInventoryProvider
@Override
public Inventory getInventory() {
return inventory;
}
// IRecipeCrafterProvider
@Override
public RecipeCrafter getRecipeCrafter() {
return crafter;
}
}
|
Dimmerworld/TechReborn
|
src/main/java/techreborn/tiles/TileGenericMachine.java
|
Java
|
mit
| 3,620 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package elektra;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.BufferedOutputStream;
import java.io.FileWriter;
import java.util.ResourceBundle;
import java.util.Properties;
import java.util.Date;
import java.net.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpSession;
import javax.servlet.RequestDispatcher;
import javax.mail.*;
import javax.activation.*;
import javax.mail.internet.*;
/**
*
* @author Rolfs
*/
public class WebChangeCustomerPassword extends HttpServlet
{
protected String szElektraConfig = "";
protected String szElektraServer = "";
protected String szElektraServerPort = "";
protected String szRequest = "27"; // Kundenpaßwort ändern
protected String szVersion = "270";
protected Integer nDebug;
protected String strJSP = "";
protected String strJSPError = "";
protected String strJSPReload = "";
protected ServletContext context;
ResourceBundle resource = ResourceBundle.getBundle("elektra.Resource");
/** Adresse/Name des Mailservers, definiert in elektra.properties */
protected String szMailServer = "";
/** gewuenschte From-Adresse, definiert in elektra.properties */
protected String szMailFrom = "";
/** Liste der CC-Adressen, definiert in elektra.properties */
protected String szMailCC = "";
/** Liste der BCC-Adressen, definiert in elektra.properties */
protected String szMailBCC = "";
/** Liste der Reply-Adressen, definiert in elektra.properties */
protected String szMailReply = "";
/** Benutzer auf Mailserver: optional, definiert in elektra.properties */
protected String szMailUserName = "";
/** Passwort auf Mailserver: optional, definiert in elektra.properties */
protected String szMailUserPassword = "";
public void init(ServletConfig config) throws ServletException
{
super.init(config);
// Remember context
context = config.getServletContext();
try { szElektraConfig = context.getInitParameter("ElektraConfig"); } catch (Exception e) { e.printStackTrace(); }
if (null == szElektraConfig)
{
throw new ServletException("Servlet configuration property \"ElektraConfig\" is not defined!");
}
String szDebug = "";
try { szDebug = context.getInitParameter("Debug"); } catch (Exception e) { e.printStackTrace(); }
if (null == szDebug)
nDebug = new Integer(0);
else
nDebug = new Integer(szDebug);
// Properties laden
Properties props = new Properties();
try
{
props.load(new FileInputStream(szElektraConfig));
strJSP = props.getProperty("ChangeCustomerPasswordPage");
if (null == strJSP)
strJSP = "/jsp/webchangecustomerpassword.jsp";
strJSPError = props.getProperty("ChangeCustomerPasswordErrorPage");
if (null == strJSPError)
strJSPError = "/jsp/webchangecustomerpassworderr.jsp";
strJSPReload = props.getProperty("ChangeCustomerPasswordReloadPage");
if (null == strJSPReload)
strJSPReload = "/jsp/webchangecustomerpasswordreload.jsp";
}
catch (IOException ex)
{
ex.printStackTrace();
}
// Remember context
context = config.getServletContext();
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Date d = new Date(); // Getting current date
ChangeCustomerPasswordInData changecustomerpasswordData = new ChangeCustomerPasswordInData();
boolean bHeaderPrinted = false;
int nCnt = 1;
WriteDebug wd = new WriteDebug();
String szTemp = "";
HttpSession session = request.getSession();
session.getLastAccessedTime();
//
try { szTemp = request.getParameter(resource.getString("SysID")); } catch (Exception e) { wd.write(response, "Feld "+resource.getString("SysID")+" fehlt", e, nDebug); }
changecustomerpasswordData.setSysID(szTemp);
//
try { szTemp = request.getParameter(resource.getString("ClientID")); } catch (Exception e) { wd.write(response, "Feld "+resource.getString("ClientID")+" fehlt", e, nDebug); }
changecustomerpasswordData.setClientID(szTemp);
//
try { szTemp = request.getParameter("CustomerNumber"); } catch (Exception e) { wd.write(response, "Feld CustomerNumber fehlt", e, nDebug); }
if (null == szTemp)
changecustomerpasswordData.setCustomerNumber("0");
else
changecustomerpasswordData.setCustomerNumber(szTemp);
try { szTemp = request.getParameter("Password"); } catch (Exception e) { wd.write(response, "Feld Password fehlt", e, nDebug); }
changecustomerpasswordData.setCustomerPassword(szTemp);
try { szTemp = request.getParameter("NewPassword"); } catch (Exception e) { wd.write(response, "Feld NewPassword fehlt", e, nDebug); }
changecustomerpasswordData.setNewCustomerPassword(szTemp);
try { szTemp = request.getParameter("EMail"); } catch (Exception e) { wd.write(response, "Feld EMail fehlt", e, nDebug); }
changecustomerpasswordData.setEMail(szTemp);
changecustomerpasswordData.setSession(session.getId());
// Properties laden
Configuration Conf = new Configuration(context, szElektraConfig, "ElektraServerChangeCustomerPassword", changecustomerpasswordData.getSysID(), changecustomerpasswordData.getClientID(), nDebug.intValue());
szElektraServer = Conf.getServerName();
szElektraServerPort = Conf.getServerPort();
szMailServer = Conf.getMailServer();
szMailFrom = Conf.getMailFrom();
szMailCC = Conf.getMailCC();
szMailBCC = Conf.getMailBCC();
szMailReply = Conf.getMailReply();
if (null == szElektraServer)
{
wd.write(response, "Internal error!<br />System error: Elektra-Server not defined<br />", nDebug);
context.log("Elektra-Server not defined!");
}
else
{
// Daten an DB-Server senden
Socket socket = null;
ChangeCustomerPasswordOutData changecustomerpasswordOut = new ChangeCustomerPasswordOutData();
if (nDebug.intValue() > 0)
context.log(" starting ChangeCustomerpassword.");
try
{
socket = new Socket(szElektraServer, Integer.parseInt(szElektraServerPort));
if (nDebug.intValue() > 1)
context.log(" socket created.");
//BufferedInputStream is = new BufferedInputStream(socket.getInputStream());
BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream()));
BufferedOutputStream os = new BufferedOutputStream(socket.getOutputStream());
// Daten senden
try { os.write(szVersion.getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
try { os.write(szRequest.getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
// Encryption
try { os.write("NONE".getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
// compression
try { os.write("NONE".getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
try { os.write(changecustomerpasswordData.getSysID().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
try { os.write(changecustomerpasswordData.getClientID().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
try { os.write(changecustomerpasswordData.getCustomerNumber().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
try { os.write(changecustomerpasswordData.getCustomerPassword().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
try { os.write(changecustomerpasswordData.getSession().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
try { os.write(changecustomerpasswordData.getNewCustomerPassword().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
try { os.write(changecustomerpasswordData.getEMail().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
os.write( 9 );
if (nDebug.intValue() > 1)
context.log(" flushing: "+os.toString());
os.flush();
// Daten senden, nun auf die Buchung warten
changecustomerpasswordOut.readSock(in, szVersion);
if (nDebug.intValue() > 4)
{
wd.write(response, "<br><h2>Getting:</h2>Error: "+changecustomerpasswordOut.getErrorCode(), nDebug );
}
if (nDebug.intValue() > 0)
context.log(" changecustomerpasswordData performed.");
request.setAttribute("changecustomerpasswordData", changecustomerpasswordData);
request.setAttribute("changecustomerpasswordOut", changecustomerpasswordOut);
// Im Fehlerfall
if (0 != changecustomerpasswordOut.getErrorCode())
{
context.log("Systemerror: "+changecustomerpasswordOut.getErrorCode());
// hole den Request Dispatcher fuer die JSP Datei
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strJSPError);
//leite auf die JSP Datei zum Anzeigen der Liste weiter
dispatcher.forward(request, response);
}
else
{
// hole den Request Dispatcher fuer die JSP Datei
// Alles OK Password per Mail
if (null != szMailServer)
{
String szMailText = "";
String szKopfText = "";
szKopfText = szKopfText.concat("Ihr neues Password");
/*
szMailText = szMailText.concat("Seher geehrte(r) ");
szMailText = szMailText.concat(changecustomerpasswordData.getSalution());
szMailText = szMailText.concat(" ");
szMailText = szMailText.concat(changecustomerpasswordOut.getName1());
szMailText = szMailText.concat(" ");
szMailText = szMailText.concat(changecustomerpasswordOut.getName2());
szMailText = szMailText.concat(" ");
szMailText = szMailText.concat(changecustomerpasswordOut.getName3());
szMailText = szMailText.concat(",\r\n\r\n");
szMailText = szMailText.concat("anbei das geaenderte Password für Ihren Kundenzugriff auf den Server von Frankfurt Ticket.\r\n\r\n");
szMailText = szMailText.concat("Ihre Kundennummer : ");
szMailText = szMailText.concat(changecustomerpasswordOut.getCustId());
szMailText = szMailText.concat("\r\n");
szMailText = szMailText.concat("Ihr geaendertes Password: ");
szMailText = szMailText.concat(changecustomerpasswordOut.getNewPassword());
szMailText = szMailText.concat("\r\n");
Mail m = new Mail(szMailServer, szMailFrom , changecustomerpasswordOut.getEMail(), szMailBCC, szMailCC, szMailReply, szKopfText, szMailText);
MailSender.getInstance().sendMail(m);
*/
}
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strJSP);
//leite auf die JSP Datei zum Anzeigen der Liste weiter
dispatcher.forward(request, response);
}
}
catch (IOException ioex)
{
changecustomerpasswordOut.setErrorCode( -999);
changecustomerpasswordOut.setErrorMessage(ioex.getLocalizedMessage());
if ( (null != strJSPError) && !strJSPError.equals(""))
{
request.setAttribute("changecustomerpasswordData", changecustomerpasswordData);
request.setAttribute("changecustomerpasswordOut", changecustomerpasswordOut);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strJSPError);
//leite auf die JSP Datei zum Anzeigen der Liste weiter
dispatcher.forward(request, response);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (socket != null)
{
try
{
socket.close();
}
catch (IOException ioex)
{
ioex.printStackTrace();
}
}
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
yanhongwang/TicketBookingSystem
|
src/elektra/WebChangeCustomerPassword.java
|
Java
|
mit
| 14,526 |
package com.ke2g.cued_recall;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.List;
public class LoginActivity extends ActionBarActivity {
public static final String TAG = LoginActivity.class.getSimpleName();
private int discretization;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void doLogin(View V){
if(!getUsername().equals("")) {
Intent i = new Intent(this, returnIntent.class);
startActivityForResult(i, 1);
}
}
private ArrayList<Point> getUserPoints(String username){
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = appSharedPrefs.getString(username, "");
if(json.equals("")){
return null;
} else {
User u = gson.fromJson(json, User.class);
return u.getPoints();
}
}
private String getUserHash(String username){
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = appSharedPrefs.getString(username, "");
if(json.equals("")){
return null;
} else {
User u = gson.fromJson(json, User.class);
return u.getHash();
}
}
private void setTry(String username, int total, int invalid) {
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = appSharedPrefs.getString(username, "");
if(!json.equals("")){
User u = gson.fromJson(json, User.class);
u.setInvalidLogins(invalid);
u.setTotalLogins(total);
json = gson.toJson(u);
prefsEditor.putString(username, json);
prefsEditor.commit();
}
}
private int getTolerance(){
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
return Integer.parseInt(SP.getString("tolerance", "75"));
}
private String getUsername() {
EditText et = (EditText) findViewById(R.id.editText_login);
return et.getText().toString().trim();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
ArrayList<Point> points = data.getParcelableArrayListExtra("RESULT_CLICKS");
//check if points are the saved ones
if(getDiscretization() == 1){
if (CuedRecallIntent.areHashEqual(points, getUserHash(getUsername()), getTolerance())) {
setTry(getUsername(), 1, 0);
Toast.makeText(this, "Correct username and password", Toast.LENGTH_LONG).show();
} else {
setTry(getUsername(), 1, 1);
Toast.makeText(this, "Username and password don't match", Toast.LENGTH_LONG).show();
}
} else {
if (CuedRecallIntent.arePointsEqual(points, getUserPoints(getUsername()), getTolerance())) {
setTry(getUsername(), 1, 0);
Toast.makeText(this, "Correct username and password", Toast.LENGTH_LONG).show();
} else {
setTry(getUsername(), 1, 1);
Toast.makeText(this, "Username and password don't match", Toast.LENGTH_LONG).show();
}
}
}
}
public int getDiscretization() {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
return Integer.parseInt(SP.getString("discreType", "0"));
}
}
|
ke2g/cuedRecall
|
app/src/main/java/com/ke2g/cued_recall/LoginActivity.java
|
Java
|
mit
| 5,334 |
package BusinessLogic.ConnectionStates;
import BusinessLogic.ActualConnection;
import BusinessLogic.Message;
public class MessageMenuState implements ConnectionState{
public void dial(String key, ActualConnection connection)
{
if (key.equals("1"))
{
String output = "";
Message m = connection.currentMailbox.getCurrentMessage();
if (m == null) output += "No messages." + "\n";
else output += m.getText() + "\n";
output += ActualConnection.MESSAGE_MENU_TEXT;
connection.speakToAllUIs(output);
}
else if (key.equals("2"))
{
connection.currentMailbox.saveCurrentMessage();
connection.speakToAllUIs(ActualConnection.MESSAGE_MENU_TEXT);
}
else if (key.equals("3"))
{
connection.currentMailbox.removeCurrentMessage();
connection.speakToAllUIs(ActualConnection.MESSAGE_MENU_TEXT);
}
else if (key.equals("4"))
{
//connection.state = Connection.MAILBOX_MENU;
connection.currentState = new MailBoxMenuState();
connection.speakToAllUIs(ActualConnection.MAILBOX_MENU_TEXT);
}
}
public int getState(){
return 4;
}
}
|
PatriciaRosembluth/VoiceMailSimulator
|
src/BusinessLogic/ConnectionStates/MessageMenuState.java
|
Java
|
mit
| 1,243 |
/**
*
*/
package com.sivalabs.jcart.common.services;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import com.sivalabs.jcart.JCartException;
/**
* @author Siva
*
*/
@Component
public class EmailService
{
private static final JCLogger logger = JCLogger.getLogger(EmailService.class);
@Autowired JavaMailSender javaMailSender;
@Value("${support.email}") String supportEmail;
public void sendEmail(String to, String subject, String content)
{
try
{
// Prepare message using a Spring helper
final MimeMessage mimeMessage = this.javaMailSender.createMimeMessage();
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
message.setSubject(subject);
message.setFrom(supportEmail);
message.setTo(to);
message.setText(content, true /* isHtml */);
javaMailSender.send(message.getMimeMessage());
}
catch (MailException | MessagingException e)
{
logger.error(e);
throw new JCartException("Unable to send email");
}
}
}
|
sivaprasadreddy/jcart
|
jcart-core/src/main/java/com/sivalabs/jcart/common/services/EmailService.java
|
Java
|
mit
| 1,464 |
package cz.vhromada.utils.file.gui;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import cz.vhromada.validators.Validators;
import org.springframework.util.StringUtils;
/**
* A class represents file visitor for copying directories and files.
*/
public class CopyingFileVisitor extends SimpleFileVisitor<Path> {
/**
* Delimiter in replacing text
*/
private static final String REPLACING_TEXT_DELIMITER = ",";
/**
* Source directory
*/
private Path source;
/**
* Target directory
*/
private Path target;
/**
* Replacing patterns
*/
private List<ReplacePattern> replacePatterns;
/**
* Directories
*/
private Deque<Path> directories;
/**
* Creates a new instance of CopyingFileVisitor.
*
* @param source source directory
* @param target target directory
* @param replacingText replacing text
* @param newText new text
* @throws IllegalArgumentException if source directory is null
* or target directory is null
* or replacing text is null
* or new text is null
* or count of replacing texts is different from count of new texts
*/
public CopyingFileVisitor(final Path source, final Path target, final String replacingText, final String newText) {
Validators.validateArgumentNotNull(source, "Source");
Validators.validateArgumentNotNull(target, "Target");
Validators.validateArgumentNotNull(replacingText, "Replacing text");
Validators.validateArgumentNotNull(newText, "New text");
this.source = source;
this.target = target;
this.directories = new LinkedList<>();
this.replacePatterns = createReplacePatterns(replacingText, newText);
}
@Override
public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
final Path directory = getDirectoryName(dir);
directories.addLast(directory);
if (!Files.exists(directory)) {
Files.createDirectory(directory);
}
return super.preVisitDirectory(dir, attrs);
}
@Override
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
directories.removeLast();
return super.postVisitDirectory(dir, exc);
}
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
FileCopy.copy(file, directories.getLast(), replacePatterns);
return super.visitFile(file, attrs);
}
/**
* Returns created replace patters.
*
* @param replacingText replacing text
* @param newText new text
* @return created replace patters
* @throws IllegalArgumentException if count of replacing texts is different from count of new texts
*/
private static List<ReplacePattern> createReplacePatterns(final String replacingText, final String newText) {
final String[] replacingTexts = StringUtils.tokenizeToStringArray(replacingText, REPLACING_TEXT_DELIMITER);
final String[] newTexts = StringUtils.tokenizeToStringArray(newText, REPLACING_TEXT_DELIMITER);
if (replacingTexts.length != newTexts.length) {
throw new IllegalArgumentException("Count of replacing texts is different from count of new texts");
}
final List<ReplacePattern> result = new ArrayList<>();
for (int i = 0; i < replacingTexts.length; i++) {
final String source = replacingTexts[i];
final String target = newTexts[i];
result.add(new ReplacePattern(source, target));
result.add(new ReplacePattern(source.toLowerCase(), target.toLowerCase()));
result.add(new ReplacePattern(StringUtils.capitalize(source.toLowerCase()), StringUtils.capitalize(target.toLowerCase())));
result.add(new ReplacePattern(source.toUpperCase(), target.toUpperCase()));
}
return result;
}
/**
* Returns directory name.
*
* @param directory directory
* @return directory name
*/
private Path getDirectoryName(final Path directory) {
final String sourcePath = source.toAbsolutePath().toString();
final String targetPath = target.toAbsolutePath().toString();
final String directoryPath = directory.toAbsolutePath().toString();
final String result = directoryPath.replace(sourcePath, targetPath);
final String replacedResult = FileCopy.replaceText(result, replacePatterns);
return Paths.get(replacedResult);
}
}
|
vhromada/File_utils
|
src/main/java/cz/vhromada/utils/file/gui/CopyingFileVisitor.java
|
Java
|
mit
| 5,102 |
package org.lua.commons.customapi.javafunctions.handlers;
import org.lua.commons.baseapi.LuaThread;
import org.lua.commons.baseapi.extensions.LuaExtension;
import org.lua.commons.baseapi.types.LuaObject;
import org.lua.commons.customapi.javafunctions.handlers.types.Type;
public interface TypeCastManager extends LuaExtension {
public void addHandler(Class<? extends TypeHandler> handler);
public void add(Class<? extends TypeHandler> handler, Class<?>... keys);
public void remove(Class<?> key);
public Object castFrom(LuaThread thread, LuaObject obj, Type expected);
public LuaObject castTo(LuaThread thread, Object obj);
}
|
mrkosterix/lua-commons
|
lua-commons-3-custom-level/src/main/java/org/lua/commons/customapi/javafunctions/handlers/TypeCastManager.java
|
Java
|
mit
| 653 |
package orestes.bloomfilter.redis.helper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;
import redis.clients.jedis.exceptions.JedisConnectionException;
import backport.java.util.function.Consumer;
import backport.java.util.function.Function;
/**
* Encapsulates a Connection Pool and offers convenience methods for safe access through Java 8 Lambdas.
*/
public class RedisPool {
private final JedisPool pool;
private List<RedisPool> slavePools;
private Random random;
public RedisPool(JedisPool pool) {
this.pool = pool;
}
public RedisPool(JedisPool pool, int redisConnections, Set<Entry<String, Integer>> readSlaves) {
this(pool);
if (readSlaves != null && !readSlaves.isEmpty()) {
slavePools = new ArrayList<>();
random = new Random();
for (Entry<String, Integer> slave : readSlaves) {
slavePools.add(new RedisPool(slave.getKey(), slave.getValue(), redisConnections));
}
}
}
public RedisPool(String host, int port, int redisConnections) {
this(createJedisPool(host, port, redisConnections));
}
public RedisPool(String host, int port, int redisConnections, Set<Entry<String, Integer>> readSlaves) {
this(createJedisPool(host, port, redisConnections), redisConnections, readSlaves);
}
private static JedisPool createJedisPool(String host, int port, int redisConnections) {
JedisPoolConfig config = new JedisPoolConfig();
config.setBlockWhenExhausted(true);
config.setMaxTotal(redisConnections);
return new JedisPool(config, host, port);
}
public RedisPool allowingSlaves() {
if(slavePools == null)
return this;
int index = random.nextInt(slavePools.size());
return slavePools.get(index);
}
public void safelyDo(final Consumer<Jedis> f) {
safelyReturn(new Function<Jedis, Object>() {
@Override
public Object apply(Jedis jedis) {
f.accept(jedis);
return null;
}
});
}
public <T> T safelyReturn(Function<Jedis, T> f) {
T result;
Jedis jedis = pool.getResource();
try {
result = f.apply(jedis);
return result;
} catch (JedisConnectionException e) {
if (jedis != null) {
pool.returnBrokenResource(jedis);
jedis = null;
}
throw e;
} finally {
if (jedis != null)
pool.returnResource(jedis);
}
}
@SuppressWarnings("unchecked")
public <T> List<T> transactionallyDo(final Consumer<Pipeline> f, final String... watch) {
return (List<T>) safelyReturn(new Function<Jedis, Object>() {
@Override
public Object apply(Jedis jedis) {
Pipeline p = jedis.pipelined();
if (watch.length != 0) p.watch(watch);
p.multi();
f.accept(p);
Response<List<Object>> exec = p.exec();
p.sync();
return exec.get();
}
});
}
public <T> List<T> transactionallyRetry(Consumer<Pipeline> f, String... watch) {
while(true) {
List<T> result = transactionallyDo(f, watch);
if(result != null)
return result;
}
}
public <T> T transactionallyDoAndReturn(final Function<Pipeline, T> f, final String... watch) {
return safelyReturn(new Function<Jedis, T>() {
@Override
public T apply(Jedis jedis) {
Pipeline p = jedis.pipelined();
if (watch.length != 0) p.watch(watch);
p.multi();
T responses = f.apply(p);
Response<List<Object>> exec = p.exec();
p.sync();
if(exec.get() == null) {
return null; // failed
}
return responses;
}
});
}
public <T> T transactionallyRetryAndReturn(Function<Pipeline, T> f, String... watch) {
while(true) {
T result = transactionallyDoAndReturn(f, watch);
if(result != null)
return result;
}
}
public void destroy() {
pool.destroy();
}
}
|
Crystark/Orestes-Bloomfilter
|
src/main/java/orestes/bloomfilter/redis/helper/RedisPool.java
|
Java
|
mit
| 4,691 |
package com.weixin.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.thoughtworks.xstream.XStream;
import com.weixin.vo.TextMessage;
/**
* @author : Jay
*/
public class MessageUtil {
/**
* xml 转为 map
* @param request
* @return
* @throws IOException
* @throws DocumentException
*/
public static Map<String, String> xmlToMap(HttpServletRequest request)
throws IOException, DocumentException {
Map<String, String> map = new HashMap<String, String>();
SAXReader reader = new SAXReader();
InputStream ins = request.getInputStream();
org.dom4j.Document doc = reader.read(ins);
Element root = doc.getRootElement();
List<Element> list = root.elements();
for (Element e : list) {
map.put(e.getName(), e.getText());
}
ins.close();
return map;
}
/**
* 将文本消息对象转为xml
* @return
*/
public static String textMessageToXml(TextMessage textMessage){
XStream xstream = new XStream();
xstream.alias("xml", textMessage.getClass());
return xstream.toXML(textMessage);
}
/**
* 初始化文本消
* @param toUserName
* @param fromUserName
* @param content
* @return
*/
public static String initText(String toUserName, String fromUserName,String content){
TextMessage text = new TextMessage();
text.setFromUserName(toUserName);
text.setToUserName(fromUserName);
text.setMsgType("text");
text.setCreateTime(new Date().getTime());
text.setContent(content);
return MessageUtil.textMessageToXml(text);
}
}
|
ScorpionJay/wechat
|
src/main/java/com/weixin/util/MessageUtil.java
|
Java
|
mit
| 1,844 |
package org.data2semantics.mustard.rdfvault;
import java.util.List;
import java.util.Set;
import org.data2semantics.mustard.kernels.ComputationTimeTracker;
import org.data2semantics.mustard.kernels.FeatureInspector;
import org.data2semantics.mustard.kernels.KernelUtils;
import org.data2semantics.mustard.kernels.data.RDFData;
import org.data2semantics.mustard.kernels.data.SingleDTGraph;
import org.data2semantics.mustard.kernels.graphkernels.FeatureVectorKernel;
import org.data2semantics.mustard.kernels.graphkernels.GraphKernel;
import org.data2semantics.mustard.kernels.graphkernels.singledtgraph.DTGraphGraphListWLSubTreeKernel;
import org.data2semantics.mustard.kernels.SparseVector;
import org.data2semantics.mustard.rdf.RDFDataSet;
import org.data2semantics.mustard.rdf.RDFUtils;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
public class RDFGraphListURIPrefixKernel implements GraphKernel<RDFData>, FeatureVectorKernel<RDFData>, ComputationTimeTracker {
private int depth;
private boolean inference;
private DTGraphGraphListURIPrefixKernel kernel;
private SingleDTGraph graph;
public RDFGraphListURIPrefixKernel(double lambda, int depth, boolean inference, boolean normalize) {
super();
this.depth = depth;
this.inference = inference;
kernel = new DTGraphGraphListURIPrefixKernel(lambda, depth, normalize);
}
public String getLabel() {
return KernelUtils.createLabel(this) + "_" + kernel.getLabel();
}
public void setNormalize(boolean normalize) {
kernel.setNormalize(normalize);
}
public SparseVector[] computeFeatureVectors(RDFData data) {
init(data.getDataset(), data.getInstances(), data.getBlackList());
return kernel.computeFeatureVectors(graph);
}
public double[][] compute(RDFData data) {
init(data.getDataset(), data.getInstances(), data.getBlackList());
return kernel.compute(graph);
}
private void init(RDFDataSet dataset, List<Resource> instances, List<Statement> blackList) {
Set<Statement> stmts = RDFUtils.getStatements4Depth(dataset, instances, depth, inference);
stmts.removeAll(blackList);
graph = RDFUtils.statements2Graph(stmts, RDFUtils.REGULAR_LITERALS, instances, true);
}
public long getComputationTime() {
return kernel.getComputationTime();
}
}
|
Data2Semantics/mustard
|
mustard-experiments/src/main/java/org/data2semantics/mustard/rdfvault/RDFGraphListURIPrefixKernel.java
|
Java
|
mit
| 2,327 |
package com.hzq.sphinxwebview;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Build;
import android.webkit.WebSettings;
/**
* Created by friencis on 2017/4/3 0003.
*/
public class WebViewConfig {
}
|
hzqjyyx/SphinxWebView
|
app/src/main/java/com/hzq/sphinxwebview/WebViewConfig.java
|
Java
|
mit
| 243 |
package me.coley.bmf.insn.impl;
import me.coley.bmf.insn.Instruction;
import me.coley.bmf.insn.OpType;
public class CALOAD extends Instruction {
public CALOAD() {
super(OpType.ARRAY, Instruction.CALOAD, 1);
}
}
|
Col-E/Bytecode-Modification-Framework
|
src/main/java/me/coley/bmf/insn/impl/CALOAD.java
|
Java
|
mit
| 229 |
package epsi.md4.com.epsicalendar.activities;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
import epsi.md4.com.epsicalendar.Common;
import epsi.md4.com.epsicalendar.R;
import epsi.md4.com.epsicalendar.adapters.EventItemAdapter;
import epsi.md4.com.epsicalendar.beans.Event;
import epsi.md4.com.epsicalendar.ws.ApiClient;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;
public class EventListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
public static final int EVENT_FORM_ACTIVITY_REQUEST_CODE = 1;
public static final String TAG = EventListActivity.class.getName();
public static final String EXTRA_EVENT_ID = "EXTRA_EVENT_ID";
private ListView mList;
private ApiClient mApiClient;
private SharedPreferences mSharedPrefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Init view
setContentView(R.layout.activity_event_list);
// Init fields
this.mList = (ListView) findViewById(R.id.event_list_view);
this.mSharedPrefs = getSharedPreferences(Common.PREFS_SCOPE, Context.MODE_PRIVATE);
mApiClient = new ApiClient(this);
}
/**
* Refresh data
*/
private void refreshData() {
mApiClient.listEvents().enqueue(new Callback<List<Event>>() {
@Override
public void onResponse(Response<List<Event>> response, Retrofit retrofit) {
Log.v(TAG, String.format("listEvents.response: %d", response.code()));
if (response.isSuccess()) {
EventItemAdapter eventItemAdapter = new EventItemAdapter(EventListActivity.this, response.body());
mList.setOnItemClickListener(EventListActivity.this);
mList.setAdapter(eventItemAdapter);
} else {
Log.e(TAG, "can't get events from api ");
}
}
@Override
public void onFailure(Throwable t) {
Log.e(TAG, String.format("Error: %s", t.getMessage()));
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == EventFormActivity.REQUEST_CODE) {
if (resultCode == EventFormActivity.RESULT_OK) {
Log.d(TAG, "new event, refreshing list");
refreshData();
} else if (resultCode == EventFormActivity.RESULT_CANCELED) {
Log.d(TAG, "operation cancelled");
}
}
}
public void onClickAddEvent(View view) {
Intent intent = new Intent(EventListActivity.this, EventFormActivity.class);
this.startActivityForResult(intent, EVENT_FORM_ACTIVITY_REQUEST_CODE);
}
@Override
protected void onResume() {
super.onResume();
Log.v(TAG, String.format("prefs.USER_EMAIL_KEY = %s", mSharedPrefs.getString(Common.USER_EMAIL_KEY, "")));
if (mSharedPrefs.getString(Common.USER_EMAIL_KEY, "").equals("")) {
Intent intent = new Intent(this, UserFormActivity.class);
startActivity(intent);
} else {
refreshData();
}
}
public void onClickDisconnect(View view) {
mApiClient.logout().enqueue(new Callback<Void>() {
@Override
public void onResponse(Response<Void> response, Retrofit retrofit) {
localDisconnect();
onResume();
}
@Override
public void onFailure(Throwable t) {
Toast.makeText(EventListActivity.this, "Can not logout", Toast.LENGTH_SHORT).show();
Log.e(TAG, String.format("Error while logging out: %s", t.getLocalizedMessage()));
}
});
}
private void localDisconnect() {
Log.v(TAG, String.format("Clearing %s prefs", Common.PREFS_SCOPE));
SharedPreferences.Editor edit = this.mSharedPrefs.edit();
edit.clear();
edit.apply();
}
/**
* Listener for list item click
*
* @param parent
* @param view
* @param position
* @param id
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Event clickedItem = (Event) parent.getItemAtPosition(position);
Log.v(TAG, clickedItem.toString());
Intent intent = new Intent(this, EventItemActivity.class);
intent.putExtra(EXTRA_EVENT_ID, clickedItem.getId().toString());
startActivity(intent);
}
}
|
MD4/EPSICalendar
|
app/src/main/java/epsi/md4/com/epsicalendar/activities/EventListActivity.java
|
Java
|
mit
| 5,006 |
package com.blamejared.compat.tcomplement.highoven;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.blamejared.ModTweaker;
import com.blamejared.compat.mantle.RecipeMatchIIngredient;
import com.blamejared.compat.tcomplement.highoven.recipes.HeatRecipeTweaker;
import com.blamejared.compat.tcomplement.highoven.recipes.HighOvenFuelTweaker;
import com.blamejared.compat.tcomplement.highoven.recipes.MixRecipeTweaker;
import com.blamejared.compat.tconstruct.recipes.MeltingRecipeTweaker;
import com.blamejared.mtlib.helpers.InputHelper;
import com.blamejared.mtlib.helpers.LogHelper;
import com.blamejared.mtlib.utils.BaseAction;
import crafttweaker.CraftTweakerAPI;
import crafttweaker.annotations.ModOnly;
import crafttweaker.annotations.ZenRegister;
import crafttweaker.api.item.IIngredient;
import crafttweaker.api.item.IItemStack;
import crafttweaker.api.liquid.ILiquidStack;
import crafttweaker.mc1120.item.MCItemStack;
import knightminer.tcomplement.library.TCompRegistry;
import knightminer.tcomplement.library.events.TCompRegisterEvent;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import stanhebben.zenscript.annotations.Optional;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
import stanhebben.zenscript.util.Pair;
@ZenClass("mods.tcomplement.highoven.HighOven")
@ZenRegister
@ModOnly("tcomplement")
public class HighOven {
public static final List<IIngredient> REMOVED_FUELS = new LinkedList<>();
public static final Map<ILiquidStack, IItemStack> REMOVED_OVERRIDES = new LinkedHashMap<>();
public static final List<Pair<FluidStack, FluidStack>> REMOVED_HEAT_RECIPES = new LinkedList<>();
public static final List<Pair<FluidStack, FluidStack>> REMOVED_MIX_RECIPES = new LinkedList<>();
private static boolean init = false;
private static void init() {
if (!init) {
MinecraftForge.EVENT_BUS.register(new HighOven());
init = true;
}
}
/*-------------------------------------------------------------------------*\
| High Oven Fuels |
\*-------------------------------------------------------------------------*/
@ZenMethod
public static void removeFuel(IIngredient stack) {
init();
CraftTweakerAPI.apply(new HighOven.RemoveFuel(stack));
}
@ZenMethod
public static void addFuel(IIngredient fuel, int burnTime, int tempRate) {
init();
ModTweaker.LATE_ADDITIONS.add(new HighOven.AddFuel(fuel, burnTime, tempRate));
}
private static class AddFuel extends BaseAction {
private IIngredient fuel;
private int time;
private int rate;
public AddFuel(IIngredient fuel, int time, int rate) {
super("High Oven fuel");
this.fuel = fuel;
this.time = time;
this.rate = rate;
}
@Override
public void apply() {
TCompRegistry.registerFuel(new HighOvenFuelTweaker(new RecipeMatchIIngredient(fuel), time, rate));
}
@Override
public String describe() {
return String.format("Adding %s as %s", this.getRecipeInfo(), this.name);
}
@Override
public String getRecipeInfo() {
return LogHelper.getStackDescription(fuel);
}
}
private static class RemoveFuel extends BaseAction {
private IIngredient fuel;
public RemoveFuel(IIngredient fuel) {
super("High Oven fuel");
this.fuel = fuel;
};
@Override
public void apply() {
REMOVED_FUELS.add(fuel);
}
@Override
public String describe() {
return String.format("Removing %s as %s", this.getRecipeInfo(), this.name);
}
@Override
public String getRecipeInfo() {
return LogHelper.getStackDescription(fuel);
}
}
/*-------------------------------------------------------------------------*\
| High Oven Melting |
\*-------------------------------------------------------------------------*/
@ZenMethod
public static void addMeltingOverride(ILiquidStack output, IIngredient input, @Optional int temp) {
init();
ModTweaker.LATE_ADDITIONS
.add(new HighOven.AddMelting(InputHelper.toFluid(output), input, (temp == 0 ? -1 : temp)));
}
@ZenMethod
public static void removeMeltingOverride(ILiquidStack output, @Optional IItemStack input) {
init();
CraftTweakerAPI.apply(new HighOven.RemoveMelting(output, input));
}
private static class AddMelting extends BaseAction {
private IIngredient input;
private FluidStack output;
private int temp;
public AddMelting(FluidStack output, IIngredient input, int temp) {
super("High Oven melting override");
this.input = input;
this.output = output;
this.temp = temp;
}
@Override
public void apply() {
if (temp > 0) {
TCompRegistry.registerHighOvenOverride(
new MeltingRecipeTweaker(new RecipeMatchIIngredient(input, output.amount), output, temp));
} else {
TCompRegistry.registerHighOvenOverride(
new MeltingRecipeTweaker(new RecipeMatchIIngredient(input, output.amount), output));
}
}
@Override
public String describe() {
return String.format("Adding %s for %s", this.name, this.getRecipeInfo());
}
@Override
protected String getRecipeInfo() {
return LogHelper.getStackDescription(input) + ", now yields " + LogHelper.getStackDescription(output);
}
}
private static class RemoveMelting extends BaseAction {
private ILiquidStack output;
private IItemStack input;
public RemoveMelting(ILiquidStack output, IItemStack input) {
super("High Oven melting override");
this.input = input;
this.output = output;
}
@Override
public void apply() {
REMOVED_OVERRIDES.put(output, input);
}
@Override
public String describe() {
return String.format("Removing %s Recipe(s) for %s", this.name, this.getRecipeInfo());
}
@Override
protected String getRecipeInfo() {
return LogHelper.getStackDescription(output);
}
}
/*-------------------------------------------------------------------------*\
| High Oven Heat |
\*-------------------------------------------------------------------------*/
@ZenMethod
public static void removeHeatRecipe(ILiquidStack output, @Optional ILiquidStack input) {
init();
CraftTweakerAPI.apply(new RemoveHeat(input, output));
}
@ZenMethod
public static void addHeatRecipe(ILiquidStack output, ILiquidStack input, int temp) {
init();
ModTweaker.LATE_ADDITIONS
.add(new HighOven.AddHeat(InputHelper.toFluid(output), InputHelper.toFluid(input), temp));
}
private static class AddHeat extends BaseAction {
private FluidStack output, input;
private int temp;
public AddHeat(FluidStack output, FluidStack input, int temp) {
super("High Oven Heat");
this.output = output;
this.input = input;
this.temp = temp;
}
@Override
public void apply() {
TCompRegistry.registerHeatRecipe(new HeatRecipeTweaker(input, output, temp));
}
@Override
public String describe() {
return String.format("Adding %s Recipe for %s", this.name, this.getRecipeInfo());
}
@Override
protected String getRecipeInfo() {
return LogHelper.getStackDescription(output);
}
}
private static class RemoveHeat extends BaseAction {
private ILiquidStack input;
private ILiquidStack output;
public RemoveHeat(ILiquidStack input, ILiquidStack output) {
super("High Oven Heat");
this.input = input;
this.output = output;
}
@Override
public void apply() {
REMOVED_HEAT_RECIPES.add(new Pair<>(InputHelper.toFluid(input), InputHelper.toFluid(output)));
}
@Override
public String describe() {
return String.format("Removing %s Recipe(s) for %s", this.name, this.getRecipeInfo());
}
@Override
public String getRecipeInfo() {
return LogHelper.getStackDescription(output)
+ ((input == null) ? "" : (" from " + LogHelper.getStackDescription(input)));
}
}
/*-------------------------------------------------------------------------*\
| High Oven Mix |
\*-------------------------------------------------------------------------*/
@ZenMethod
public static void removeMixRecipe(ILiquidStack output, @Optional ILiquidStack input) {
init();
CraftTweakerAPI.apply(new RemoveMix(output, input));
}
@ZenMethod
public static MixRecipeBuilder newMixRecipe(ILiquidStack output, ILiquidStack input, int temp) {
init();
return new MixRecipeBuilder(output, input, temp);
}
@ZenMethod
public static MixRecipeManager manageMixRecipe(ILiquidStack output, ILiquidStack input) {
init();
return new MixRecipeManager(output, input);
}
private static class RemoveMix extends BaseAction {
private ILiquidStack output;
private ILiquidStack input;
public RemoveMix(ILiquidStack output, ILiquidStack input) {
super("High Oven Mix");
this.output = output;
this.input = input;
}
@Override
public void apply() {
REMOVED_MIX_RECIPES.add(new Pair<>(InputHelper.toFluid(input), InputHelper.toFluid(output)));
}
@Override
public String describe() {
return String.format("Removing %s Recipe(s) for %s", this.name, this.getRecipeInfo());
}
@Override
protected String getRecipeInfo() {
return LogHelper.getStackDescription(output)
+ ((input == null) ? "" : (" from " + LogHelper.getStackDescription(input)));
}
}
/*-------------------------------------------------------------------------*\
| Event handlers |
\*-------------------------------------------------------------------------*/
@SubscribeEvent
public void onHighOvenFuelRegister(TCompRegisterEvent.HighOvenFuelRegisterEvent event) {
if (event.getRecipe() instanceof HighOvenFuelTweaker) {
return;
}
for (IIngredient entry : REMOVED_FUELS) {
for (ItemStack fuel : event.getRecipe().getFuels()) {
if (entry.matches(new MCItemStack(fuel))) {
event.setCanceled(true);
return;
}
}
}
}
@SubscribeEvent
public void onHighOvenHeatRegister(TCompRegisterEvent.HighOvenHeatRegisterEvent event) {
if (event.getRecipe() instanceof HeatRecipeTweaker) {
return;
} else {
for (Pair<FluidStack, FluidStack> entry : REMOVED_HEAT_RECIPES) {
if (event.getRecipe().matches(entry.getKey(), entry.getValue())) {
event.setCanceled(true);
return;
}
}
}
}
@SubscribeEvent
public void onHighOvenMixRegister(TCompRegisterEvent.HighOvenMixRegisterEvent event) {
if (event.getRecipe() instanceof MixRecipeTweaker) {
return;
} else {
for (Pair<FluidStack, FluidStack> entry : REMOVED_MIX_RECIPES) {
if (event.getRecipe().matches(entry.getKey(), entry.getValue())) {
event.setCanceled(true);
return;
}
}
}
}
@SubscribeEvent
public void onHighOvenOverrideRegister(TCompRegisterEvent.HighOvenOverrideRegisterEvent event) {
if (event.getRecipe() instanceof MeltingRecipeTweaker) {
return;
}
for (Map.Entry<ILiquidStack, IItemStack> entry : REMOVED_OVERRIDES.entrySet()) {
if (event.getRecipe().getResult().isFluidEqual(((FluidStack) entry.getKey().getInternal()))) {
if (entry.getValue() != null) {
if (event.getRecipe().input
.matches(NonNullList.withSize(1, (ItemStack) entry.getValue().getInternal())).isPresent()) {
event.setCanceled(true);
}
} else
event.setCanceled(true);
}
}
}
}
|
jaredlll08/ModTweaker
|
src/main/java/com/blamejared/compat/tcomplement/highoven/HighOven.java
|
Java
|
mit
| 11,580 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2017-2020 Yegor Bugayenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.cactoos.io;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* InputStream that returns content in small portions.
*
* @since 0.12
*/
public final class SlowInputStream extends InputStream {
/**
* Original stream.
*/
private final InputStream origin;
/**
* Ctor.
* @param size The size of the array to encapsulate
*/
public SlowInputStream(final int size) {
this(new ByteArrayInputStream(new byte[size]));
}
/**
* Ctor.
* @param stream Original stream to encapsulate and make slower
*/
SlowInputStream(final InputStream stream) {
super();
this.origin = stream;
}
@Override
public int read() throws IOException {
final byte[] buf = new byte[1];
final int result;
if (this.read(buf) < 0) {
result = -1;
} else {
result = Byte.toUnsignedInt(buf[0]);
}
return result;
}
@Override
public int read(final byte[] buf, final int offset, final int len)
throws IOException {
final int result;
if (len > 1) {
result = this.origin.read(buf, offset, len - 1);
} else {
result = this.origin.read(buf, offset, len);
}
return result;
}
@Override
public int read(final byte[] buf) throws IOException {
return this.read(buf, 0, buf.length);
}
}
|
yegor256/cactoos
|
src/test/java/org/cactoos/io/SlowInputStream.java
|
Java
|
mit
| 2,637 |
package ru.otus.java_2017_04.golovnin.hw09;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity(name = "user")
@Table(name = "users")
public class User extends DataSet{
@Column(name = "name")
private String name;
@Column(name = "age", nullable = false, length = 3)
private int age;
User(){
super();
name = "";
age = 0;
}
User(long id, String name, int age){
super(id);
this.name = name;
this.age = age;
}
String getName(){
return name;
}
int getAge() {
return age;
}
}
|
vladimir-golovnin/otus-java-2017-04-golovnin
|
hw09/src/main/java/ru/otus/java_2017_04/golovnin/hw09/User.java
|
Java
|
mit
| 642 |
package com.purvotara.airbnbmapexample.model;
import android.content.Context;
import com.android.volley.Request;
import com.google.gson.Gson;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import com.purvotara.airbnbmapexample.constants.NetworkConstants;
import com.purvotara.airbnbmapexample.controller.BaseInterface;
import com.purvotara.airbnbmapexample.network.BaseNetwork;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
/**
* Created by skytreasure on 15/4/16.
*/
public class AddressModel extends BaseModel {
@SerializedName("address_id")
@Expose
private Integer addressId;
@SerializedName("mPincode")
@Expose
private String mPincode;
@SerializedName("city")
@Expose
private String city;
@SerializedName("line_1")
@Expose
private String line1;
@SerializedName("line_2")
@Expose
private String line2;
@SerializedName("longitude")
@Expose
private String longitude;
@SerializedName("latitude")
@Expose
private String latitude;
@SerializedName("address_type")
@Expose
private String addressType;
@SerializedName("default")
@Expose
private Boolean _default;
@SerializedName("image")
@Expose
private String image;
@SerializedName("rating")
@Expose
private String rating;
@SerializedName("distance")
@Expose
private String distance;
/**
* Constructor for the base model
*
* @param context the application mContext
* @param baseInterface it is the instance of baseinterface,
*/
public AddressModel(Context context, BaseInterface baseInterface) {
super(context, baseInterface);
}
public void fetchAddressFromServer() {
BaseNetwork baseNetwork = new BaseNetwork(mContext, this);
baseNetwork.getJSONObjectForRequest(Request.Method.GET, NetworkConstants.ADDRESS_URL, null, NetworkConstants.ADDRESS_REQUEST);
}
@Override
public void parseAndNotifyResponse(JSONObject response, int requestType) throws JSONException {
try {
// boolean error = response.getBoolean(NetworkConstants.ERROR);
Gson gson = new Gson();
switch (requestType) {
case NetworkConstants.ADDRESS_REQUEST:
JSONArray addressArray = response.getJSONArray(NetworkConstants.ADDRESS);
List<AddressModel> addressList = gson.fromJson(addressArray.toString(),
new TypeToken<List<AddressModel>>() {
}.getType());
mBaseInterface.handleNetworkCall(addressList, requestType);
break;
}
} catch (Exception e) {
mBaseInterface.handleNetworkCall(e.getMessage(), requestType);
}
}
@Override
public HashMap<String, Object> getRequestBodyObject(int requestType) {
return null;
}
@Override
public HashMap<String, String> getRequestBodyString(int requestType) {
return null;
}
public Integer getAddressId() {
return addressId;
}
public void setAddressId(Integer addressId) {
this.addressId = addressId;
}
public String getmPincode() {
return mPincode;
}
public void setmPincode(String mPincode) {
this.mPincode = mPincode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getLine1() {
return line1;
}
public void setLine1(String line1) {
this.line1 = line1;
}
public String getLine2() {
return line2;
}
public void setLine2(String line2) {
this.line2 = line2;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getAddressType() {
return addressType;
}
public void setAddressType(String addressType) {
this.addressType = addressType;
}
public Boolean get_default() {
return _default;
}
public void set_default(Boolean _default) {
this._default = _default;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
}
|
SkyTreasure/Airbnb-Android-Google-Map-View
|
app/src/main/java/com/purvotara/airbnbmapexample/model/AddressModel.java
|
Java
|
mit
| 5,013 |
package models.factories;
import models.squares.PropertySquare;
import java.util.Set;
/**
* @author Ani Kristo
*/
interface PropertyFactory {
Set<? extends PropertySquare> makeSquares();
}
|
CS319-G12/uMonopoly
|
src/models/factories/PropertyFactory.java
|
Java
|
mit
| 198 |
/**
* Created by yangge on 1/29/2016.
*/
public class EggPlant extends Veggies {
}
|
eroicaleo/DesignPatterns
|
HeadFirst/ch04/PizzaStoreAbstractFactory/EggPlant.java
|
Java
|
mit
| 85 |
/*
* This file is part of the Turtle project
*
* (c) 2011 Julien Brochet <julien.brochet@etu.univ-lyon1.fr>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package turtle.gui.panel;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
import turtle.behavior.team.TeamBehaviorInterface;
import turtle.controller.Kernel;
import turtle.entity.Team;
import turtle.util.Log;
/**
* Représentation du panel permettant le changement du
* comportement d'une équipe
*
* @author Julien Brochet <julien.brochet@etu.univ-lyon1.fr>
* @since 1.0
*/
public class TeamBehaviorPanel extends JPanel implements ActionListener
{
/**
* L'équipe concernée
*/
protected Team mTeam;
/**
* Le contrôlleur
*/
protected Kernel mKernel;
public TeamBehaviorPanel(Kernel kernel, Team team)
{
mTeam = team;
mKernel = kernel;
initialize();
}
/**
* Création de la fenêtre et de ses composants
*/
private void initialize()
{
Border paddingBorder = BorderFactory.createEmptyBorder(0,10,10,0);
JLabel label = new JLabel("Comportement de l'équipe " + mTeam.getName());
label.setBorder(paddingBorder);
JComboBox comboBox = new JComboBox(mTeam.getAvailableBehaviors().toArray());
comboBox.addActionListener(this);
comboBox.setSelectedIndex(-1);
setLayout(new BorderLayout());
add(label, BorderLayout.NORTH);
add(comboBox, BorderLayout.SOUTH);
}
@Override
public void actionPerformed(ActionEvent e)
{
JComboBox cb = (JComboBox) e.getSource();
TeamBehaviorInterface behavior = (TeamBehaviorInterface) cb.getSelectedItem();
TeamBehaviorInterface oldBehavior = mTeam.getBehavior();
if (behavior != oldBehavior) {
Log.i(String.format("Behavior change for Team %s (old=%s, new=%s)", mTeam.getName(), mTeam.getBehavior(), behavior));
mKernel.changeTeamBehavior(mTeam, behavior);
}
}
}
|
aerialls/Turtle
|
src/turtle/gui/panel/TeamBehaviorPanel.java
|
Java
|
mit
| 2,309 |
package platzi.app;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
public interface InstructorRepository extends JpaRepository<Instructor, Long> {
Optional<Instructor> findByUsername(String username);
}
|
erikmr/Java-Api-Rest
|
src/main/java/platzi/app/InstructorRepository.java
|
Java
|
mit
| 250 |
package com.qiniu.android.dns.http;
import com.qiniu.android.dns.Domain;
import com.qiniu.android.dns.IResolver;
import com.qiniu.android.dns.NetworkInfo;
import com.qiniu.android.dns.Record;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by bailong on 15/6/12.
*/
public final class DnspodFree implements IResolver {
@Override
public Record[] query(Domain domain, NetworkInfo info) throws IOException {
URL url = new URL("http://119.29.29.29/d?ttl=1&dn=" + domain.domain);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
return null;
}
int length = httpConn.getContentLength();
if (length > 1024 || length == 0) {
return null;
}
InputStream is = httpConn.getInputStream();
byte[] data = new byte[length];
int read = is.read(data);
is.close();
String response = new String(data, 0, read);
String[] r1 = response.split(",");
if (r1.length != 2) {
return null;
}
int ttl;
try {
ttl = Integer.parseInt(r1[1]);
} catch (Exception e) {
return null;
}
String[] ips = r1[0].split(";");
if (ips.length == 0) {
return null;
}
Record[] records = new Record[ips.length];
long time = System.currentTimeMillis() / 1000;
for (int i = 0; i < ips.length; i++) {
records[i] = new Record(ips[i], Record.TYPE_A, ttl, time);
}
return records;
}
}
|
longbai/happy-dns-android
|
library/src/main/java/com/qiniu/android/dns/http/DnspodFree.java
|
Java
|
mit
| 1,751 |
package test.ethereum.core;
import test.ethereum.TestContext;
import org.ethereum.config.SystemProperties;
import org.ethereum.core.Block;
import org.ethereum.core.BlockchainImpl;
import org.ethereum.core.Genesis;
import org.ethereum.facade.Blockchain;
import org.ethereum.manager.WorldManager;
import org.junit.After;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class BlockTest {
private static final Logger logger = LoggerFactory.getLogger("test");
@Configuration
@ComponentScan(basePackages = "org.ethereum")
static class ContextConfiguration extends TestContext {
}
@Autowired
WorldManager worldManager;
// https://ethereum.etherpad.mozilla.org/12
private String PoC7_GENESIS_HEX_RLP_ENCODED = "f9012ef90129a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347940000000000000000000000000000000000000000a0156df8ef53c723b40f97aff55dd785489cae8b457495916147687746bd5ee077a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b840000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000080830f4240808080a004994f67dc55b09e814ab7ffc8df3686b4afb2bb53e60eae97ef043fe03fb829c0c0";
private String PoC7_GENESIS_HEX_HASH = "c9cb614fddd89b3bc6e2f0ed1f8e58e8a0d826612a607a6151be6f39c991a941";
String block_2 = "f8b5f8b1a0cf4b25b08b39350304fe12a16e4216c01a426f8f3dbf0d392b5b45"
+ "8ffb6a399da01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a1"
+ "42fd40d493479476f5eabe4b342ee56b8ceba6ab2a770c3e2198e7a08a22d58b"
+ "a5c65b2bf660a961b075a43f564374d38bfe6cc69823eea574d1d16e80833fe0"
+ "04028609184e72a000830f3aab80845387c60380a00000000000000000000000"
+ "0000000000000000000000000033172b6669131179c0c0";
String block_17 = "f9016df8d3a0aa142573b355c6f2e8306471c869b0d12d0638cea3f57d39991a"
+ "b1b03ffa40daa01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40"
+ "d4934794e559de5527492bcb42ec68d07df0742a98ec3f1ea031c973c20e7a15c319a9ff"
+ "9b0aab5bdc121320767fee71fb2b771ce1c93cf812a01b224ec310c2bfb40fd0e6a668ee"
+ "7c06a5a4a4bfb99620d0fea8f7b43315dd59833f3130118609184e72a000830f01ec8201"
+ "f4845387f36980a00000000000000000000000000000000000000000000000000532c3ae"
+ "9b3503f6f895f893f86d018609184e72a0008201f494f625565ac58ec5dadfce1b8f9fb1"
+ "dd30db48613b8862cf5246d0c80000801ca05caa26abb350e0521a25b8df229806f3777d"
+ "9e262996493846a590c7011697dba07bb7680a256ede4034212b7a1ae6c7caea73190cb0"
+ "7dedb91a07b72f34074e76a00cd22d78d556175604407dc6109797f5c8d990d05f1b352e"
+ "10c71b3dd74bc70f8201f4c0";
String block_32 = "f8f8f8f4a00a312c2b0a8f125c60a3976b6e508e740e095eb59943988d9bbfb8"
+ "aa43922e31a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d4"
+ "934794e559de5527492bcb42ec68d07df0742a98ec3f1ea050188ab86bdf164ac90eb283"
+ "5a04a8930aae5393c3a2ef1166fb95028f9456b88080b840000000000000000000000000"
+ "000000000000000000000000000000000000000000000000000000000000000000000000"
+ "00000000000000000000000000000000833ee248208609184e72a000830eca0080845387"
+ "fd2080a00000000000000000000000000000000000000000000000001f52ebb192c4ea97"
+ "c0c0";
@After
public void doReset() {
worldManager.reset();
}
@Test /* got from go guy */
public void testGenesisFromRLP() {
// from RLP encoding
byte[] genesisBytes = Hex.decode(PoC7_GENESIS_HEX_RLP_ENCODED);
Block genesisFromRLP = new Block(genesisBytes);
Block genesis = Genesis.getInstance();
assertEquals(Hex.toHexString(genesis.getHash()), Hex.toHexString(genesisFromRLP.getHash()));
assertEquals(Hex.toHexString(genesis.getParentHash()), Hex.toHexString(genesisFromRLP.getParentHash()));
assertEquals(Hex.toHexString(genesis.getStateRoot()), Hex.toHexString(genesisFromRLP.getStateRoot()));
}
@Test
public void testGenesisFromNew() {
Block genesis = Genesis.getInstance();
logger.info(genesis.toString());
logger.info("genesis hash: [{}]", Hex.toHexString(genesis.getHash()));
logger.info("genesis rlp: [{}]", Hex.toHexString(genesis.getEncoded()));
assertEquals(PoC7_GENESIS_HEX_HASH, Hex.toHexString(genesis.getHash()));
assertEquals(PoC7_GENESIS_HEX_RLP_ENCODED, Hex.toHexString(genesis.getEncoded()));
}
@Test /* block without transactions - block#32 in PoC5 cpp-chain */
public void testEmptyBlock() {
byte[] payload = Hex.decode(block_32);
Block blockData = new Block(payload);
logger.info(blockData.toString());
}
@Test /* block with single balance transfer transaction - block#17 in PoC5 cpp-chain */
@Ignore
public void testSingleBalanceTransfer() {
byte[] payload = Hex.decode(block_17); // todo: find out an uptodate block wire
Block blockData = new Block(payload);
logger.info(blockData.toString());
}
@Test /* large block with 5 transactions -block#1 in PoC5 cpp-chain */
public void testBlockWithContractCreation() {
byte[] payload = Hex.decode(PoC7_GENESIS_HEX_RLP_ENCODED);
Block block = new Block(payload);
logger.info(block.toString());
}
@Test
public void testCalcDifficulty() {
Blockchain blockchain = worldManager.getBlockchain();
Block genesis = Genesis.getInstance();
BigInteger difficulty = new BigInteger(1, genesis.calcDifficulty());
logger.info("Genesis difficulty: [{}]", difficulty.toString());
assertEquals(new BigInteger(1, Genesis.DIFFICULTY), difficulty);
// Storing genesis because the parent needs to be in the DB for calculation.
blockchain.add(genesis);
Block block1 = new Block(Hex.decode(PoC7_GENESIS_HEX_RLP_ENCODED));
BigInteger calcDifficulty = new BigInteger(1, block1.calcDifficulty());
BigInteger actualDifficulty = new BigInteger(1, block1.getDifficulty());
logger.info("Block#1 actual difficulty: [{}] ", actualDifficulty.toString());
logger.info("Block#1 calculated difficulty: [{}] ", calcDifficulty.toString());
assertEquals(actualDifficulty, calcDifficulty);
}
@Test
public void testCalcGasLimit() {
BlockchainImpl blockchain = (BlockchainImpl) worldManager.getBlockchain();
Block genesis = Genesis.getInstance();
long gasLimit = blockchain.calcGasLimit(genesis.getHeader());
logger.info("Genesis gasLimit: [{}] ", gasLimit);
assertEquals(Genesis.GAS_LIMIT, gasLimit);
// Test with block
Block block1 = new Block(Hex.decode(PoC7_GENESIS_HEX_RLP_ENCODED));
long calcGasLimit = blockchain.calcGasLimit(block1.getHeader());
long actualGasLimit = block1.getGasLimit();
blockchain.tryToConnect(block1);
logger.info("Block#1 actual gasLimit [{}] ", actualGasLimit);
logger.info("Block#1 calculated gasLimit [{}] ", calcGasLimit);
assertEquals(actualGasLimit, calcGasLimit);
}
@Ignore
@Test
public void testScenario1() throws URISyntaxException, IOException {
BlockchainImpl blockchain = (BlockchainImpl) worldManager.getBlockchain();
URL scenario1 = ClassLoader
.getSystemResource("blockload/scenario1.dmp");
File file = new File(scenario1.toURI());
List<String> strData = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
byte[] root = Genesis.getInstance().getStateRoot();
for (String blockRLP : strData) {
Block block = new Block(
Hex.decode(blockRLP));
logger.info("sending block.hash: {}", Hex.toHexString(block.getHash()));
blockchain.tryToConnect(block);
root = block.getStateRoot();
}
logger.info("asserting root state is: {}", Hex.toHexString(root));
//expected root: fb8be59e6420892916e3967c60adfdf48836af040db0072ca411d7aaf5663804
assertEquals(Hex.toHexString(root),
Hex.toHexString(worldManager.getRepository().getRoot()));
}
@Ignore
@Test
public void testScenario2() throws URISyntaxException, IOException {
BlockchainImpl blockchain = (BlockchainImpl) worldManager.getBlockchain();
URL scenario1 = ClassLoader
.getSystemResource("blockload/scenario2.dmp");
File file = new File(scenario1.toURI());
List<String> strData = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
byte[] root = Genesis.getInstance().getStateRoot();
for (String blockRLP : strData) {
Block block = new Block(
Hex.decode(blockRLP));
logger.info("sending block.hash: {}", Hex.toHexString(block.getHash()));
blockchain.tryToConnect(block);
root = block.getStateRoot();
}
logger.info("asserting root state is: {}", Hex.toHexString(root));
//expected root: a5e2a18bdbc4ab97775f44852382ff5585b948ccb15b1d69f0abb71e2d8f727d
assertEquals(Hex.toHexString(root),
Hex.toHexString(worldManager.getRepository().getRoot()));
}
@Test
@Ignore
public void testUncleValidGenerationGap() {
// TODO
fail("Not yet implemented");
}
@Test
@Ignore
public void testUncleInvalidGenerationGap() {
// TODO
fail("Not yet implemented");
}
@Test
@Ignore
public void testUncleInvalidParentGenerationGap() {
// TODO
fail("Not yet implemented");
}
}
|
swaldman/ethereumj
|
ethereumj-core/src/test/java/test/ethereum/core/BlockTest.java
|
Java
|
mit
| 10,826 |
package com.wabbit.libraries;
import android.content.Context;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;
public class Installation {
private static String sID = null;
private static final String INSTALLATION = "INSTALLATION";
public synchronized static String id(Context context) {
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists())
writeInstallationFile(installation);
sID = readInstallationFile(installation);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return sID;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
private static void writeInstallationFile(File installation) throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String id = UUID.randomUUID().toString();
out.write(id.getBytes());
out.close();
}
}
|
DobrinAlexandru/Wabbit-Messenger---android-client
|
Wabbit/src/com/wabbit/libraries/Installation.java
|
Java
|
mit
| 1,373 |
package BubbleSort2D;
public class person {
String name;
int age;
boolean sortme = false;
public person(String n, int a) {
name = n;
age = a;
}
public String toString(){
return name + " " + Integer.toString(age);
}
}
|
mrswoop/BubbleSort2DArrayRange
|
BubbleSort2D/src/BubbleSort2D/person.java
|
Java
|
mit
| 253 |
package com.github.mmonkey.Automator.Migrations;
import com.github.mmonkey.Automator.Automator;
public abstract class MigrationRunner {
protected Automator plugin;
protected int version;
protected int latest = 0;
public void run() {
while (this.version != this.latest) {
MigrationInterface migration = this.getMigration(this.version);
if (migration != null) {
migration.up();
this.version++;
}
}
}
abstract MigrationInterface getMigration(int version);
public MigrationRunner(Automator plugin, int version) {
this.plugin = plugin;
this.version = version;
}
}
|
mmonkey/Automator
|
src/main/java/com/github/mmonkey/Automator/Migrations/MigrationRunner.java
|
Java
|
mit
| 701 |
/*
* Copyright 2001-2014 Aspose Pty Ltd. All Rights Reserved.
*
* This file is part of Aspose.Words. The source code in this file
* is only intended as a supplement to the documentation, and is provided
* "as is", without warranty of any kind, either expressed or implied.
*/
package loadingandsaving.loadingandsavinghtml.splitintohtmlpages.java;
/**
* A simple class to hold a topic title and HTML file name together.
*/
class Topic
{
Topic(String title, String fileName) throws Exception
{
mTitle = title;
mFileName = fileName;
}
String getTitle() throws Exception { return mTitle; }
String getFileName() throws Exception { return mFileName; }
private final String mTitle;
private final String mFileName;
}
|
asposemarketplace/Aspose-Words-Java
|
src/loadingandsaving/loadingandsavinghtml/splitintohtmlpages/java/Topic.java
|
Java
|
mit
| 791 |
/**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package org.opengroup.archimate.xmlexchange;
/**
* XML Exception
*
* @author Phillip Beauvoir
*/
public class XMLModelParserException extends Exception {
public XMLModelParserException() {
super(Messages.XMLModelParserException_0);
}
public XMLModelParserException(String message) {
super(message);
}
public XMLModelParserException(String message, Throwable cause) {
super(message, cause);
}
}
|
archimatetool/archi
|
org.opengroup.archimate.xmlexchange/src/org/opengroup/archimate/xmlexchange/XMLModelParserException.java
|
Java
|
mit
| 597 |
package com.aliumujib.majlis.mkan_report_app.addnew.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.aliumujib.majlis.mkan_report_app.R;
import com.stepstone.stepper.VerificationError;
public class SihateJismaniPart2 extends BaseReportFragment {
public static SihateJismaniPart2 newInstance() {
SihateJismaniPart2 fragment = new SihateJismaniPart2();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sihate_jismani_part2, container, false);
}
@Override
public VerificationError verifyStep() {
return null;
}
@Override
public void onSelected() {
}
}
|
MKA-Nigeria/MKAN-Report-Android
|
mkan_report_app/src/main/java/com/aliumujib/majlis/mkan_report_app/addnew/fragments/SihateJismaniPart2.java
|
Java
|
mit
| 1,164 |
package com.hypebeast.sdk.api.model.hypebeaststore;
import com.google.gson.annotations.SerializedName;
import com.hypebeast.sdk.api.model.Alternative;
import com.hypebeast.sdk.api.model.symfony.taxonomy;
/**
* Created by hesk on 7/1/2015.
*/
public class ReponseNormal extends Alternative {
@SerializedName("products")
public ResponseProductList product_list;
@SerializedName("taxon")
public taxonomy taxon_result;
}
|
jjhesk/slideSelectionList
|
SmartSelectionList/hbsdk/src/main/java/com/hypebeast/sdk/api/model/hypebeaststore/ReponseNormal.java
|
Java
|
mit
| 438 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.containerservice.generated;
import com.azure.core.util.Context;
/** Samples for ManagedClusters List. */
public final class ManagedClustersListSamples {
/*
* x-ms-original-file: specification/containerservice/resource-manager/Microsoft.ContainerService/stable/2022-01-01/examples/ManagedClustersList.json
*/
/**
* Sample code: List Managed Clusters.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void listManagedClusters(com.azure.resourcemanager.AzureResourceManager azure) {
azure.kubernetesClusters().manager().serviceClient().getManagedClusters().list(Context.NONE);
}
}
|
Azure/azure-sdk-for-java
|
sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/containerservice/generated/ManagedClustersListSamples.java
|
Java
|
mit
| 875 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.compute.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.compute.fluent.models.ProximityPlacementGroupInner;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** The List Proximity Placement Group operation response. */
@Fluent
public final class ProximityPlacementGroupListResult {
/*
* The list of proximity placement groups
*/
@JsonProperty(value = "value", required = true)
private List<ProximityPlacementGroupInner> value;
/*
* The URI to fetch the next page of proximity placement groups.
*/
@JsonProperty(value = "nextLink")
private String nextLink;
/**
* Get the value property: The list of proximity placement groups.
*
* @return the value value.
*/
public List<ProximityPlacementGroupInner> value() {
return this.value;
}
/**
* Set the value property: The list of proximity placement groups.
*
* @param value the value value to set.
* @return the ProximityPlacementGroupListResult object itself.
*/
public ProximityPlacementGroupListResult withValue(List<ProximityPlacementGroupInner> value) {
this.value = value;
return this;
}
/**
* Get the nextLink property: The URI to fetch the next page of proximity placement groups.
*
* @return the nextLink value.
*/
public String nextLink() {
return this.nextLink;
}
/**
* Set the nextLink property: The URI to fetch the next page of proximity placement groups.
*
* @param nextLink the nextLink value to set.
* @return the ProximityPlacementGroupListResult object itself.
*/
public ProximityPlacementGroupListResult withNextLink(String nextLink) {
this.nextLink = nextLink;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (value() == null) {
throw LOGGER
.logExceptionAsError(
new IllegalArgumentException(
"Missing required property value in model ProximityPlacementGroupListResult"));
} else {
value().forEach(e -> e.validate());
}
}
private static final ClientLogger LOGGER = new ClientLogger(ProximityPlacementGroupListResult.class);
}
|
Azure/azure-sdk-for-java
|
sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/models/ProximityPlacementGroupListResult.java
|
Java
|
mit
| 2,679 |
/**
* The MIT License
* Copyright (c) 2003 David G Jones
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package info.dgjones.st2x.transform.method.intra;
import java.util.List;
import info.dgjones.st2x.ClassParser;
import info.dgjones.st2x.JavaMethod;
import info.dgjones.st2x.javatoken.JavaCallStart;
import info.dgjones.st2x.javatoken.JavaIdentifier;
import info.dgjones.st2x.javatoken.JavaKeyword;
import info.dgjones.st2x.javatoken.JavaToken;
import info.dgjones.st2x.transform.method.AbstractMethodBodyTransformation;
import info.dgjones.st2x.transform.tokenmatcher.TokenMatcher;
import info.dgjones.st2x.transform.tokenmatcher.TokenMatcherFactory;
public class TransformCreateCall extends AbstractMethodBodyTransformation {
public TransformCreateCall() {
super();
}
public TransformCreateCall(TokenMatcherFactory factory) {
super(factory);
}
protected TokenMatcher matchers(TokenMatcherFactory factory) {
return factory.token(JavaCallStart.class, "create.*");
}
protected int transform(JavaMethod javaMethod, List tokens, int i) {
JavaCallStart call = (JavaCallStart)tokens.get(i);
if (ClassParser.NON_CONSTRUCTORS.contains(call.value)) {
return i;
}
if (i > 0 && (tokens.get(i - 1) instanceof JavaIdentifier)) {
JavaToken token = (JavaToken) tokens.get(i - 1);
if (token.value.equals("super")) {
return i;
} else if (token.value.equals(javaMethod.javaClass.className) && javaMethod.isConstructor()) {
call.value = "this";
tokens.remove(i-1);
return i-1;
}
call.value = token.value;
tokens.remove(i - 1);
tokens.add(i - 1, new JavaKeyword("new"));
} else if (javaMethod.isConstructor()) {
call.value = "this";
} else {
call.value = javaMethod.javaClass.className;
tokens.add(i, new JavaKeyword("new"));
}
return i;
}
}
|
jonesd/st2x
|
src/main/java/info/dgjones/st2x/transform/method/intra/TransformCreateCall.java
|
Java
|
mit
| 2,846 |
package ie.lc.fallApp;
import java.text.DecimalFormat;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class ActivityFallHeight extends Activity
{
private double persistentRandomNumber;
private static final String persistentRandomNumberKey = "prn";
private final int planetRequestCode = 1337;
private final Interlock fieldInterlock = new Interlock();
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_fall );
setupActions();
persistentRandomNumber = Math.random() * 10.0;
}
protected void onSaveInstanceState( Bundle out ) {
out.putDouble( persistentRandomNumberKey, persistentRandomNumber );
showToastMessage( "Saved instance variable: " + persistentRandomNumber );
}
protected void onRestoreInstanceState( Bundle in ) {
persistentRandomNumber = in.getDouble( persistentRandomNumberKey );
showToastMessage( "Restored instance variable: " + persistentRandomNumber );
}
protected void onActivityResult( int requestCode, int resultCode, Intent data ) {
if (requestCode == planetRequestCode
&& resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Planet selectedPlanet = (Planet) extras.getSerializable( Common.planetSelectIdentifier );
Planet activePlanet = Physics.getActivePlanet();
if ( ! selectedPlanet.equals(activePlanet)) {
Physics.setActivePlanet( selectedPlanet );
showToastMessage( getString(R.string.planetChanged) + " " + selectedPlanet + "." );
updateDisplayedHeightFromVelocity();
}
}
}
public boolean onCreateOptionsMenu( Menu menu ) {
getMenuInflater().inflate( R.menu.fall_height, menu );
return true;
}
/** Used by computeAndShow */
private interface ComputeCallback {
double execute( String textInput ) throws NumberFormatException;
}
private void computeAndShow( EditText targetField, String textInput, ComputeCallback comp ) {
if ( ! fieldInterlock.isLocked()) {
fieldInterlock.setLocked( true );
String textOutput = "";
try {
double num = comp.execute( textInput );
textOutput = formatTwoDecimalPlaces( num );
}
catch (Exception ex) {
// Ducked
}
targetField.setText( textOutput );
fieldInterlock.setLocked( false );
}
}
private void setupActions() {
final EditText velocityField = (EditText) findViewById( R.id.velocityField );
final EditText heightField = (EditText) findViewById( R.id.heightField );
final Button optionsButton = (Button) findViewById( R.id.optionsButton );
final Button showBigButton = (Button) findViewById( R.id.showBigButton );
velocityField.addTextChangedListener( new TextWatcherAdapter() {
public void afterTextChanged( Editable e ) {
computeAndShow( heightField, e.toString(), new ComputeCallback() {
public double execute( String textInput ) throws NumberFormatException {
double vKmh = Double.parseDouble( textInput );
double vMps = Physics.kilometresPerHourToMetresPerSec( vKmh );
return Physics.computeEquivalentFallHeight( vMps );
}
});
}
});
heightField.addTextChangedListener( new TextWatcherAdapter() {
public void afterTextChanged( Editable e ) {
computeAndShow( velocityField, e.toString(), new ComputeCallback() {
public double execute( String textInput ) throws NumberFormatException {
double height = Double.parseDouble( textInput );
double vMps = Physics.computeEquivalentVelocity( height );
return Physics.metresPerSecToKilometresPerHour( vMps );
}
});
}
});
optionsButton.setOnClickListener( new OnClickListener() {
public void onClick( View v ) {
Intent intent = new Intent( ActivityFallHeight.this, ActivityOptions.class );
intent.putExtra( Common.planetSelectIdentifier, Physics.getActivePlanet() );
startActivityForResult( intent, planetRequestCode );
}
});
showBigButton.setOnClickListener( new OnClickListener() {
public void onClick( View v ) {
Intent intent = new Intent( ActivityFallHeight.this, ActivityDisplay.class );
intent.putExtra( Common.displayHeightIdentifier, heightField.getText().toString() );
startActivity( intent );
}
});
}
private void updateDisplayedHeightFromVelocity() {
final EditText velocityField = (EditText) findViewById( R.id.velocityField );
velocityField.setText( velocityField.getText() ); // Triggers event.
}
private static String formatTwoDecimalPlaces( double num ) {
DecimalFormat f = new DecimalFormat( "0.00" );
return f.format( num );
}
private void showToastMessage( String str ) {
Toast.makeText( this, str, Toast.LENGTH_SHORT ).show();
}
}
|
LeeCIT/FallApp
|
FallApp/src/ie/lc/fallApp/ActivityFallHeight.java
|
Java
|
mit
| 5,073 |
package com.maximusvladimir.randomfinder;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JProgressBar;
import javax.swing.Timer;
import javax.swing.JTextPane;
import java.awt.Font;
public class Test extends JFrame {
private JTextField textField;
private Searcher scanner;
private JTextPane txtpncodeWillGenerate;
public static void main(String[] args) { new Test(); }
public Test() {
setVisible(true);
setSize(324,270);
setTitle("Test");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
scanner = new Searcher();
JLabel lblEnterStringTo = new JLabel("Enter string to find:");
lblEnterStringTo.setBounds(10, 11, 136, 14);
getContentPane().add(lblEnterStringTo);
textField = new JTextField();
textField.setBounds(10, 30, 189, 20);
getContentPane().add(textField);
textField.setColumns(10);
final JButton btnGo = new JButton("Go!");
btnGo.setBounds(209, 29, 89, 23);
getContentPane().add(btnGo);
final JProgressBar progressBar = new JProgressBar();
progressBar.setBounds(10, 90, 288, 20);
getContentPane().add(progressBar);
JLabel lblMaximumTimeRemaining = new JLabel("Maximum time remaining:");
lblMaximumTimeRemaining.setBounds(10, 61, 178, 14);
getContentPane().add(lblMaximumTimeRemaining);
final JLabel lblResult = new JLabel("Result:");
lblResult.setBounds(10, 121, 189, 14);
getContentPane().add(lblResult);
txtpncodeWillGenerate = new JTextPane();
txtpncodeWillGenerate.setFont(new Font("Courier New", Font.PLAIN, 10));
txtpncodeWillGenerate.setText("(Code will generate here)");
txtpncodeWillGenerate.setBounds(10, 141, 298, 90);
getContentPane().add(txtpncodeWillGenerate);
btnGo.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
if (btnGo.getText().equals("Go!")) {
btnGo.setText("Halt");
lblResult.setText("Result:");
try {
scanner.setString(textField.getText());
}
catch (Throwable t) {
JOptionPane.showMessageDialog(Test.this, t.getMessage());
}
scanner.startAsync();
Test.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
else {
Test.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
btnGo.setText("Go!");
scanner.halt();
}
}
});
new Timer(250,new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
progressBar.setValue((int)(100 * scanner.getProgress()));
if (scanner.isFinished()) {
Test.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
if (scanner.getResultSeed() == Integer.MIN_VALUE)
lblResult.setText("Result: Not found.");
else {
lblResult.setText("Result: " + scanner.getResultSeed());
genCode();
}
btnGo.setText("Go!");
}
}
}).start();
repaint();
}
private void genCode() {
String pieces = "";
for (int i = 0; i < scanner.getString().length(); i++) {
pieces += "((char)(rand.nextInt(96)+32)) + \"\"";
pieces += " +";
}
if (scanner.getString().length() >= 1)
pieces = pieces.substring(0,pieces.length()-2);
txtpncodeWillGenerate.setText("Random rand = new Random("+scanner.getResultSeed()+");\n"+
"System.out.println(" + pieces + ");\n"+
"// Outputs " + scanner.getString());
}
}
|
maximusvladimir/randomfinder
|
src/com/maximusvladimir/randomfinder/Test.java
|
Java
|
mit
| 3,649 |
package com.walkertribe.ian.protocol.core.weap;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.walkertribe.ian.enums.BeamFrequency;
import com.walkertribe.ian.enums.Origin;
import com.walkertribe.ian.protocol.AbstractPacketTester;
public class SetBeamFreqPacketTest extends AbstractPacketTester<SetBeamFreqPacket> {
@Test
public void test() {
execute("core/weap/SetBeamFreqPacket.txt", Origin.CLIENT, 1);
}
@Test
public void testConstruct() {
test(new SetBeamFreqPacket(BeamFrequency.B));
}
@Test(expected = IllegalArgumentException.class)
public void testConstructNullBeamFrequency() {
new SetBeamFreqPacket((BeamFrequency) null);
}
@Override
protected void testPackets(List<SetBeamFreqPacket> packets) {
test(packets.get(0));
}
private void test(SetBeamFreqPacket pkt) {
Assert.assertEquals(BeamFrequency.B, pkt.getBeamFrequency());
}
}
|
rjwut/ian
|
src/test/java/com/walkertribe/ian/protocol/core/weap/SetBeamFreqPacketTest.java
|
Java
|
mit
| 906 |
package soliddomino.game.exceptions;
public class IncorrectMoveFormatException extends Exception {
public IncorrectMoveFormatException(String format) {
super(format + " is not the correct format. Expected \'#number-direction(e.g left, right).\'\nExample: 4-right");
}
}
|
Beta-nanos/SolidDomino
|
SolidDomino/src/soliddomino/game/exceptions/IncorrectMoveFormatException.java
|
Java
|
mit
| 289 |
package com.giantbomb.main;
public class ListOfGamesGenerator
{
public static void main(final String[] args)
{
}
}
|
brentnash/gbecho
|
src/main/java/com/giantbomb/main/ListOfGamesGenerator.java
|
Java
|
mit
| 137 |
/*
* 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.util;
import org.gluu.oxauth.model.common.ResponseMode;
import org.jboss.resteasy.specimpl.ResponseBuilderImpl;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import java.net.MalformedURLException;
import java.net.URI;
import static org.gluu.oxauth.client.AuthorizationRequest.NO_REDIRECT_HEADER;
/**
* @version October 7, 2019
*/
public class RedirectUtil {
private final static Logger log = LoggerFactory.getLogger(RedirectUtil.class);
static String JSON_REDIRECT_PROPNAME = "redirect";
static int HTTP_REDIRECT = 302;
public static ResponseBuilder getRedirectResponseBuilder(RedirectUri redirectUriResponse, HttpServletRequest httpRequest) {
ResponseBuilder builder;
if (httpRequest != null && httpRequest.getHeader(NO_REDIRECT_HEADER) != null) {
try {
URI redirectURI = URI.create(redirectUriResponse.toString());
JSONObject jsonObject = new JSONObject();
jsonObject.put(JSON_REDIRECT_PROPNAME, redirectURI.toURL());
String jsonResp = jsonObject.toString();
jsonResp = jsonResp.replace("\\/", "/");
builder = Response.ok(
new GenericEntity<String>(jsonResp, String.class),
MediaType.APPLICATION_JSON_TYPE
);
} catch (MalformedURLException e) {
builder = Response.serverError();
log.debug(e.getMessage(), e);
} catch (JSONException e) {
builder = Response.serverError();
log.debug(e.getMessage(), e);
}
} else if (redirectUriResponse.getResponseMode() != ResponseMode.FORM_POST) {
URI redirectURI = URI.create(redirectUriResponse.toString());
builder = new ResponseBuilderImpl();
builder = Response.status(HTTP_REDIRECT);
builder.location(redirectURI);
} else {
builder = new ResponseBuilderImpl();
builder.status(Response.Status.OK);
builder.type(MediaType.TEXT_HTML_TYPE);
builder.cacheControl(CacheControl.valueOf("no-cache, no-store"));
builder.header("Pragma", "no-cache");
builder.entity(redirectUriResponse.toString());
}
return builder;
}
}
|
GluuFederation/oxAuth
|
Server/src/main/java/org/gluu/oxauth/util/RedirectUtil.java
|
Java
|
mit
| 2,806 |
package filediff.myers;
public class DifferentiationFailedException extends DiffException {
private static final long serialVersionUID = 1L;
public DifferentiationFailedException() {
}
public DifferentiationFailedException(String msg) {
super(msg);
}
}
|
nendhruv/data-dictionary
|
src/java/filediff/myers/DifferentiationFailedException.java
|
Java
|
mit
| 294 |
/*
* Copyright 2012 Google 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 ua.org.gdg.devfest.iosched.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import ua.org.gdg.devfest.iosched.service.SessionAlarmService;
import static ua.org.gdg.devfest.iosched.util.LogUtils.makeLogTag;
/**
* {@link BroadcastReceiver} to reinitialize {@link android.app.AlarmManager} for all starred
* session blocks.
*/
public class SessionAlarmReceiver extends BroadcastReceiver {
public static final String TAG = makeLogTag(SessionAlarmReceiver.class);
@Override
public void onReceive(Context context, Intent intent) {
Intent scheduleIntent = new Intent(
SessionAlarmService.ACTION_SCHEDULE_ALL_STARRED_BLOCKS,
null, context, SessionAlarmService.class);
context.startService(scheduleIntent);
}
}
|
zasadnyy/android-hothack-13
|
example/source/src/main/java/ua/org/gdg/devfest/iosched/receiver/SessionAlarmReceiver.java
|
Java
|
mit
| 1,444 |
package me.ronggenliu.dp.creation.builder;
/**
* Created by garliu on 2017/5/29.
*/
public class Product {
private String partA;
private String partB;
private String partC;
public String getPartA() {
return partA;
}
public void setPartA(String partA) {
this.partA = partA;
}
public String getPartB() {
return partB;
}
public void setPartB(String partB) {
this.partB = partB;
}
public String getPartC() {
return partC;
}
public void setPartC(String partC) {
this.partC = partC;
}
}
|
ronggenliu/DesignPattern
|
src/me/ronggenliu/dp/creation/builder/Product.java
|
Java
|
mit
| 544 |
package com.recursivechaos.boredgames.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.data.annotation.Id;
/**
* Created by Andrew Bell 5/28/2015
* www.recursivechaos.com
* andrew@recursivechaos.com
* Licensed under MIT License 2015. See license.txt for details.
*/
public class Game {
@Id
@JsonIgnore
private String id;
private String title;
private String description;
public Game() {
}
public Game(String id) {
this.id = id;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
|
AndrewBell/boredgames-mongo
|
src/main/java/com/recursivechaos/boredgames/domain/Game.java
|
Java
|
mit
| 888 |
package edu.harvard.fas.rbrady.tpteam.tpbridge.hibernate;
// Generated Nov 10, 2006 5:22:58 PM by Hibernate Tools 3.2.0.beta8
import java.util.HashSet;
import java.util.Set;
/**
* TestType generated by hbm2java
*/
public class TestType implements java.io.Serializable {
// Fields
private static final long serialVersionUID = 1L;
private int id;
private String name;
private Set<Test> tests = new HashSet<Test>(0);
// Constructors
/** default constructor */
public TestType() {
}
/** minimal constructor */
public TestType(int id) {
this.id = id;
}
/** full constructor */
public TestType(int id, String name, Set<Test> tests) {
this.id = id;
this.name = name;
this.tests = tests;
}
// Property accessors
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Set<Test> getTests() {
return this.tests;
}
public void setTests(Set<Test> tests) {
this.tests = tests;
}
}
|
bobbrady/tpteam
|
tpbridge/src/edu/harvard/fas/rbrady/tpteam/tpbridge/hibernate/TestType.java
|
Java
|
mit
| 1,142 |
package domain;
import java.util.Date;
/**
* @author Verbroucht Johann
* Test Java Date : 15 aot. 2011
*/
public class Mark {
private Date date;
private int mark;
public Mark(Date _date, int _mark) {
this.date = _date;
this.mark = _mark;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getMark() {
return mark;
}
public void setMark(int mark) {
this.mark = mark;
}
}
|
johannv/javaTestEasy
|
src/domain/Mark.java
|
Java
|
mit
| 497 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Gareth Jon Lynch
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.gazbert.bxbot.exchanges.trading.api.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import com.gazbert.bxbot.trading.api.OrderType;
import java.math.BigDecimal;
import java.util.Date;
import org.junit.Test;
/**
* Tests the Open Order impl behaves as expected.
*
* @author gazbert
*/
public class TestOpenOrderImpl {
private static final String ID = "abc_123_def_456_ghi_789";
private static final Date CREATION_DATE = new Date();
private static final String MARKET_ID = "BTC_USD";
private static final BigDecimal PRICE = new BigDecimal("671.91");
private static final BigDecimal ORIGINAL_QUANTITY = new BigDecimal("0.01433434");
private static final BigDecimal TOTAL = PRICE.multiply(ORIGINAL_QUANTITY);
private static final BigDecimal QUANTITY =
ORIGINAL_QUANTITY.subtract(new BigDecimal("0.00112112"));
@Test
public void testOpenOrderIsInitialisedAsExpected() {
final OpenOrderImpl openOrder =
new OpenOrderImpl(
ID,
CREATION_DATE,
MARKET_ID,
OrderType.SELL,
PRICE,
QUANTITY,
ORIGINAL_QUANTITY,
TOTAL);
assertEquals(ID, openOrder.getId());
assertEquals(CREATION_DATE, openOrder.getCreationDate());
assertEquals(MARKET_ID, openOrder.getMarketId());
assertEquals(OrderType.SELL, openOrder.getType());
assertEquals(PRICE, openOrder.getPrice());
assertEquals(QUANTITY, openOrder.getQuantity());
assertEquals(ORIGINAL_QUANTITY, openOrder.getOriginalQuantity());
assertEquals(TOTAL, openOrder.getTotal());
}
@Test
public void testSettersWorkAsExpected() {
final OpenOrderImpl openOrder =
new OpenOrderImpl(null, null, null, null, null, null, null, null);
assertNull(openOrder.getId());
assertNull(openOrder.getCreationDate());
assertNull(openOrder.getMarketId());
assertNull(openOrder.getType());
assertNull(openOrder.getPrice());
assertNull(openOrder.getQuantity());
assertNull(openOrder.getOriginalQuantity());
assertNull(openOrder.getTotal());
openOrder.setId(ID);
assertEquals(ID, openOrder.getId());
openOrder.setCreationDate(CREATION_DATE);
assertEquals(CREATION_DATE, openOrder.getCreationDate());
openOrder.setMarketId(MARKET_ID);
assertEquals(MARKET_ID, openOrder.getMarketId());
openOrder.setType(OrderType.BUY);
assertEquals(OrderType.BUY, openOrder.getType());
openOrder.setPrice(PRICE);
assertEquals(PRICE, openOrder.getPrice());
openOrder.setQuantity(QUANTITY);
assertEquals(QUANTITY, openOrder.getQuantity());
openOrder.setOriginalQuantity(ORIGINAL_QUANTITY);
assertEquals(ORIGINAL_QUANTITY, openOrder.getOriginalQuantity());
openOrder.setTotal(TOTAL);
assertEquals(TOTAL, openOrder.getTotal());
}
@Test
public void testEqualsWorksAsExpected() {
final OpenOrderImpl openOrder1 =
new OpenOrderImpl(
ID,
CREATION_DATE,
MARKET_ID,
OrderType.SELL,
PRICE,
QUANTITY,
ORIGINAL_QUANTITY,
TOTAL);
final OpenOrderImpl openOrder2 =
new OpenOrderImpl(
"different-id",
CREATION_DATE,
MARKET_ID,
OrderType.SELL,
PRICE,
QUANTITY,
ORIGINAL_QUANTITY,
TOTAL);
final OpenOrderImpl openOrder3 =
new OpenOrderImpl(
ID,
CREATION_DATE,
"diff-market",
OrderType.SELL,
PRICE,
QUANTITY,
ORIGINAL_QUANTITY,
TOTAL);
final OpenOrderImpl openOrder4 =
new OpenOrderImpl(
ID, CREATION_DATE, MARKET_ID, OrderType.BUY, PRICE, QUANTITY, ORIGINAL_QUANTITY, TOTAL);
assertEquals(openOrder1, openOrder1);
assertNotEquals(openOrder1, openOrder2);
assertNotEquals(openOrder1, openOrder3);
assertNotEquals(openOrder1, openOrder4);
}
}
|
gazbert/BX-bot
|
bxbot-exchanges/src/test/java/com/gazbert/bxbot/exchanges/trading/api/impl/TestOpenOrderImpl.java
|
Java
|
mit
| 5,233 |
/*
* Copyright 2013 Google 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.mardin.job.widgets.wizard.ui;
import com.mardin.job.R;
import com.mardin.job.widgets.wizard.model.Page;
import com.mardin.job.widgets.wizard.model.SingleFixedChoicePage;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class SingleChoiceFragment extends ListFragment {
private static final String ARG_KEY = "key";
private PageFragmentCallbacks mCallbacks;
private List<String> mChoices;
private String mKey;
private Page mPage;
public static SingleChoiceFragment create(String key) {
Bundle args = new Bundle();
args.putString(ARG_KEY, key);
SingleChoiceFragment fragment = new SingleChoiceFragment();
fragment.setArguments(args);
return fragment;
}
public SingleChoiceFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
mKey = args.getString(ARG_KEY);
mPage = mCallbacks.onGetPage(mKey);
SingleFixedChoicePage fixedChoicePage = (SingleFixedChoicePage) mPage;
mChoices = new ArrayList<String>();
for (int i = 0; i < fixedChoicePage.getOptionCount(); i++) {
mChoices.add(fixedChoicePage.getOptionAt(i));
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_page, container, false);
((TextView) rootView.findViewById(android.R.id.title)).setText(mPage.getTitle());
final ListView listView = (ListView) rootView.findViewById(android.R.id.list);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_single_choice,
android.R.id.text1,
mChoices));
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// Pre-select currently selected item.
new Handler().post(new Runnable() {
@Override
public void run() {
String selection = mPage.getData().getString(Page.SIMPLE_DATA_KEY);
for (int i = 0; i < mChoices.size(); i++) {
if (mChoices.get(i).equals(selection)) {
listView.setItemChecked(i, true);
break;
}
}
}
});
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof PageFragmentCallbacks)) {
throw new ClassCastException("Activity must implement PageFragmentCallbacks");
}
mCallbacks = (PageFragmentCallbacks) activity;
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
mPage.getData().putString(Page.SIMPLE_DATA_KEY,
getListAdapter().getItem(position).toString());
mPage.notifyDataChanged();
}
}
|
wawaeasybuy/jobandroid
|
Job/app/src/main/java/com/mardin/job/widgets/wizard/ui/SingleChoiceFragment.java
|
Java
|
mit
| 4,068 |
package sample.rabbitmq;
import static sample.rabbitmq.annotation.RabbitDirectRouting.*;
import java.util.Arrays;
import java.util.concurrent.*;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.ListenerContainerConsumerFailedEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
import sample.model.News;
import sample.rabbitmq.annotation.RabbitDirectRouting;
/**
* RabbitMQ の Exchange#Direct ( 1-1 ) 接続サンプル。
* <p>Sender -> Receiver
* <p>利用する Exchange / Queue は RabbitListener を用いて自動的に作成しています。
* <p>Rabbit の依存を避けてベタに定義したい場合は Queue / Exchange をコンテナに登録し、
* 受信コンポーネントを SimpleMessageListenerContainer で構築してください。
*/
@Slf4j
@Component
public class RabbitDirectChecker {
@Autowired
private NewsSender newsSender;
@Autowired
private NewsReceiver newsReceiver;
public void checkDirect() {
log.info("## RabbitMQ DirectCheck ###");
log.info("### send");
newsSender.send(new News(1L, "subject", "body"));
log.info("### wait...");
newsReceiver.waitMessage();
log.info("### finish");
}
/**
* コンシューマ定義。
* <p>RabbitListener と admin 指定を利用する事で動的に Exchange と Queue の定義 ( Binding 含 ) を行っている。
* 1-n の時は使い捨ての Queue を前提にして名称は未指定で。
* <pre>
* [NewsRoutingKey] -> -1- [NewsQueue] -1-> Queue
* </pre>
* <p>アノテーションを別途切り出す例 ( RabbitDirectRouting )。逆に分かりにくいかも、、
*/
@Component
@RabbitDirectRouting
static class NewsReceiver {
private final CountDownLatch latch = new CountDownLatch(1);
@RabbitHandler
public void receiveMessage(News... news) {
log.info("receive message.");
Arrays.stream(news)
.map(News::toString)
.forEach(log::info);
latch.countDown();
}
public void waitMessage() {
try {
latch.await(5000, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
}
}
/** <pre>Message -> [NewsRoutingKey]</pre> */
@Component
static class NewsSender {
@Autowired
RabbitTemplate tmpl;
public NewsSender send(News... news) {
tmpl.convertAndSend(NewsDirect, NewsRoutingKey, news);
return this;
}
}
@EventListener
void handleContextRefresh(ListenerContainerConsumerFailedEvent event) {
log.error("起動失敗事由: " + event.getReason());
}
}
|
jkazama/sandbox
|
amqp/src/main/java/sample/rabbitmq/RabbitDirectChecker.java
|
Java
|
mit
| 3,030 |
package graphql.analysis;
import graphql.PublicApi;
import graphql.execution.AbortExecutionException;
import graphql.execution.instrumentation.InstrumentationContext;
import graphql.execution.instrumentation.SimpleInstrumentation;
import graphql.execution.instrumentation.parameters.InstrumentationValidationParameters;
import graphql.validation.ValidationError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import static graphql.Assert.assertNotNull;
import static graphql.execution.instrumentation.SimpleInstrumentationContext.whenCompleted;
import static java.util.Optional.ofNullable;
/**
* Prevents execution if the query complexity is greater than the specified maxComplexity.
*
* Use the {@code Function<QueryComplexityInfo, Boolean>} parameter to supply a function to perform a custom action when the max complexity
* is exceeded. If the function returns {@code true} a {@link AbortExecutionException} is thrown.
*/
@PublicApi
public class MaxQueryComplexityInstrumentation extends SimpleInstrumentation {
private static final Logger log = LoggerFactory.getLogger(MaxQueryComplexityInstrumentation.class);
private final int maxComplexity;
private final FieldComplexityCalculator fieldComplexityCalculator;
private final Function<QueryComplexityInfo, Boolean> maxQueryComplexityExceededFunction;
/**
* new Instrumentation with default complexity calculator which is `1 + childComplexity`
*
* @param maxComplexity max allowed complexity, otherwise execution will be aborted
*/
public MaxQueryComplexityInstrumentation(int maxComplexity) {
this(maxComplexity, (queryComplexityInfo) -> true);
}
/**
* new Instrumentation with default complexity calculator which is `1 + childComplexity`
*
* @param maxComplexity max allowed complexity, otherwise execution will be aborted
* @param maxQueryComplexityExceededFunction the function to perform when the max complexity is exceeded
*/
public MaxQueryComplexityInstrumentation(int maxComplexity, Function<QueryComplexityInfo, Boolean> maxQueryComplexityExceededFunction) {
this(maxComplexity, (env, childComplexity) -> 1 + childComplexity, maxQueryComplexityExceededFunction);
}
/**
* new Instrumentation with custom complexity calculator
*
* @param maxComplexity max allowed complexity, otherwise execution will be aborted
* @param fieldComplexityCalculator custom complexity calculator
*/
public MaxQueryComplexityInstrumentation(int maxComplexity, FieldComplexityCalculator fieldComplexityCalculator) {
this(maxComplexity, fieldComplexityCalculator, (queryComplexityInfo) -> true);
}
/**
* new Instrumentation with custom complexity calculator
*
* @param maxComplexity max allowed complexity, otherwise execution will be aborted
* @param fieldComplexityCalculator custom complexity calculator
* @param maxQueryComplexityExceededFunction the function to perform when the max complexity is exceeded
*/
public MaxQueryComplexityInstrumentation(int maxComplexity, FieldComplexityCalculator fieldComplexityCalculator,
Function<QueryComplexityInfo, Boolean> maxQueryComplexityExceededFunction) {
this.maxComplexity = maxComplexity;
this.fieldComplexityCalculator = assertNotNull(fieldComplexityCalculator, () -> "calculator can't be null");
this.maxQueryComplexityExceededFunction = maxQueryComplexityExceededFunction;
}
@Override
public InstrumentationContext<List<ValidationError>> beginValidation(InstrumentationValidationParameters parameters) {
return whenCompleted((errors, throwable) -> {
if ((errors != null && errors.size() > 0) || throwable != null) {
return;
}
QueryTraverser queryTraverser = newQueryTraverser(parameters);
Map<QueryVisitorFieldEnvironment, Integer> valuesByParent = new LinkedHashMap<>();
queryTraverser.visitPostOrder(new QueryVisitorStub() {
@Override
public void visitField(QueryVisitorFieldEnvironment env) {
int childsComplexity = valuesByParent.getOrDefault(env, 0);
int value = calculateComplexity(env, childsComplexity);
valuesByParent.compute(env.getParentEnvironment(), (key, oldValue) ->
ofNullable(oldValue).orElse(0) + value
);
}
});
int totalComplexity = valuesByParent.getOrDefault(null, 0);
if (log.isDebugEnabled()) {
log.debug("Query complexity: {}", totalComplexity);
}
if (totalComplexity > maxComplexity) {
QueryComplexityInfo queryComplexityInfo = QueryComplexityInfo.newQueryComplexityInfo()
.complexity(totalComplexity)
.instrumentationValidationParameters(parameters)
.build();
boolean throwAbortException = maxQueryComplexityExceededFunction.apply(queryComplexityInfo);
if (throwAbortException) {
throw mkAbortException(totalComplexity, maxComplexity);
}
}
});
}
/**
* Called to generate your own error message or custom exception class
*
* @param totalComplexity the complexity of the query
* @param maxComplexity the maximum complexity allowed
*
* @return a instance of AbortExecutionException
*/
protected AbortExecutionException mkAbortException(int totalComplexity, int maxComplexity) {
return new AbortExecutionException("maximum query complexity exceeded " + totalComplexity + " > " + maxComplexity);
}
QueryTraverser newQueryTraverser(InstrumentationValidationParameters parameters) {
return QueryTraverser.newQueryTraverser()
.schema(parameters.getSchema())
.document(parameters.getDocument())
.operationName(parameters.getOperation())
.variables(parameters.getVariables())
.build();
}
private int calculateComplexity(QueryVisitorFieldEnvironment queryVisitorFieldEnvironment, int childsComplexity) {
if (queryVisitorFieldEnvironment.isTypeNameIntrospectionField()) {
return 0;
}
FieldComplexityEnvironment fieldComplexityEnvironment = convertEnv(queryVisitorFieldEnvironment);
return fieldComplexityCalculator.calculate(fieldComplexityEnvironment, childsComplexity);
}
private FieldComplexityEnvironment convertEnv(QueryVisitorFieldEnvironment queryVisitorFieldEnvironment) {
FieldComplexityEnvironment parentEnv = null;
if (queryVisitorFieldEnvironment.getParentEnvironment() != null) {
parentEnv = convertEnv(queryVisitorFieldEnvironment.getParentEnvironment());
}
return new FieldComplexityEnvironment(
queryVisitorFieldEnvironment.getField(),
queryVisitorFieldEnvironment.getFieldDefinition(),
queryVisitorFieldEnvironment.getFieldsContainer(),
queryVisitorFieldEnvironment.getArguments(),
parentEnv
);
}
}
|
graphql-java/graphql-java
|
src/main/java/graphql/analysis/MaxQueryComplexityInstrumentation.java
|
Java
|
mit
| 7,538 |
package com.github.maxopoly.finale.combat;
public class CombatConfig {
private int cpsLimit;
private long cpsCounterInterval;
private boolean noCooldown;
private double maxReach;
private boolean sweepEnabled;
private CombatSoundConfig combatSounds;
private double horizontalKb;
private double verticalKb;
private double sprintHorizontal;
private double sprintVertical;
private double airHorizontal;
private double airVertical;
private double waterHorizontal;
private double waterVertical;
private double attackMotionModifier;
private boolean stopSprinting;
private double potionCutOffDistance;
public CombatConfig(boolean noCooldown, int cpsLimit, long cpsCounterInterval, double maxReach, boolean sweepEnabled, CombatSoundConfig combatSounds,
double horizontalKb, double verticalKb, double sprintHorizontal, double sprintVertical, double airHorizontal, double airVertical,
double waterHorizontal, double waterVertical, double attackMotionModifier, boolean stopSprinting, double potionCutOffDistance) {
this.noCooldown = noCooldown;
this.cpsLimit = cpsLimit;
this.cpsCounterInterval = cpsCounterInterval;
this.maxReach = maxReach;
this.sweepEnabled = sweepEnabled;
this.combatSounds = combatSounds;
this.horizontalKb = horizontalKb;
this.verticalKb = verticalKb;
this.sprintHorizontal = sprintHorizontal;
this.sprintVertical = sprintVertical;
this.airHorizontal = airHorizontal;
this.airVertical = airVertical;
this.waterHorizontal = waterHorizontal;
this.waterVertical = waterVertical;
this.attackMotionModifier = attackMotionModifier;
this.stopSprinting = stopSprinting;
this.potionCutOffDistance = potionCutOffDistance;
}
public void setPotionCutOffDistance(double potionCutOffDistance) {
this.potionCutOffDistance = potionCutOffDistance;
}
public double getPotionCutOffDistance() {
return potionCutOffDistance;
}
public void setHorizontalKb(double horizontalKb) {
this.horizontalKb = horizontalKb;
}
public void setVerticalKb(double verticalKb) {
this.verticalKb = verticalKb;
}
public void setSprintHorizontal(double sprintHorizontal) {
this.sprintHorizontal = sprintHorizontal;
}
public void setSprintVertical(double sprintVertical) {
this.sprintVertical = sprintVertical;
}
public void setAirHorizontal(double airHorizontal) {
this.airHorizontal = airHorizontal;
}
public void setAirVertical(double airVertical) {
this.airVertical = airVertical;
}
public void setWaterHorizontal(double waterHorizontal) {
this.waterHorizontal = waterHorizontal;
}
public void setWaterVertical(double waterVertical) {
this.waterVertical = waterVertical;
}
public void setAttackMotionModifier(double attackMotionModifier) {
this.attackMotionModifier = attackMotionModifier;
}
public void setStopSprinting(boolean stopSprinting) {
this.stopSprinting = stopSprinting;
}
public double getAirHorizontal() {
return airHorizontal;
}
public double getAirVertical() {
return airVertical;
}
public double getWaterHorizontal() {
return waterHorizontal;
}
public double getWaterVertical() {
return waterVertical;
}
public boolean isStopSprinting() {
return stopSprinting;
}
public double getHorizontalKb() {
return horizontalKb;
}
public double getVerticalKb() {
return verticalKb;
}
public double getSprintHorizontal() {
return sprintHorizontal;
}
public double getSprintVertical() {
return sprintVertical;
}
public double getAttackMotionModifier() {
return attackMotionModifier;
}
public int getCPSLimit() {
return cpsLimit;
}
public long getCpsCounterInterval() {
return cpsCounterInterval;
}
public boolean isNoCooldown() {
return noCooldown;
}
public double getMaxReach() {
return maxReach;
}
public boolean isSweepEnabled() {
return sweepEnabled;
}
public CombatSoundConfig getCombatSounds() {
return combatSounds;
}
public double getHorizontalKB() {
return horizontalKb;
}
public double getVerticalKB() {
return verticalKb;
}
}
|
Maxopoly/Finale
|
src/main/java/com/github/maxopoly/finale/combat/CombatConfig.java
|
Java
|
mit
| 4,053 |
package redis.clients.jedis.util;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* The class implements a buffered output stream without synchronization There are also special
* operations like in-place string encoding. This stream fully ignore mark/reset and should not be
* used outside Jedis
*/
public final class RedisOutputStream extends FilterOutputStream {
protected final byte[] buf;
protected int count;
private final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999,
999999999, Integer.MAX_VALUE };
private final static byte[] DigitTens = { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1',
'1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', '2',
'2', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '4', '4',
'4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', '6', '6', '6', '6', '6',
'6', '6', '6', '6', '6', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8',
'8', '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', };
private final static byte[] DigitOnes = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2',
'3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', };
private final static byte[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z' };
public RedisOutputStream(final OutputStream out) {
this(out, 8192);
}
public RedisOutputStream(final OutputStream out, final int size) {
super(out);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
private void flushBuffer() throws IOException {
if (count > 0) {
out.write(buf, 0, count);
count = 0;
}
}
public void write(final byte b) throws IOException {
if (count == buf.length) {
flushBuffer();
}
buf[count++] = b;
}
@Override
public void write(final byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
if (len >= buf.length) {
flushBuffer();
out.write(b, off, len);
} else {
if (len >= buf.length - count) {
flushBuffer();
}
System.arraycopy(b, off, buf, count, len);
count += len;
}
}
public void writeCrLf() throws IOException {
if (2 >= buf.length - count) {
flushBuffer();
}
buf[count++] = '\r';
buf[count++] = '\n';
}
public void writeIntCrLf(int value) throws IOException {
if (value < 0) {
write((byte) '-');
value = -value;
}
int size = 0;
while (value > sizeTable[size])
size++;
size++;
if (size >= buf.length - count) {
flushBuffer();
}
int q, r;
int charPos = count + size;
while (value >= 65536) {
q = value / 100;
r = value - ((q << 6) + (q << 5) + (q << 2));
value = q;
buf[--charPos] = DigitOnes[r];
buf[--charPos] = DigitTens[r];
}
for (;;) {
q = (value * 52429) >>> (16 + 3);
r = value - ((q << 3) + (q << 1));
buf[--charPos] = digits[r];
value = q;
if (value == 0) break;
}
count += size;
writeCrLf();
}
@Override
public void flush() throws IOException {
flushBuffer();
out.flush();
}
}
|
xetorthio/jedis
|
src/main/java/redis/clients/jedis/util/RedisOutputStream.java
|
Java
|
mit
| 4,015 |
package com.imrenagi.service_auth.service.security;
import com.imrenagi.service_auth.AuthApplication;
import com.imrenagi.service_auth.domain.User;
import com.imrenagi.service_auth.repository.UserRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
/**
* Created by imrenagi on 5/14/17.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = AuthApplication.class)
@WebAppConfiguration
public class MysqlUserDetailsServiceTest {
@InjectMocks
private MysqlUserDetailsService userDetailsService;
@Mock
private UserRepository repository;
@Before
public void setup() {
initMocks(this);
}
@Test
public void shouldReturnUserDetailWhenAUserIsFound() throws Exception {
final User user = new User("imrenagi", "1234", "imre", "nagi");
doReturn(user).when(repository).findByUsername(user.getUsername());
UserDetails found = userDetailsService.loadUserByUsername(user.getUsername());
assertEquals(user.getUsername(), found.getUsername());
assertEquals(user.getPassword(), found.getPassword());
verify(repository, times(1)).findByUsername(user.getUsername());
}
@Test
public void shouldFailWhenUserIsNotFound() throws Exception {
doReturn(null).when(repository).findByUsername(anyString());
try {
userDetailsService.loadUserByUsername(anyString());
fail();
} catch (Exception e) {
}
}
}
|
imrenagi/microservice-skeleton
|
service-auth/src/test/java/com/imrenagi/service_auth/service/security/MysqlUserDetailsServiceTest.java
|
Java
|
mit
| 2,072 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package net.daw.bean;
import com.google.gson.annotations.Expose;
/**
*
* @author rafa
*/
public class Element implements IElement {
@Expose
private String tag;
// @Expose
// private String name;
@Expose
private String id;
@Expose
private String clase;
@Override
public String getTag() {
return tag;
}
@Override
public void setTag(String tag) {
this.tag = tag;
}
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public void setName(String name) {
// this.name = name;
// }
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
@Override
public String getTagClass() {
return clase;
}
@Override
public void setTagClass(String clase) {
this.clase = clase;
}
}
|
Josecho93/ExamenCliente
|
src/main/java/net/daw/bean/Element.java
|
Java
|
mit
| 1,120 |
package org.vitrivr.cineast.api.rest.handlers.actions.metadata;
import io.javalin.http.Context;
import io.javalin.plugin.openapi.dsl.OpenApiBuilder;
import io.javalin.plugin.openapi.dsl.OpenApiDocumentation;
import java.util.Map;
import org.vitrivr.cineast.api.messages.result.MediaObjectMetadataQueryResult;
import org.vitrivr.cineast.api.rest.OpenApiCompatHelper;
import org.vitrivr.cineast.api.rest.handlers.interfaces.GetRestHandler;
import org.vitrivr.cineast.api.rest.services.MetadataRetrievalService;
/**
* This class handles GET requests with an object id, domain and key and returns all matching metadata descriptors.
* <p>
* <h3>GET</h3>
* This action's resource should have the following structure: {@code find/metadata/of/:id/in/:domain/with/:key}. It returns then all metadata of the object with this id, belonging to that domain with the specified key.
* </p>
*/
public class FindObjectMetadataFullyQualifiedGetHandler implements
GetRestHandler<MediaObjectMetadataQueryResult> {
public static final String OBJECT_ID_NAME = "id";
public static final String DOMAIN_NAME = "domain";
public static final String KEY_NAME = "key";
public static final String ROUTE = "find/metadata/of/{" + OBJECT_ID_NAME + "}/in/{" + DOMAIN_NAME + "}/with/{" + KEY_NAME + "}";
@Override
public MediaObjectMetadataQueryResult doGet(Context ctx) {
final Map<String, String> parameters = ctx.pathParamMap();
final String objectId = parameters.get(OBJECT_ID_NAME);
final String domain = parameters.get(DOMAIN_NAME);
final String key = parameters.get(KEY_NAME);
final MetadataRetrievalService service = new MetadataRetrievalService();
return new MediaObjectMetadataQueryResult("", service.find(objectId, domain, key)
);
}
public OpenApiDocumentation docs() {
return OpenApiBuilder.document()
.operation(op -> {
op.description("The description");
op.summary("Find metadata for specific object id in given domain with given key");
op.addTagsItem(OpenApiCompatHelper.METADATA_OAS_TAG);
op.operationId("findMetaFullyQualified");
})
.pathParam(OBJECT_ID_NAME, String.class, param -> {
param.description("The object id");
})
.pathParam(DOMAIN_NAME, String.class, param -> {
param.description("The domain name");
})
.pathParam(KEY_NAME, String.class, param -> param.description("Metadata key"))
.json("200", outClass());
}
@Override
public String route() {
return ROUTE;
}
@Override
public Class<MediaObjectMetadataQueryResult> outClass() {
return MediaObjectMetadataQueryResult.class;
}
/* TODO Actually, there is a lot of refactoring potential in this entire package */
}
|
vitrivr/cineast
|
cineast-api/src/main/java/org/vitrivr/cineast/api/rest/handlers/actions/metadata/FindObjectMetadataFullyQualifiedGetHandler.java
|
Java
|
mit
| 2,769 |
package com.indignado.logicbricks.utils.builders.joints;
import com.badlogic.gdx.physics.box2d.World;
/**
* @author Rubentxu
*/
public class JointBuilder {
private final World world;
private DistanceJointBuilder distanceJointBuilder;
private FrictionJointBuilder frictionJointBuilder;
private GearJointBuilder gearJointBuilder;
private PrismaticJointBuilder prismaticJointBuilder;
private PulleyJointBuilder pulleyJointBuilder;
private RevoluteJointBuilder revoluteJointBuilder;
private RopeJointBuilder ropeJointBuilder;
private WeldJointBuilder weldJointBuilder;
private WheelJointBuilder wheelJointBuilder;
public JointBuilder(World world) {
this.world = world;
}
public DistanceJointBuilder distanceJoint() {
if (distanceJointBuilder == null) distanceJointBuilder = new DistanceJointBuilder(world);
else distanceJointBuilder.reset();
return distanceJointBuilder;
}
public FrictionJointBuilder frictionJoint() {
if (frictionJointBuilder == null) frictionJointBuilder = new FrictionJointBuilder(world);
else frictionJointBuilder.reset();
return frictionJointBuilder;
}
public GearJointBuilder gearJoint() {
if (gearJointBuilder == null) gearJointBuilder = new GearJointBuilder(world);
else gearJointBuilder.reset();
return gearJointBuilder;
}
public PrismaticJointBuilder prismaticJoint() {
if (prismaticJointBuilder == null) prismaticJointBuilder = new PrismaticJointBuilder(world);
else prismaticJointBuilder.reset();
return prismaticJointBuilder;
}
public PulleyJointBuilder pulleyJoint() {
if (pulleyJointBuilder == null) pulleyJointBuilder = new PulleyJointBuilder(world);
else pulleyJointBuilder.reset();
return pulleyJointBuilder;
}
public RevoluteJointBuilder revoluteJoint() {
if (revoluteJointBuilder == null) revoluteJointBuilder = new RevoluteJointBuilder(world);
else revoluteJointBuilder.reset();
return revoluteJointBuilder;
}
public RopeJointBuilder ropeJoint() {
if (ropeJointBuilder == null) ropeJointBuilder = new RopeJointBuilder(world);
else ropeJointBuilder.reset();
return ropeJointBuilder;
}
public WeldJointBuilder weldJoint() {
if (weldJointBuilder == null) weldJointBuilder = new WeldJointBuilder(world);
else weldJointBuilder.reset();
return weldJointBuilder;
}
public WheelJointBuilder wheelJoint() {
if (wheelJointBuilder == null) wheelJointBuilder = new WheelJointBuilder(world);
else wheelJointBuilder.reset();
return wheelJointBuilder;
}
}
|
Rubentxu/GDX-Logic-Bricks
|
gdx-logic-bricks/src/main/java/com/indignado/logicbricks/utils/builders/joints/JointBuilder.java
|
Java
|
mit
| 2,754 |
package checkers.logic.main;
import java.util.Scanner;
public class Player {
public static void main(String[] args) {
consolePlayer();
}
private static void consolePlayer(){
CheckersGame g = new CheckersGame();
Scanner in = new Scanner(System.in);
int x;
int y;
while(!g.gameOver()){
//g.testPrint();
System.out.println(g.getBoardStateString());
x = in.nextInt();
y = in.nextInt();
g.act(Util.coord(x, y));
}
}
}
|
kristinclemens/checkers
|
GameLogic/src/checkers/logic/main/Player.java
|
Java
|
mit
| 451 |
package com.github.daneko.simpleitemanimator;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPropertyAnimatorCompat;
import android.view.View;
import fj.F;
import fj.F2;
import fj.F3;
import fj.Unit;
import fj.data.Option;
/**
* @see {@link android.support.v7.widget.DefaultItemAnimator}
*/
public class DefaultAnimations {
public static F<View, Unit> addPrepareStateSetter() {
return (view -> {
ViewCompat.setAlpha(view, 0);
return Unit.unit();
});
}
public static F<View, Unit> removePrepareStateSetter() {
return (view -> Unit.unit());
}
public static F2<View, SimpleItemAnimator.EventParam, Unit> movePrepareStateSetter() {
return ((view, param) -> {
if (param.getFromPoint().isNone() || param.getToPoint().isNone()) {
return Unit.unit();
}
final int deltaX =
param.getToPoint().some().x -
param.getFromPoint().some().x +
(int) ViewCompat.getTranslationX(view);
final int deltaY =
param.getToPoint().some().y -
param.getFromPoint().some().y +
(int) ViewCompat.getTranslationY(view);
ViewCompat.setTranslationX(view, -deltaX);
ViewCompat.setTranslationY(view, -deltaY);
return Unit.unit();
});
}
public static F3<View, Option<View>, SimpleItemAnimator.EventParam, Unit> changePrepareStateSetter() {
return ((oldView, newViewOption, param) -> {
if (param.getFromPoint().isNone() || param.getToPoint().isNone() || newViewOption.isNone()) {
return Unit.unit();
}
final View newView = newViewOption.some();
final int deltaX =
param.getToPoint().some().x -
param.getFromPoint().some().x +
(int) ViewCompat.getTranslationX(oldView);
final int deltaY =
param.getToPoint().some().y -
param.getFromPoint().some().y +
(int) ViewCompat.getTranslationY(oldView);
ViewCompat.setTranslationX(newView, -deltaX);
ViewCompat.setTranslationY(newView, -deltaY);
ViewCompat.setAlpha(newView, 0);
return Unit.unit();
});
}
public static F<ViewPropertyAnimatorCompat, ViewPropertyAnimatorCompat> addEventAnimation() {
return (animator -> animator.alpha(1f));
}
public static F<ViewPropertyAnimatorCompat, ViewPropertyAnimatorCompat> removeEventAnimation() {
return (animator -> animator.alpha(0f));
}
public static F2<ViewPropertyAnimatorCompat, SimpleItemAnimator.EventParam, ViewPropertyAnimatorCompat> moveEventAnimation() {
return ((animator, param) -> animator.translationY(0f).translationX(0f));
}
public static F2<ViewPropertyAnimatorCompat, SimpleItemAnimator.EventParam, ViewPropertyAnimatorCompat> changeEventAnimationForOldView() {
return ((animator, param) -> {
if (param.getFromPoint().isNone() || param.getToPoint().isNone()) {
return animator;
}
final int deltaX = param.getToPoint().some().x - param.getFromPoint().some().x;
final int deltaY = param.getToPoint().some().y - param.getFromPoint().some().y;
return animator.translationX(deltaX).translationY(deltaY).alpha(0f);
});
}
public static F2<ViewPropertyAnimatorCompat, SimpleItemAnimator.EventParam, ViewPropertyAnimatorCompat> changeEventAnimationForNewView() {
return ((animator, param) -> animator.translationX(0f).translationY(0f).alpha(0f));
}
}
|
daneko/SimpleItemAnimator
|
library/src/main/java/com/github/daneko/simpleitemanimator/DefaultAnimations.java
|
Java
|
mit
| 3,855 |
// **********************************************************************
//
// <copyright>
//
// BBN Technologies
// 10 Moulton Street
// Cambridge, MA 02138
// (617) 873-8000
//
// Copyright (C) BBNT Solutions LLC. All rights reserved.
//
// </copyright>
// **********************************************************************
//
// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/image/ImageServerUtils.java,v $
// $RCSfile: ImageServerUtils.java,v $
// $Revision: 1.10 $
// $Date: 2006/02/16 16:22:49 $
// $Author: dietrick $
//
// **********************************************************************
package com.bbn.openmap.image;
import java.awt.Color;
import java.awt.Paint;
import java.awt.geom.Point2D;
import java.util.Properties;
import com.bbn.openmap.omGraphics.OMColor;
import com.bbn.openmap.proj.Proj;
import com.bbn.openmap.proj.Projection;
import com.bbn.openmap.proj.ProjectionFactory;
import com.bbn.openmap.util.Debug;
import com.bbn.openmap.util.PropUtils;
/**
* A class to contain convenience functions for parsing web image requests.
*/
public class ImageServerUtils implements ImageServerConstants {
/**
* Create an OpenMap projection from the values stored in a Properties
* object. The properties inside should be parsed out from a map request,
* with the keywords being those defined in the ImageServerConstants
* interface. Assumes that the shared instance of the ProjectionFactory has
* been initialized with the expected Projections.
*/
public static Proj createOMProjection(Properties props,
Projection defaultProj) {
float scale = PropUtils.floatFromProperties(props,
SCALE,
defaultProj.getScale());
int height = PropUtils.intFromProperties(props,
HEIGHT,
defaultProj.getHeight());
int width = PropUtils.intFromProperties(props,
WIDTH,
defaultProj.getWidth());
Point2D llp = defaultProj.getCenter();
float longitude = PropUtils.floatFromProperties(props,
LON,
(float) llp.getX());
float latitude = PropUtils.floatFromProperties(props,
LAT,
(float) llp.getY());
Class<? extends Projection> projClass = null;
String projType = props.getProperty(PROJTYPE);
ProjectionFactory projFactory = ProjectionFactory.loadDefaultProjections();
if (projType != null) {
projClass = projFactory.getProjClassForName(projType);
}
if (projClass == null) {
projClass = defaultProj.getClass();
}
if (Debug.debugging("imageserver")) {
Debug.output("ImageServerUtils.createOMProjection: projection "
+ projClass.getName() + ", with HEIGHT = " + height
+ ", WIDTH = " + width + ", lat = " + latitude + ", lon = "
+ longitude + ", scale = " + scale);
}
Proj proj = (Proj) projFactory.makeProjection(projClass,
new Point2D.Float(longitude, latitude),
scale,
width,
height);
return (Proj) proj;
}
/**
* Create a Color object from the properties TRANSPARENT and BGCOLOR
* properties. Default color returned is white.
*
* @param props the Properties containing background color information.
* @return Color object for background.
*/
public static Color getBackground(Properties props) {
return (Color) getBackground(props, Color.white);
}
/**
* Create a Color object from the properties TRANSPARENT and BGCOLOR
* properties. Default color returned is white.
*
* @param props the Properties containing background color information.
* @param defPaint the default Paint to use in case the color isn't defined
* in the properties.
* @return Color object for background.
*/
public static Paint getBackground(Properties props, Paint defPaint) {
boolean transparent = PropUtils.booleanFromProperties(props,
TRANSPARENT,
false);
Paint backgroundColor = PropUtils.parseColorFromProperties(props,
BGCOLOR,
defPaint);
if (backgroundColor == null) {
backgroundColor = Color.white;
}
if (transparent) {
if (backgroundColor instanceof Color) {
Color bgc = (Color) backgroundColor;
backgroundColor = new Color(bgc.getRed(), bgc.getGreen(), bgc.getBlue(), 0x00);
} else {
backgroundColor = OMColor.clear;
}
}
if (Debug.debugging("imageserver")) {
Debug.output("ImageServerUtils.createOMProjection: projection color: "
+ (backgroundColor instanceof Color ? Integer.toHexString(((Color) backgroundColor).getRGB())
: backgroundColor.toString())
+ ", transparent("
+ transparent + ")");
}
return backgroundColor;
}
}
|
d2fn/passage
|
src/main/java/com/bbn/openmap/image/ImageServerUtils.java
|
Java
|
mit
| 5,229 |
/*
* Copyright (C) 2013-2018 The Project Lombok Authors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package lombok.javac;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCArrayAccess;
import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree;
import com.sun.tools.javac.tree.JCTree.JCAssert;
import com.sun.tools.javac.tree.JCTree.JCAssign;
import com.sun.tools.javac.tree.JCTree.JCAssignOp;
import com.sun.tools.javac.tree.JCTree.JCBinary;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCBreak;
import com.sun.tools.javac.tree.JCTree.JCCase;
import com.sun.tools.javac.tree.JCTree.JCCatch;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCConditional;
import com.sun.tools.javac.tree.JCTree.JCContinue;
import com.sun.tools.javac.tree.JCTree.JCDoWhileLoop;
import com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop;
import com.sun.tools.javac.tree.JCTree.JCErroneous;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCForLoop;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.JCTree.JCIf;
import com.sun.tools.javac.tree.JCTree.JCImport;
import com.sun.tools.javac.tree.JCTree.JCInstanceOf;
import com.sun.tools.javac.tree.JCTree.JCLabeledStatement;
import com.sun.tools.javac.tree.JCTree.JCLiteral;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import com.sun.tools.javac.tree.JCTree.JCModifiers;
import com.sun.tools.javac.tree.JCTree.JCNewArray;
import com.sun.tools.javac.tree.JCTree.JCNewClass;
import com.sun.tools.javac.tree.JCTree.JCParens;
import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree;
import com.sun.tools.javac.tree.JCTree.JCReturn;
import com.sun.tools.javac.tree.JCTree.JCSkip;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCSwitch;
import com.sun.tools.javac.tree.JCTree.JCSynchronized;
import com.sun.tools.javac.tree.JCTree.JCThrow;
import com.sun.tools.javac.tree.JCTree.JCTry;
import com.sun.tools.javac.tree.JCTree.JCTypeApply;
import com.sun.tools.javac.tree.JCTree.JCTypeCast;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.tree.JCTree.JCUnary;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.tree.JCTree.JCWhileLoop;
import com.sun.tools.javac.tree.JCTree.JCWildcard;
import com.sun.tools.javac.tree.JCTree.LetExpr;
import com.sun.tools.javac.tree.JCTree.TypeBoundKind;
import com.sun.tools.javac.tree.TreeInfo;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Name;
import lombok.permit.Permit;
public class JavacTreeMaker {
private final TreeMaker tm;
public JavacTreeMaker(TreeMaker tm) {
this.tm = tm;
}
public TreeMaker getUnderlyingTreeMaker() {
return tm;
}
public JavacTreeMaker at(int pos) {
tm.at(pos);
return this;
}
private static class MethodId<J> {
private final Class<?> owner;
private final String name;
private final Class<J> returnType;
private final Class<?>[] paramTypes;
MethodId(Class<?> owner, String name, Class<J> returnType, Class<?>... types) {
this.owner = owner;
this.name = name;
this.paramTypes = types;
this.returnType = returnType;
}
@Override public String toString() {
StringBuilder out = new StringBuilder();
out.append(returnType.getName()).append(" ").append(owner.getName()).append(".").append(name).append("(");
boolean f = true;
for (Class<?> p : paramTypes) {
if (f) f = false;
else out.append(", ");
out.append(p.getName());
}
return out.append(")").toString();
}
}
private static class SchroedingerType {
final Object value;
private SchroedingerType(Object value) {
this.value = value;
}
@Override public int hashCode() {
return value == null ? -1 : value.hashCode();
}
@Override public boolean equals(Object obj) {
if (obj instanceof SchroedingerType) {
Object other = ((SchroedingerType) obj).value;
return value == null ? other == null : value.equals(other);
}
return false;
}
static Object getFieldCached(ConcurrentMap<String, Object> cache, String className, String fieldName) {
Object value = cache.get(fieldName);
if (value != null) return value;
try {
value = Permit.getField(Class.forName(className), fieldName).get(null);
} catch (NoSuchFieldException e) {
throw Javac.sneakyThrow(e);
} catch (IllegalAccessException e) {
throw Javac.sneakyThrow(e);
} catch (ClassNotFoundException e) {
throw Javac.sneakyThrow(e);
}
cache.putIfAbsent(fieldName, value);
return value;
}
private static Field NOSUCHFIELDEX_MARKER;
static {
try {
NOSUCHFIELDEX_MARKER = Permit.getField(SchroedingerType.class, "NOSUCHFIELDEX_MARKER");
} catch (NoSuchFieldException e) {
throw Javac.sneakyThrow(e);
}
}
static Object getFieldCached(ConcurrentMap<Class<?>, Field> cache, Object ref, String fieldName) throws NoSuchFieldException {
Class<?> c = ref.getClass();
Field field = cache.get(c);
if (field == null) {
try {
field = Permit.getField(c, fieldName);
} catch (NoSuchFieldException e) {
cache.putIfAbsent(c, NOSUCHFIELDEX_MARKER);
throw Javac.sneakyThrow(e);
}
Permit.setAccessible(field);
Field old = cache.putIfAbsent(c, field);
if (old != null) field = old;
}
if (field == NOSUCHFIELDEX_MARKER) throw new NoSuchFieldException(fieldName);
try {
return field.get(ref);
} catch (IllegalAccessException e) {
throw Javac.sneakyThrow(e);
}
}
}
public static class TypeTag extends SchroedingerType {
private static final ConcurrentMap<String, Object> TYPE_TAG_CACHE = new ConcurrentHashMap<String, Object>();
private static final ConcurrentMap<Class<?>, Field> FIELD_CACHE = new ConcurrentHashMap<Class<?>, Field>();
private static final Method TYPE_TYPETAG_METHOD;
static {
Method m = null;
try {
m = Permit.getMethod(Type.class, "getTag");
} catch (NoSuchMethodException e) {}
TYPE_TYPETAG_METHOD = m;
}
private TypeTag(Object value) {
super(value);
}
public static TypeTag typeTag(JCTree o) {
try {
return new TypeTag(getFieldCached(FIELD_CACHE, o, "typetag"));
} catch (NoSuchFieldException e) {
throw Javac.sneakyThrow(e);
}
}
public static TypeTag typeTag(Type t) {
if (t == null) return Javac.CTC_VOID;
try {
return new TypeTag(getFieldCached(FIELD_CACHE, t, "tag"));
} catch (NoSuchFieldException e) {
if (TYPE_TYPETAG_METHOD == null) throw new IllegalStateException("Type " + t.getClass() + " has neither 'tag' nor getTag()");
try {
return new TypeTag(TYPE_TYPETAG_METHOD.invoke(t));
} catch (IllegalAccessException ex) {
throw Javac.sneakyThrow(ex);
} catch (InvocationTargetException ex) {
throw Javac.sneakyThrow(ex.getCause());
}
}
}
public static TypeTag typeTag(String identifier) {
return new TypeTag(getFieldCached(TYPE_TAG_CACHE, Javac.getJavaCompilerVersion() < 8 ? "com.sun.tools.javac.code.TypeTags" : "com.sun.tools.javac.code.TypeTag", identifier));
}
}
public static class TreeTag extends SchroedingerType {
private static final ConcurrentMap<String, Object> TREE_TAG_CACHE = new ConcurrentHashMap<String, Object>();
private static final Field TAG_FIELD;
private static final Method TAG_METHOD;
private static final MethodId<Integer> OP_PREC = MethodId(TreeInfo.class, "opPrec", int.class, TreeTag.class);
static {
Method m = null;
try {
m = Permit.getMethod(JCTree.class, "getTag");
} catch (NoSuchMethodException e) {}
if (m != null) {
TAG_FIELD = null;
TAG_METHOD = m;
} else {
Field f = null;
try {
f = Permit.getField(JCTree.class, "tag");
} catch (NoSuchFieldException e) {}
TAG_FIELD = f;
TAG_METHOD = null;
}
}
private TreeTag(Object value) {
super(value);
}
public static TreeTag treeTag(JCTree o) {
try {
if (TAG_METHOD != null) return new TreeTag(TAG_METHOD.invoke(o));
else return new TreeTag(TAG_FIELD.get(o));
} catch (InvocationTargetException e) {
throw Javac.sneakyThrow(e.getCause());
} catch (IllegalAccessException e) {
throw Javac.sneakyThrow(e);
}
}
public static TreeTag treeTag(String identifier) {
return new TreeTag(getFieldCached(TREE_TAG_CACHE, Javac.getJavaCompilerVersion() < 8 ? "com.sun.tools.javac.tree.JCTree" : "com.sun.tools.javac.tree.JCTree$Tag", identifier));
}
public int getOperatorPrecedenceLevel() {
return invokeAny(null, OP_PREC, value);
}
public boolean isPrefixUnaryOp() {
return Javac.CTC_NEG.equals(this) || Javac.CTC_POS.equals(this) || Javac.CTC_NOT.equals(this) || Javac.CTC_COMPL.equals(this) || Javac.CTC_PREDEC.equals(this) || Javac.CTC_PREINC.equals(this);
}
}
static <J> MethodId<J> MethodId(Class<?> owner, String name, Class<J> returnType, Class<?>... types) {
return new MethodId<J>(owner, name, returnType, types);
}
/**
* Creates a new method ID based on the name of the method to invoke, the return type of that method, and the types of the parameters.
*
* A method matches if the return type matches, and for each parameter the following holds:
*
* Either (A) the type listed here is the same as, or a subtype of, the type of the method in javac's TreeMaker, or
* (B) the type listed here is a subtype of SchroedingerType.
*/
static <J> MethodId<J> MethodId(String name, Class<J> returnType, Class<?>... types) {
return new MethodId<J>(TreeMaker.class, name, returnType, types);
}
/**
* Creates a new method ID based on the name of a method in this class, assuming the name of the method to invoke in TreeMaker has the same name,
* the same return type, and the same parameters (under the same rules as the other MethodId method).
*/
static <J> MethodId<J> MethodId(String name) {
for (Method m : JavacTreeMaker.class.getDeclaredMethods()) {
if (m.getName().equals(name)) {
@SuppressWarnings("unchecked") Class<J> r = (Class<J>) m.getReturnType();
Class<?>[] p = m.getParameterTypes();
return new MethodId<J>(TreeMaker.class, name, r, p);
}
}
throw new InternalError("Not found: " + name);
}
private static final Object METHOD_NOT_FOUND = new Object[0];
private static final Object METHOD_MULTIPLE_FOUND = new Object[0];
private static final ConcurrentHashMap<MethodId<?>, Object> METHOD_CACHE = new ConcurrentHashMap<MethodId<?>, Object>();
private <J> J invoke(MethodId<J> m, Object... args) {
return invokeAny(tm, m, args);
}
@SuppressWarnings("unchecked") private static <J> J invokeAny(Object owner, MethodId<J> m, Object... args) {
Method method = getFromCache(m);
try {
if (m.returnType.isPrimitive()) {
Object res = method.invoke(owner, args);
String sn = res.getClass().getSimpleName().toLowerCase();
if (!sn.startsWith(m.returnType.getSimpleName())) throw new ClassCastException(res.getClass() + " to " + m.returnType);
return (J) res;
}
return m.returnType.cast(method.invoke(owner, args));
} catch (InvocationTargetException e) {
throw Javac.sneakyThrow(e.getCause());
} catch (IllegalAccessException e) {
throw Javac.sneakyThrow(e);
} catch (IllegalArgumentException e) {
System.err.println(method);
throw Javac.sneakyThrow(e);
}
}
private static boolean tryResolve(MethodId<?> m) {
Object s = METHOD_CACHE.get(m);
if (s == null) s = addToCache(m);
if (s instanceof Method) return true;
return false;
}
private static Method getFromCache(MethodId<?> m) {
Object s = METHOD_CACHE.get(m);
if (s == null) s = addToCache(m);
if (s == METHOD_MULTIPLE_FOUND) throw new IllegalStateException("Lombok TreeMaker frontend issue: multiple matches when looking for method: " + m);
if (s == METHOD_NOT_FOUND) throw new IllegalStateException("Lombok TreeMaker frontend issue: no match when looking for method: " + m);
return (Method) s;
}
private static Object addToCache(MethodId<?> m) {
Method found = null;
outer:
for (Method method : m.owner.getDeclaredMethods()) {
if (!m.name.equals(method.getName())) continue;
Class<?>[] t = method.getParameterTypes();
if (t.length != m.paramTypes.length) continue;
for (int i = 0; i < t.length; i++) {
if (Symbol.class.isAssignableFrom(t[i])) continue outer;
if (!SchroedingerType.class.isAssignableFrom(m.paramTypes[i])) {
if (t[i].isPrimitive()) {
if (t[i] != m.paramTypes[i]) continue outer;
} else {
if (!t[i].isAssignableFrom(m.paramTypes[i])) continue outer;
}
}
}
if (found == null) found = method;
else {
METHOD_CACHE.putIfAbsent(m, METHOD_MULTIPLE_FOUND);
return METHOD_MULTIPLE_FOUND;
}
}
if (found == null) {
METHOD_CACHE.putIfAbsent(m, METHOD_NOT_FOUND);
return METHOD_NOT_FOUND;
}
Permit.setAccessible(found);
Object marker = METHOD_CACHE.putIfAbsent(m, found);
if (marker == null) return found;
return marker;
}
//javac versions: 6-8
private static final MethodId<JCCompilationUnit> TopLevel = MethodId("TopLevel");
public JCCompilationUnit TopLevel(List<JCAnnotation> packageAnnotations, JCExpression pid, List<JCTree> defs) {
return invoke(TopLevel, packageAnnotations, pid, defs);
}
//javac versions: 6-8
private static final MethodId<JCImport> Import = MethodId("Import");
public JCImport Import(JCTree qualid, boolean staticImport) {
return invoke(Import, qualid, staticImport);
}
//javac versions: 6-8
private static final MethodId<JCClassDecl> ClassDef = MethodId("ClassDef");
public JCClassDecl ClassDef(JCModifiers mods, Name name, List<JCTypeParameter> typarams, JCExpression extending, List<JCExpression> implementing, List<JCTree> defs) {
return invoke(ClassDef, mods, name, typarams, extending, implementing, defs);
}
//javac versions: 6-8
private static final MethodId<JCMethodDecl> MethodDef = MethodId("MethodDef", JCMethodDecl.class, JCModifiers.class, Name.class, JCExpression.class, List.class, List.class, List.class, JCBlock.class, JCExpression.class);
public JCMethodDecl MethodDef(JCModifiers mods, Name name, JCExpression resType, List<JCTypeParameter> typarams, List<JCVariableDecl> params, List<JCExpression> thrown, JCBlock body, JCExpression defaultValue) {
return invoke(MethodDef, mods, name, resType, typarams, params, thrown, body, defaultValue);
}
//javac versions: 8
private static final MethodId<JCMethodDecl> MethodDefWithRecvParam = MethodId("MethodDef", JCMethodDecl.class, JCModifiers.class, Name.class, JCExpression.class, List.class, JCVariableDecl.class, List.class, List.class, JCBlock.class, JCExpression.class);
public JCMethodDecl MethodDef(JCModifiers mods, Name name, JCExpression resType, List<JCTypeParameter> typarams, JCVariableDecl recvparam, List<JCVariableDecl> params, List<JCExpression> thrown, JCBlock body, JCExpression defaultValue) {
return invoke(MethodDefWithRecvParam, mods, name, resType, recvparam, typarams, params, thrown, body, defaultValue);
}
//javac versions: 6-8
private static final MethodId<JCVariableDecl> VarDef = MethodId("VarDef");
public JCVariableDecl VarDef(JCModifiers mods, Name name, JCExpression vartype, JCExpression init) {
JCVariableDecl varDef = invoke(VarDef, mods, name, vartype, init);
// We use 'position of the type is -1' as indicator in delombok that the original node was written using JDK10's 'var' feature, because javac desugars 'var' to the real type and doesn't leave any markers other than the
// node position to indicate that it did so. Unfortunately, that means vardecls we generate look like 'var' to delombok. Adjust the position to avoid this.
if (varDef.vartype != null && varDef.vartype.pos == -1) varDef.vartype.pos = 0;
return varDef;
}
//javac versions: 8
private static final MethodId<JCVariableDecl> ReceiverVarDef = MethodId("ReceiverVarDef");
public JCVariableDecl ReceiverVarDef(JCModifiers mods, JCExpression name, JCExpression vartype) {
return invoke(ReceiverVarDef, mods, name, vartype);
}
//javac versions: 6-8
private static final MethodId<JCSkip> Skip = MethodId("Skip");
public JCSkip Skip() {
return invoke(Skip);
}
//javac versions: 6-8
private static final MethodId<JCBlock> Block = MethodId("Block");
public JCBlock Block(long flags, List<JCStatement> stats) {
return invoke(Block, flags, stats);
}
//javac versions: 6-8
private static final MethodId<JCDoWhileLoop> DoLoop = MethodId("DoLoop");
public JCDoWhileLoop DoLoop(JCStatement body, JCExpression cond) {
return invoke(DoLoop, body, cond);
}
//javac versions: 6-8
private static final MethodId<JCWhileLoop> WhileLoop = MethodId("WhileLoop");
public JCWhileLoop WhileLoop(JCExpression cond, JCStatement body) {
return invoke(WhileLoop, cond, body);
}
//javac versions: 6-8
private static final MethodId<JCForLoop> ForLoop = MethodId("ForLoop");
public JCForLoop ForLoop(List<JCStatement> init, JCExpression cond, List<JCExpressionStatement> step, JCStatement body) {
return invoke(ForLoop, init, cond, step, body);
}
//javac versions: 6-8
private static final MethodId<JCEnhancedForLoop> ForeachLoop = MethodId("ForeachLoop");
public JCEnhancedForLoop ForeachLoop(JCVariableDecl var, JCExpression expr, JCStatement body) {
return invoke(ForeachLoop, var, expr, body);
}
//javac versions: 6-8
private static final MethodId<JCLabeledStatement> Labelled = MethodId("Labelled");
public JCLabeledStatement Labelled(Name label, JCStatement body) {
return invoke(Labelled, label, body);
}
//javac versions: 6-8
private static final MethodId<JCSwitch> Switch = MethodId("Switch");
public JCSwitch Switch(JCExpression selector, List<JCCase> cases) {
return invoke(Switch, selector, cases);
}
//javac versions: 6-11
private static final MethodId<JCCase> Case11 = MethodId("Case", JCCase.class, JCExpression.class, com.sun.tools.javac.util.List.class);
//javac version: 12+
public static class Case12 {
private static final Class<?> CASE_KIND_CLASS = classForName(TreeMaker.class, "com.sun.source.tree.CaseTree$CaseKind");
static final MethodId<JCCase> Case12 = MethodId("Case", JCCase.class, CASE_KIND_CLASS, com.sun.tools.javac.util.List.class, com.sun.tools.javac.util.List.class, JCTree.class);
static final Object CASE_KIND_STATEMENT = CASE_KIND_CLASS.getEnumConstants()[0];
}
static Class<?> classForName(Class<?> context, String name) {
try {
return context.getClassLoader().loadClass(name);
} catch (ClassNotFoundException e) {
Error x = new NoClassDefFoundError(e.getMessage());
x.setStackTrace(e.getStackTrace());
throw x;
}
}
public JCCase Case(JCExpression pat, List<JCStatement> stats) {
if (tryResolve(Case11)) return invoke(Case11, pat, stats);
return invoke(Case12.Case12, Case12.CASE_KIND_STATEMENT, pat == null ? com.sun.tools.javac.util.List.nil() : com.sun.tools.javac.util.List.of(pat), stats, null);
}
//javac versions: 6-8
private static final MethodId<JCSynchronized> Synchronized = MethodId("Synchronized");
public JCSynchronized Synchronized(JCExpression lock, JCBlock body) {
return invoke(Synchronized, lock, body);
}
//javac versions: 6-8
private static final MethodId<JCTry> Try = MethodId("Try", JCTry.class, JCBlock.class, List.class, JCBlock.class);
public JCTry Try(JCBlock body, List<JCCatch> catchers, JCBlock finalizer) {
return invoke(Try, body, catchers, finalizer);
}
//javac versions: 7-8
private static final MethodId<JCTry> TryWithResources = MethodId("Try", JCTry.class, List.class, JCBlock.class, List.class, JCBlock.class);
public JCTry Try(List<JCTree> resources, JCBlock body, List<JCCatch> catchers, JCBlock finalizer) {
return invoke(TryWithResources, resources, body, catchers, finalizer);
}
//javac versions: 6-8
private static final MethodId<JCCatch> Catch = MethodId("Catch");
public JCCatch Catch(JCVariableDecl param, JCBlock body) {
return invoke(Catch, param, body);
}
//javac versions: 6-8
private static final MethodId<JCConditional> Conditional = MethodId("Conditional");
public JCConditional Conditional(JCExpression cond, JCExpression thenpart, JCExpression elsepart) {
return invoke(Conditional, cond, thenpart, elsepart);
}
//javac versions: 6-8
private static final MethodId<JCIf> If = MethodId("If");
public JCIf If(JCExpression cond, JCStatement thenpart, JCStatement elsepart) {
return invoke(If, cond, thenpart, elsepart);
}
//javac versions: 6-8
private static final MethodId<JCExpressionStatement> Exec = MethodId("Exec");
public JCExpressionStatement Exec(JCExpression expr) {
return invoke(Exec, expr);
}
//javac version: 6-11
private static final MethodId<JCBreak> Break11 = MethodId("Break", JCBreak.class, Name.class);
//javac version: 12+
private static final MethodId<JCBreak> Break12 = MethodId("Break", JCBreak.class, JCExpression.class);
public JCBreak Break(Name label) {
if (tryResolve(Break11)) return invoke(Break11, label);
return invoke(Break12, label != null ? Ident(label) : null);
}
//javac versions: 6-8
private static final MethodId<JCContinue> Continue = MethodId("Continue");
public JCContinue Continue(Name label) {
return invoke(Continue, label);
}
//javac versions: 6-8
private static final MethodId<JCReturn> Return = MethodId("Return");
public JCReturn Return(JCExpression expr) {
return invoke(Return, expr);
}
//javac versions: 6-8
private static final MethodId<JCThrow> Throw = MethodId("Throw");
public JCThrow Throw(JCExpression expr) {
return invoke(Throw, expr);
}
//javac versions: 6-8
private static final MethodId<JCAssert> Assert = MethodId("Assert");
public JCAssert Assert(JCExpression cond, JCExpression detail) {
return invoke(Assert, cond, detail);
}
//javac versions: 6-8
private static final MethodId<JCMethodInvocation> Apply = MethodId("Apply");
public JCMethodInvocation Apply(List<JCExpression> typeargs, JCExpression fn, List<JCExpression> args) {
return invoke(Apply, typeargs, fn, args);
}
//javac versions: 6-8
private static final MethodId<JCNewClass> NewClass = MethodId("NewClass");
public JCNewClass NewClass(JCExpression encl, List<JCExpression> typeargs, JCExpression clazz, List<JCExpression> args, JCClassDecl def) {
return invoke(NewClass, encl, typeargs, clazz, args, def);
}
//javac versions: 6-8
private static final MethodId<JCNewArray> NewArray = MethodId("NewArray");
public JCNewArray NewArray(JCExpression elemtype, List<JCExpression> dims, List<JCExpression> elems) {
return invoke(NewArray, elemtype, dims, elems);
}
//javac versions: 8
// private static final MethodId<JCLambda> Lambda = MethodId("Lambda");
// public JCLambda Lambda(List<JCVariableDecl> params, JCTree body) {
// return invoke(Lambda, params, body);
// }
//javac versions: 6-8
private static final MethodId<JCParens> Parens = MethodId("Parens");
public JCParens Parens(JCExpression expr) {
return invoke(Parens, expr);
}
//javac versions: 6-8
private static final MethodId<JCAssign> Assign = MethodId("Assign");
public JCAssign Assign(JCExpression lhs, JCExpression rhs) {
return invoke(Assign, lhs, rhs);
}
//javac versions: 6-8
//opcode = [6-7] int [8] JCTree.Tag
private static final MethodId<JCAssignOp> Assignop = MethodId("Assignop");
public JCAssignOp Assignop(TreeTag opcode, JCTree lhs, JCTree rhs) {
return invoke(Assignop, opcode.value, lhs, rhs);
}
//javac versions: 6-8
//opcode = [6-7] int [8] JCTree.Tag
private static final MethodId<JCUnary> Unary = MethodId("Unary");
public JCUnary Unary(TreeTag opcode, JCExpression arg) {
return invoke(Unary, opcode.value, arg);
}
//javac versions: 6-8
//opcode = [6-7] int [8] JCTree.Tag
private static final MethodId<JCBinary> Binary = MethodId("Binary");
public JCBinary Binary(TreeTag opcode, JCExpression lhs, JCExpression rhs) {
return invoke(Binary, opcode.value, lhs, rhs);
}
//javac versions: 6-8
private static final MethodId<JCTypeCast> TypeCast = MethodId("TypeCast");
public JCTypeCast TypeCast(JCTree expr, JCExpression type) {
return invoke(TypeCast, expr, type);
}
//javac versions: 6-8
private static final MethodId<JCInstanceOf> TypeTest = MethodId("TypeTest");
public JCInstanceOf TypeTest(JCExpression expr, JCTree clazz) {
return invoke(TypeTest, expr, clazz);
}
//javac versions: 6-8
private static final MethodId<JCArrayAccess> Indexed = MethodId("Indexed");
public JCArrayAccess Indexed(JCExpression indexed, JCExpression index) {
return invoke(Indexed, indexed, index);
}
//javac versions: 6-8
private static final MethodId<JCFieldAccess> Select = MethodId("Select");
public JCFieldAccess Select(JCExpression selected, Name selector) {
return invoke(Select, selected, selector);
}
//javac versions: 8
// private static final MethodId<JCMemberReference> Reference = MethodId("Reference");
// public JCMemberReference Reference(JCMemberReference.ReferenceMode mode, Name name, JCExpression expr, List<JCExpression> typeargs) {
// return invoke(Reference, mode, name, expr, typeargs);
// }
//javac versions: 6-8
private static final MethodId<JCIdent> Ident = MethodId("Ident", JCIdent.class, Name.class);
public JCIdent Ident(Name idname) {
return invoke(Ident, idname);
}
//javac versions: 6-8
//tag = [6-7] int [8] TypeTag
private static final MethodId<JCLiteral> Literal = MethodId("Literal", JCLiteral.class, TypeTag.class, Object.class);
public JCLiteral Literal(TypeTag tag, Object value) {
return invoke(Literal, tag.value, value);
}
//javac versions: 6-8
//typetag = [6-7] int [8] TypeTag
private static final MethodId<JCPrimitiveTypeTree> TypeIdent = MethodId("TypeIdent");
public JCPrimitiveTypeTree TypeIdent(TypeTag typetag) {
return invoke(TypeIdent, typetag.value);
}
//javac versions: 6-8
private static final MethodId<JCArrayTypeTree> TypeArray = MethodId("TypeArray");
public JCArrayTypeTree TypeArray(JCExpression elemtype) {
return invoke(TypeArray, elemtype);
}
//javac versions: 6-8
private static final MethodId<JCTypeApply> TypeApply = MethodId("TypeApply");
public JCTypeApply TypeApply(JCExpression clazz, List<JCExpression> arguments) {
return invoke(TypeApply, clazz, arguments);
}
//javac versions: 7-8
// private static final MethodId<JCTypeUnion> TypeUnion = MethodId("TypeUnion");
// public JCTypeUnion TypeUnion(List<JCExpression> components) {
// return invoke(TypeUnion, compoonents);
// }
//javac versions: 8
// private static final MethodId<JCTypeIntersection> TypeIntersection = MethodId("TypeIntersection");
// public JCTypeIntersection TypeIntersection(List<JCExpression> components) {
// return invoke(TypeIntersection, components);
// }
//javac versions: 6-8
private static final MethodId<JCTypeParameter> TypeParameter = MethodId("TypeParameter", JCTypeParameter.class, Name.class, List.class);
public JCTypeParameter TypeParameter(Name name, List<JCExpression> bounds) {
return invoke(TypeParameter, name, bounds);
}
//javac versions: 8
private static final MethodId<JCTypeParameter> TypeParameterWithAnnos = MethodId("TypeParameter", JCTypeParameter.class, Name.class, List.class, List.class);
public JCTypeParameter TypeParameter(Name name, List<JCExpression> bounds, List<JCAnnotation> annos) {
return invoke(TypeParameterWithAnnos, name, bounds, annos);
}
//javac versions: 6-8
private static final MethodId<JCWildcard> Wildcard = MethodId("Wildcard");
public JCWildcard Wildcard(TypeBoundKind kind, JCTree type) {
return invoke(Wildcard, kind, type);
}
//javac versions: 6-8
private static final MethodId<TypeBoundKind> TypeBoundKind = MethodId("TypeBoundKind");
public TypeBoundKind TypeBoundKind(BoundKind kind) {
return invoke(TypeBoundKind, kind);
}
//javac versions: 6-8
private static final MethodId<JCAnnotation> Annotation = MethodId("Annotation", JCAnnotation.class, JCTree.class, List.class);
public JCAnnotation Annotation(JCTree annotationType, List<JCExpression> args) {
return invoke(Annotation, annotationType, args);
}
//javac versions: 8
private static final MethodId<JCAnnotation> TypeAnnotation = MethodId("TypeAnnotation", JCAnnotation.class, JCTree.class, List.class);
public JCAnnotation TypeAnnotation(JCTree annotationType, List<JCExpression> args) {
return invoke(TypeAnnotation, annotationType, args);
}
//javac versions: 6-8
private static final MethodId<JCModifiers> ModifiersWithAnnotations = MethodId("Modifiers", JCModifiers.class, long.class, List.class);
public JCModifiers Modifiers(long flags, List<JCAnnotation> annotations) {
return invoke(ModifiersWithAnnotations, flags, annotations);
}
//javac versions: 6-8
private static final MethodId<JCModifiers> Modifiers = MethodId("Modifiers", JCModifiers.class, long.class);
public JCModifiers Modifiers(long flags) {
return invoke(Modifiers, flags);
}
//javac versions: 8
// private static final MethodId<JCAnnotatedType> AnnotatedType = MethodId("AnnotatedType");
// public JCAnnotatedType AnnotatedType(List<JCAnnotation> annotations, JCExpression underlyingType) {
// return invoke(AnnotatedType, annotations, underlyingType);
// }
//javac versions: 6-8
private static final MethodId<JCErroneous> Erroneous = MethodId("Erroneous", JCErroneous.class);
public JCErroneous Erroneous() {
return invoke(Erroneous);
}
//javac versions: 6-8
private static final MethodId<JCErroneous> ErroneousWithErrs = MethodId("Erroneous", JCErroneous.class, List.class);
public JCErroneous Erroneous(List<? extends JCTree> errs) {
return invoke(ErroneousWithErrs, errs);
}
//javac versions: 6-8
private static final MethodId<LetExpr> LetExpr = MethodId("LetExpr", LetExpr.class, List.class, JCTree.class);
public LetExpr LetExpr(List<JCVariableDecl> defs, JCTree expr) {
return invoke(LetExpr, defs, expr);
}
//javac versions: 6-8
private static final MethodId<JCClassDecl> AnonymousClassDef = MethodId("AnonymousClassDef");
public JCClassDecl AnonymousClassDef(JCModifiers mods, List<JCTree> defs) {
return invoke(AnonymousClassDef, mods, defs);
}
//javac versions: 6-8
private static final MethodId<LetExpr> LetExprSingle = MethodId("LetExpr", LetExpr.class, JCVariableDecl.class, JCTree.class);
public LetExpr LetExpr(JCVariableDecl def, JCTree expr) {
return invoke(LetExprSingle, def, expr);
}
//javac versions: 6-8
private static final MethodId<JCIdent> IdentVarDecl = MethodId("Ident", JCIdent.class, JCVariableDecl.class);
public JCExpression Ident(JCVariableDecl param) {
return invoke(IdentVarDecl, param);
}
//javac versions: 6-8
private static final MethodId<List<JCExpression>> Idents = MethodId("Idents");
public List<JCExpression> Idents(List<JCVariableDecl> params) {
return invoke(Idents, params);
}
//javac versions: 6-8
private static final MethodId<JCMethodInvocation> App2 = MethodId("App", JCMethodInvocation.class, JCExpression.class, List.class);
public JCMethodInvocation App(JCExpression meth, List<JCExpression> args) {
return invoke(App2, meth, args);
}
//javac versions: 6-8
private static final MethodId<JCMethodInvocation> App1 = MethodId("App", JCMethodInvocation.class, JCExpression.class);
public JCMethodInvocation App(JCExpression meth) {
return invoke(App1, meth);
}
//javac versions: 6-8
private static final MethodId<List<JCAnnotation>> Annotations = MethodId("Annotations");
public List<JCAnnotation> Annotations(List<Attribute.Compound> attributes) {
return invoke(Annotations, attributes);
}
//javac versions: 6-8
private static final MethodId<JCLiteral> LiteralWithValue = MethodId("Literal", JCLiteral.class, Object.class);
public JCLiteral Literal(Object value) {
return invoke(LiteralWithValue, value);
}
//javac versions: 6-8
private static final MethodId<JCAnnotation> AnnotationWithAttributeOnly = MethodId("Annotation", JCAnnotation.class, Attribute.class);
public JCAnnotation Annotation(Attribute a) {
return invoke(AnnotationWithAttributeOnly, a);
}
//javac versions: 8
private static final MethodId<JCAnnotation> TypeAnnotationWithAttributeOnly = MethodId("TypeAnnotation", JCAnnotation.class, Attribute.class);
public JCAnnotation TypeAnnotation(Attribute a) {
return invoke(TypeAnnotationWithAttributeOnly, a);
}
//javac versions: 6-8
private static final MethodId<JCStatement> Call = MethodId("Call");
public JCStatement Call(JCExpression apply) {
return invoke(Call, apply);
}
//javac versions: 6-8
private static final MethodId<JCExpression> Type = MethodId("Type");
public JCExpression Type(Type type) {
return invoke(Type, type);
}
}
|
Lekanich/lombok
|
src/utils/lombok/javac/JavacTreeMaker.java
|
Java
|
mit
| 34,532 |
package com.jsoniter.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonIgnore {
boolean ignoreDecoding() default true;
boolean ignoreEncoding() default true;
}
|
json-iterator/java
|
src/main/java/com/jsoniter/annotation/JsonIgnore.java
|
Java
|
mit
| 452 |
package com.fteams.siftrain.entities;
import com.fteams.siftrain.util.SongUtils;
public class SimpleNotesInfo implements Comparable<SimpleNotesInfo>{
public Double timing_sec;
public Integer effect;
public Double effect_value;
public Integer position;
@Override
public int compareTo(SimpleNotesInfo o) {
if (!o.timing_sec.equals(timing_sec))
return Double.compare(timing_sec, o.timing_sec);
return SongUtils.compare(position, o.position);
}
}
|
kbz/SIFTrain
|
core/src/com/fteams/siftrain/entities/SimpleNotesInfo.java
|
Java
|
mit
| 503 |
package org.nww.core.data.filter;
import java.util.List;
/**
* A simple filter criteria implementation checking the existence of a string
* inside a list of strings. Does only match if the list contains a totally
* equal string like the context one.
*
* @author MGA
*/
public class StringInListFilterCriteria implements FilterCriteria<List<String>, String> {
/**
* Checks whether the passed list contains the context string.
*
* @param toCheck list of string where to find the context in
* @param context the context string to be found
* @return true if the context is found inside the list of strings
*/
@Override
public boolean match(List<String> toCheck, String context) {
if (toCheck.isEmpty()) {
return true;
}
return toCheck.contains(context);
}
}
|
NetzwerkWohnen/NWW
|
src/main/java/org/nww/core/data/filter/StringInListFilterCriteria.java
|
Java
|
mit
| 877 |
package com.dreamteam.octodrive.model;
import com.parse.ParseObject;
public abstract class OctoObject {
protected String _objectId;
protected ParseObject _parseObject;
public ParseObject parseObject() {
return _parseObject;
}
public void setObjectId(String objectId) {
_objectId = objectId;
}
public String objectId() {
if (_objectId == null) {
_objectId = _parseObject.getObjectId();
}
return _objectId;
}
}
|
lordzsolt/OctoDrive
|
app/src/main/java/com/dreamteam/octodrive/model/OctoObject.java
|
Java
|
mit
| 500 |
package ca.ulaval.glo2004.Domain.Matrix;
import ca.ulaval.glo2004.Domain.StationExitPoint;
import java.io.Serializable;
public class ExitProductSortingHolder implements Serializable{
public StationExitPoint exitPoint;
public double value;
public ExitProductSortingHolder(StationExitPoint exitPoint, double value){
this.exitPoint = exitPoint;
this.value = value;
}
}
|
klafooty/projetJava
|
src/main/java/ca/ulaval/glo2004/Domain/Matrix/ExitProductSortingHolder.java
|
Java
|
mit
| 401 |
package junit.util;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
/**
* JUnit4からのassertThatアサーションを使いやすくするためのラッパー処理群。<br>
* isのためのimportが面倒、Boxingは避けたいという御仁向け。<br>
* assertThatのシグネチャが改善される可能性を考慮してメソッド名は別名にしています。
*
* @author cobot00
*/
public final class AssertWrapper {
private AssertWrapper() {
// コンストラクタの隠蔽
}
public static void assertThatWrapper(int actual, int expected) {
assertThat(Integer.valueOf(actual), is(Integer.valueOf(expected)));
}
public static void assertThatWrapper(long actual, long expected) {
assertThat(Long.valueOf(actual), is(Long.valueOf(expected)));
}
public static void assertThatWrapper(double actual, double expected) {
assertThat(Double.valueOf(actual), is(Double.valueOf(expected)));
}
public static void assertThatWrapper(String actual, String expected) {
assertThat(actual, is(expected));
}
public static void assertEqualsWrapper(boolean actual, boolean expected) {
if (expected) {
assertTrue("\n Expected [" + expected + "] But actual [" + actual + "]", actual);
} else {
assertFalse("\n Expected [" + expected + "] But actual [" + actual + "]", actual);
}
}
public static void assertThatWrapper(int actual, int expected, String message) {
assertThat(message, Integer.valueOf(actual), is(Integer.valueOf(expected)));
}
public static void assertThatWrapper(double actual, double expected, String message) {
assertThat(message, Double.valueOf(actual), is(Double.valueOf(expected)));
}
public static void assertThatWrapper(long actual, long expected, String message) {
assertThat(message, Long.valueOf(actual), is(Long.valueOf(expected)));
}
public static void assertThatWrapper(String actual, String expected, String message) {
assertThat(message, actual, is(expected));
}
}
|
cobot00/JUnitForEnterprise
|
test/junit/util/AssertWrapper.java
|
Java
|
mit
| 2,145 |
/**
* Copyright 2014 Kakao Corp.
*
* Redistribution and modification in source or binary forms are not permitted without specific prior written permission.
*
* 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.kakao;
import com.kakao.helper.Logger;
/**
* unlink 요청 ({@link UserManagement#requestUnlink(com.kakao.UnlinkResponseCallback)}) 호출할 때 넘겨주고 콜백을 받는다.
* @author MJ
*/
public abstract class UnlinkResponseCallback extends UserResponseCallback {
/**
* unlink를 성공적으로 마친 경우로
* 일반적으로 로그인창으로 이동하도록 구현한다.
* @param userId unlink된 사용자 id
*/
protected abstract void onSuccess(final long userId);
/**
* unlink 요청전이나 요청 결과가 세션이 close된 경우로
* 일반적으로 로그인창으로 이동하도록 구현한다.
* @param errorResult 세션이 닫힌 이유
*/
protected abstract void onSessionClosedFailure(final APIErrorResult errorResult);
/**
* 세션이 닫힌 경우({@link #onSessionClosedFailure})를 제외한 이유로 가입 요청이 실패한 경우
* 아래 에러 종류에 따라 적절한 처리를 한다. <br/>
* {@link ErrorCode#INVALID_PARAM_CODE}, <br/>
* {@link ErrorCode#INVALID_SCOPE_CODE}, <br/>
* {@link ErrorCode#NOT_SUPPORTED_API_CODE}, <br/>
* {@link ErrorCode#INTERNAL_ERROR_CODE}, <br/>
* {@link ErrorCode#NOT_REGISTERED_USER_CODE}, <br/>
* {@link ErrorCode#CLIENT_ERROR_CODE}, <br/>
* {@link ErrorCode#EXCEED_LIMIT_CODE}, <br/>
* {@link ErrorCode#KAKAO_MAINTENANCE_CODE} <br/>
* @param errorResult unlink를 실패한 이유
*/
protected abstract void onFailure(final APIErrorResult errorResult);
/**
* {@link UserResponseCallback}를 구현한 것으로 unlink 요청이 성공했을 때 호출된다.
* 세션을 닫고 케시를 지우고, 사용자 콜백 {@link #onSuccess(long)}을 호출한다.
* 결과 User 객체가 비정상이면 에러처리한다.
* @param user unlink된 사용자 id를 포함한 사용자 객체
*/
@Override
protected void onSuccessUser(final User user) {
if (user == null || user.getId() <= 0)
onError("UnlinkResponseCallback : onSuccessUser is called but the result user is null.", new APIErrorResult(null, "the result of Signup request is null."));
else {
Logger.getInstance().d("UnlinkResponseCallback : unlinked successfully. user = " + user);
Session.getCurrentSession().close(null);
onSuccess(user.getId());
}
}
/**
* {@link com.kakao.http.HttpResponseHandler}를 구현한 것으로 unlink 요청 전 또는 요청 중에 세션이 닫혀 로그인이 필요할 때 호출된다.
* 사용자 콜백 {@link #onSessionClosedFailure(APIErrorResult)}을 호출한다.
* @param errorResult 세션이 닫히 계기
*/
@Override
protected void onHttpSessionClosedFailure(final APIErrorResult errorResult) {
Logger.getInstance().d("UnlinkResponseCallback : session is closed before requesting unlink. errorResult = " + errorResult);
onSessionClosedFailure(errorResult);
}
/**
* {@link com.kakao.http.HttpResponseHandler}를 구현한 것으로 unlink 요청 중에 서버에서 요청을 수행하지 못했다는 결과를 받았을 때 호출된다.
* 세션의 상태에 따라 {@link #onSessionClosedFailure(APIErrorResult)} 콜백 또는 {@link #onFailure(APIErrorResult)}} 콜백을 호출한다.
* @param errorResult 실패한 결과
*/
@Override
protected void onHttpFailure(final APIErrorResult errorResult) {
onError("UnlinkResponseCallback : server error occurred during requesting unlink.", errorResult);
}
/**
* 에러가 발생했을 때의 처리로
* 세션이 닫혔으면 {@link #onSessionClosedFailure(APIErrorResult)} 콜백을 아니면 {@link #onFailure(APIErrorResult)}} 콜백을 호출한다.
* @param msg 로깅 메시지
* @param errorResult 에러 발생원인
*/
private void onError(final String msg, final APIErrorResult errorResult) {
Logger.getInstance().d(msg + errorResult);
if (!Session.getCurrentSession().isOpened())
onSessionClosedFailure(errorResult);
else
onFailure(errorResult);
}
}
|
haruio/haru-example-memo
|
kakao/src/com/kakao/UnlinkResponseCallback.java
|
Java
|
mit
| 4,973 |
package com.target.control;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class JpaUtil {
private static EntityManager em;
private static EntityManagerFactory factory;
static {
try {
factory = Persistence.createEntityManagerFactory("jpa");
em = factory.createEntityManager();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
public static EntityManager getFactory() {
return em;
}
}
|
Malehaly/studies-java-jpa-junit
|
jpa/ExercicioHandsOn09/src/com/target/control/JpaUtil.java
|
Java
|
mit
| 530 |
package com.crescentflare.appconfig.helper;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Build;
import android.util.TypedValue;
/**
* Library helper: resource access
* A helper library to access app resources for skinning the user interface
*/
public class AppConfigResourceHelper
{
static public int getAccentColor(Context context)
{
int identifier = context.getResources().getIdentifier("colorAccent", "attr", context.getPackageName());
if (identifier == 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
identifier = android.R.attr.colorAccent;
}
if (identifier > 0)
{
TypedValue typedValue = new TypedValue();
TypedArray a = context.obtainStyledAttributes(typedValue.data, new int[]{identifier});
if (a != null)
{
int color = a.getColor(0, 0);
a.recycle();
return color;
}
}
return Color.BLACK;
}
static public int getColor(Context context, String name)
{
int identifier = context.getResources().getIdentifier(name, "color", context.getPackageName());
if (identifier > 0)
{
return context.getResources().getColor(identifier);
}
return Color.TRANSPARENT;
}
static public String getString(Context context, String name)
{
int identifier = context.getResources().getIdentifier(name, "string", context.getPackageName());
if (identifier > 0)
{
return context.getResources().getString(identifier);
}
return "";
}
static public int getIdentifier(Context context, String name)
{
return context.getResources().getIdentifier(name, "id", context.getPackageName());
}
}
|
crescentflare/DynamicAppConfigAndroid
|
AppConfigLib/src/main/java/com/crescentflare/appconfig/helper/AppConfigResourceHelper.java
|
Java
|
mit
| 1,901 |
package gr.iti.openzoo.pojos;
/**
*
* @author Michalis Lazaridis <michalis.lazaridis@iti.gr>
*/
public class Triple<L,M,R> {
private final L left;
private final M middle;
private final R right;
public Triple(L left, M middle, R right) {
this.left = left;
this.middle = middle;
this.right = right;
}
public L getLeft() { return left; }
public M getMiddle() { return middle; }
public R getRight() { return right; }
@Override
public int hashCode() { return (left.hashCode() ^ middle.hashCode() ^ right.hashCode()) % Integer.MAX_VALUE; }
@Override
public boolean equals(Object o) {
if (!(o instanceof Triple)) return false;
Triple triplo = (Triple) o;
return this.left.equals(triplo.getLeft()) &&
this.middle.equals(triplo.getMiddle()) &&
this.right.equals(triplo.getRight());
}
@Override
public String toString()
{
return "Triple ( " + getLeft().toString() + ", " + getMiddle().toString() + ", " + getRight().toString() + " )";
}
}
|
VisualComputingLab/OpenZoo
|
OpenZUI/src/java/gr/iti/openzoo/pojos/Triple.java
|
Java
|
mit
| 1,025 |
package us.myles.ViaVersion.protocols.protocol1_9to1_8;
import us.myles.ViaVersion.api.PacketWrapper;
import us.myles.ViaVersion.api.remapper.PacketHandler;
import us.myles.ViaVersion.api.type.Type;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.storage.MovementTracker;
public class PlayerMovementMapper extends PacketHandler {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
MovementTracker tracker = wrapper.user().get(MovementTracker.class);
tracker.incrementIdlePacket();
// If packet has the ground data
if (wrapper.is(Type.BOOLEAN, 0)) {
tracker.setGround(wrapper.get(Type.BOOLEAN, 0));
}
}
}
|
Matsv/ViaVersion
|
common/src/main/java/us/myles/ViaVersion/protocols/protocol1_9to1_8/PlayerMovementMapper.java
|
Java
|
mit
| 696 |
package dp;
/**
* Question: http://www.geeksforgeeks.org/count-number-binary-strings-without-consecutive-1s/
*/
public class CountBinaryWithoutConsecutiveOnes {
public int count(int N) {
int[][] memo = new int[N + 1][2];
for (int i = 0; i < memo.length; i++) {
for (int j = 0; j < memo[i].length; j++) {
memo[i][j] = -1;
}
}
return countBinary(N, false, memo);
}
private int countBinary(int N, boolean prevSet, int[][] memo) {
if (N == 0) return 1;
int i = (prevSet) ? 1 : 0;
if (memo[N][i] == -1) {
memo[N][i] = countBinary(N - 1, false, memo);
if (!prevSet) {
memo[N][i] += countBinary(N - 1, true, memo);
}
}
return memo[N][i];
}
public int countBottomUp(int N) {
int a = 1, b = 1, c = 0;
for (int i = 1; i <= N; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
}
|
scaffeinate/crack-the-code
|
geeks-for-geeks/src/dp/CountBinaryWithoutConsecutiveOnes.java
|
Java
|
mit
| 1,025 |
package Problems;
import java.io.IOException;
import java.util.Scanner;
/**
* Created by nhs0912 on 2016-12-15.
*/
public class P_10039 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int sum = 0;
int score = 0;
for (int i = 0; i < 5; i++) {
score = sc.nextInt();
if (score < 40) {
score = 40;
}
sum += score;
}
System.out.println(sum / 5);
}
}
|
nhs0912/BOJ
|
src/Problems/P_10039.java
|
Java
|
mit
| 520 |
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import hudson.ExtensionPoint;
import hudson.Launcher;
import hudson.Plugin;
import hudson.tasks.BuildStep;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import hudson.tasks.BuildStepMonitor;
import java.io.IOException;
import org.kohsuke.stapler.export.ExportedBean;
/**
* Extensible property of {@link Job}.
*
* <p>
* {@link Plugin}s can extend this to define custom properties
* for {@link Job}s. {@link JobProperty}s show up in the user
* configuration screen, and they are persisted with the job object.
*
* <p>
* Configuration screen should be defined in <tt>config.jelly</tt>.
* Within this page, the {@link JobProperty} instance is available
* as <tt>instance</tt> variable (while <tt>it</tt> refers to {@link Job}.
*
* <p>
* Starting 1.150, {@link JobProperty} implements {@link BuildStep},
* meaning it gets the same hook as {@link Publisher} and {@link Builder}.
* The primary intention of this mechanism is so that {@link JobProperty}s
* can add actions to the new build. The {@link #perform(AbstractBuild, Launcher, BuildListener)}
* and {@link #prebuild(AbstractBuild, BuildListener)} are invoked after those
* of {@link Publisher}s.
*
* @param <J>
* When you restrict your job property to be only applicable to a certain
* subtype of {@link Job}, you can use this type parameter to improve
* the type signature of this class. See {@link JobPropertyDescriptor#isApplicable(Class)}.
*
* @author Kohsuke Kawaguchi
* @see JobPropertyDescriptor
* @since 1.72
*/
@ExportedBean
public abstract class JobProperty<J extends Job<?,?>> implements Describable<JobProperty<?>>, BuildStep, ExtensionPoint {
/**
* The {@link Job} object that owns this property.
* This value will be set by the Hudson code.
* Derived classes can expect this value to be always set.
*/
protected transient J owner;
/**
* Hook for performing post-initialization action.
*
* <p>
* This method is invoked in two cases. One is when the {@link Job} that owns
* this property is loaded from disk, and the other is when a job is re-configured
* and all the {@link JobProperty} instances got re-created.
*/
protected void setOwner(J owner) {
this.owner = owner;
}
/**
* {@inheritDoc}
*/
public JobPropertyDescriptor getDescriptor() {
return (JobPropertyDescriptor)Hudson.getInstance().getDescriptor(getClass());
}
/**
* {@link Action} to be displayed in the job page.
*
* <p>
* Returning non-null from this method allows a job property to add an item
* to the left navigation bar in the job page.
*
* <p>
* {@link Action} can implement additional marker interface to integrate
* with the UI in different ways.
*
* @param job
* Always the same as {@link #owner} but passed in anyway for backward compatibility (I guess.)
* You really need not use this value at all.
* @return
* null if there's no such action.
* @since 1.102
* @see ProminentProjectAction
* @see PermalinkProjectAction
*/
public Action getJobAction(J job) {
return null;
}
//
// default no-op implementation
//
public boolean prebuild(AbstractBuild<?,?> build, BuildListener listener) {
return true;
}
/**
* {@inheritDoc}
*
* <p>
* Invoked after {@link Publisher}s have run.
*/
public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
return true;
}
/**
* Returns {@link BuildStepMonitor#NONE} by default, as {@link JobProperty}s normally don't depend
* on its previous result.
*/
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
public final Action getProjectAction(AbstractProject<?,?> project) {
return getJobAction((J)project);
}
}
|
fujibee/hudson
|
core/src/main/java/hudson/model/JobProperty.java
|
Java
|
mit
| 5,215 |
package modulo0.tree;
public class Declare extends Stat {
public Declare(Var x, Expr e, Stat s) {
super("Declare", new M0Node[] { x, e, s });
}
@Override
protected Stat copy() {
return new Declare((Var) getChild(0), (Expr) getChild(1), (Stat) getChild(2));
}
}
|
nuthatchery/modulo0
|
modulo0/src/modulo0/tree/Declare.java
|
Java
|
mit
| 275 |
package main.java.test;
import java.util.Optional;
import main.java.modul.Catalog;
import main.java.modul.Categorie;
import main.java.modul.Oferta;
import main.java.modul.Produs;
import main.java.service.Log;
import main.java.util.Printer;
import main.java.util.Sort;
import main.java.util.SortUtil1;
import main.java.util.Sorter;
import main.java.util.Streams;
import main.java.util.TVAprice;
/**
*
* @author mancim
*/
public class Test {
public static void main(String[] args) {
addProduse(Catalog.getInstanec());
//Sort.orderPrice7(Catalog.getInstanec().getProduse());
//Sort.orderPrice8(Catalog.getInstanec().getProduse(), SortUtil1::Sort);
//Sorter s = new Sorter();
//s.Sort(Catalog.getInstanec().getProduse());
new Oferta(1231, 20);
new Oferta(1712, 5);
new Oferta(2334, 10);
//Streams.L();
//Streams.M();
//Streams.N();
//Streams.O();
//Streams.P();
//Streams.Q();
//Streams.R();
//Streams.S();
//Streams.T();
//Streams.U();
//Streams.V();
Catalog.getInstanec().getProduse().stream().forEach(Log.logger::trace);
//System.out.println(TVAprice.addTVARON(100.0, 19.0));
//System.out.println(TVAprice.addTVAEURO(100.0, 24.0));
//System.out.println(TVAprice.addTVARON(100.0, 19.0));
//System.out.println(TVAprice.TVAEURO(100.0, 24.0));
}
public static void addProduse(Catalog catalog) {
catalog.addProdus(new Produs(1712, "Electrocasnic 1", 234.99, Categorie.ELECTROCASNICE));
catalog.addProdus(new Produs(1231, "Electrocasnic 2", 4234.99, Categorie.ELECTROCASNICE));
catalog.addProdus(new Produs(1773, "Electrocasnic 3", 99.99, Categorie.ELECTROCASNICE));
catalog.addProdus(new Produs(1221, "Electrocasnic 4", 56.99, Categorie.ELECTROCASNICE));
catalog.addProdus(new Produs(1956, "Electrocasnic 5", 233.99, Categorie.ELECTROCASNICE));
catalog.addProdus(new Produs(1918, "Electrocasnic 6", 564.99, Categorie.ELECTROCASNICE));
catalog.addProdus(new Produs(2334, "Telefon 1", 2189.99, Categorie.TELEFON));
catalog.addProdus(new Produs(2231, "Telefon 2", 1449.99, Categorie.TELEFON));
catalog.addProdus(new Produs(2456, "Telefon 3", 649.99, Categorie.TELEFON));
catalog.addProdus(new Produs(2528, "Telefon 4", 899.99, Categorie.TELEFON));
catalog.addProdus(new Produs(2445, "Telefon 5", 467.99, Categorie.TELEFON));
catalog.addProdus(new Produs(2149, "Telefon 6", 355.99, Categorie.TELEFON));
catalog.addProdus(new Produs(2859, "Telefon 7", 3578.99, Categorie.TELEFON));
catalog.addProdus(new Produs(2995, "Telefon 8", 344.99, Categorie.TELEFON));
catalog.addProdus(new Produs(3412, "Calculator 1", 2189.99, Categorie.CALCULATOR));
catalog.addProdus(new Produs(3419, "Calculator 2", 2289.99, Categorie.CALCULATOR));
catalog.addProdus(new Produs(3742, "Calculator 3", 999.99, Categorie.CALCULATOR));
catalog.addProdus(new Produs(3316, "Calculator 4", 1189.99, Categorie.CALCULATOR));
catalog.addProdus(new Produs(3123, "Calculator 5", 949.99, Categorie.CALCULATOR));
}
}
|
stoiandan/msg-code
|
Marius/Day6/src/main/java/test/Test.java
|
Java
|
mit
| 3,349 |
package svc.managers;
import javax.inject.Inject;
import org.springframework.stereotype.Component;
import svc.data.users.UserDAO;
import svc.models.User;
@Component
public class UserManager {
@Inject
private UserDAO userDAO;
public User Login(String userId, String pwd) {
return userDAO.checkUserLogin(userId, pwd);
}
public User GetUserByPhone(String phone) {
return userDAO.getUserByPhone(phone);
}
}
|
gh6-team/less-homelessness-api
|
src/main/java/svc/managers/UserManager.java
|
Java
|
mit
| 431 |
package conqueror.security;
import io.jsonwebtoken.JwtException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
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;
class StatelessAuthenticationFilter extends GenericFilterBean {
private final TokenAuthenticationService tokenAuthenticationService;
StatelessAuthenticationFilter(TokenAuthenticationService tokenAuthenticationService) {
this.tokenAuthenticationService = tokenAuthenticationService;
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
try {
Authentication authentication = tokenAuthenticationService.getAuthentication((HttpServletRequest) req);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(req, res);
SecurityContextHolder.getContext().setAuthentication(null);
} catch (AuthenticationException | JwtException e) {
SecurityContextHolder.clearContext();
((HttpServletResponse) res).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
}
|
moonik/conqueror
|
src/main/java/conqueror/security/StatelessAuthenticationFilter.java
|
Java
|
mit
| 1,573 |
/*Copyright (c) 2011 Anton Yakimov.
GELF created by Lennart Koopmann, Aleksey Palazhchenko.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.graylog2;
import org.json.simple.JSONValue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.zip.GZIPOutputStream;
public class GelfMessage {
private static final String ID_NAME = "id";
private static final String GELF_VERSION = "1.0";
private static final byte[] GELF_CHUNKED_ID = new byte[]{0x1e, 0x0f};
private static final int MAXIMUM_CHUNK_SIZE = 1420;
private static final BigDecimal TIME_DIVISOR = new BigDecimal(1000);
private String version = GELF_VERSION;
private String host;
private byte[] hostBytes = lastFourAsciiBytes("none");
private String shortMessage;
private String fullMessage;
private long javaTimestamp;
private String level;
private String facility = "gelf-java";
private String line;
private String file;
private Map<String, Object> additonalFields = new HashMap<String, Object>();
public GelfMessage() {
}
// todo: merge these constructors.
public GelfMessage(String shortMessage, String fullMessage, Date timestamp, String level) {
this.shortMessage = shortMessage;
this.fullMessage = fullMessage;
this.javaTimestamp = timestamp.getTime();
this.level = level;
}
public GelfMessage(String shortMessage, String fullMessage, Long timestamp, String level, String line, String file) {
this.shortMessage = shortMessage;
this.fullMessage = fullMessage;
this.javaTimestamp = timestamp;
this.level = level;
this.line = line;
this.file = file;
}
public String toJson() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("version", getVersion());
map.put("host", getHost());
map.put("short_message", getShortMessage());
map.put("full_message", getFullMessage());
map.put("timestamp", getTimestamp());
map.put("level", getLevel());
map.put("facility", getFacility());
if( null != getFile() )
{
map.put("file", getFile());
}
if( null != getLine() )
{
map.put("line", getLine());
}
for (Map.Entry<String, Object> additionalField : additonalFields.entrySet()) {
if (!ID_NAME.equals(additionalField.getKey())) {
map.put("_" + additionalField.getKey(), additionalField.getValue());
}
}
return JSONValue.toJSONString(map);
}
public List<byte[]> toDatagrams() {
byte[] messageBytes = gzipMessage(toJson());
List<byte[]> datagrams = new ArrayList<byte[]>();
if (messageBytes.length > MAXIMUM_CHUNK_SIZE) {
sliceDatagrams(messageBytes, datagrams);
} else {
datagrams.add(messageBytes);
}
return datagrams;
}
private void sliceDatagrams(byte[] messageBytes, List<byte[]> datagrams) {
int messageLength = messageBytes.length;
byte[] messageId = ByteBuffer.allocate(8)
.putInt((int) System.currentTimeMillis()) // 4 least-significant-bytes of the time in millis
.put(hostBytes) // 4 least-significant-bytes of the host
.array();
int num = ((Double) Math.ceil((double) messageLength / MAXIMUM_CHUNK_SIZE)).intValue();
for (int idx = 0; idx < num; idx++) {
byte[] header = concatByteArray(GELF_CHUNKED_ID, concatByteArray(messageId, new byte[]{(byte) idx, (byte) num}));
int from = idx * MAXIMUM_CHUNK_SIZE;
int to = from + MAXIMUM_CHUNK_SIZE;
if (to >= messageLength) {
to = messageLength;
}
byte[] datagram = concatByteArray(header, Arrays.copyOfRange(messageBytes, from, to));
datagrams.add(datagram);
}
}
private byte[] gzipMessage(String message) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
GZIPOutputStream stream = new GZIPOutputStream(bos);
stream.write(message.getBytes());
stream.finish();
stream.close();
byte[] zipped = bos.toByteArray();
bos.close();
return zipped;
} catch (IOException e) {
return null;
}
}
private byte[] lastFourAsciiBytes(String host) {
final String shortHost = host.length() >= 4 ? host.substring(host.length() - 4) : host;
try {
return shortHost.getBytes("ASCII");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("JVM without ascii support?", e);
}
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
this.hostBytes = lastFourAsciiBytes(host);
}
public String getShortMessage() {
return shortMessage;
}
public void setShortMessage(String shortMessage) {
this.shortMessage = shortMessage;
}
public String getFullMessage() {
return fullMessage;
}
public void setFullMessage(String fullMessage) {
this.fullMessage = fullMessage;
}
public String getTimestamp() {
return new BigDecimal(javaTimestamp).divide(TIME_DIVISOR).toPlainString();
}
public Long getJavaTimestamp() {
return javaTimestamp;
}
public void setJavaTimestamp(long javaTimestamp) {
this.javaTimestamp = javaTimestamp;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getFacility() {
return facility;
}
public void setFacility(String facility) {
this.facility = facility;
}
public String getLine() {
return line;
}
public void setLine(String line) {
this.line = line;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public GelfMessage addField(String key, String value) {
getAdditonalFields().put(key, value);
return this;
}
public GelfMessage addField(String key, Object value) {
getAdditonalFields().put(key, value);
return this;
}
public Map<String, Object> getAdditonalFields() {
return additonalFields;
}
public void setAdditonalFields(Map<String, Object> additonalFields) {
this.additonalFields = additonalFields;
}
public boolean isValid() {
return !isEmpty(version) && !isEmpty(host) && !isEmpty(shortMessage) && !isEmpty(facility);
}
public boolean isEmpty(String str) {
return str == null || "".equals(str.trim());
}
private byte[] concatByteArray(byte[] first, byte[] second) {
byte[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
}
|
krisachai/GelfLogger
|
src/org/graylog2/GelfMessage.java
|
Java
|
mit
| 8,476 |
package com.mypodcasts.support.injection;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import javax.inject.Inject;
import javax.inject.Provider;
public class ImageLoaderProvider implements Provider<ImageLoader> {
@Inject
private ImageLoader.ImageCache imageCache;
@Inject
private RequestQueue requestQueue;
@Override
public ImageLoader get() {
ImageLoader imageLoader = new ImageLoader(requestQueue, imageCache);
return imageLoader;
}
}
|
alabeduarte/mypodcasts-android
|
app/src/main/java/com/mypodcasts/support/injection/ImageLoaderProvider.java
|
Java
|
mit
| 506 |
package seedu.address.logic.commands;
import seedu.address.commons.core.IndexPrefix;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.Model;
import seedu.address.model.task.DeadlineTask;
import seedu.address.model.task.DeadlineTaskBuilder;
public class MarkDeadlineUnfinishedCommand implements Command {
private static final String MSG_SUCCESS = "Deadline task " + IndexPrefix.DEADLINE.getPrefixString()
+ "%s unfinished.";
private final int targetIndex;
public MarkDeadlineUnfinishedCommand(int targetIndex) {
this.targetIndex = targetIndex;
}
public int getTargetIndex() {
return targetIndex;
}
@Override
public CommandResult execute(Model model) throws CommandException {
assert model != null;
final DeadlineTask oldDeadlineTask;
try {
oldDeadlineTask = model.getDeadlineTask(targetIndex);
} catch (IllegalValueException e) {
throw new CommandException(e);
}
final DeadlineTask finishedDeadlineTask = new DeadlineTaskBuilder(oldDeadlineTask)
.setFinished(false)
.build();
try {
model.setDeadlineTask(targetIndex, finishedDeadlineTask);
} catch (IllegalValueException e) {
throw new AssertionError("The target deadline cannot be missing", e);
}
return new CommandResult(String.format(MSG_SUCCESS, targetIndex));
}
}
|
snehasp13/main
|
src/main/java/seedu/address/logic/commands/MarkDeadlineUnfinishedCommand.java
|
Java
|
mit
| 1,602 |
package com.zhanghedr.mvc;
/**
* Created by zhanghedr on 1/2/17.
*/
public class User {
private String name;
private String email;
public User(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
zhanghedr/design-pattern
|
src/main/java/com/zhanghedr/mvc/User.java
|
Java
|
mit
| 518 |
package com.almasb.fxglgames.geowars.component;
import com.almasb.fxgl.dsl.FXGL;
import com.almasb.fxgl.dsl.components.HealthIntComponent;
import com.almasb.fxgl.entity.component.Component;
import com.almasb.fxgl.texture.Texture;
import com.almasb.fxgl.time.LocalTimer;
import com.almasb.fxglgames.geowars.GeoWarsApp;
import com.almasb.fxglgames.geowars.GeoWarsType;
import javafx.geometry.Rectangle2D;
import javafx.util.Duration;
import static com.almasb.fxgl.dsl.FXGL.*;
/**
* @author Almas Baimagambetov (almaslvl@gmail.com)
*/
public class MineComponent extends Component {
private Texture overlay;
private LocalTimer beepTimer = newLocalTimer();
@Override
public void onAdded() {
overlay = texture("mine_red.png", 315 * 0.25, 315 * 0.25);
beepTimer.capture();
}
@Override
public void onUpdate(double tpf) {
if (beepTimer.elapsed(Duration.seconds(0.25))) {
if (overlay.getParent() == null) {
entity.getViewComponent().addChild(overlay);
} else {
entity.getViewComponent().removeChild(overlay);
}
beepTimer.capture();
}
}
public void explode() {
getGameWorld().getEntitiesInRange(entity.getBoundingBoxComponent().range(150, 150))
.stream()
.filter(e -> e.hasComponent(HealthIntComponent.class))
.forEach(e -> FXGL.<GeoWarsApp>getAppCast().killEnemy(e));
getGameWorld().getSingleton(GeoWarsType.GRID).getComponent(GridComponent.class)
.applyExplosiveForce(2500, entity.getCenter(), 150);
}
@Override
public boolean isComponentInjectionRequired() {
return false;
}
}
|
AlmasB/FXGLGames
|
GeometryWars/src/main/java/com/almasb/fxglgames/geowars/component/MineComponent.java
|
Java
|
mit
| 1,735 |
package graphql.analysis;
import graphql.PublicApi;
import graphql.language.Argument;
import graphql.language.Node;
import graphql.schema.GraphQLArgument;
import graphql.schema.GraphQLFieldDefinition;
import graphql.schema.GraphQLSchema;
import graphql.util.TraverserContext;
import java.util.Map;
@PublicApi
public interface QueryVisitorFieldArgumentEnvironment {
GraphQLSchema getSchema();
GraphQLFieldDefinition getFieldDefinition();
GraphQLArgument getGraphQLArgument();
Argument getArgument();
Object getArgumentValue();
Map<String, Object> getVariables();
QueryVisitorFieldEnvironment getParentEnvironment();
TraverserContext<Node> getTraverserContext();
}
|
graphql-java/graphql-java
|
src/main/java/graphql/analysis/QueryVisitorFieldArgumentEnvironment.java
|
Java
|
mit
| 706 |
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.office.impl;
import com.wilutions.com.*;
@SuppressWarnings("all")
@CoClass(guid="{C09B8C5A-A463-DB41-5DAE-69E7A5F7FCBC}")
public class ODSOColumnImpl extends Dispatch implements com.wilutions.mslib.office.ODSOColumn {
@DeclDISPID(1610743808) public IDispatch getApplication() throws ComException {
final Object obj = this._dispatchCall(1610743808,"Application", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (IDispatch)obj;
}
@DeclDISPID(1610743809) public Integer getCreator() throws ComException {
final Object obj = this._dispatchCall(1610743809,"Creator", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (Integer)obj;
}
@DeclDISPID(1) public Integer getIndex() throws ComException {
final Object obj = this._dispatchCall(1,"Index", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (Integer)obj;
}
@DeclDISPID(2) public String getName() throws ComException {
final Object obj = this._dispatchCall(2,"Name", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (String)obj;
}
@DeclDISPID(3) public IDispatch getParent() throws ComException {
final Object obj = this._dispatchCall(3,"Parent", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (IDispatch)obj;
}
@DeclDISPID(4) public String getValue() throws ComException {
final Object obj = this._dispatchCall(4,"Value", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (String)obj;
}
public ODSOColumnImpl(String progId) throws ComException {
super(progId, "{000C1531-0000-0000-C000-000000000046}");
}
protected ODSOColumnImpl(long ndisp) {
super(ndisp);
}
public String toString() {
return "[ODSOColumnImpl" + super.toString() + "]";
}
}
|
wolfgangimig/joa
|
java/joa/src-gen/com/wilutions/mslib/office/impl/ODSOColumnImpl.java
|
Java
|
mit
| 1,933 |
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt
package com.google.appinventor.components.runtime;
import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.common.YaVersion;
/**
* Component for obtaining Phone Information. Currently supports
* obtaining the IP Address of the phone and whether or not it is
* connected via a WiFi connection.
*
* @author lmercer@mit.edu (Logan Mercer)
*
*/
@DesignerComponent(version = YaVersion.PHONESTATUS_COMPONENT_VERSION,
description = "Component that returns information about the phone.",
category = ComponentCategory.INTERNAL,
nonVisible = true,
iconName = "images/phoneip.png")
@SimpleObject
public class PhoneStatus extends AndroidNonvisibleComponent implements Component {
private static Activity activity;
public PhoneStatus(ComponentContainer container) {
super(container.$form());
activity = container.$context();
}
@SimpleFunction(description = "Returns the IP address of the phone in the form of a String")
public static String GetWifiIpAddress() {
DhcpInfo ip;
Object wifiManager = activity.getSystemService("wifi");
ip = ((WifiManager) wifiManager).getDhcpInfo();
int s_ipAddress= ip.ipAddress;
String ipAddress;
if (isConnected())
ipAddress = intToIp(s_ipAddress);
else
ipAddress = "Error: No Wifi Connection";
return ipAddress;
}
@SimpleFunction(description = "Returns TRUE if the phone is on Wifi, FALSE otherwise")
public static boolean isConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) activity.getSystemService("connectivity");
NetworkInfo networkInfo = null;
if (connectivityManager != null) {
networkInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}
return networkInfo == null ? false : networkInfo.isConnected();
}
public static String intToIp(int i) {
return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >>24) & 0xFF);
}
}
|
rkipper/AppInventor_RK
|
appinventor/components/src/com/google/appinventor/components/runtime/PhoneStatus.java
|
Java
|
mit
| 2,694 |
/*
* The MIT License
*
* Copyright 2013 Thomas Schaffer <thomas.schaffer@epitech.eu>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package shaft.poker.game.table;
import shaft.poker.game.ITable;
import shaft.poker.game.ITable.*;
/**
*
* @author Thomas Schaffer <thomas.schaffer@epitech.eu>
*/
public interface IPlayerActionListener {
public void gameAction(ITable table, IPlayerData plData, ActionType type, int amount);
public void leave(ITable table, IPlayerData plData);
}
|
loopfz/Lucki
|
src/shaft/poker/game/table/IPlayerActionListener.java
|
Java
|
mit
| 1,532 |
package umm3601.plant;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.junit.Before;
import org.junit.Test;
import umm3601.digitalDisplayGarden.PlantController;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import static org.junit.Assert.*;
public class TestPlantComment {
private final static String databaseName = "data-for-testing-only";
private PlantController plantController;
@Before
public void populateDB() throws IOException {
PopulateMockDatabase db = new PopulateMockDatabase();
db.clearAndPopulateDBAgain();
plantController = new PlantController(databaseName);
}
@Test
public void successfulInputOfComment() throws IOException {
String json = "{ plantId: \"58d1c36efb0cac4e15afd278\", comment : \"Here is our comment for this test\" }";
assertTrue(plantController.addComment(json, "second uploadId"));
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase(databaseName);
MongoCollection<Document> plants = db.getCollection("plants");
Document filterDoc = new Document();
filterDoc.append("_id", new ObjectId("58d1c36efb0cac4e15afd278"));
filterDoc.append("uploadId", "second uploadId");
Iterator<Document> iter = plants.find(filterDoc).iterator();
Document plant = iter.next();
List<Document> plantComments = (List<Document>) ((Document) plant.get("metadata")).get("comments");
long comments = plantComments.size();
assertEquals(1, comments);
assertEquals("Here is our comment for this test", plantComments.get(0).getString("comment"));
assertNotNull(plantComments.get(0).getObjectId("_id"));
}
@Test
public void failedInputOfComment() throws IOException {
String json = "{ plantId: \"58d1c36efb0cac4e15afd27\", comment : \"Here is our comment for this test\" }";
assertFalse(plantController.addComment(json, "second uploadId"));
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase(databaseName);
MongoCollection<Document> plants = db.getCollection("plants");
FindIterable findIterable = plants.find();
Iterator iterator = findIterable.iterator();
while(iterator.hasNext()){
Document plant = (Document) iterator.next();
List<Document> plantComments = (List<Document>) ((Document) plant.get("metadata")).get("comments");
assertEquals(0,plantComments.size());
}
}
}
|
UMM-CSci-3601-S17/digital-display-garden-iteration-3-dorfner
|
server/src/test/java/umm3601/plant/TestPlantComment.java
|
Java
|
mit
| 2,771 |
package com.example.android.popularmoviesapp;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
|
dswallow/PopMovies
|
app/src/test/java/com/example/android/popularmoviesapp/ExampleUnitTest.java
|
Java
|
mit
| 329 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.