hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
d622da27a06ce65a1d94bc2a802d3621613c751f | 4,055 | /*
* Copyright 2012 Shared Learning Collaborative, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.slc.sli.dashboard.unit.client;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.slc.sli.dashboard.client.RESTClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;
/**
*
* @author svankina
*
*/
public class RESTClientTest {
@Test
public void testSessionCheck() {
final String jsonText = "{\"name\": \"something\"}";
RESTClient client = new RESTClient() {
public String makeJsonRequestWHeaders(String path, String token) {
return jsonText;
}
};
JsonParser parser = new JsonParser();
JsonObject obj2 = client.sessionCheck(null);
JsonObject obj1 = parser.parse(jsonText).getAsJsonObject();
assertEquals(obj2, obj1);
}
@Test
public void testMakeJsonRequestWHeaders() {
//TODO: Change the overridden function to support HTTPEntity
RESTClient client = new RESTClient() {
public HttpEntity<String> exchange(RestTemplate template, String url, HttpMethod method, HttpEntity entity, Class cl) {
return new HttpEntity<String>("fakeResponse");
}
};
String s = client.makeJsonRequestWHeaders("http://www.google.com", "fakeToken");
assertEquals(s, "fakeResponse");
}
@Test
public void testPutJsonRequestWHeaders() {
String path = "http://local.slidev.org";
String token = "token";
String id = "id";
String json = "{" + "\"component_1\": " + "{" + "\"id\" : \"component_1\", " + "\"name\" : \"Component 1\", "
+ "\"type\" : \"LAYOUT\", " + "\"items\": ["
+ "{\"id\" : \"component_1_1\", \"name\": \"First Child Component\", \"type\": \"PANEL\"}, "
+ "{\"id\" : \"component_1_2\", \"name\": \"Second Child Component\", \"type\": \"PANEL\"}" + "]" + "}"
+ "}";
RESTClient client = new RESTClient();
RestTemplate mockTemplate = mock(RestTemplate.class);
client.setTemplate(mockTemplate);
RestTemplateAnswer restTemplateAnswer = new RestTemplateAnswer();
Mockito.doAnswer(restTemplateAnswer).when(mockTemplate).put(Mockito.anyString(), Mockito.anyObject());
client.putJsonRequestWHeaders(path, token, json);
String customJson = restTemplateAnswer.getJson();
assertNotNull(customJson);
assertEquals(json, customJson);
}
private static class RestTemplateAnswer implements Answer {
private String json;
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
HttpEntity httpEntity = (HttpEntity) invocation.getArguments()[1];
json = (String) httpEntity.getBody();
return null;
}
public String getJson() {
return json;
}
}
}
| 34.956897 | 132 | 0.61455 |
80d2b4996df920019046a47d6e1b779c0b6f2745 | 18,763 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.ui;
import com.intellij.history.LocalHistory;
import com.intellij.history.LocalHistoryAction;
import com.intellij.ide.util.DelegatingProgressIndicator;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.application.TransactionGuard;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.changes.*;
import com.intellij.openapi.vcs.changes.actions.MoveChangesToAnotherListAction;
import com.intellij.openapi.vcs.changes.committed.CommittedChangesCache;
import com.intellij.openapi.vcs.checkin.CheckinEnvironment;
import com.intellij.openapi.vcs.checkin.CheckinHandler;
import com.intellij.openapi.vcs.update.RefreshVFsSynchronously;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.NullableFunction;
import com.intellij.util.concurrency.Semaphore;
import org.jetbrains.annotations.CalledInAwt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import static com.intellij.openapi.application.ApplicationManager.getApplication;
import static com.intellij.openapi.progress.ProgressManager.progress;
import static com.intellij.openapi.ui.Messages.getQuestionIcon;
import static com.intellij.openapi.vcs.VcsBundle.message;
import static com.intellij.openapi.vcs.VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY;
import static com.intellij.openapi.vcs.changes.ChangesUtil.processChangesByVcs;
import static com.intellij.util.ArrayUtil.toObjectArray;
import static com.intellij.util.ObjectUtils.notNull;
import static com.intellij.util.WaitForProgressToShow.runOrInvokeLaterAboveProgress;
import static com.intellij.util.containers.ContainerUtil.*;
import static com.intellij.util.ui.ConfirmationDialog.requestForConfirmation;
import static java.util.Collections.emptyList;
public class CommitHelper {
public static final Key<Object> DOCUMENT_BEING_COMMITTED_KEY = new Key<>("DOCUMENT_BEING_COMMITTED");
private final static Logger LOG = Logger.getInstance(CommitHelper.class);
@NotNull private final Project myProject;
@NotNull private final ChangeList myChangeList;
@NotNull private final List<Change> myIncludedChanges;
@NotNull private final String myActionName;
@NotNull private final String myCommitMessage;
@NotNull private final List<? extends CheckinHandler> myHandlers;
private final boolean myAllOfDefaultChangeListChangesIncluded;
private final boolean myForceSyncCommit;
@NotNull private final NullableFunction<Object, Object> myAdditionalData;
@NotNull private final CommitResultHandler myResultHandler;
@NotNull private final List<Document> myCommittingDocuments = newArrayList();
@NotNull private final VcsConfiguration myConfiguration;
@NotNull private final HashSet<String> myFeedback = newHashSet();
@NotNull private final GeneralCommitProcessor myCommitProcessor;
@SuppressWarnings("unused") // Required for compatibility with external plugins.
public CommitHelper(@NotNull Project project,
@NotNull ChangeList changeList,
@NotNull List<Change> includedChanges,
@NotNull String actionName,
@NotNull String commitMessage,
@NotNull List<? extends CheckinHandler> handlers,
boolean allOfDefaultChangeListChangesIncluded,
boolean synchronously,
@NotNull NullableFunction<Object, Object> additionalDataHolder,
@Nullable CommitResultHandler customResultHandler) {
this(project, changeList, includedChanges, actionName, commitMessage, handlers, allOfDefaultChangeListChangesIncluded, synchronously,
additionalDataHolder, customResultHandler, false, null);
}
public CommitHelper(@NotNull Project project,
@NotNull ChangeList changeList,
@NotNull List<Change> includedChanges,
@NotNull String actionName,
@NotNull String commitMessage,
@NotNull List<? extends CheckinHandler> handlers,
boolean allOfDefaultChangeListChangesIncluded,
boolean synchronously,
@NotNull NullableFunction<Object, Object> additionalDataHolder,
@Nullable CommitResultHandler resultHandler,
boolean isAlien,
@Nullable AbstractVcs vcs) {
myProject = project;
myChangeList = changeList;
myIncludedChanges = includedChanges;
myActionName = actionName;
myCommitMessage = commitMessage;
myHandlers = handlers;
myAllOfDefaultChangeListChangesIncluded = allOfDefaultChangeListChangesIncluded;
myForceSyncCommit = synchronously;
myAdditionalData = additionalDataHolder;
myConfiguration = VcsConfiguration.getInstance(myProject);
myCommitProcessor = isAlien ? new AlienCommitProcessor(notNull(vcs)) : new CommitProcessor(vcs);
myResultHandler =
notNull(resultHandler, new DefaultCommitResultHandler(myProject, myIncludedChanges, myCommitMessage, myCommitProcessor, myFeedback));
}
@SuppressWarnings("UnusedReturnValue")
public boolean doCommit() {
Task.Backgroundable task = new Task.Backgroundable(myProject, myActionName, true, myConfiguration.getCommitOption()) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(myProject);
vcsManager.startBackgroundVcsOperation();
try {
delegateCommitToVcsThread();
}
finally {
vcsManager.stopBackgroundVcsOperation();
}
}
@Override
public boolean shouldStartInBackground() {
return !myForceSyncCommit && super.shouldStartInBackground();
}
@Override
public boolean isConditionalModal() {
return myForceSyncCommit;
}
};
ProgressManager.getInstance().run(task);
return true;
}
private void delegateCommitToVcsThread() {
ProgressIndicator indicator = new DelegatingProgressIndicator();
TransactionGuard.getInstance().assertWriteSafeContext(indicator.getModalityState());
Semaphore endSemaphore = new Semaphore();
endSemaphore.down();
ChangeListManagerImpl.getInstanceImpl(myProject).executeOnUpdaterThread(() -> {
indicator.setText("Performing VCS commit...");
try {
ProgressManager.getInstance().runProcess(() -> {
indicator.checkCanceled();
generalCommit();
}, indicator);
}
finally {
endSemaphore.up();
}
});
indicator.setText("Waiting for VCS background tasks to finish...");
while (!endSemaphore.waitFor(20)) {
indicator.checkCanceled();
}
}
static boolean hasOnlyWarnings(@NotNull List<? extends VcsException> exceptions) {
return exceptions.stream().allMatch(VcsException::isWarning);
}
private void generalCommit() throws RuntimeException {
try {
ReadAction.run(() -> markCommittingDocuments());
try {
myCommitProcessor.callSelf();
}
finally {
ReadAction.run(() -> unmarkCommittingDocuments());
}
myCommitProcessor.doBeforeRefresh();
}
catch (ProcessCanceledException pce) {
throw pce;
}
catch (Throwable e) {
LOG.error(e);
myCommitProcessor.myVcsExceptions.add(new VcsException(e));
ExceptionUtil.rethrow(e);
}
finally {
commitCompleted(myCommitProcessor.getVcsExceptions());
myCommitProcessor.customRefresh();
runOrInvokeLaterAboveProgress(() -> myCommitProcessor.doPostRefresh(), null, myProject);
}
}
private class AlienCommitProcessor extends GeneralCommitProcessor {
@NotNull private final AbstractVcs myVcs;
private AlienCommitProcessor(@NotNull AbstractVcs vcs) {
myVcs = vcs;
}
@Override
public void callSelf() {
ChangesUtil.processItemsByVcs(myIncludedChanges, change -> myVcs, this::process);
}
@Override
protected void process(@NotNull AbstractVcs vcs, @NotNull List<Change> items) {
if (!myVcs.getName().equals(vcs.getName())) return;
super.process(vcs, items);
}
@Override
public void afterSuccessfulCheckIn() {
}
@Override
public void afterFailedCheckIn() {
}
@Override
public void doBeforeRefresh() {
}
@Override
public void customRefresh() {
}
@Override
public void doPostRefresh() {
}
}
abstract class GeneralCommitProcessor {
@NotNull protected final List<FilePath> myPathsToRefresh = newArrayList();
@NotNull protected final List<VcsException> myVcsExceptions = newArrayList();
@NotNull protected final List<Change> myChangesFailedToCommit = newArrayList();
public abstract void callSelf();
public abstract void afterSuccessfulCheckIn();
public abstract void afterFailedCheckIn();
public abstract void doBeforeRefresh();
public abstract void customRefresh();
public abstract void doPostRefresh();
protected void process(@NotNull AbstractVcs vcs, @NotNull List<Change> changes) {
CheckinEnvironment environment = vcs.getCheckinEnvironment();
if (environment != null) {
myPathsToRefresh.addAll(ChangesUtil.getPaths(changes));
List<VcsException> exceptions = environment.commit(changes, myCommitMessage, myAdditionalData, myFeedback);
if (!isEmpty(exceptions)) {
myVcsExceptions.addAll(exceptions);
myChangesFailedToCommit.addAll(changes);
}
}
}
@NotNull
public List<FilePath> getPathsToRefresh() {
return myPathsToRefresh;
}
@NotNull
public List<VcsException> getVcsExceptions() {
return myVcsExceptions;
}
@NotNull
public List<Change> getChangesFailedToCommit() {
return myChangesFailedToCommit;
}
}
private class CommitProcessor extends GeneralCommitProcessor {
@NotNull private LocalHistoryAction myAction = LocalHistoryAction.NULL;
private boolean myCommitSuccess;
@Nullable private final AbstractVcs myVcs;
private CommitProcessor(@Nullable AbstractVcs vcs) {
myVcs = vcs;
}
@Override
public void callSelf() {
if (myVcs != null && myIncludedChanges.isEmpty()) {
process(myVcs, myIncludedChanges);
}
processChangesByVcs(myProject, myIncludedChanges, this::process);
}
@Override
public void afterSuccessfulCheckIn() {
myCommitSuccess = true;
}
@Override
public void afterFailedCheckIn() {
getApplication().invokeLater(
() -> moveToFailedList(myChangeList, myCommitMessage, getChangesFailedToCommit(),
message("commit.dialog.failed.commit.template", myChangeList.getName()), myProject),
ModalityState.defaultModalityState(), myProject.getDisposed());
}
@Override
public void doBeforeRefresh() {
ChangeListManagerImpl.getInstanceImpl(myProject).showLocalChangesInvalidated();
myAction = ReadAction.compute(() -> LocalHistory.getInstance().startAction(myActionName));
}
@Override
public void customRefresh() {
List<Change> toRefresh = newArrayList();
processChangesByVcs(myProject, myIncludedChanges, (vcs, changes) -> {
CheckinEnvironment environment = vcs.getCheckinEnvironment();
if (environment != null && environment.isRefreshAfterCommitNeeded()) {
toRefresh.addAll(changes);
}
});
if (!toRefresh.isEmpty()) {
progress(message("commit.dialog.refresh.files"));
RefreshVFsSynchronously.updateChanges(toRefresh);
}
}
@Override
public void doPostRefresh() {
myAction.finish();
if (!myProject.isDisposed()) {
// after vcs refresh is completed, outdated notifiers should be removed if some exists...
VcsDirtyScopeManager.getInstance(myProject).filePathsDirty(getPathsToRefresh(), null);
ChangeListManager clManager = ChangeListManager.getInstance(myProject);
clManager.invokeAfterUpdate(
() -> {
if (myCommitSuccess) {
updateChangelistAfterRefresh();
}
CommittedChangesCache cache = CommittedChangesCache.getInstance(myProject);
// in background since commit must have authorized
cache.refreshAllCachesAsync(false, true);
cache.refreshIncomingChangesAsync();
}, InvokeAfterUpdateMode.SILENT, null, null);
LocalHistory.getInstance().putSystemLabel(myProject, myActionName + ": " + myCommitMessage);
}
}
private void updateChangelistAfterRefresh() {
if (!(myChangeList instanceof LocalChangeList)) return;
ChangeListManagerEx clManager = (ChangeListManagerEx)ChangeListManager.getInstance(myProject);
String listName = myChangeList.getName();
LocalChangeList localList = clManager.findChangeList(listName);
if (localList == null) return;
clManager.editChangeListData(listName, null);
if (!localList.isDefault()) {
clManager.scheduleAutomaticEmptyChangeListDeletion(localList);
}
else {
Collection<Change> changes = localList.getChanges();
if (myConfiguration.OFFER_MOVE_TO_ANOTHER_CHANGELIST_ON_PARTIAL_COMMIT &&
!changes.isEmpty() &&
myAllOfDefaultChangeListChangesIncluded) {
ChangelistMoveOfferDialog dialog = new ChangelistMoveOfferDialog(myConfiguration);
if (dialog.showAndGet()) {
MoveChangesToAnotherListAction.askAndMove(myProject, changes, emptyList());
}
}
}
}
}
private void markCommittingDocuments() {
myCommittingDocuments.addAll(markCommittingDocuments(myProject, myIncludedChanges));
}
private void unmarkCommittingDocuments() {
unmarkCommittingDocuments(myCommittingDocuments);
myCommittingDocuments.clear();
}
/**
* Marks {@link Document documents} related to the given changes as "being committed".
* @return documents which were marked that way.
* @see #unmarkCommittingDocuments(Collection)
* @see VetoSavingCommittingDocumentsAdapter
*/
@NotNull
private static Collection<Document> markCommittingDocuments(@NotNull Project project, @NotNull List<Change> changes) {
Collection<Document> result = newArrayList();
for (Change change : changes) {
VirtualFile virtualFile = ChangesUtil.getFilePath(change).getVirtualFile();
if (virtualFile != null && !virtualFile.getFileType().isBinary()) {
Document doc = FileDocumentManager.getInstance().getDocument(virtualFile);
if (doc != null) {
doc.putUserData(DOCUMENT_BEING_COMMITTED_KEY, project);
result.add(doc);
}
}
}
return result;
}
/**
* Removes the "being committed marker" from the given {@link Document documents}.
* @see #markCommittingDocuments(Project, List)
* @see VetoSavingCommittingDocumentsAdapter
*/
private static void unmarkCommittingDocuments(@NotNull Collection<Document> committingDocs) {
committingDocs.forEach(document -> document.putUserData(DOCUMENT_BEING_COMMITTED_KEY, null));
}
private void commitCompleted(@NotNull List<VcsException> allExceptions) {
List<VcsException> errors = collectErrors(allExceptions);
boolean noErrors = errors.isEmpty();
boolean noWarnings = allExceptions.isEmpty();
if (noErrors) {
myHandlers.forEach(CheckinHandler::checkinSuccessful);
myCommitProcessor.afterSuccessfulCheckIn();
myResultHandler.onSuccess(myCommitMessage);
if (noWarnings) {
progress(message("commit.dialog.completed.successfully"));
}
}
else {
myHandlers.forEach(handler -> handler.checkinFailed(errors));
myCommitProcessor.afterFailedCheckIn();
myResultHandler.onFailure();
}
}
@CalledInAwt
public static void moveToFailedList(@NotNull ChangeList changeList,
@NotNull String commitMessage,
@NotNull List<? extends Change> failedChanges,
@NotNull String newChangelistName,
@NotNull Project project) {
// No need to move since we'll get exactly the same changelist.
if (failedChanges.containsAll(changeList.getChanges())) return;
VcsConfiguration configuration = VcsConfiguration.getInstance(project);
if (configuration.MOVE_TO_FAILED_COMMIT_CHANGELIST != DO_ACTION_SILENTLY) {
VcsShowConfirmationOption option = new VcsShowConfirmationOption() {
@Override
public Value getValue() {
return configuration.MOVE_TO_FAILED_COMMIT_CHANGELIST;
}
@Override
public void setValue(Value value) {
configuration.MOVE_TO_FAILED_COMMIT_CHANGELIST = value;
}
@Override
public boolean isPersistent() {
return true;
}
};
boolean result =
requestForConfirmation(option, project, message("commit.failed.confirm.prompt"), message("commit.failed.confirm.title"),
getQuestionIcon());
if (!result) return;
}
ChangeListManager changeListManager = ChangeListManager.getInstance(project);
int index = 1;
String failedListName = newChangelistName;
while (changeListManager.findChangeList(failedListName) != null) {
index++;
failedListName = newChangelistName + " (" + index + ")";
}
LocalChangeList failedList = changeListManager.addChangeList(failedListName, commitMessage);
changeListManager.moveChangesTo(failedList, toObjectArray(failedChanges, Change.class));
}
@NotNull
static List<VcsException> collectErrors(@NotNull List<? extends VcsException> exceptions) {
return filter(exceptions, e -> !e.isWarning());
}
}
| 37.828629 | 140 | 0.707083 |
52189ff7c11a3ce7fc1f387c2423b91d116c6226 | 1,864 | package thaumicenergistics.client.gui.buttons;
import java.util.List;
import appeng.api.config.SearchBoxMode;
import appeng.core.localization.ButtonToolTips;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.util.EnumChatFormatting;
import thaumicenergistics.client.textures.AEStateIconsEnum;
/**
* Displays search mode icons.
*
* @author Nividica
*
*/
@SideOnly(Side.CLIENT)
public class GuiButtonSearchMode
extends ThEStateButton
{
private String tooltipMode = "";
public GuiButtonSearchMode( final int ID, final int xPosition, final int yPosition, final int buttonWidth, final int buttonHeight,
final SearchBoxMode currentMode )
{
super( ID, xPosition, yPosition, buttonWidth, buttonHeight, null, 0, 0, AEStateIconsEnum.REGULAR_BUTTON );
this.setSearchMode( currentMode );
}
@Override
public void getTooltip( final List<String> tooltip )
{
this.addAboutToTooltip( tooltip, ButtonToolTips.SearchMode.getLocal(), EnumChatFormatting.GRAY + this.tooltipMode );
}
/**
* Sets the icon and tooltip based on the specified mode.
*
* @param mode
*/
public void setSearchMode( final SearchBoxMode mode )
{
switch ( mode )
{
case AUTOSEARCH:
this.tooltipMode = ButtonToolTips.SearchMode_Auto.getLocal();
this.stateIcon = AEStateIconsEnum.SEARCH_MODE_AUTO;
break;
case MANUAL_SEARCH:
this.tooltipMode = ButtonToolTips.SearchMode_Standard.getLocal();
this.stateIcon = AEStateIconsEnum.SEARCH_MODE_MANUAL;
break;
case NEI_AUTOSEARCH:
this.tooltipMode = ButtonToolTips.SearchMode_NEIAuto.getLocal();
this.stateIcon = AEStateIconsEnum.SEARCH_MODE_NEI_AUTO;
break;
case NEI_MANUAL_SEARCH:
this.tooltipMode = ButtonToolTips.SearchMode_NEIStandard.getLocal();
this.stateIcon = AEStateIconsEnum.SEARCH_MODE_NEI_MANUAL;
break;
}
}
}
| 26.628571 | 131 | 0.767704 |
c3fc877908ebc3190b8809a51c1556dcac9bcb60 | 395 | package com.ruoyi.common.annotation;
import com.ruoyi.common.enums.DataSourceType;
import java.lang.annotation.*;
/**
* @Author Leejiyun
* @Date 2021/8/7
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface DataSource {
/**
* 切换数据源的名称
* */
DataSourceType value() default DataSourceType.MASTER;
}
| 18.809524 | 57 | 0.721519 |
40956dcc72a13d725e983c3ef5c9b90e8336fe0e | 1,737 | package <%= package %>.controller;
import <%= package %>.model.dto.<%= dto %>;
import <%= package %>.service.<%= entity %>Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import javax.validation.Valid;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.NO_CONTENT;
@RestController
@RequestMapping("<%= path %>")
@RequiredArgsConstructor
@Slf4j
public class <%= controller %> {
private final <%= service %> service;
@GetMapping("/{id}")
public Mono<<%= dto %>> findById(@PathVariable String id) {
return service.findById(id);
}
@PostMapping
@ResponseStatus(CREATED)
public Mono<<%= dto %>> create(@RequestBody @Valid <%= dto %> dto) {
return service.create(dto);
}
@PatchMapping("/{id}")
public Mono<<%= dto %>> update(@PathVariable String id, @RequestBody @Valid <%= dto %> dto) {
return service.update(id, dto);
}
@DeleteMapping("/{id}")
@ResponseStatus(NO_CONTENT)
public Mono<Void> deleteById(@PathVariable String id) {
return service.deleteById(id);
}
}
| 33.403846 | 97 | 0.731146 |
4f2fceaf96e64d8285e8ca6c842f7f8add56cbbc | 3,889 | package com.puls.gyan.google;
import com.google.api.client.auth.oauth2.Credential;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.puls.gyan.config.ConfigService;
import com.puls.gyan.exception.ConfigServiceException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
public class GoogleOauthHelper implements GoogleOauthHelperIfc {
private ConfigService configService;
/**
* CLIENT_ID constant before proceeding, set this up at
* https://code.google.com/apis/console/
*/
private static String CLIENT_ID = "<your>authid";
/**
* CLIENT_SECRET constant before proceeding, set this up at
* https://code.google.com/apis/console/
*/
private static String CLIENT_SECRET = "<your-auth-secret>";
/**
* Callback URI that google will redirect to after successful authentication
*/
public String CALLBACK_URI = "http://localhost:8080/gyan/home";
private static final Collection<String> SCOPE = Arrays
.asList("https://www.googleapis.com/auth/userinfo.profile;https://www.googleapis.com/auth/userinfo.email"
.split(";"));
private static final String USER_INFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo";
private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private final GoogleAuthorizationCodeFlow flow;
/**
* Constructor initializes the Google Authorization Code Flow with CLIENT
* ID, SECRET, and SCOPE
*/
public GoogleOauthHelper() {
flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, SCOPE)
.build();
}
/* (non-Javadoc)
* @see com.puls.gyan.google.GoogleOauthHelperIfc#buildLoginUrl(java.lang.String)
*/
@Override
public String buildLoginUrl(String callBackUrl) {
final GoogleAuthorizationCodeRequestUrl url = flow.newAuthorizationUrl();
if(callBackUrl!=null) {
CALLBACK_URI = callBackUrl;
}
return url.setRedirectUri(CALLBACK_URI).build();
}
/* (non-Javadoc)
* @see com.puls.gyan.google.GoogleOauthHelperIfc#getUserInfoJson(java.lang.String)
*/
@Override
public GoogleUserInfo getUserInfoJson(final String authCode) throws IOException {
String callBackUrl;
try {
callBackUrl = configService.findByName("CALLBACK_URI");
CALLBACK_URI = callBackUrl;
} catch (ConfigServiceException e) {
e.printStackTrace();
}
GoogleTokenResponse response = flow.newTokenRequest(authCode).setRedirectUri(CALLBACK_URI).execute();
Credential credential = flow.createAndStoreCredential(response, null);
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);
// Make an authenticated request
GenericUrl url = new GenericUrl(USER_INFO_URL);
HttpRequest request = requestFactory.buildGetRequest(url);
request.getHeaders().setContentType("application/json");
String jsonIdentity = request.execute().parseAsString();
Gson gson = new GsonBuilder().create();
GoogleUserInfo userInfo = gson.fromJson(jsonIdentity,GoogleUserInfo.class);
return userInfo;
}
public ConfigService getConfigService() {
return configService;
}
public void setConfigService(ConfigService configService) {
this.configService = configService;
}
}
| 33.817391 | 111 | 0.779378 |
1b2a0c9145f5b43702a51104aea5e7bcbb6a13a7 | 706 | package org.imagearchive.lsm.toolbox.info.scaninfo;
import java.util.LinkedHashMap;
public class Marker{
public LinkedHashMap<String, Object> records = new LinkedHashMap<String, Object>();
public Object[][] data = {
{new Long(0x014000001),DataType.STRING,"MARKER_NAME"},
{new Long(0x014000002),DataType.STRING,"DESCRIPTION"},
{new Long(0x014000003),DataType.STRING,"TRIGGER_IN"},
{new Long(0x014000004),DataType.STRING,"TRIGGER_OUT"}
};
public static boolean isMarkers(long tagEntry) {
if (tagEntry == 0x013000000)
return true;
else
return false;
}
public static boolean isMarker(long tagEntry) {
if (tagEntry == 0x014000000)
return true;
else
return false;
}
}
| 24.344828 | 84 | 0.725212 |
c8503d0ad9b6297856c44c8ef3e23e292f61cdd2 | 329 | package org.jglrxavpok.jlsl.fragments;
public class MethodCallFragment extends CodeFragment {
public String methodOwner;
public String methodName;
public String[] argumentsTypes;
public InvokeTypes invokeType;
public String returnType;
public enum InvokeTypes {
STATIC, VIRTUAL, SPECIAL
}
}
| 23.5 | 54 | 0.735562 |
0338beeadc1d457076a0aebc1e67bf3bff5c03d3 | 1,705 | package com.qimo.bean;
import java.util.ArrayList;
import java.util.Arrays;
public class CustomOrder {
private int tid;
private Users user;
private String tfids;
private String tnums;
private double tmoney;
private ArrayList<Flower> fList;
private String[] numList;
public int getTid() {
return tid;
}
public void setTid(int tid) {
this.tid = tid;
}
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
public String getTfids() {
return tfids;
}
public void setTfids(String tfids) {
this.tfids = tfids;
}
public String getTnums() {
return tnums;
}
public void setTnums(String tnums) {
this.tnums = tnums;
}
public double getTmoney() {
return tmoney;
}
public void setTmoney(double tmoney) {
this.tmoney = tmoney;
}
public ArrayList<Flower> getfList() {
return fList;
}
public void setfList(ArrayList<Flower> fList) {
this.fList = fList;
}
public String[] getNumList() {
return numList;
}
public void setNumList(String[] numList) {
this.numList = numList;
}
public CustomOrder(int tid, Users user, String tfids, String tnums,
double tmoney, ArrayList<Flower> fList, String[] numList) {
super();
this.tid = tid;
this.user = user;
this.tfids = tfids;
this.tnums = tnums;
this.tmoney = tmoney;
this.fList = fList;
this.numList = numList;
}
public CustomOrder() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "CustomOrder [tid=" + tid + ", user=" + user + ", tfids="
+ tfids + ", tnums=" + tnums + ", tmoney=" + tmoney
+ ", fList=" + fList + ", numList=" + Arrays.toString(numList)
+ "]";
}
}
| 17.760417 | 68 | 0.660997 |
d3e75cf5db1d3bb5bdbf40328189c762dc19635f | 3,120 | package kademlia.simulations;
import kademlia.JKademliaNode;
import kademlia.node.KademliaId;
import java.io.IOException;
/**
* Testing connecting 2 nodes to each other
*
* @author Joshua Kissoon
* @created 20140219
*/
public class NodeConnectionTest {
public static void main(String[] args) {
try {
/* Setting up 2 Kad networks */
JKademliaNode kad1 = new JKademliaNode("JoshuaK", new KademliaId(), 7574);
System.out.println("Created Node Kad 1: " + kad1.getNode().getNodeId());
JKademliaNode kad2 = new JKademliaNode("Crystal", new KademliaId(), 7572);
//KademliaId diff12 = kad1.getNode().getNodeId().xor(kad2.getNode().getNodeId());
System.out.println("Created Node Kad 2: " + kad2.getNode().getNodeId());
// System.out.println(kad1.getNode().getNodeId() + " ^ " + kad2.getNode().getNodeId() + " = " + diff12);
//System.out.println("Kad 1 - Kad 2 distance: " + diff12.getFirstSetBitIndex());
/* Connecting 2 to 1 */
System.out.println("Connecting Kad 1 and Kad 2");
kad1.bootstrap(kad2.getNode());
System.out.println("Kad 1: ");
//System.out.println(kad1.getNode().getRoutingTable());
// System.out.println("Kad 2: ");
// System.out.println(kad2.getNode().getRoutingTable());
/* Creating a new node 3 and connecting it to 1, hoping it'll get onto 2 also */
JKademliaNode kad3 = new JKademliaNode("Jessica", new KademliaId(), 7783);
System.out.println("\n\n\n\n\n\nCreated Node Kad 3: " + kad3.getNode().getNodeId());
System.out.println("Connecting Kad 3 and Kad 2");
kad3.bootstrap(kad2.getNode());
// NodeId diff32 = kad3.getNode().getNodeId().xor(kad2.getNode().getNodeId());
// NodeId diff31 = kad1.getNode().getNodeId().xor(kad3.getNode().getNodeId());
// System.out.println("Kad 3 - Kad 1 distance: " + diff31.getFirstSetBitIndex());
// System.out.println("Kad 3 - Kad 2 distance: " + diff32.getFirstSetBitIndex());
JKademliaNode kad4 = new JKademliaNode("Sandy", new KademliaId(), 7789);
System.out.println("\n\n\n\n\n\nCreated Node Kad 4: " + kad4.getNode().getNodeId());
System.out.println("Connecting Kad 4 and Kad 2");
kad4.bootstrap(kad2.getNode());
System.out.println("\n\nKad 1: " + kad1.getNode().getNodeId() + " Routing Table: ");
System.out.println(kad1.getRoutingTable());
System.out.println("\n\nKad 2: " + kad2.getNode().getNodeId() + " Routing Table: ");
System.out.println(kad2.getRoutingTable());
System.out.println("\n\nKad 3: " + kad3.getNode().getNodeId() + " Routing Table: ");
System.out.println(kad3.getRoutingTable());
System.out.println("\n\nKad 4: " + kad4.getNode().getNodeId() + " Routing Table: ");
System.out.println(kad4.getRoutingTable());
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 46.567164 | 115 | 0.598077 |
83395fa96ec46afa4289f226bcab34564d0d01ce | 9,210 | package util.swt.editor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import net.miginfocom.swt.MigLayout;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StyledCellLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import util.swt.ResourceManager;
import util.swt.event.OnEvent;
class AutoCompleteShell {
static final Image KEYWORD16 = ResourceManager.getImage(AutoCompleteShell.class, "keyword-16.png");
static final Image TEMPLATE16 = ResourceManager.getImage(AutoCompleteShell.class, "template-16.gif");
static final Image TEXT16 = ResourceManager.getImage(AutoCompleteShell.class, "text-16.png");
private EditorHelper _editorHelper;
private StyledText _editor;
private Display _display;
private List<Template> _templatePropositions;
private List<String> _wordPropositions;
private List<Keyword> _keywordPropositions;
private Table _table;
private TableViewer _tableViewer;
private int _caretPos;
private String _word;
Shell _shell;
private int _shellWidth;
public AutoCompleteShell( EditorHelper editorHelper, int pos, String w, List<Template> templates, List<String> words, List<Keyword> keywords, int shellWidth ) {
_editorHelper = editorHelper;
_caretPos = pos;
_word = w;
_keywordPropositions = keywords;
_shellWidth = shellWidth;
_editor = _editorHelper._editor;
_display = _editor.getDisplay();
_templatePropositions = templates;
_wordPropositions = words;
_keywordPropositions = keywords;
}
public void keyDown( Event e ) {
if ( e.character == SWT.ESC ) {
_shell.dispose();
}
if ( e.keyCode == SWT.PAGE_DOWN ) {
int selectionIndex = _table.getSelectionIndex();
int itemCount = _table.getItemCount();
int itemsPerPage = _table.getSize().y / _table.getItemHeight() - 1;
int targetIndex = Math.min(itemCount - 1, selectionIndex + itemsPerPage);
_table.setSelection(targetIndex);
}
if ( e.keyCode == SWT.PAGE_UP ) {
int selectionIndex = _table.getSelectionIndex();
int itemsPerPage = _table.getSize().y / _table.getItemHeight() - 1;
int targetIndex = Math.max(0, selectionIndex - itemsPerPage);
_table.setSelection(targetIndex);
}
if ( e.keyCode == SWT.ARROW_DOWN ) {
int selectionIndex = _table.getSelectionIndex();
int itemCount = _table.getItemCount();
if ( selectionIndex + 1 < itemCount ) {
_table.setSelection(selectionIndex + 1);
} else {
_table.setSelection(0);
}
}
if ( e.keyCode == SWT.ARROW_UP ) {
int selectionIndex = _table.getSelectionIndex();
if ( selectionIndex > 0 ) {
_table.setSelection(selectionIndex - 1);
} else {
_table.setSelection(_table.getItemCount() - 1);
}
}
if ( e.keyCode == SWT.CR ) {
expand();
}
}
public void open() {
_shell = new Shell(_editor.getShell(), SWT.ON_TOP | SWT.TOOL | SWT.NO_FOCUS | SWT.RESIZE);
_shell.setLayout(new MigLayout("ins 0"));
OnEvent.addListener(_shell, SWT.Dispose).on(getClass(), this).shellDisposed(null);
_tableViewer = new TableViewer(_shell, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.VIRTUAL);
_table = _tableViewer.getTable();
_table.setHeaderVisible(false);
_table.setLinesVisible(false);
_table.setLayoutData("wmin 10, h 10:200:, grow, push");
_table.setRedraw(false);
OnEvent.addListener(_table, SWT.MouseDoubleClick).on(getClass(), this).mouseDoubleClicked(null);
_tableViewer.setContentProvider(new ArrayContentProvider());
List input = new ArrayList();
input.addAll(_templatePropositions);
input.addAll(_wordPropositions);
input.addAll(_keywordPropositions);
Collections.sort(input, new Comparator() {
@Override
public int compare( Object o1, Object o2 ) {
int sortWeight1 = getSortWeight(o1);
int sortWeight2 = getSortWeight(o2);
if ( sortWeight1 != sortWeight2 ) {
return (sortWeight1 < sortWeight2 ? 1 : (sortWeight1 == sortWeight2 ? 0 : -1));
}
return o1.toString().compareToIgnoreCase(o2.toString());
}
});
_tableViewer.setInput(input);
_tableViewer.setSelection(new StructuredSelection(input.get(0)));
_tableViewer.setLabelProvider(new AutoCompleteLabelProvider());
_table.setRedraw(true);
_shell.layout();
Point loc = _editor.getLocationAtOffset(_editor.getCaretOffset());
loc.y += _editor.getLineHeight();
setBounds(_shell.computeSize(_shellWidth, SWT.DEFAULT), _editor.toDisplay(loc));
_shell.setVisible(true);
}
protected int getSortWeight( Object o ) {
if ( o instanceof Template ) {
return 2;
}
if ( o instanceof Keyword ) {
return 1;
}
return 0;
}
void mouseDoubleClicked( Event e ) {
expand();
}
void shellDisposed( Event e ) {
_editorHelper._autoCompleteShell = null;
}
private void expand() {
IStructuredSelection selection = (IStructuredSelection)_tableViewer.getSelection();
Object element = selection.getFirstElement();
if ( element instanceof String ) {
_editor.replaceTextRange(_caretPos - _word.length(), _word.length(), (String)element);
_editor.setCaretOffset(_caretPos + ((String)element).length() - _word.length());
} else if ( element instanceof Template ) {
_editorHelper.expandTemplate(_editor.getText(), _editor.getCaretOffset(), ((Template)element)._handle, _word);
} else if ( element instanceof Keyword ) {
_editorHelper.expandKeyword(_editor.getText(), _editor.getCaretOffset(), ((Keyword)element)._handle, _word);
}
_shell.dispose();
}
private Monitor getMonitor() {
Point editorLocation = _editor.toDisplay(_editor.getLocation());
for ( Monitor m : _display.getMonitors() ) {
if ( m.getBounds().contains(editorLocation) ) {
return m;
}
}
return _display.getPrimaryMonitor();
}
private void setBounds( Point size, Point loc ) {
Monitor m = getMonitor();
Rectangle clientArea = m.getClientArea();
Rectangle bounds = new Rectangle(Math.max(loc.x, clientArea.x), Math.max(loc.y, clientArea.y), size.x, size.y);
if ( (!clientArea.contains(bounds.x, bounds.y + bounds.height) || //
!clientArea.contains(bounds.x + bounds.width, bounds.y + bounds.height)) ) {
if ( clientArea.x > bounds.x ) {
bounds.x += clientArea.x - bounds.x;
} else if ( clientArea.x + clientArea.width < bounds.x + bounds.width ) {
bounds.x -= bounds.x + bounds.width - clientArea.x - clientArea.width;
}
if ( clientArea.y > bounds.y ) {
bounds.y += clientArea.y - bounds.y;
} else if ( clientArea.y + clientArea.height < bounds.y + bounds.height ) {
bounds.y -= bounds.y + bounds.height - clientArea.y - clientArea.height;
}
}
_shell.setBounds(bounds);
}
private static class AutoCompleteLabelProvider extends StyledCellLabelProvider {
@Override
public void update( ViewerCell cell ) {
Object element = cell.getElement();
String label;
if ( element instanceof Template ) {
Template t = (Template)element;
label = t._handle + " - " + t._name;
StyleRange style = new StyleRange(t._handle.length(), label.length() - t._handle.length(), ResourceManager.getColor(SWT.COLOR_DARK_GRAY), null);
cell.setStyleRanges(new StyleRange[] { style });
cell.setImage(TEMPLATE16);
} else if ( element instanceof Keyword ) {
Keyword k = (Keyword)element;
label = k._handle + " - " + k._description;
StyleRange style = new StyleRange(k._handle.length(), label.length() - k._handle.length(), ResourceManager.getColor(SWT.COLOR_DARK_GRAY), null);
cell.setStyleRanges(new StyleRange[] { style });
cell.setImage(KEYWORD16);
} else {
label = element.toString();
cell.setImage(TEXT16);
}
cell.setText(label);
super.update(cell);
}
}
}
| 37.901235 | 163 | 0.647014 |
e0a9753b24bef07f77c2013b116a8fc6aef0bb3b | 6,020 | /*
* Copyright 2016 John Grosh (jagrosh).
*
* 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 spectra.commands;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import net.dv8tion.jda.events.message.MessageReceivedEvent;
import spectra.Argument;
import spectra.Command;
import spectra.Sender;
import spectra.SpConst;
import spectra.datasources.Reminders;
import spectra.utils.FormatUtil;
/**
*
* @author John Grosh (jagrosh)
*/
public class Reminder extends Command {
private final Reminders reminders;
public Reminder(Reminders reminders)
{
this.reminders = reminders;
this.command = "reminder";
this.help = "sets a reminder";
this.longhelp = "This command is used to set reminders. The reminder will be sent "
+ "to the channel it was set in (or in DMs if you set it in DMs or the channel "
+ "is no longer available).";
this.aliases = new String[]{"remind","remindme"};
this.cooldown = 30;
this.cooldownKey = event -> event.getAuthor().getId()+"|reminder";
this.arguments = new Argument[]{
new Argument("time",Argument.Type.TIME,true,60,63072000),
new Argument("message",Argument.Type.LONGSTRING,true)
};
this.children = new Command[]{
new RemindList(),
new RemindRemove()
};
}
@Override
protected boolean execute(Object[] args, MessageReceivedEvent event) {
long seconds = (long)args[0];
String message = (String)args[1];
String[] reminder = new String[reminders.getSize()];
reminder[Reminders.USERID] = event.getAuthor().getId();
reminder[Reminders.CHANNELID] = event.isPrivate() ? "private" : event.getTextChannel().getId();
reminder[Reminders.EXPIRETIME] = (OffsetDateTime.now().toInstant().toEpochMilli() + (seconds * 1000)) + "";
reminder[Reminders.MESSAGE] = message +" ~set "+OffsetDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME);
reminders.set(reminder);
Sender.sendResponse(SpConst.SUCCESS+"Reminder set to expire in "+FormatUtil.secondsToTime(seconds), event);
return true;
}
private class RemindList extends Command
{
private RemindList()
{
this.command = "list";
this.help = "shows a list of your current reminders";
this.longhelp = "This command lists all of the reminders you have set, as well as where they are set for.";
}
@Override
protected boolean execute(Object[] args, MessageReceivedEvent event) {
List<String[]> list = reminders.getRemindersForUser(event.getAuthor().getId());
if(list.isEmpty())
{
Sender.sendResponse(SpConst.WARNING+"You don't have any reminders set!", event);
return false;
}
StringBuilder builder = new StringBuilder(SpConst.SUCCESS+"**"+list.size()+"** reminders:");
for(int i=0; i<list.size(); i++)
{
builder.append("\n`").append(i).append(".` ");
String channelid = list.get(i)[Reminders.CHANNELID];
builder.append(channelid.equals("private") ? "Direct Message - \"" : "<#"+channelid+"> - \"");
String message = list.get(i)[Reminders.MESSAGE].length() > 20 ? list.get(i)[Reminders.MESSAGE].substring(0,20)+"..." : list.get(i)[Reminders.MESSAGE];
builder.append(message).append("\" in ")
.append(FormatUtil.secondsToTime((Long.parseLong(list.get(i)[Reminders.EXPIRETIME]) - OffsetDateTime.now().toInstant().toEpochMilli())/1000));
}
Sender.sendResponse(builder.toString(), event);
return true;
}
}
private class RemindRemove extends Command
{
private RemindRemove()
{
this.command = "remove";
this.aliases = new String[]{"delete","cancel","clear"};
this.help = "cancels a reminder from the list";
this.longhelp = "This command cancels a reminder. The index must be the number "
+ "of the given reminder when using `"+SpConst.PREFIX+"remind list`";
this.arguments = new Argument[]{
new Argument("index",Argument.Type.INTEGER,true,0,100)
};
}
@Override
protected boolean execute(Object[] args, MessageReceivedEvent event) {
long index = (long)args[0];
List<String[]> list = reminders.getRemindersForUser(event.getAuthor().getId());
if(list.isEmpty())
{
Sender.sendResponse(SpConst.ERROR+"You cannot clear a reminder because you do not have any set!", event);
return false;
}
if(index+1 > list.size())
{
Sender.sendResponse(SpConst.ERROR+"There is no reminder at that index! Please enter a number 0 - "+(list.size()-1)+", or try `"+SpConst.PREFIX+"remind list`", event);
return false;
}
reminders.removeReminder(list.get((int)index));
Sender.sendResponse(SpConst.SUCCESS+"You have removed a reminder.", event);
return true;
}
}
}
| 44.264706 | 183 | 0.598505 |
2d28aa408bb983c913e8709f359d820c07687448 | 2,262 | /**
* Copyright (C) 2006-2020 Talend Inc. - www.talend.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.talend.sdk.component.api.configuration.ui.layout;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.talend.sdk.component.api.configuration.ui.meta.Ui;
import org.talend.sdk.component.api.meta.Documentation;
@Ui
@Documentation("Advanced layout to place properties by row, this is exclusive with `@OptionsOrder`.\n"
+ "\nNOTE: the logic to handle forms (gridlayout names) is to use the only layout if there is only one defined, "
+ "else to check if there are `Main` and `Advanced` and if at least `Main` exists, use them, else "
+ "use all available layouts.")
@Target(TYPE)
@Retention(RUNTIME)
@Repeatable(GridLayouts.class)
public @interface GridLayout {
interface FormType {
String MAIN = "Main";
String ADVANCED = "Advanced";
@Deprecated // this one means nothing, surely to drop and use main instead
String CITIZEN = "CitizenUser";
}
/**
* @return the ordered list of rows of the layout.
*/
Row[] value();
/**
* @return the form name associated to this definition.
*/
String[] names() default FormType.MAIN;
/**
* Defines a UI row (list of widgets).
*/
@Target(PARAMETER)
@Retention(RUNTIME)
@interface Row {
/**
* @return the ordered list of property/widgets to set on this row.
*/
String[] value();
}
}
| 31.416667 | 121 | 0.693192 |
d6586252f631f12f659d271af80ad20aae5cb4b7 | 923 | package com.gersion.pictureshow.ui.adapter;
import android.view.View;
import com.gersion.pictureshow.R;
import com.gersion.pictureshow.base.BaseRVAdapter;
import com.gersion.pictureshow.base.BaseViewHolder;
import com.gersion.pictureshow.model.bean.DataBean;
import com.gersion.pictureshow.model.bean.JokeBean;
import com.gersion.pictureshow.ui.viewholder.PictureJokeViewHolder;
import java.util.List;
/**
* @作者 Gersy
* @版本
* @包名 com.gersion.pictureshow.ui.adapter
* @待完成
* @创建时间 2016/11/24
* @功能描述 TODO
* @更新人 $
* @更新时间 $
* @更新版本 $
*/
public class PictureJokeAdapter extends BaseRVAdapter<DataBean> {
public PictureJokeAdapter(List<DataBean> data) {
super(data);
}
@Override
protected BaseViewHolder setViewHolder(View view) {
return new PictureJokeViewHolder(view);
}
@Override
protected int setResourseId() {
return R.layout.item_picture_joke;
}
}
| 23.075 | 67 | 0.726977 |
764ade510ad2875712366f4ed2753541f2864236 | 10,141 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.api.response;
import java.util.Date;
import java.util.Map;
import com.google.gson.annotations.SerializedName;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseResponse;
import org.apache.cloudstack.api.EntityReference;
import com.cloud.offering.ServiceOffering;
import com.cloud.serializer.Param;
@EntityReference(value = ServiceOffering.class)
public class ServiceOfferingResponse extends BaseResponse {
@SerializedName("id")
@Param(description = "the id of the service offering")
private String id;
@SerializedName("name")
@Param(description = "the name of the service offering")
private String name;
@SerializedName("displaytext")
@Param(description = "an alternate display text of the service offering.")
private String displayText;
@SerializedName("cpunumber")
@Param(description = "the number of CPU")
private Integer cpuNumber;
@SerializedName("cpuspeed")
@Param(description = "the clock rate CPU speed in Mhz")
private Integer cpuSpeed;
@SerializedName("memory")
@Param(description = "the memory in MB")
private Integer memory;
@SerializedName("created")
@Param(description = "the date this service offering was created")
private Date created;
@SerializedName("storagetype")
@Param(description = "the storage type for this service offering")
private String storageType;
@SerializedName("offerha")
@Param(description = "the ha support in the service offering")
private Boolean offerHa;
@SerializedName("limitcpuuse")
@Param(description = "restrict the CPU usage to committed service offering")
private Boolean limitCpuUse;
@SerializedName("isvolatile")
@Param(description = "true if the vm needs to be volatile, i.e., on every reboot of vm from API root disk is discarded and creates a new root disk")
private Boolean isVolatile;
@SerializedName("tags")
@Param(description = "the tags for the service offering")
private String tags;
@SerializedName("domainid")
@Param(description = "the domain id of the service offering")
private String domainId;
@SerializedName(ApiConstants.DOMAIN)
@Param(description = "Domain name for the offering")
private String domain;
@SerializedName(ApiConstants.HOST_TAGS)
@Param(description = "the host tag for the service offering")
private String hostTag;
@SerializedName(ApiConstants.IS_SYSTEM_OFFERING)
@Param(description = "is this a system vm offering")
private Boolean isSystem;
@SerializedName(ApiConstants.IS_DEFAULT_USE)
@Param(description = "is this a default system vm offering")
private Boolean defaultUse;
@SerializedName(ApiConstants.SYSTEM_VM_TYPE)
@Param(description = "is this a the systemvm type for system vm offering")
private String vmType;
@SerializedName(ApiConstants.NETWORKRATE)
@Param(description = "data transfer rate in megabits per second allowed.")
private Integer networkRate;
@SerializedName("iscustomizediops")
@Param(description = "true if disk offering uses custom iops, false otherwise", since = "4.4")
private Boolean customizedIops;
@SerializedName(ApiConstants.MIN_IOPS)
@Param(description = "the min iops of the disk offering", since = "4.4")
private Long minIops;
@SerializedName(ApiConstants.MAX_IOPS)
@Param(description = "the max iops of the disk offering", since = "4.4")
private Long maxIops;
@SerializedName(ApiConstants.HYPERVISOR_SNAPSHOT_RESERVE)
@Param(description = "Hypervisor snapshot reserve space as a percent of a volume (for managed storage using Xen or VMware)", since = "4.4")
private Integer hypervisorSnapshotReserve;
@SerializedName("diskBytesReadRate")
@Param(description = "bytes read rate of the service offering")
private Long bytesReadRate;
@SerializedName("diskBytesWriteRate")
@Param(description = "bytes write rate of the service offering")
private Long bytesWriteRate;
@SerializedName("diskIopsReadRate")
@Param(description = "io requests read rate of the service offering")
private Long iopsReadRate;
@SerializedName("diskIopsWriteRate")
@Param(description = "io requests write rate of the service offering")
private Long iopsWriteRate;
@SerializedName(ApiConstants.DEPLOYMENT_PLANNER)
@Param(description = "deployment strategy used to deploy VM.")
private String deploymentPlanner;
@SerializedName(ApiConstants.SERVICE_OFFERING_DETAILS)
@Param(description = "additional key/value details tied with this service offering", since = "4.2.0")
private Map<String, String> details;
@SerializedName("iscustomized")
@Param(description = "is true if the offering is customized", since = "4.3.0")
private Boolean isCustomized;
public ServiceOfferingResponse() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getIsSystem() {
return isSystem;
}
public void setIsSystemOffering(Boolean isSystem) {
this.isSystem = isSystem;
}
public Boolean getDefaultUse() {
return defaultUse;
}
public void setDefaultUse(Boolean defaultUse) {
this.defaultUse = defaultUse;
}
public String getSystemVmType() {
return vmType;
}
public void setSystemVmType(String vmtype) {
vmType = vmtype;
}
public String getDisplayText() {
return displayText;
}
public void setDisplayText(String displayText) {
this.displayText = displayText;
}
public int getCpuNumber() {
return cpuNumber;
}
public void setCpuNumber(Integer cpuNumber) {
this.cpuNumber = cpuNumber;
}
public int getCpuSpeed() {
return cpuSpeed;
}
public void setCpuSpeed(Integer cpuSpeed) {
this.cpuSpeed = cpuSpeed;
}
public int getMemory() {
return memory;
}
public void setMemory(Integer memory) {
this.memory = memory;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getStorageType() {
return storageType;
}
public void setStorageType(String storageType) {
this.storageType = storageType;
}
public Boolean getOfferHa() {
return offerHa;
}
public void setOfferHa(Boolean offerHa) {
this.offerHa = offerHa;
}
public Boolean getLimitCpuUse() {
return limitCpuUse;
}
public void setLimitCpuUse(Boolean limitCpuUse) {
this.limitCpuUse = limitCpuUse;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getDomainId() {
return domainId;
}
public void setDomainId(String domainId) {
this.domainId = domainId;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getHostTag() {
return hostTag;
}
public void setHostTag(String hostTag) {
this.hostTag = hostTag;
}
public void setNetworkRate(Integer networkRate) {
this.networkRate = networkRate;
}
public String getDeploymentPlanner() {
return deploymentPlanner;
}
public void setDeploymentPlanner(String deploymentPlanner) {
this.deploymentPlanner = deploymentPlanner;
}
public boolean getVolatileVm() {
return isVolatile;
}
public void setVolatileVm(boolean isVolatile) {
this.isVolatile = isVolatile;
}
public Boolean isCustomizedIops() {
return customizedIops;
}
public void setCustomizedIops(Boolean customizedIops) {
this.customizedIops = customizedIops;
}
public Long getMinIops() {
return minIops;
}
public void setMinIops(Long minIops) {
this.minIops = minIops;
}
public Long getMaxIops() {
return maxIops;
}
public void setMaxIops(Long maxIops) {
this.maxIops = maxIops;
}
public Integer getHypervisorSnapshotReserve() {
return hypervisorSnapshotReserve;
}
public void setHypervisorSnapshotReserve(Integer hypervisorSnapshotReserve) {
this.hypervisorSnapshotReserve = hypervisorSnapshotReserve;
}
public void setBytesReadRate(Long bytesReadRate) {
this.bytesReadRate = bytesReadRate;
}
public void setBytesWriteRate(Long bytesWriteRate) {
this.bytesWriteRate = bytesWriteRate;
}
public void setIopsReadRate(Long iopsReadRate) {
this.iopsReadRate = iopsReadRate;
}
public void setIopsWriteRate(Long iopsWriteRate) {
this.iopsWriteRate = iopsWriteRate;
}
public void setDetails(Map<String, String> details) {
this.details = details;
}
public void setIscutomized(boolean iscutomized) {
this.isCustomized = iscutomized;
}
}
| 27.408108 | 152 | 0.687112 |
d2d17de576c622ee933b113b4cb5f3cd4f67f09e | 9,961 | /*
* Elastic Cloud API
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.client.model.AllocatedInstancePlansInfo;
import io.swagger.v3.oas.annotations.media.Schema;
import java.io.IOException;
/**
* The status of the allocated Kibana instance or APM Server.
*/
@Schema(description = "The status of the allocated Kibana instance or APM Server.")
@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.JavaClientCodegen", date = "2020-03-10T16:33:30.970+05:30[Asia/Kolkata]")
public class AllocatedInstanceStatus {
@SerializedName("cluster_type")
private String clusterType = null;
@SerializedName("cluster_id")
private String clusterId = null;
@SerializedName("cluster_name")
private String clusterName = null;
@SerializedName("instance_name")
private String instanceName = null;
@SerializedName("node_memory")
private Integer nodeMemory = null;
@SerializedName("healthy")
private Boolean healthy = null;
@SerializedName("cluster_healthy")
private Boolean clusterHealthy = null;
@SerializedName("instance_configuration_id")
private String instanceConfigurationId = null;
@SerializedName("moving")
private Boolean moving = null;
@SerializedName("plans_info")
private AllocatedInstancePlansInfo plansInfo = null;
@SerializedName("deployment_id")
private String deploymentId = null;
public AllocatedInstanceStatus clusterType(String clusterType) {
this.clusterType = clusterType;
return this;
}
/**
* Type of instance that is running. E.g. elasticsearch, kibana
* @return clusterType
**/
@Schema(required = true, description = "Type of instance that is running. E.g. elasticsearch, kibana")
public String getClusterType() {
return clusterType;
}
public void setClusterType(String clusterType) {
this.clusterType = clusterType;
}
public AllocatedInstanceStatus clusterId(String clusterId) {
this.clusterId = clusterId;
return this;
}
/**
* Identifier for the cluster this instance belongs
* @return clusterId
**/
@Schema(required = true, description = "Identifier for the cluster this instance belongs")
public String getClusterId() {
return clusterId;
}
public void setClusterId(String clusterId) {
this.clusterId = clusterId;
}
public AllocatedInstanceStatus clusterName(String clusterName) {
this.clusterName = clusterName;
return this;
}
/**
* Name of cluster this instance belongs, if available
* @return clusterName
**/
@Schema(description = "Name of cluster this instance belongs, if available")
public String getClusterName() {
return clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public AllocatedInstanceStatus instanceName(String instanceName) {
this.instanceName = instanceName;
return this;
}
/**
* Instance ID of the instance
* @return instanceName
**/
@Schema(required = true, description = "Instance ID of the instance")
public String getInstanceName() {
return instanceName;
}
public void setInstanceName(String instanceName) {
this.instanceName = instanceName;
}
public AllocatedInstanceStatus nodeMemory(Integer nodeMemory) {
this.nodeMemory = nodeMemory;
return this;
}
/**
* Memory assigned to this instance
* @return nodeMemory
**/
@Schema(required = true, description = "Memory assigned to this instance")
public Integer getNodeMemory() {
return nodeMemory;
}
public void setNodeMemory(Integer nodeMemory) {
this.nodeMemory = nodeMemory;
}
public AllocatedInstanceStatus healthy(Boolean healthy) {
this.healthy = healthy;
return this;
}
/**
* Indicates whether the instance is healthy
* @return healthy
**/
@Schema(description = "Indicates whether the instance is healthy")
public Boolean isHealthy() {
return healthy;
}
public void setHealthy(Boolean healthy) {
this.healthy = healthy;
}
public AllocatedInstanceStatus clusterHealthy(Boolean clusterHealthy) {
this.clusterHealthy = clusterHealthy;
return this;
}
/**
* Indicates whether the cluster the instance belongs to is healthy
* @return clusterHealthy
**/
@Schema(description = "Indicates whether the cluster the instance belongs to is healthy")
public Boolean isClusterHealthy() {
return clusterHealthy;
}
public void setClusterHealthy(Boolean clusterHealthy) {
this.clusterHealthy = clusterHealthy;
}
public AllocatedInstanceStatus instanceConfigurationId(String instanceConfigurationId) {
this.instanceConfigurationId = instanceConfigurationId;
return this;
}
/**
* The instance configuration id of this instance
* @return instanceConfigurationId
**/
@Schema(description = "The instance configuration id of this instance")
public String getInstanceConfigurationId() {
return instanceConfigurationId;
}
public void setInstanceConfigurationId(String instanceConfigurationId) {
this.instanceConfigurationId = instanceConfigurationId;
}
public AllocatedInstanceStatus moving(Boolean moving) {
this.moving = moving;
return this;
}
/**
* Indicates whether the instance is vacating away from this allocator. Note that this is currently not populated when returned from the search endpoint.
* @return moving
**/
@Schema(description = "Indicates whether the instance is vacating away from this allocator. Note that this is currently not populated when returned from the search endpoint.")
public Boolean isMoving() {
return moving;
}
public void setMoving(Boolean moving) {
this.moving = moving;
}
public AllocatedInstanceStatus plansInfo(AllocatedInstancePlansInfo plansInfo) {
this.plansInfo = plansInfo;
return this;
}
/**
* Get plansInfo
* @return plansInfo
**/
@Schema(description = "")
public AllocatedInstancePlansInfo getPlansInfo() {
return plansInfo;
}
public void setPlansInfo(AllocatedInstancePlansInfo plansInfo) {
this.plansInfo = plansInfo;
}
public AllocatedInstanceStatus deploymentId(String deploymentId) {
this.deploymentId = deploymentId;
return this;
}
/**
* The id of the deployment this cluster belongs to.
* @return deploymentId
**/
@Schema(description = "The id of the deployment this cluster belongs to.")
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AllocatedInstanceStatus allocatedInstanceStatus = (AllocatedInstanceStatus) o;
return Objects.equals(this.clusterType, allocatedInstanceStatus.clusterType) &&
Objects.equals(this.clusterId, allocatedInstanceStatus.clusterId) &&
Objects.equals(this.clusterName, allocatedInstanceStatus.clusterName) &&
Objects.equals(this.instanceName, allocatedInstanceStatus.instanceName) &&
Objects.equals(this.nodeMemory, allocatedInstanceStatus.nodeMemory) &&
Objects.equals(this.healthy, allocatedInstanceStatus.healthy) &&
Objects.equals(this.clusterHealthy, allocatedInstanceStatus.clusterHealthy) &&
Objects.equals(this.instanceConfigurationId, allocatedInstanceStatus.instanceConfigurationId) &&
Objects.equals(this.moving, allocatedInstanceStatus.moving) &&
Objects.equals(this.plansInfo, allocatedInstanceStatus.plansInfo) &&
Objects.equals(this.deploymentId, allocatedInstanceStatus.deploymentId);
}
@Override
public int hashCode() {
return Objects.hash(clusterType, clusterId, clusterName, instanceName, nodeMemory, healthy, clusterHealthy, instanceConfigurationId, moving, plansInfo, deploymentId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class AllocatedInstanceStatus {\n");
sb.append(" clusterType: ").append(toIndentedString(clusterType)).append("\n");
sb.append(" clusterId: ").append(toIndentedString(clusterId)).append("\n");
sb.append(" clusterName: ").append(toIndentedString(clusterName)).append("\n");
sb.append(" instanceName: ").append(toIndentedString(instanceName)).append("\n");
sb.append(" nodeMemory: ").append(toIndentedString(nodeMemory)).append("\n");
sb.append(" healthy: ").append(toIndentedString(healthy)).append("\n");
sb.append(" clusterHealthy: ").append(toIndentedString(clusterHealthy)).append("\n");
sb.append(" instanceConfigurationId: ").append(toIndentedString(instanceConfigurationId)).append("\n");
sb.append(" moving: ").append(toIndentedString(moving)).append("\n");
sb.append(" plansInfo: ").append(toIndentedString(plansInfo)).append("\n");
sb.append(" deploymentId: ").append(toIndentedString(deploymentId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 30.839009 | 177 | 0.721815 |
155e600e9780caae913fff0562591ab532eedfcd | 6,859 | /**
* @author Ivan Chernukha on 06.02.17.
*/
package util.distributed;
import com.google.gson.Gson;
import com.mongodb.spark.MongoSpark;
import detection.Location;
import org.apache.log4j.Logger;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.*;
import org.apache.spark.sql.*;
import scala.Tuple2;
import util.HtmlUtil;
import util.MongoUtil;
import util.sequential.LDATopicDetector;
import java.util.*;
public class DistributedQuadManagerMongo {
static final Logger logger = Logger.getLogger(DistributedQuadManagerMongo.class);
private static Dataset<Row> dsQuad;
private static SparkSession sparkSession;
private static JavaSparkContext jsc;
private static JavaRDD<Row> smallestQuads;
/**
*
* @param args
*/
public static void main(String[] args) {
try {
logger.info("DistributedQuadManagerMongo started!");
jsc = createJavaSparkContext();
logger.info("SPARK conf created successfully!");
sparkSession = SparkSession.builder().getOrCreate();
logger.info("SPARKsession has been built successfully!");
//
dsQuad = MongoSpark.load(jsc).toDF();
logger.info("SPARK quads from mongodb retrieved successfully!");
// if (args[0].equals("true")){
computeTopicStatsSmallestQuads();
// }
//TODO: select quads inside given area
// JavaRDD<Tuple2<String,Integer>> computed = getStatsByMapReduce(smallestQuads);
// List<Tuple2<String, Integer>> compList = computed.collect();
computeAllTopics();
//TODO: aggregate stats by mongodb/spark
jsc.close();
} catch (Exception e){
logger.error("Failed " + e.getMessage());
}
}
private static JavaSparkContext createJavaSparkContext() {
String uri = getMongoClientURI();
SparkConf conf = new SparkConf()
.setMaster("spark://" + MongoUtil.HOST +":7077")
.setAppName("UrlMining")
.set("spark.mongodb.input.uri", uri)
.set("spark.mongodb.output.uri", uri);
return new JavaSparkContext(conf);
}
private static String getMongoClientURI() {
String uri;
uri = "mongodb://"+ MongoUtil.HOST + "/test.quad"; // default
return uri;
}
public Hashtable<Long, String> getTopics(Location topleft, double distanceToBottomRight, int S) {
// JavaMongoRDD<Document> aggregatedRdd = rddQuads.withPipeline()
return null;
}
public static void computeTopicStatsSmallestQuads() {
logger.info("computeTopicStatsSmallestQuads started");
try {
dsQuad.createOrReplaceTempView("smallestQuads");
Dataset<Row> smallestQuadsDS = sparkSession.sql(
"SELECT * from smallestQuads WHERE urls IS NOT NULL");
smallestQuadsDS.head(2);
smallestQuads = getRddWithTopics(smallestQuadsDS);
smallestQuads.collect();
logger.info("SUCCESS");
//save to mongodb
// MongoSpark.save(smallestQuads); // TODO:convert RDD<Row> to RDD<Document>
// .option("collection", "allquads").mode("overwrite").save();
} catch (Exception e) {
e.printStackTrace();
logger.error("computeTopicStatsSmallestQuads error " + e.getMessage());
}
logger.info("computeTopicStatsSmallestQuads finished");
}
private static void computeAllTopics() {
logger.info("computeAllTopics started");
try {
dsQuad.createOrReplaceTempView("quadsByLevel");
// for (int i = Quad.QUAD_SIDE_MIN; i < 2048; i *= 2 ) {
// int j = i * 2;
// Dataset<Row> quadsOnSameLevel = sparkSession.sql(
// "SELECT * from quadsByLevel WHERE qSide = " + Integer.toString(j));
// JavaRDD<Tuple2<String,Integer>> computed = getStatsByMapReduce(smallestQuads);
List<Tuple2<String, Integer>> computed = getStatsByMapReduce(smallestQuads);
// List<Tuple2<String, Integer>> compList = computed.collect();
//
// }
}catch (Exception e){
logger.error("computeAllTopics error " + e.getMessage());
}
logger.info("computeAllTopics finished");
}
private static JavaRDD<Row> getRddWithTopics(Dataset<Row> smallestQuads){
JavaRDD<Row> computedDS = smallestQuads.toJavaRDD().map(
new Function<Row, Row>(){
@Override
public Row call(Row row) throws Exception {
List<String> urls = row.getList(row.size() - 1);
// Hashtable<String, Integer> topicStats =
// .getTopicStatsByUrls(urls, HtmlUtil.PAGE_TYPE.URL_LOCATION);
// String json = new Gson().toJson(topicStats);
//
// Document doc = Document.parse(json);
// doc.append("qId", row.getLong(4));// qId
// doc.append("stats", topicStats);
// Row r = RowFactory.create(row.getLong(4), topicStats); //4 поле - qId
return null;
}
});
return computedDS;
}
/**
* Compute stats for all quads in quads by map reducing
*/
private static List<Tuple2<String, Integer>> getStatsByMapReduce(JavaRDD<Row> quads) {
JavaPairRDD<String,Integer> pairs = quads.flatMapToPair(new PairFlatMapFunction<Row, String, Integer>() {
@Override
public Iterator<Tuple2<String, Integer>> call(Row row) throws Exception {
HashMap<String,Integer> hashMap = (HashMap<String,Integer>)row.get(1);
Tuple2<String,Integer>[] tupleStats = new Tuple2[hashMap.size()];
int i = 0;
for(Map.Entry e: hashMap.entrySet()){
Tuple2<String,Integer> t = new Tuple2<>(
(String)e.getKey(),(Integer)e.getValue());
tupleStats[i] = t;
i++;
}
return Arrays.asList(tupleStats).iterator();
}
});
JavaPairRDD<String, Integer> counts = pairs.reduceByKey(new Function2<Integer, Integer, Integer>() {
@Override
public Integer call(Integer v1, Integer v2) throws Exception {
return v1 + v2;
}
});
List<Tuple2<String, Integer>> output = counts.collect();
return output;
}
}
| 36.291005 | 114 | 0.5858 |
3387540d93b98e048c8e1a3569a344c737290379 | 511 | package com.qintingfm.web.service.xmlrpc;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/**
* apache的StringSerializer有一个bug对于字符串没有生成string标签,有一些解析器会出错
*
* @author guliuzhong
*/
public class StringSerializer extends org.apache.xmlrpc.serializer.StringSerializer {
public StringSerializer() {
super();
}
@Override
public void write(ContentHandler pHandler, Object pObject) throws SAXException {
write(pHandler, STRING_TAG, pObject.toString());
}
}
| 24.333333 | 85 | 0.739726 |
fddf2eb9713194c8286dcacbc026b568c6bf8e2f | 1,892 | package tp6;
import common.ParticleGenerators;
import common.Vector2D;
import tp5.DynamicGridBeeman;
import tp5.GranularParticleStats;
import utils.PointDumper;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
private static double frameRate = 30;
private static Long seed = null;
private static int M = 8;
private static int N = 10;
private static float L = 20, W = 20, minRadius = 0.25f, maxRadius = 0.29f, mass = 65.0f, v = 2.25f;
private static double DeltaTime = 4E-4;
private static double k = 1.2E5, gamma = 100, mu = 0.1, kt = 2.4E5;
private static double D = 1.2;
private static double A = 2000;
private static double B = 0.08;
private static double tau = 0.5;
private static int dumpEach = (int) ((1.0/frameRate) / DeltaTime);
private static double pathRadius = 0.5;
public static void main(String[] args) throws Exception {
if(seed == null)
seed = System.currentTimeMillis();
System.out.println(seed);
Random r = new Random(seed);
List<Vector2D> list = new ArrayList<>();
list.add(new Vector2D(10, 0));
list.add(new Vector2D(10, -100));
DynamicGridPed grid = new DynamicGridPed(L, W, M, r, D, list, pathRadius);
ParticleGenerators.generatePedestrians(L, W, N, minRadius, maxRadius,v, mass, k, kt, gamma, mu, A,B,tau,r).forEach(grid::add);
PointDumper dumper = new PointDumper("./tp6/ovito/", PointDumper.FileMode.DYNAMIC, PointDumper.Dimensions._2D);
int frame = 0;
for (int i = 0; grid.size() > 0; i ++) {
boolean dump = i % dumpEach == 0;
grid.update(frame, DeltaTime, dumper, dump);
if(dump) {
frame++;
System.out.println(grid.size());
}
}
dumper.dumpPedStats();
}
}
| 34.4 | 134 | 0.622622 |
56de3db871f4fc38a6fb70f2d12726634112df2d | 2,898 | import java.util.*;
import org.junit.Test;
import static org.junit.Assert.*;
// LC452: https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/
//
// There are a number of spherical balloons spread in two-dimensional space. For
// each balloon, provided input is the start and end coordinates of the
// horizontal diameter. Since it's horizontal, y-coordinates don't matter and
// hence the x-coordinates of start and end of the diameter suffice. Start is
// always smaller than end. There will be at most 10 ^ 4 balloons.
// An arrow can be shot up exactly vertically from different points along the
// x-axis. A balloon with xstart and xend bursts by an arrow shot at x if
// xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot.
// An arrow once shot keeps travelling up infinitely. The problem is to find the
// minimum number of arrows that must be shot to burst all balloons.
public class MinArrowShots {
// Heap
// beats N/A(45 ms for 43 tests)
public int findMinArrowShots(int[][] points) {
PriorityQueue<int[]> pq = new PriorityQueue<int[]>(
new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[0] - b[0];
}
});
for (int[] p : points) {
pq.offer(p);
}
for (int count = 0;; count++) {
if (pq.isEmpty()) return count;
int[] p1 = pq.poll();
for (int end = p1[1]; !pq.isEmpty(); ) {
int[] p2 = pq.peek();
if (p2[0] <= end) {
end = Math.min(end, pq.poll()[1]);
} else break;
}
}
}
// Sort
// beats N/A(42 ms for 43 tests)
public int findMinArrowShots2(int[][] points) {
Arrays.sort(points, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[0] - b[0];
}
});
Integer end = null;
int count = 0;
for (int[] p : points) {
if (end == null || end < p[0]) {
end = p[1];
count++;
} else {
end = Math.min(end, p[1]);
}
}
return count;
}
void test(int[][] points, int expected) {
assertEquals(expected, findMinArrowShots(points));
assertEquals(expected, findMinArrowShots2(points));
}
@Test
public void test() {
test(new int[][] {{-2147483648, 2147483647}}, 1);
test(new int[][] {{1, 2}, {3, 4}, {5, 6}, {7, 8}}, 4);
test(new int[][] {}, 0);
test(new int[][] {{10, 16}, {2, 8}, {1, 6}, {7, 12}}, 2);
test(new int[][] {{9, 12}, {1, 10}, {4, 11}, {8, 12}, {3, 9}, {6, 9}, {6, 7}}, 2);
}
public static void main(String[] args) {
org.junit.runner.JUnitCore.main("MinArrowShots");
}
}
| 34.915663 | 90 | 0.532781 |
58812aada42472ffc18f85e4a358c4af93b4fb45 | 3,438 | /*
* Copyright 2015 Flipkart Internet Pvt. Ltd.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.appform.ranger.zookeeper.servicefinder;
import com.google.common.base.Preconditions;
import io.appform.ranger.core.finder.SimpleShardedServiceFinder;
import io.appform.ranger.core.finder.SimpleShardedServiceFinderBuilder;
import io.appform.ranger.core.model.NodeDataSource;
import io.appform.ranger.core.model.Service;
import io.appform.ranger.core.signals.Signal;
import io.appform.ranger.zookeeper.serde.ZkNodeDataDeserializer;
import io.appform.ranger.zookeeper.servicefinder.signals.ZkWatcherRegistryUpdateSignal;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import java.util.Collections;
import java.util.List;
/**
*
*/
@Slf4j
public class ZkSimpleShardedServiceFinderBuilder<T> extends SimpleShardedServiceFinderBuilder<T, ZkSimpleShardedServiceFinderBuilder<T>, ZkNodeDataDeserializer<T>> {
protected CuratorFramework curatorFramework;
protected String connectionString;
public ZkSimpleShardedServiceFinderBuilder<T> withCuratorFramework(CuratorFramework curatorFramework) {
this.curatorFramework = curatorFramework;
return this;
}
public ZkSimpleShardedServiceFinderBuilder<T> withConnectionString(final String connectionString) {
this.connectionString = connectionString;
return this;
}
@Override
public SimpleShardedServiceFinder<T> build() {
val curatorProvided = curatorFramework != null;
if (!curatorProvided) {
Preconditions.checkNotNull(connectionString);
curatorFramework = CuratorFrameworkFactory.builder()
.namespace(namespace)
.connectString(connectionString)
.retryPolicy(new ExponentialBackoffRetry(1000, 100)).build();
super.withStartSignalHandler(x -> curatorFramework.start());
super.withStopSignalHandler(x -> curatorFramework.close());
}
return buildFinder();
}
@Override
protected NodeDataSource<T, ZkNodeDataDeserializer<T>> dataSource(Service service) {
return new ZkNodeDataSource<>(service, curatorFramework);
}
@Override
protected List<Signal<T>> implementationSpecificRefreshSignals(final Service service, final NodeDataSource<T, ZkNodeDataDeserializer<T>> nodeDataSource) {
if (!disablePushUpdaters) {
return Collections.singletonList(
new ZkWatcherRegistryUpdateSignal<>(service, nodeDataSource, curatorFramework));
}
else {
log.info("Push based signal updater not registered for service: {}", service.getServiceName());
}
return Collections.emptyList();
}
}
| 40.447059 | 165 | 0.737638 |
26646c7604f6574e5f4b974ae0857c32b78236aa | 5,781 | package com.fundynamic.d2tm.game.map.renderer;
import com.fundynamic.d2tm.game.map.Map;
import com.fundynamic.d2tm.game.map.MapEditor;
import com.fundynamic.d2tm.game.terrain.TerrainFactory;
import com.fundynamic.d2tm.game.terrain.impl.DuneTerrain;
import com.fundynamic.d2tm.game.terrain.impl.DuneTerrainFactory;
import com.fundynamic.d2tm.graphics.Shroud;
import com.fundynamic.d2tm.graphics.Theme;
import com.fundynamic.d2tm.math.MapCoordinate;
import org.junit.Before;
import org.junit.Test;
import org.newdawn.slick.Image;
import static com.fundynamic.d2tm.game.map.Cell.TILE_SIZE;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
public class MapEditorTest {
private Shroud shroud;
private MapEditor mapEditor;
@Before
public void setUp() {
TerrainFactory terrainFactory = new DuneTerrainFactory(new Theme(mock(Image.class), TILE_SIZE));
shroud = new Shroud(mock(Image.class), TILE_SIZE);
mapEditor = new MapEditor(terrainFactory);
}
@Test
public void createMapOfCorrectDimensions() {
Map map = mapEditor.create(shroud, 3, 3, DuneTerrain.TERRAIN_ROCK);
assertThat(map.getHeight(), is(3));
assertThat(map.getWidth(), is(3));
}
@Test
public void createMapWithExpectedTerrain() {
Map map = mapEditor.create(shroud, 3, 3, DuneTerrain.TERRAIN_ROCK);
assertThat(map.getTerrainMap(), is(
"RRR\n" +
"RRR\n" +
"RRR\n"
));
}
@Test
public void mountainInCenterOf3By3MapHasFullRockCellsAroundIt() {
Map map = mapEditor.create(shroud, 3, 3, DuneTerrain.TERRAIN_ROCK);
mapEditor.putTerrainOnCell(map, MapCoordinate.create(2, 2), DuneTerrain.TERRAIN_MOUNTAIN);
assertThat(map.getTerrainMap(), is(
"RRR\n" +
"RMR\n" +
"RRR\n"
));
mapEditor.smooth(map);
assertThat(map.getTerrainFacing(2, 2), is(MapEditor.TerrainFacing.SINGLE));
// full rock facing entirely
// left side
assertThat(map.getTerrainFacing(1, 1), is(MapEditor.TerrainFacing.FULL));
assertThat(map.getTerrainFacing(1, 2), is(MapEditor.TerrainFacing.FULL));
assertThat(map.getTerrainFacing(1, 3), is(MapEditor.TerrainFacing.FULL));
// top and bottom
assertThat(map.getTerrainFacing(2, 1), is(MapEditor.TerrainFacing.FULL));
assertThat(map.getTerrainFacing(2, 3), is(MapEditor.TerrainFacing.FULL));
// right side
assertThat(map.getTerrainFacing(3, 1), is(MapEditor.TerrainFacing.FULL));
assertThat(map.getTerrainFacing(3, 2), is(MapEditor.TerrainFacing.FULL));
assertThat(map.getTerrainFacing(3, 3), is(MapEditor.TerrainFacing.FULL));
}
@Test
public void spiceHillInCenterOf3By3MapHasFullSpiceCellsAroundIt() {
Map map = mapEditor.create(shroud, 3, 3, DuneTerrain.TERRAIN_SPICE);
mapEditor.putTerrainOnCell(map, MapCoordinate.create(2, 2), DuneTerrain.TERRAIN_SPICE_HILL);
assertThat(map.getTerrainMap(), is(
"###\n" +
"#H#\n" +
"###\n"
));
mapEditor.smooth(map);
assertThat(map.getTerrainFacing(2, 2), is(MapEditor.TerrainFacing.SINGLE));
// full rock facing entirely
// left side
assertThat(map.getTerrainFacing(1, 1), is(MapEditor.TerrainFacing.FULL));
assertThat(map.getTerrainFacing(1, 2), is(MapEditor.TerrainFacing.FULL));
assertThat(map.getTerrainFacing(1, 3), is(MapEditor.TerrainFacing.FULL));
// top and bottom
assertThat(map.getTerrainFacing(2, 1), is(MapEditor.TerrainFacing.FULL));
assertThat(map.getTerrainFacing(2, 3), is(MapEditor.TerrainFacing.FULL));
// right side
assertThat(map.getTerrainFacing(3, 1), is(MapEditor.TerrainFacing.FULL));
assertThat(map.getTerrainFacing(3, 2), is(MapEditor.TerrainFacing.FULL));
assertThat(map.getTerrainFacing(3, 3), is(MapEditor.TerrainFacing.FULL));
}
@Test
public void canGenerateRandomMap() {
int width = 33;
int height = 63;
Map map = mapEditor.generateRandom(shroud, width, height);
assertThat(map.getWidth(), is(width));
assertThat(map.getHeight(), is(height));
}
@Test
public void returnsMiddleWhenNoSameTypeOfNeighbours() throws Exception {
assertEquals(MapEditor.TerrainFacing.SINGLE, MapEditor.getFacing(false, false, false, false));
}
@Test
public void returnsTopWhenDifferentTypeAbove() throws Exception {
assertEquals(MapEditor.TerrainFacing.TOP, MapEditor.getFacing(false, true, true, true));
}
@Test
public void returnsRightWhenDifferentTypeRight() throws Exception {
assertEquals(MapEditor.TerrainFacing.RIGHT, MapEditor.getFacing(true, false, true, true));
}
@Test
public void returnsBottomWhenDifferentTypeBottom() throws Exception {
assertEquals(MapEditor.TerrainFacing.BOTTOM, MapEditor.getFacing(true, true, false, true));
}
@Test
public void returnsLeftWhenDifferentTypeLeft() throws Exception {
assertEquals(MapEditor.TerrainFacing.LEFT, MapEditor.getFacing(true, true, true, false));
}
@Test
public void returnsTopRightWhenSameTypeBottomAndLeft() throws Exception {
assertEquals(MapEditor.TerrainFacing.TOP_RIGHT, MapEditor.getFacing(false, false, true, true));
}
@Test
public void returnsFullWhenAllSameTypeOfNeighbours() throws Exception {
assertEquals(MapEditor.TerrainFacing.FULL, MapEditor.getFacing(true, true, true, true));
}
} | 35.685185 | 104 | 0.682581 |
aa44816bd8a47c464142332b8b9ab35425bbabb0 | 4,498 | package com.uludag.can.dagger2_sample_app.ui.newslist;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ProgressBar;
import com.uludag.can.dagger2_sample_app.R;
import com.uludag.can.dagger2_sample_app.listeners.NewsListCardOnClickListener;
import com.uludag.can.dagger2_sample_app.model.Article;
import com.uludag.can.dagger2_sample_app.model.ArticlesResponse;
import com.uludag.can.dagger2_sample_app.networking.NewsApiService;
import com.uludag.can.dagger2_sample_app.root.NewsApplication;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class NewsListActivity extends AppCompatActivity implements NewsListCardOnClickListener{
@BindView(R.id.news_list_container)
ConstraintLayout newsListContainer;
@BindView(R.id.newslist_recyclerview)
RecyclerView newsListRecyclerView;
@BindView(R.id.news_list_progressbar)
ProgressBar newsListProgressbar;
@Inject
Context mContext;
@Inject
NewsApiService mNewsApiService;
private List<Article> mArticles;
private NewsListAdapter mNewsListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_list);
ButterKnife.bind(this);
// Initialize injection for this activity
((NewsApplication) getApplication()).getNewsApplicationComponent().inject(this);
setupRecyclerView();
getArticles();
}
private void setupRecyclerView() {
newsListRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
newsListRecyclerView.setHasFixedSize(true);
}
private void setAdapterForRecyclerView(List<Article> articles) {
mNewsListAdapter = new NewsListAdapter(articles, this);
newsListRecyclerView.setAdapter(mNewsListAdapter);
}
private void getArticles() {
mNewsApiService.getArticles("techcrunch").enqueue(new Callback<ArticlesResponse>() {
@Override
public void onResponse(Call<ArticlesResponse> call, Response<ArticlesResponse> response) {
ArticlesResponse articlesResponse = response.body();
if (articlesResponse != null) {
mArticles = articlesResponse.getArticles();
setAdapterForRecyclerView(mArticles);
newsListProgressbar.setVisibility(View.GONE);
} else {
Snackbar errorSnackBar = createSnackBar("An error occured");
errorSnackBar.setAction("Retry", new View.OnClickListener() {
@Override
public void onClick(View v) {
getArticles();
}
});
errorSnackBar.show();
}
}
@Override
public void onFailure(Call<ArticlesResponse> call, Throwable t) {
Snackbar errorSnackBar = createSnackBar("An error occured");
errorSnackBar.setAction("Retry", new View.OnClickListener() {
@Override
public void onClick(View v) {
getArticles();
}
});
errorSnackBar.show();
}
});
}
private Snackbar createSnackBar(String message) {
return Snackbar.make(newsListContainer, message, Snackbar.LENGTH_LONG);
}
@Override
public void onCardClick(final Article selectedArticle) {
Snackbar cardClickSnackbar = createSnackBar(selectedArticle.getTitle());
cardClickSnackbar.setAction("Go to website", new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(selectedArticle.getUrl()));
startActivity(i);
}
});
cardClickSnackbar.show();
}
}
| 33.318519 | 102 | 0.663851 |
6b3a858736451a2f0f8597e4e05eb67165e1badc | 994 | /*
* Created on Mar 8, 2010
*/
package gov.fnal.elab.analysis;
import gov.fnal.elab.analysis.notifiers.DefaultAnalysisNotifier;
import gov.fnal.elab.analysis.notifiers.UploadNotifier;
import java.util.HashMap;
import java.util.Map;
public class AnalysisNotifierFactory {
private static final Map<String, Class<? extends AnalysisNotifier>> NOTIFIERS;
static {
NOTIFIERS = new HashMap<String, Class<? extends AnalysisNotifier>>();
NOTIFIERS.put("default", DefaultAnalysisNotifier.class);
NOTIFIERS.put("upload", UploadNotifier.class);
}
public static AnalysisNotifier newNotifier(String type) {
Class<? extends AnalysisNotifier> cls = NOTIFIERS.get(type);
if (cls == null) {
throw new IllegalArgumentException("No such notifier type: " + type);
}
try {
return cls.newInstance();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 28.4 | 82 | 0.652918 |
2aadabe1a240a3aa38c36362161f0776df823c7c | 4,174 | package agp.ajax;
import static agp.ajax.AjaxHandler.FILENAME;
import static agp.ajax.AjaxHandler.FILE_PARAMETER;
import static agp.ajax.AjaxHandler.PENDING;
import static agp.ajax.AjaxHandler.PENDING_FILE;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
public class AjaxServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
AjaxHandler handler;
public void init(ServletConfig config) throws ServletException {
super.init(config);
String handlerClass = getServletConfig().getInitParameter("handler-class");
Class<?> clazz;
try {
clazz = Class.forName(handlerClass);
handler = (AjaxHandler) clazz.newInstance();
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
throw new RuntimeException("Incorrect parameter handler-class in portlet.xml");
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
GenericSession session = new GenericSession(request.getSession());
if (PENDING.equals(request.getParameter(FILE_PARAMETER))) {
fileResponse(response, session);
} else {
renderResponse(request, response, session);
}
}
private void renderResponse(HttpServletRequest request, HttpServletResponse response, GenericSession session)
throws ServletException, IOException {
String page = request.getParameter("page");
if (page == null) // if this is the initial render
page = handler.getDefaultPage();
String csrfToken = CsrfUtils.registerCSRFToken(session, page);
request.setAttribute("ajaxUrl", request.getRequestURL().toString() + "?page=" + page);
request.setAttribute("csrfToken", csrfToken);
RequestDispatcher disp = request.getRequestDispatcher(page + ".jsp");
disp.forward(request, response);
}
private void fileResponse(HttpServletResponse response, GenericSession session) throws IOException {
byte[] file = (byte[]) session.getAttribute(PENDING_FILE);
OutputStream os = response.getOutputStream();
os.write(file);
response.setHeader("Content-Disposition", "attachment; filename=" + session.getAttribute(FILENAME));
os.close();
session.removeAttribute(FILENAME);
session.removeAttribute(PENDING_FILE);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
String payload = IOUtils.toString(request.getReader());
String csrfToken = request.getHeader("csrf-token");
GenericSession session = new GenericSession(request.getSession());
String page = request.getParameter("page");
CsrfUtils.validateCSRFToken(page, csrfToken, session);
GenericResponse handlerResponse = handler.handleAjaxRequest(payload, page, session);
checkForFileResponse(handlerResponse, request, session);
checkForRedirectResponse(handlerResponse, request);
PrintWriter writer = response.getWriter();
writer.write(handlerResponse.getResponse());
}
private void checkForFileResponse(GenericResponse handlerResponse, HttpServletRequest request,
GenericSession session) {
if (ResponseType.FILE.equals(handlerResponse.getResponseType())) {
String url = request.getRequestURL().toString() + "?" + FILE_PARAMETER + "=" + PENDING;
session.setAttribute(PENDING_FILE, handlerResponse.getFile());
session.setAttribute(FILENAME, handlerResponse.getResponse());
AjaxHandler.convertResponseToRedirect(handlerResponse, url);
}
}
private void checkForRedirectResponse(GenericResponse handlerResponse, HttpServletRequest request) {
if (ResponseType.REDIRECT.equals(handlerResponse.getResponseType())) {
String url = request.getRequestURL().toString() + "?page=" + handlerResponse.getResponse();
AjaxHandler.convertResponseToRedirect(handlerResponse, url.toString());
}
}
}
| 40.134615 | 116 | 0.764015 |
b7016d919d52f12d7615a400ceb9249575b31a98 | 629 | package unsw.graphics.world;
/**
* A collection of useful math methods
*
* @author malcolmr
*/
public class MathUtil {
/**
* Normalise an angle to the range [-180, 180)
*
* @param angle
* @return
*/
public static float normaliseAngle(float angle) {
return ((angle + 180f) % 360f + 360f) % 360f - 180f;
}
/**
* Clamp a value to the given range
*
* @param value
* @param min
* @param max
* @return
*/
public static float clamp(float value, float min, float max) {
return Math.max(min, Math.min(max, value));
}
}
| 19.060606 | 66 | 0.5469 |
fa43e4858242b63044732b53b04fa6353a38d4ea | 5,070 | package com.ayush.user.dao.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
import com.ayush.user.dao.UserDAO;
import com.ayush.user.model.User;
public class SimpleJdbcUserDAO extends SimpleJdbcDaoSupport implements UserDAO {
// insert using placeholder and sequence is important
public void insert(User user) {
String sql = "INSERT INTO USERS " +
"(USER_ID, FIRST_NAME, LAST_NAME, MOBILE, EMAIL_ID, DOB, CREATED_BY, CREATION_DATE) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
getSimpleJdbcTemplate().update(sql,
user.getUser_id(),
user.getFirst_name(),
user.getLast_name(),
user.getMobile(),
user.getEmail_id(),
user.getDob(),
user.getCreated_by(),
user.getCreation_date()
);
}
// insert using named parameters. sequence is not important. we can use our own names after colon.
public void insertNamedParameter(User user) {
String sql = "INSERT INTO USERS " +
"(USER_ID, FIRST_NAME, LAST_NAME, MOBILE, EMAIL_ID, DOB, CREATED_BY, CREATION_DATE) VALUES (:user_id, :first_name, :last_name, :mobile, :email_id, :dob, :created_by, :creation_date)";
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("user_id", user.getUser_id());
parameters.put("first_name", user.getFirst_name());
parameters.put("last_name", user.getLast_name());
parameters.put("mobile", user.getMobile());
parameters.put("email_id", user.getEmail_id());
parameters.put("dob", user.getDob());
parameters.put("created_by", user.getCreated_by());
parameters.put("creation_date", user.getCreation_date());
getSimpleJdbcTemplate().update(sql, parameters);
}
public void insertBatch(List<User> users) {
String sql = "INSERT INTO USERS " +
"(USER_ID, FIRST_NAME, LAST_NAME, MOBILE, EMAIL_ID, DOB, CREATED_BY, CREATION_DATE) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
List<Object[]> parameters = new ArrayList<Object[]>();
for (User user : users) {
parameters.add(new Object[] {user.getUser_id(), user.getFirst_name(), user.getLast_name(), user.getMobile(), user.getEmail_id(), user.getDob(), user.getCreated_by(), user.getCreation_date()});
}
getSimpleJdbcTemplate().batchUpdate(sql, parameters);
}
public void insertBatchNamedParameter(List<User> users) {
String sql = "INSERT INTO USERS " +
"(USER_ID, FIRST_NAME, LAST_NAME, MOBILE, EMAIL_ID, DOB, CREATED_BY, CREATION_DATE) VALUES (:user_id, :first_name, :last_name, :mobile, :email_id, :dob, :created_by, :creation_date)";
List<SqlParameterSource> parameters = new ArrayList<SqlParameterSource>();
for (User user : users) {
parameters.add(new BeanPropertySqlParameterSource(user));
}
getSimpleJdbcTemplate().batchUpdate(sql,
parameters.toArray(new SqlParameterSource[0]));
}
public void insertBatchNamedParameter2(List<User> users) {
SqlParameterSource[] params = SqlParameterSourceUtils.createBatch(users.toArray());
getSimpleJdbcTemplate().batchUpdate(
"INSERT INTO USERS (USER_ID, FIRST_NAME, LAST_NAME, MOBILE, EMAIL_ID, DOB, CREATED_BY, CREATION_DATE) VALUES (:user_id, :first_name, :last_name, :mobile, :email_id, :dob, :created_by, :creation_date)",
params);
}
public void insertBatchSQL(String sql) {
getJdbcTemplate().batchUpdate(new String[]{sql});
}
public User findByUserId(int user_id) {
//custom parameterized row mapper is used when fields in table and pojo class is not same
return null;
}
public User findByUserId2(int user_id) {
String sql = "SELECT * FROM USERS WHERE USER_ID = ?";
User user = getSimpleJdbcTemplate().queryForObject(
sql,ParameterizedBeanPropertyRowMapper.newInstance(User.class), user_id);
return user;
}
public List<User> findAll() {
String sql = "SELECT * FROM USERS";
List<User> users =
getSimpleJdbcTemplate().query(sql, ParameterizedBeanPropertyRowMapper.newInstance(User.class));
return users;
}
public List<User> findAll2() {
String sql = "SELECT * FROM USERS";
List<User> users =
getSimpleJdbcTemplate().query(sql, ParameterizedBeanPropertyRowMapper.newInstance(User.class));
return users;
}
public String findUserNameById(int user_id) {
String sql = "SELECT NAME FROM USERS WHERE USER_ID = ?";
String name = getSimpleJdbcTemplate().queryForObject(
sql, String.class, user_id);
return name;
}
public int findTotalUser() {
String sql = "SELECT COUNT(*) FROM USERS";
int total = getSimpleJdbcTemplate().queryForInt(sql);
return total;
}
}
| 34.256757 | 217 | 0.702367 |
27757e28eb7c26a30599e4d38e951bb186a9d16c | 7,949 | /*
* Copyright 2014-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.dbflute.properties;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.torque.engine.database.model.Table;
import org.dbflute.helper.message.ExceptionMessageBuilder;
import org.dbflute.properties.assistant.base.DfTableListProvider;
import org.dbflute.util.DfTypeUtil;
import org.dbflute.util.Srl;
/**
* @author jflute
* @since 0.8.8.1 (2009/01/09 Friday)
*/
public final class DfOptimisticLockProperties extends DfAbstractDBFluteProperties {
// ===================================================================================
// Constructor
// ===========
/**
* @param prop Properties. (NotNull)
*/
public DfOptimisticLockProperties(Properties prop) {
super(prop);
}
// ===================================================================================
// Optimistic Lock Definition Map
// ==============================
public static final String KEY_optimisticLockMap = "optimisticLockMap";
public static final String KEY_oldOptimisticLockMap = "optimisticLockDefinitionMap";
protected Map<String, Object> _optimisticLockMap;
public Map<String, Object> getOptimisticLockMap() {
if (_optimisticLockMap == null) {
Map<String, Object> map = mapProp("torque." + KEY_optimisticLockMap, null);
if (map == null) {
map = getLittleAdjustmentProperties().getOptimisticLockFacadeMap(); // primary @since 1.1.0-sp3
if (map == null) {
map = mapProp("torque." + KEY_oldOptimisticLockMap, DEFAULT_EMPTY_MAP); // for compatible
}
}
_optimisticLockMap = newLinkedHashMap();
_optimisticLockMap.putAll(map);
}
return _optimisticLockMap;
}
// -----------------------------------------------------
// Check Definition
// ----------------
public void checkDefinition(DfTableListProvider provider) {
if (!hasExplicitOptimisticLockColumn()) {
return;
}
final List<Table> tableList = provider.provideTableList();
boolean exists = false;
for (Table table : tableList) {
if (table.hasOptimisticLock()) {
exists = true;
break;
}
}
if (!exists) {
throwOptimisticLockRelatedTableNotFoundException();
}
}
protected void throwOptimisticLockRelatedTableNotFoundException() {
final ExceptionMessageBuilder br = new ExceptionMessageBuilder();
br.addNotice("The table related to optimistic lock was not found.");
br.addItem("Advice");
br.addElement("At least one table should be related to optimistic lock");
br.addElement("when the optimistic lock column is specified explicitly.");
br.addElement("Make sure your definition is correct.");
br.addItem("Specified Column");
br.addElement(getExplicitOptimisticLockColumn());
final String msg = br.buildExceptionMessage();
throw new DfOptimisticLockRelatedTableNotFoundException(msg);
}
public static class DfOptimisticLockRelatedTableNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public DfOptimisticLockRelatedTableNotFoundException(String msg) {
super(msg);
}
}
protected boolean hasExplicitOptimisticLockColumn() {
return getExplicitOptimisticLockColumn() != null;
}
protected String getExplicitOptimisticLockColumn() {
final String updateDateFieldName = doGetUpdateDateFieldName(""); // as no default
if (Srl.is_NotNull_and_NotTrimmedEmpty(updateDateFieldName)) {
return updateDateFieldName;
}
final String versionNoFieldName = doGetVersionNoFieldName(""); // as no default
if (Srl.is_NotNull_and_NotTrimmedEmpty(versionNoFieldName)) {
return versionNoFieldName;
}
return null;
}
// ===================================================================================
// Field Name
// ==========
public String getUpdateDateFieldName() {
return doGetUpdateDateFieldName("");
}
protected String doGetUpdateDateFieldName(String defaultValue) {
return getProperty("updateDateFieldName", defaultValue);
}
public String getVersionNoFieldName() {
return doGetVersionNoFieldName("version_no");
}
protected String doGetVersionNoFieldName(String defaultValue) {
return getProperty("versionNoFieldName", defaultValue);
}
public boolean isOptimisticLockColumn(String columnName) {
final String updateDate = getUpdateDateFieldName();
if (Srl.is_NotNull_and_NotTrimmedEmpty(updateDate) && updateDate.equalsIgnoreCase(columnName)) {
return true;
}
final String versionNo = getVersionNoFieldName();
if (Srl.is_NotNull_and_NotTrimmedEmpty(versionNo) && versionNo.equalsIgnoreCase(columnName)) {
return true;
}
return false;
}
// ===================================================================================
// Property Helper
// ===============
protected String getProperty(String key, String defaultValue) {
Map<String, Object> map = getOptimisticLockMap();
Object obj = map.get(key);
if (obj != null) {
if (!(obj instanceof String)) {
String msg = "The key's value should be string:";
msg = msg + " " + DfTypeUtil.toClassTitle(obj) + "=" + obj;
throw new IllegalStateException(msg);
}
String value = (String) obj;
if (value.trim().length() > 0) {
return value;
} else {
return defaultValue;
}
}
return stringProp("torque." + key, defaultValue);
}
protected boolean isProperty(String key, boolean defaultValue) {
Map<String, Object> map = getOptimisticLockMap();
Object obj = map.get(key);
if (obj != null) {
if (!(obj instanceof String)) {
String msg = "The key's value should be boolean:";
msg = msg + " " + DfTypeUtil.toClassTitle(obj) + "=" + obj;
throw new IllegalStateException(msg);
}
String value = (String) obj;
if (value.trim().length() > 0) {
return value.trim().equalsIgnoreCase("true");
} else {
return defaultValue;
}
}
return booleanProp("torque." + key, defaultValue);
}
} | 40.974227 | 111 | 0.548622 |
b0f562b9d26a52faa6516030b5911bb8b6a105e5 | 2,440 | /*******************************************************************************
* Copyright 2019 T-Mobile USA, 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.
* See the LICENSE file for additional language around disclaimer of warranties.
* Trademark Disclaimer: Neither the name of "T-Mobile, USA" nor the names of
* its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
******************************************************************************/
package com.tmobile.kardio.bean;
/**
* HealthCheckTypeVO this stores the health check type details Health Check type listing
*
*/
public class HealthCheckTypeVO {
private int healthCheckTypeId;
private String healthCheckTypeName;
private String healthCheckTypeDesc;
/**
* @return the healthCheckTypeId
*/
public int getHealthCheckTypeId() {
return healthCheckTypeId;
}
/**
* @param healthCheckTypeId
* the healthCheckTypeId to set
*/
public void setHealthCheckTypeId(int healthCheckTypeId) {
this.healthCheckTypeId = healthCheckTypeId;
}
/**
* @return the healthCheckTypeName
*/
public String getHealthCheckTypeName() {
return healthCheckTypeName;
}
/**
* @param healthCheckTypeName
* the healthCheckTypeName to set
*/
public void setHealthCheckTypeName(String healthCheckTypeName) {
this.healthCheckTypeName = healthCheckTypeName;
}
/**
* @return the healthCheckTypeDesc
*/
public String getHealthCheckTypeDesc() {
return healthCheckTypeDesc;
}
/**
* @param healthCheckTypeDesc
* the healthCheckTypeDesc to set
*/
public void setHealthCheckTypeDesc(String healthCheckTypeDesc) {
this.healthCheckTypeDesc = healthCheckTypeDesc;
}
}
| 31.282051 | 88 | 0.64877 |
a324c230b2301c9e89ee42622da0e96404f394a6 | 1,921 | /*
* Copyright 2015-2016 Boundless, http://boundlessgeo.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License
*
*/
package com.boundlessgeo;
import java.util.Collection;
import com.boundlessgeo.module.GeoHeatmapModule;
import com.boundlessgeo.rest.GeoHeatmapRestAction;
import com.boundlessgeo.service.GeoHeatmapService;
import org.elasticsearch.common.component.LifecycleComponent;
import org.elasticsearch.common.inject.Module;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.rest.RestModule;
import com.google.common.collect.Lists;
public class GeoHeatmapPlugin extends Plugin {
@Override
public String name() {
return "GeoHeatmapPlugin";
}
@Override
public String description() {
return "This is a elasticsearch-heatmap plugin.";
}
public void onModule(final RestModule module) {
module.addRestAction(GeoHeatmapRestAction.class);
}
@Override
public Collection<Module> nodeModules() {
final Collection<Module> modules = Lists.newArrayList();
modules.add(new GeoHeatmapModule());
return modules;
}
@SuppressWarnings("rawtypes")
@Override
public Collection<Class<? extends LifecycleComponent>> nodeServices() {
final Collection<Class<? extends LifecycleComponent>> services = Lists.newArrayList();
services.add(GeoHeatmapService.class);
return services;
}
}
| 31.491803 | 100 | 0.735554 |
c7122f9e9e00028cc02000878aef3595909d3f34 | 3,649 | package compilation.analysis.syntax;
import org.junit.jupiter.api.Test;
import types.ExpressionType;
import util.TestFactory;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ParserTest
{
@Test
public void parserIdentifiesLiteralExpression()
{
String message = "Failed to identify literal expression: ";
HashMap<String, Object> literalCollection = TestFactory.literalCollection();
literalCollection.forEach((input, redundant) -> {
ExpressionType actual = expressionTypeOf(input);
ExpressionType expected = ExpressionType.LITERAL_EXPRESSION;
assertEquals(expected, actual, message + input);
});
}
@Test
public void parserIdentifiesUnaryExpression()
{
String message = "Failed to identify unary expression: ";
HashMap<String, Object> unaryCollection = TestFactory.unaryCollection();
unaryCollection.forEach((input, redundant) -> {
ExpressionType actual = expressionTypeOf(input);
ExpressionType expected = ExpressionType.UNARY_EXPRESSION;
assertEquals(expected, actual, message + input);
});
}
@Test
public void parserIdentifiesBinaryExpression()
{
String message = "Failed to identify binary expression: ";
HashMap<String, Object> binaryCollection = TestFactory.binaryCollection();
binaryCollection.forEach((input, redundant) -> {
ExpressionType actual = expressionTypeOf(input);
ExpressionType expected = ExpressionType.BINARY_EXPRESSION;
assertEquals(expected, actual, message + input);
});
}
@Test
public void parserIdentifiesIdentifierExpression()
{
String message = "Failed to identify identifier expression: ";
HashMap<String, Object> identifierCollection = TestFactory.identifierCollection();
identifierCollection.forEach((input, redundant) -> {
ExpressionType actual = expressionTypeOf(input);
ExpressionType expected = ExpressionType.IDENTIFIER_EXPRESSION;
assertEquals(expected, actual, message + input);
});
}
@Test
public void parserIdentifiesAssignmentExpression()
{
String message = "Failed to identify assignment expression: ";
HashMap<String, Object> assignmentCollection = TestFactory.assignmentCollection();
assignmentCollection.forEach((input, redundant) -> {
ExpressionType actual = expressionTypeOf(input);
ExpressionType expected = ExpressionType.ASSIGNMENT_EXPRESSION;
assertEquals(expected, actual, message + input);
});
}
@Test
public void parserIdentifiesParenthesizedExpression()
{
String message = "Failed to identify parenthesized expression: ";
HashMap<String, Object> parenthesizedCollection = TestFactory.parenthesizedCollection();
parenthesizedCollection.forEach((input, redundant) -> {
ExpressionType actual = expressionTypeOf(input);
ExpressionType expected = ExpressionType.PARENTHESIZED_EXPRESSION;
assertEquals(expected, actual, message + input);
});
}
private static ExpressionType expressionTypeOf(String input)
{
Parser parser = TestFactory.createParser(input, true);
SourceStatement statement = (SourceStatement) parser.getParseTree().getStatement();
ExpressionStatement expression = (ExpressionStatement) statement.getStatements().get(0);
return expression.getExpression().getExpressionType();
}
}
| 36.49 | 96 | 0.685941 |
70d2c46cbe89569310f2b24c3d830e2300138558 | 3,273 | /* Copyright (C) 2017-2019 Andreas Shimokawa, Carsten Pfeiffer
This file is part of Gadgetbridge.
Gadgetbridge is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Gadgetbridge is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package nodomain.freeyourgadget.gadgetbridge.service.devices.huami.amazfitcor;
import android.content.Context;
import android.net.Uri;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Set;
import nodomain.freeyourgadget.gadgetbridge.devices.huami.HuamiCoordinator;
import nodomain.freeyourgadget.gadgetbridge.devices.huami.HuamiFWHelper;
import nodomain.freeyourgadget.gadgetbridge.devices.huami.HuamiService;
import nodomain.freeyourgadget.gadgetbridge.devices.huami.amazfitcor.AmazfitCorFWHelper;
import nodomain.freeyourgadget.gadgetbridge.devices.huami.amazfitcor.AmazfitCorService;
import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder;
import nodomain.freeyourgadget.gadgetbridge.service.devices.huami.amazfitbip.AmazfitBipSupport;
public class AmazfitCorSupport extends AmazfitBipSupport {
private static final Logger LOG = LoggerFactory.getLogger(AmazfitCorSupport.class);
@Override
protected AmazfitCorSupport setDisplayItems(TransactionBuilder builder) {
Set<String> pages = HuamiCoordinator.getDisplayItems(getDevice().getAddress());
LOG.info("Setting display items to " + (pages == null ? "none" : pages));
byte[] command = AmazfitCorService.COMMAND_CHANGE_SCREENS.clone();
if (pages != null) {
if (pages.contains("status")) {
command[1] |= 0x02;
}
if (pages.contains("notifications")) {
command[1] |= 0x04;
}
if (pages.contains("activity")) {
command[1] |= 0x08;
}
if (pages.contains("weather")) {
command[1] |= 0x10;
}
if (pages.contains("alarm")) {
command[1] |= 0x20;
}
if (pages.contains("timer")) {
command[1] |= 0x40;
}
if (pages.contains("settings")) {
command[1] |= 0x80;
}
if (pages.contains("alipay")) {
command[2] |= 0x01;
}
if (pages.contains("music")) {
command[2] |= 0x02;
}
}
builder.write(getCharacteristic(HuamiService.UUID_CHARACTERISTIC_3_CONFIGURATION), command);
return this;
}
@Override
public HuamiFWHelper createFWHelper(Uri uri, Context context) throws IOException {
return new AmazfitCorFWHelper(uri, context);
}
}
| 38.05814 | 100 | 0.667278 |
6e4f0f51cbc4814ef3350d55de4d8df0c1d9817d | 527 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.android.gms.common.api;
// Referenced classes of package com.google.android.gms.common.api:
// Api
public static final class Api$ApiOptions$NoOptions
implements dOptions
{
private Api$ApiOptions$NoOptions()
{
// 0 0:aload_0
// 1 1:invokespecial #16 <Method void Object()>
// 2 4:return
}
}
| 23.954545 | 67 | 0.673624 |
d5264d340889ebd2fcdf06f34b5066a81c33a67c | 364 | /**
*
*/
package com.cloderia.helion.client.shared.service;
import com.cloderia.helion.client.shared.model.Depreciationmethod;
import com.cloderia.helion.client.shared.ops.DepreciationmethodOperation;
/**
* @author Edward Banfa
*
*/
public interface DepreciationmethodService extends BaseEntityService<Depreciationmethod, DepreciationmethodOperation> {
}
| 22.75 | 119 | 0.802198 |
8b260d9441532952ea3cae899508e0df80dddc43 | 2,707 | /*******************************************************************************
* Software Name : RCS IMS Stack
*
* Copyright (C) 2010-2016 Orange.
*
* 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.gsma.rcs.ri.utils;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import java.util.ArrayList;
/**
* Parses a text message typed by the user looking for smileys.
*/
public class SmileyParser extends AbstractMessageParser {
private Smileys mRes;
public SmileyParser(String text, Smileys res) {
super(text, true, // smileys
false, // acronyms
false, // formatting
false, // urls
false, // music
false // me text
);
mRes = res;
}
@Override
protected Resources getResources() {
return mRes;
}
/**
* Retrieves the parsed text as a spannable string object.
*
* @param context the context for fetching smiley resources.
* @return the spannable string as CharSequence.
*/
public CharSequence getSpannableString(Context context) {
SpannableStringBuilder builder = new SpannableStringBuilder();
if (getPartCount() == 0) {
return "";
}
// should have only one part since we parse smiley only
Part part = getPart(0);
ArrayList<Token> tokens = part.getTokens();
int len = tokens.size();
for (int i = 0; i < len; i++) {
Token token = tokens.get(i);
int start = builder.length();
builder.append(token.getRawText());
if (token.getType() == AbstractMessageParser.Token.Type.SMILEY) {
int resid = mRes.getSmileyRes(token.getRawText());
if (resid != -1) {
builder.setSpan(new ImageSpan(context, resid), start, builder.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
return builder;
}
}
| 32.22619 | 91 | 0.579239 |
c26d3cce3f62952c56d90bcd10f602358ede50ff | 11,385 | package maps.gml.editor;
import java.awt.Color;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import javax.swing.undo.AbstractUndoableEdit;
import maps.gml.GMLBuilding;
import maps.gml.GMLCoordinates;
import maps.gml.GMLEdge;
import maps.gml.GMLNode;
import maps.gml.GMLRoad;
import maps.gml.GMLShape;
import maps.gml.GMLSpace;
import maps.gml.view.LineOverlay;
import maps.gml.view.NodeDecorator;
import maps.gml.view.SquareNodeDecorator;
import rescuecore2.log.Logger;
import rescuecore2.misc.Pair;
import rescuecore2.misc.geometry.GeometryTools2D;
import rescuecore2.misc.geometry.Point2D;
/**
A tool for creating edges.
*/
public class SplitShapeTool extends AbstractTool {
private static final Color HIGHLIGHT_COLOUR = Color.BLUE;
private static final int HIGHLIGHT_SIZE = 6;
private static final double THRESHOLD = 0.001;
private Listener listener;
private NodeDecorator nodeHighlight;
private LineOverlay overlay;
private GMLNode hover;
private GMLNode start;
private GMLNode end;
// private GMLEdge edge;
/**
Construct a CreateEdgeTool.
@param editor The editor instance.
*/
public SplitShapeTool(GMLEditor editor) {
super(editor);
listener = new Listener();
nodeHighlight = new SquareNodeDecorator(HIGHLIGHT_COLOUR, HIGHLIGHT_SIZE);
overlay = new LineOverlay(HIGHLIGHT_COLOUR, true);
}
@Override
public String getName() {
return "Split shape";
}
@Override
public void activate() {
editor.getViewer().addMouseListener(listener);
editor.getViewer().addMouseMotionListener(listener);
editor.getViewer().addOverlay(overlay);
hover = null;
start = null;
end = null;
// edge = null;
}
@Override
public void deactivate() {
editor.getViewer().removeMouseListener(listener);
editor.getViewer().removeMouseMotionListener(listener);
editor.getViewer().clearAllNodeDecorators();
editor.getViewer().removeOverlay(overlay);
editor.getViewer().repaint();
}
private void setHover(GMLNode node) {
if (hover == node) {
return;
}
if (hover != null) {
editor.getViewer().clearNodeDecorator(hover);
}
hover = node;
if (hover != null) {
editor.getViewer().setNodeDecorator(nodeHighlight, hover);
}
editor.getViewer().repaint();
}
private void setStart(GMLNode node) {
if (start == node) {
return;
}
if (start != null) {
editor.getViewer().clearNodeDecorator(start);
}
start = node;
if (start != null) {
editor.getViewer().setNodeDecorator(nodeHighlight, start);
}
editor.getViewer().repaint();
}
private void setEnd(GMLNode node) {
if (start == node || end == node) {
return;
}
if (end != null) {
editor.getViewer().clearNodeDecorator(end);
}
end = node;
if (end != null) {
editor.getViewer().setNodeDecorator(nodeHighlight, end);
}
editor.getViewer().repaint();
}
private class Listener implements MouseListener, MouseMotionListener {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
Point p = fixEventPoint(e.getPoint());
GMLCoordinates c = editor.getViewer().getCoordinatesAtPoint(p.x, p.y);
GMLNode node = editor.getMap().findNearestNode(c.getX(), c.getY());
overlay.setStart(new Point2D(node.getX(), node.getY()));
setStart(node);
setHover(null);
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
if (start != null && end != null) {
SplitShapeEdit edit = splitByEdge();
editor.setChanged();
if (edit != null) {
editor.addEdit(edit);
}
editor.getViewer().clearAllNodeDecorators();
overlay.setStart(null);
overlay.setEnd(null);
editor.getViewer().repaint();
start = null;
end = null;
hover = null;
}
}
}
private SplitShapeEdit splitByEdge() {
Collection<GMLShape> add = new ArrayList<GMLShape>();
Collection<GMLShape> delete = new ArrayList<GMLShape>();
GMLEdge edge = editor.getMap().createEdge(start, end);
Collection<GMLEdge> startEdges = editor.getMap().getAttachedEdges(start);
Collection<GMLEdge> endEdges = editor.getMap().getAttachedEdges(end);
Collection<GMLShape> startShapes = new HashSet<GMLShape>();
Collection<GMLShape> endShapes = new HashSet<GMLShape>();
for (GMLEdge next : startEdges) {
startShapes.addAll(editor.getMap().getAttachedShapes(next));
}
for (GMLEdge next : endEdges) {
endShapes.addAll(editor.getMap().getAttachedShapes(next));
}
for (GMLShape shape : startShapes) {
if (endShapes.contains(shape)) {
Pair<GMLShape, GMLShape> split = splitShape(shape, edge);
if (split != null) {
add.add(split.first());
add.add(split.second());
delete.add(shape);
}
}
}
if (!add.isEmpty()) {
edge.setPassable(true);
return new SplitShapeEdit(edge, add, delete);
}
else {
editor.getMap().remove(edge);
return null;
}
}
private Pair<GMLShape, GMLShape> splitShape(GMLShape shape, GMLEdge edge) {
List<GMLNode> nodes1 = new ArrayList<GMLNode>();
List<GMLNode> nodes2 = new ArrayList<GMLNode>();
boolean first = true;
for (GMLNode n : shape.getUnderlyingNodes()) {
if (n == edge.getStart() || n == edge.getEnd()) {
first = !first;
nodes1.add(n);
nodes2.add(n);
}
else if (first) {
nodes1.add(n);
}
else {
nodes2.add(n);
}
}
if (nodes1.size() <= 2 || nodes2.size() <= 2) {
return null;
}
//Check if we really split an interior edge
double oldArea = area(shape.getUnderlyingNodes());
double area1 = area(nodes1);
double area2 = area(nodes2);
if (area1 + area2 > oldArea + THRESHOLD) {
return null;
}
GMLShape s1 = null;
GMLShape s2 = null;
if (shape instanceof GMLBuilding) {
GMLBuilding b = (GMLBuilding) shape;
GMLBuilding b1 = editor.getMap().createBuildingFromNodes(nodes1);
GMLBuilding b2 = editor.getMap().createBuildingFromNodes(nodes2);
b1.setCode(b.getCode());
b2.setCode(b.getCode());
b1.setFloors(b.getFloors());
b2.setFloors(b.getFloors());
b1.setImportance(b.getImportance());
b2.setImportance(b.getImportance());
s1 = b1;
s2 = b2;
}
else if (shape instanceof GMLRoad) {
//GMLBuilding b = (GMLBuilding) shape;
s1 = editor.getMap().createRoadFromNodes(nodes1);
s2 = editor.getMap().createRoadFromNodes(nodes2);
}
else if (shape instanceof GMLSpace) {
//GMLBuilding b = (GMLBuilding) shape;
s1 = editor.getMap().createSpaceFromNodes(nodes1);
s2 = editor.getMap().createSpaceFromNodes(nodes2);
}
else {
throw new IllegalArgumentException("Shape is not a building, road or space");
}
editor.getMap().remove(shape);
return new Pair<GMLShape, GMLShape>(s1, s2);
}
private double area(List<GMLNode> nodes) {
List<Point2D> vertices = new ArrayList<Point2D>();
for (GMLNode n : nodes) {
vertices.add(new Point2D(n.getX(), n.getY()));
}
return GeometryTools2D.computeArea(vertices);
}
@Override
public void mouseDragged(MouseEvent e) {
if (start != null) {
Point p = fixEventPoint(e.getPoint());
GMLCoordinates c = editor.getViewer().getCoordinatesAtPoint(p.x, p.y);
GMLNode node = editor.getMap().findNearestNode(c.getX(), c.getY());
overlay.setEnd(new Point2D(node.getX(), node.getY()));
setEnd(node);
}
}
@Override
public void mouseMoved(MouseEvent e) {
Point p = fixEventPoint(e.getPoint());
GMLCoordinates c = editor.snap(editor.getViewer().getCoordinatesAtPoint(p.x, p.y));
GMLNode node = editor.getMap().findNearestNode(c.getX(), c.getY());
setHover(node);
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
private Point fixEventPoint(Point p) {
Insets insets = editor.getViewer().getInsets();
return new Point(p.x - insets.left, p.y - insets.top);
}
}
private class SplitShapeEdit extends AbstractUndoableEdit {
private Collection<GMLShape> add;
private Collection<GMLShape> remove;
private GMLEdge edge;
public SplitShapeEdit(GMLEdge edge, Collection<GMLShape> add, Collection<GMLShape> remove) {
this.edge = edge;
this.add = add;
this.remove = remove;
}
@Override
public void undo() {
super.undo();
editor.getMap().removeEdge(edge);
editor.getMap().remove(add);
editor.getMap().add(remove);
editor.getViewer().repaint();
}
@Override
public void redo() {
super.redo();
editor.getMap().addEdge(edge);
for (GMLShape r : remove) {
Logger.debug("remove: " + r.toString());
}
for (GMLShape r : add) {
Logger.debug("add: " + r.toString());
}
editor.getMap().remove(remove);
editor.getMap().add(add);
editor.getViewer().repaint();
}
}
} | 34.086826 | 100 | 0.541151 |
ec1bb806405a33c70c28c3053dcdc93019f3b558 | 356 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package util;
/**
*
* @author dodelien
*/
public class PairePoidsValeur<T> {
public int poids;
public T valeur;
public boolean equals(Object obj) {
PairePoidsValeur<T> ppv = (PairePoidsValeur<T>)obj;
return ppv.valeur.equals(valeur);
}
}
| 16.181818 | 53 | 0.685393 |
1a15fab774c78651fc8378cdf1ac2c0503336d50 | 463 | package com.ph.gulimall.product.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ph.common.utils.PageUtils;
import com.ph.gulimall.product.entity.CommentReplayEntity;
import java.util.Map;
/**
* 商品评价回复关系
*
* @author alanpei
* @email allen.hangpei@gmail.com
* @date 2020-05-31 10:38:02
*/
public interface CommentReplayService extends IService<CommentReplayEntity> {
PageUtils queryPage(Map<String, Object> params);
}
| 22.047619 | 77 | 0.771058 |
8cd6d5fe31e7239914571d089e342619e90d5c1d | 281 | package com.bstek.bdf2.export.pdf.model;
public class LabelData extends TextChunk {
private static final long serialVersionUID = 3867048789812567068L;
private int align;
public int getAlign() {
return align;
}
public void setAlign(int align) {
this.align = align;
}
}
| 18.733333 | 67 | 0.747331 |
55e716073711f7896d87c61b6ca5d271fa79d709 | 4,199 | /*
* https://github.com/thinking-github/nbone
*/
package org.nbone.mvc.service;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.nbone.lang.MathOperation;
import org.nbone.mvc.ISuper;
import org.nbone.mvc.domain.GroupQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
/**
* Supper Service interface
* @author thinking
* @since 2015年12月12日下午1:45:26
*
* @param <T>
* @param <IdType>
*/
public interface SuperService<T,IdType extends Serializable> extends ISuper<T, IdType> {
//static Logger logger = LoggerFactory.getLogger(SuperService.class);
//批量增删改
/**
* @param objects
*/
public void batchInsert(T[] objects,boolean jdbcBatch);
public void batchInsert(Collection<T> objects,boolean jdbcBatch);
/**
* 批量添加
* @param objects 实体对象
* @param insertProperties 可选的插入字段(可为空)
* @param jdbcBatch true jdbc batch, false db batch
*
* @return
*/
public void batchInsert(Object[] objects,String[] insertProperties,boolean jdbcBatch);
/**
* 批量添加
* @param objects 实体对象
* @param insertProperties 可选的插入字段(可为空)
* @param jdbcBatch true jdbc batch, false db batch
*
* @return
*/
public void batchInsert(Collection<?> objects,String[] insertProperties,boolean jdbcBatch);
/**
*
* @param objects 实体对象列表
* @param properties 更新的属性字段 可为空,当为空更新全部字段
*/
public void batchUpdate(T[] objects,String...properties);
/**
*
* @param objects 实体对象列表
* @param properties 更新的属性字段 可为空,当为空更新全部字段
*/
public void batchUpdate(Collection<T> objects,String...properties);
public void batchDelete(Class<T> clazz,Serializable[] ids);
public void batchDelete(Class<T> clazz,List<Serializable> ids);
//查询分页
/**
* getForPage(index,pageNow,pageSize,"and status != -1"," order by create_time DESC"); <br>
*
* getForPage(index,pageNow,pageSize," order by create_time DESC");
*
* @param object 含参数实体对象
* @param fieldNames java字段名称 可为空,为空返回全部字段
* @param pageNum 当前页
* @param pageSize 页的大小
* @param afterWhere group by/order by 子句
* @return
*/
public Page<T> getForPage(T object,String[] fieldNames, int pageNum,int pageSize,String... afterWhere);
/**
* queryForPage(index,pageNow,pageSize,"and status != -1"," order by create_time DESC"); <br>
*
* queryForPage(index,pageNow,pageSize," order by create_time DESC");
* @param object 查询实体参数
* @param pageNum 当前页
* @param pageSize 页的大小
* @param afterWhere group by/order by 子句
* @return
*/
public Page<T> queryForPage(T object,int pageNum,int pageSize,String... afterWhere);
/**
*
* @param object 查询实体参数
* @param pageNum 当前页
* @param pageSize 页的大小
* @param afterWhere group by/order by 子句
* @return
*/
public Page<T> findForPage(Object object,int pageNum,int pageSize,String... afterWhere);
/**
* getForLimit(index,10,"and status != -1"," order by create_time DESC"); <br>
*
* getForLimit(index,10," order by create_time DESC");
* @param object 查询实体参数
* @param operationMap 设置字段查询操作符号 = > < 等等 (可为空)
* @param group 分组查询 可为空
* @param limit 限制返回的大小
* @param afterWhere order by 子句
* @return
*/
public List<T> getForLimit(Object object,Map<String,String> operationMap,GroupQuery group,int limit, String... afterWhere);
//按需字段查询
/**
* 根据实体参数查询返回单个字段的列表(比返回整个实体数据提高效率)
* @param object 查询实体参数
* @param fieldName 单个字段名称 默认采用java property mapping
* @param requiredType 目标类型
* @param afterWhere 追加条件语句 或者 order by 子句 如: and id in (1,2,3,4)
* @return
* @see SqlSession#getForList(Object, String)
*/
public <E> List<E> getForList(Object object, String fieldName,Class<E> requiredType,String... afterWhere);
/**
*
* @param object
* @param property 计算字段名称 可为空,为空时 参数值不为空且为数字的加入进行数学计算
* @param mathOperation
* @param conditionFields 条件字段 可为空,默认使用主键
* @return
* @see org.nbone.persistence.SqlSession#updateMathOperation(Object, String, MathOperation)
*/
public int updateMathOperation(Object object,String property, MathOperation mathOperation,String[] conditionFields);
public int updateMathOperation(Object object,String property, MathOperation mathOperation);
}
| 27.625 | 124 | 0.711836 |
f628c494976eafa6cdfb74261e8b398b24f84184 | 465 | package io.github.icodegarden.commons.kafka.reliability;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import io.github.icodegarden.commons.lang.TimeoutableCloseable;
/**
*
* @author Fangfang.Xu
*
*/
public interface ReliabilityProcessor<K, V> extends TimeoutableCloseable {
/**
* @param records
*/
void handleReliability(ConsumerRecords<K, V> records);
/**
* @return now processing not history total
*/
long processingCount();
}
| 18.6 | 74 | 0.741935 |
e48bd5e8600a187942b1596192d046728a882820 | 17,754 | package com.xunlei.downloadprovider.personal.lixianspace;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.xunlei.common.lixian.XLLixianTask;
import com.xunlei.downloadprovider.a.h.a;
import com.xunlei.downloadprovider.a.h.b;
import com.xunlei.downloadprovider.app.BrothersApplication;
import com.xunlei.downloadprovider.commonview.UnifiedLoadingView;
import com.xunlei.downloadprovider.commonview.XLToast;
import com.xunlei.downloadprovider.commonview.XLToast.XLToastType;
import com.xunlei.downloadprovider.commonview.dialog.q;
import com.xunlei.downloadprovider.commonview.f;
import com.xunlei.downloadprovider.frame.BaseFragment;
import com.xunlei.downloadprovider.member.login.LoginHelper;
import com.xunlei.downloadprovider.member.login.LoginHelper.d;
import com.xunlei.downloadprovider.member.login.LoginHelper.g;
import com.xunlei.downloadprovider.member.login.LoginHelper.m;
import com.xunlei.downloadprovider.member.login.LoginHelper.p;
import com.xunlei.downloadprovider.member.payment.external.PayEntryParam;
import com.xunlei.downloadprovider.member.payment.external.PayFrom;
import com.xunlei.downloadprovider.member.payment.external.PayUtil;
import com.xunlei.downloadprovider.member.payment.external.PaymentEntryActivity;
import com.xunlei.downloadprovider.model.protocol.report.StatReporter;
import com.xunlei.downloadprovider.personal.lixianspace.widget.LixianSpaceListWidget;
import com.xunlei.downloadprovider.web.BrowserUtil;
import com.xunlei.tdlive.R;
import com.xunlei.xiazaibao.sdk.XZBDevice;
import java.util.HashSet;
import java.util.Set;
import org.android.agoo.message.MessageService;
public class LixianSpaceFragment extends BaseFragment {
private final g A;
private final d B;
private final c C;
private boolean D;
private final d E;
private final p F;
private final a G;
private final Handler H;
private boolean I;
private boolean J;
private m a;
private final String b;
private UnifiedLoadingView c;
private LixianSpaceListWidget d;
private com.xunlei.downloadprovider.commonview.dialog.d e;
private View f;
private View g;
private View h;
private TextView i;
private Button j;
private Button k;
private TextView l;
private f m;
private q n;
private int o;
private boolean p;
private final Set<String> q;
private PopupWindow r;
private TextView s;
private View t;
private RelativeLayout u;
private TextView v;
private TextView w;
private TextView x;
private ImageView y;
private final OnClickListener z;
public LixianSpaceFragment() {
this.b = LixianSpaceFragment.class.getSimpleName();
this.c = null;
this.d = null;
this.e = null;
this.f = null;
this.g = null;
this.h = null;
this.i = null;
this.j = null;
this.k = null;
this.l = null;
this.m = null;
this.n = null;
this.o = b.a;
this.p = false;
this.q = new HashSet();
this.r = null;
this.s = null;
this.t = null;
this.z = new a(this);
this.A = new h(this);
this.B = new i(this);
this.C = new j(this);
this.E = new k(this);
this.F = new l(this);
this.G = new n(this);
this.H = new b(this.G);
this.J = true;
}
private boolean b() {
if (this.r == null || !this.r.isShowing()) {
return false;
}
if (!(getActivity() == null || getActivity().isFinishing())) {
try {
LayoutParams attributes = getActivity().getWindow().getAttributes();
attributes.alpha = 1.0f;
getActivity().getWindow().setAttributes(attributes);
} catch (Exception e) {
}
try {
this.r.dismiss();
} catch (IllegalStateException e2) {
e2.printStackTrace();
} catch (IllegalArgumentException e3) {
e3.printStackTrace();
}
}
return true;
}
@SuppressLint({"InflateParams"})
public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
this.a = new o(this);
LoginHelper.a().a(this.a);
this.mPageRoot = (ViewGroup) LayoutInflater.from(this.mActivity).inflate(2130968857, null);
this.c = (UnifiedLoadingView) this.mPageRoot.findViewById(2131755563);
this.d = (LixianSpaceListWidget) this.mPageRoot.findViewById(2131756427);
this.f = this.mPageRoot.findViewById(2131755649);
View findViewById = this.f.findViewById(2131755654);
if (findViewById != null) {
findViewById.setVisibility(XZBDevice.Wait);
}
this.g = this.mPageRoot.findViewById(2131756428);
this.h = this.mPageRoot.findViewById(2131756430);
this.i = (TextView) this.mPageRoot.findViewById(2131756431);
this.j = (Button) this.mPageRoot.findViewById(2131755653);
this.k = (Button) this.mPageRoot.findViewById(2131755651);
this.l = (TextView) this.mPageRoot.findViewById(2131755652);
this.l.setText(2131231060);
this.x = (TextView) this.mPageRoot.findViewById(R.id.common_delete_buttom_btn_text);
this.y = (ImageView) this.mPageRoot.findViewById(R.id.common_delete_buttom_btn_icon);
this.d.setOnRefreshClickListener(new p(this));
this.m = new f(this.mPageRoot);
this.m.g.setOnClickListener(this.z);
this.m.n.setOnClickListener(this.z);
this.m.n.setVisibility(0);
this.m.n.setImageResource(R.drawable.common_menu_delete_icon_black_selector);
this.m.i.setText(2131231075);
this.m.a();
this.c.setOnClickListener(this.z);
this.d.setOnCloudListOperateListener(this.E);
this.j.setOnClickListener(this.z);
this.k.setOnClickListener(this.z);
this.u = (RelativeLayout) findViewById(2131755849);
this.v = (TextView) findViewById(2131755851);
this.w = (TextView) findViewById(2131755853);
this.w.setOnClickListener(this.z);
this.o = b.a;
LoginHelper.a().a(this.A);
LoginHelper.a().a(this.B);
return this.mPageRoot;
}
public void onResume() {
LoginHelper.a().x();
this.I = true;
c();
if (PayUtil.b) {
LoginHelper.a().a(this.F);
this.c.a();
LoginHelper.a().s();
PayUtil.b = false;
}
super.onResume();
if (this.h.getAnimation() != null) {
this.h.getAnimation().cancel();
this.h.clearAnimation();
}
this.h.setVisibility(XZBDevice.DOWNLOAD_LIST_ALL);
a();
d();
}
public void onPause() {
PayUtil.b = false;
super.onPause();
}
public void onDestroy() {
this.o = b.d;
LoginHelper.a().b(this.A);
LoginHelper.a().b(this.B);
LoginHelper.a().b(this.F);
if (this.d != null) {
this.d.b();
}
LoginHelper.a().b(this.a);
super.onDestroy();
}
public boolean onBackPressed() {
if (this.o == b.c && this.d.d) {
return super.onBackPressed();
}
if (this.f.getVisibility() != 0 && this.g.getVisibility() != 0) {
return super.onBackPressed();
}
this.J = true;
e();
return true;
}
public final void a() {
LoginHelper.a();
if (!LoginHelper.c()) {
if (this.d.getListCount() != 0 && com.xunlei.c.a.b.a(BrothersApplication.a())) {
this.u.setVisibility(0);
this.w.setText(2131231048);
this.v.setText(2131231094);
}
this.u.setVisibility(XZBDevice.Wait);
} else if (LoginHelper.a().f()) {
if (com.xunlei.downloadprovider.homepage.a.a.d.b.containsKey(MessageService.MSG_ACCS_READY_REPORT)) {
if (this.d.getListCount() != 0) {
this.u.setVisibility(0);
this.v.setText(((com.xunlei.downloadprovider.homepage.a.a.d) com.xunlei.downloadprovider.homepage.a.a.d.b.get(MessageService.MSG_ACCS_READY_REPORT)).d);
this.w.setText(((com.xunlei.downloadprovider.homepage.a.a.d) com.xunlei.downloadprovider.homepage.a.a.d.b.get(MessageService.MSG_ACCS_READY_REPORT)).e);
}
this.u.setVisibility(XZBDevice.Wait);
} else {
this.u.setVisibility(XZBDevice.Wait);
}
} else if (com.xunlei.downloadprovider.homepage.a.a.d.b.containsKey(MessageService.MSG_ACCS_READY_REPORT)) {
if (this.d.getListCount() != 0) {
this.u.setVisibility(0);
this.v.setText(((com.xunlei.downloadprovider.homepage.a.a.d) com.xunlei.downloadprovider.homepage.a.a.d.b.get(MessageService.MSG_ACCS_READY_REPORT)).d);
this.w.setText(((com.xunlei.downloadprovider.homepage.a.a.d) com.xunlei.downloadprovider.homepage.a.a.d.b.get(MessageService.MSG_ACCS_READY_REPORT)).e);
}
this.u.setVisibility(XZBDevice.Wait);
} else {
if (this.d.getListCount() != 0) {
this.u.setVisibility(0);
this.v.setText(2131231095);
this.w.setText(2131231050);
}
this.u.setVisibility(XZBDevice.Wait);
}
this.d.c();
}
private final void c() {
this.d.c();
this.d.a(this.C);
if (this.o == b.a) {
this.o = b.b;
this.c.a();
}
}
private final void d() {
a();
LoginHelper.a();
if (!LoginHelper.c()) {
return;
}
if (LoginHelper.a().f()) {
if (!com.xunlei.downloadprovider.homepage.a.a.d.b.containsKey(MessageService.MSG_ACCS_READY_REPORT)) {
return;
}
if (this.d.getListCount() == 0) {
LoginHelper.a();
StatReporter.reportVip_ContinueShow("space_lixian_middle", Boolean.valueOf(LoginHelper.c()), Boolean.valueOf(LoginHelper.a().f()), com.xunlei.downloadprovider.homepage.a.a.d.a);
return;
}
LoginHelper.a();
StatReporter.reportVip_ContinueShow("space_lixian_top", Boolean.valueOf(LoginHelper.c()), Boolean.valueOf(LoginHelper.a().f()), com.xunlei.downloadprovider.homepage.a.a.d.a);
} else if (!com.xunlei.downloadprovider.homepage.a.a.d.b.containsKey(MessageService.MSG_ACCS_READY_REPORT)) {
} else {
if (this.d.getListCount() == 0) {
LoginHelper.a();
StatReporter.reportVip_ContinueShow("space_lixian_middle", Boolean.valueOf(LoginHelper.c()), Boolean.valueOf(LoginHelper.a().f()), com.xunlei.downloadprovider.homepage.a.a.d.a);
return;
}
LoginHelper.a();
StatReporter.reportVip_ContinueShow("space_lixian_top", Boolean.valueOf(LoginHelper.c()), Boolean.valueOf(LoginHelper.a().f()), com.xunlei.downloadprovider.homepage.a.a.d.a);
}
}
private final void a(boolean z) {
this.p = z;
if (this.p) {
this.d.setListViewMode(Mode.DISABLED);
this.f.setVisibility(0);
this.g.setVisibility(0);
this.g.setOnClickListener(this.z);
g();
return;
}
Animation loadAnimation = AnimationUtils.loadAnimation(getApplicationContext(), 2131034207);
Animation loadAnimation2 = AnimationUtils.loadAnimation(getApplicationContext(), 2131034136);
loadAnimation.setAnimationListener(new c(this));
this.f.startAnimation(loadAnimation);
this.g.startAnimation(loadAnimation2);
this.f.setVisibility(XZBDevice.Wait);
this.g.setVisibility(XZBDevice.Wait);
}
private final void e() {
if (this.d.e) {
this.J = true;
this.d.d();
}
this.l.setText(null);
a(false);
}
private final void f() {
if (!this.d.e()) {
if (this.d.getListCount() > 0) {
LixianSpaceListWidget lixianSpaceListWidget = this.d;
if (this.J) {
lixianSpaceListWidget.d();
if (lixianSpaceListWidget.h != null) {
lixianSpaceListWidget.h.a(lixianSpaceListWidget.e);
}
lixianSpaceListWidget.b.clear();
} else if (lixianSpaceListWidget.b.size() < lixianSpaceListWidget.a.size()) {
lixianSpaceListWidget.b.clear();
for (XLLixianTask xLLixianTask : lixianSpaceListWidget.a) {
lixianSpaceListWidget.b.add(Long.valueOf(xLLixianTask.getTaskId()));
}
} else {
lixianSpaceListWidget.b.clear();
}
lixianSpaceListWidget.a();
this.J = false;
}
g();
}
}
private final void g() {
int deleteTaskCount = this.d.getDeleteTaskCount();
int listCount = this.d.getListCount();
if (deleteTaskCount > 0) {
if (deleteTaskCount < listCount) {
this.j.setText(2131230862);
} else {
this.j.setText(2131230861);
}
this.l.setText(String.format(BrothersApplication.a().getString(2131231368), new Object[]{Integer.valueOf(deleteTaskCount)}));
this.g.setEnabled(true);
b(true);
return;
}
this.l.setText(2131231060);
this.j.setText(2131230862);
this.g.setEnabled(false);
b(false);
}
private void b(boolean z) {
if (z) {
this.x.setEnabled(true);
this.y.setEnabled(true);
return;
}
this.x.setEnabled(false);
this.y.setEnabled(false);
}
static /* synthetic */ void c(LixianSpaceFragment lixianSpaceFragment) {
lixianSpaceFragment.f();
lixianSpaceFragment.b();
}
static /* synthetic */ void d(LixianSpaceFragment lixianSpaceFragment) {
if (lixianSpaceFragment.d.getDeleteTaskCount() <= 0) {
XLToast.a(lixianSpaceFragment.getApplicationContext(), XLToastType.XLTOAST_TYPE_ALARM, lixianSpaceFragment.getActivity().getString(2131231286));
} else if (lixianSpaceFragment.e == null || !(lixianSpaceFragment.e == null || lixianSpaceFragment.e.isShowing())) {
lixianSpaceFragment.e = new com.xunlei.downloadprovider.commonview.dialog.d(lixianSpaceFragment.getActivity());
lixianSpaceFragment.e.a(String.format(BrothersApplication.a().getString(2131231063), new Object[]{Integer.valueOf(r0)}));
lixianSpaceFragment.e.d(BrothersApplication.a().getString(2131231062));
lixianSpaceFragment.e.c(BrothersApplication.a().getString(2131231061));
lixianSpaceFragment.e.b(new e(lixianSpaceFragment));
lixianSpaceFragment.e.a(new f(lixianSpaceFragment));
lixianSpaceFragment.e.setOnDismissListener(new g(lixianSpaceFragment));
lixianSpaceFragment.e.show();
}
}
static /* synthetic */ void g(LixianSpaceFragment lixianSpaceFragment) {
Object obj = com.umeng.a.d;
if (com.xunlei.downloadprovider.homepage.a.a.d.b.containsKey(MessageService.MSG_DB_NOTIFY_DISMISS)) {
obj = ((com.xunlei.downloadprovider.homepage.a.a.d) com.xunlei.downloadprovider.homepage.a.a.d.b.get(MessageService.MSG_DB_NOTIFY_DISMISS)).h;
}
if (TextUtils.isEmpty(r0)) {
if (!(TextUtils.isEmpty(lixianSpaceFragment.w.getText()) || lixianSpaceFragment.w.getText().equals("\u5f00\u901a\u4f1a\u5458"))) {
StatReporter.reportVip_ContinueClick("space_lixian_top");
}
obj = null;
} else {
BrowserUtil.a();
BrowserUtil.a(lixianSpaceFragment.getActivity(), r0, "\u7eed\u8d39");
obj = 1;
}
if (obj == null) {
PayFrom payFrom = PayFrom.LIXIAN_SPACE;
if (!lixianSpaceFragment.w.getText().toString().contains("\u5f00\u901a")) {
payFrom = PayFrom.LIXIAN_SPACE_RENEWTIP;
}
PayEntryParam payEntryParam = new PayEntryParam(payFrom);
payEntryParam.c = com.xunlei.downloadprovider.homepage.a.a.d.a;
PaymentEntryActivity.a(lixianSpaceFragment.getActivity(), payEntryParam);
}
}
static /* synthetic */ void a(LixianSpaceFragment lixianSpaceFragment, CharSequence charSequence) {
if (lixianSpaceFragment.o != b.d) {
lixianSpaceFragment.i.setText(charSequence);
Animation loadAnimation = AnimationUtils.loadAnimation(lixianSpaceFragment.getApplicationContext(), 2131034202);
loadAnimation.setAnimationListener(new d(lixianSpaceFragment));
lixianSpaceFragment.h.startAnimation(loadAnimation);
}
}
}
| 39.896629 | 193 | 0.616931 |
92108c42b484bd044b149adb05ac059828f0e10c | 2,689 | /**
* Copyright (C)2011 - Marat Gariev <thepun599@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.thepun.pq;
import java.util.Map;
import java.util.concurrent.ThreadFactory;
public final class Configuration<T, C> {
private int headCount;
private int tailCount;
private int dataFileSize;
private int sequenceFileSize;
private String dataPath;
private ThreadFactory persisterThreadFactory;
private PersistCallback<T, C> persistCallback;
private Map<Class<? extends T>, Marshaller<? extends T, ? extends C>> serializers;
public int getTailCount() {
return tailCount;
}
public void setTailCount(int tailCount) {
this.tailCount = tailCount;
}
public int getHeadCount() {
return headCount;
}
public void setHeadCount(int headCount) {
this.headCount = headCount;
}
public String getDataPath() {
return dataPath;
}
public void setDataPath(String dataPath) {
this.dataPath = dataPath;
}
public Map<Class<? extends T>, Marshaller<? extends T, ? extends C>> getSerializers() {
return serializers;
}
public void setSerializers(Map<Class<? extends T>, Marshaller<? extends T, ? extends C>> serializers) {
this.serializers = serializers;
}
public PersistCallback<T, C> getPersistCallback() {
return persistCallback;
}
public void setPersistCallback(PersistCallback<T, C> persistCallback) {
this.persistCallback = persistCallback;
}
public int getDataFileSize() {
return dataFileSize;
}
public void setDataFileSize(int dataFileSize) {
this.dataFileSize = dataFileSize;
}
public int getSequenceFileSize() {
return sequenceFileSize;
}
public void setSequenceFileSize(int sequenceFileSize) {
this.sequenceFileSize = sequenceFileSize;
}
public ThreadFactory getPersisterThreadFactory() {
return persisterThreadFactory;
}
public void setPersisterThreadFactory(ThreadFactory persisterThreadFactory) {
this.persisterThreadFactory = persisterThreadFactory;
}
}
| 28.010417 | 107 | 0.692451 |
c5656155e14930bb1e97cbc0e98576e2721ff030 | 4,235 | /*
* Copyright 2018-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.vault.core;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.vault.VaultException;
import org.springframework.vault.support.VaultResponse;
import org.springframework.vault.support.VaultResponseSupport;
/**
* Default implementation of {@link VaultKeyValueOperations} for the key-value backend
* version 2.
*
* @author Mark Paluch
* @author Younghwan Jang
* @since 2.1
*/
class VaultKeyValue2Template extends VaultKeyValue2Accessor implements VaultKeyValueOperations {
/**
* Create a new {@link VaultKeyValue2Template} given {@link VaultOperations} and the
* mount {@code path}.
* @param vaultOperations must not be {@literal null}.
* @param path must not be empty or {@literal null}.
*/
public VaultKeyValue2Template(VaultOperations vaultOperations, String path) {
super(vaultOperations, path);
}
@Nullable
@Override
public VaultResponse get(String path) {
Assert.hasText(path, "Path must not be empty");
return doRead(path, Map.class, (response, data) -> {
VaultResponse vaultResponse = new VaultResponse();
vaultResponse.setRenewable(response.isRenewable());
vaultResponse.setAuth(response.getAuth());
vaultResponse.setLeaseDuration(response.getLeaseDuration());
vaultResponse.setLeaseId(response.getLeaseId());
vaultResponse.setMetadata(response.getMetadata());
vaultResponse.setRequestId(response.getRequestId());
vaultResponse.setWarnings(response.getWarnings());
vaultResponse.setWrapInfo(response.getWrapInfo());
vaultResponse.setData(data);
return vaultResponse;
});
}
@Nullable
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> VaultResponseSupport<T> get(String path, Class<T> responseType) {
Assert.hasText(path, "Path must not be empty");
Assert.notNull(responseType, "Response type must not be null");
return doRead(path, responseType, (response, data) -> {
VaultResponseSupport result = response;
result.setData(data);
return result;
});
}
@Override
public boolean patch(String path, Map<String, ?> patch) {
Assert.hasText(path, "Path must not be empty");
Assert.notNull(patch, "Patch body must not be null");
// To do patch operation, we need to do a read operation first
VaultResponse readResponse = get(path);
if (readResponse == null || readResponse.getData() == null) {
throw new SecretNotFoundException(
String.format("No data found at %s; patch only works on existing data", createDataPath(path)),
String.format("%s/%s", this.path, path));
}
if (readResponse.getMetadata() == null) {
throw new VaultException("Metadata must not be null");
}
Map<String, Object> metadata = readResponse.getMetadata();
Map<String, Object> data = new LinkedHashMap<>(readResponse.getRequiredData());
data.putAll(patch);
Map<String, Object> body = new HashMap<>();
body.put("data", data);
body.put("options", Collections.singletonMap("cas", metadata.get("version")));
try {
doWrite(createDataPath(path), body);
return true;
}
catch (VaultException e) {
if (e.getMessage() != null && (e.getMessage().contains("check-and-set")
|| e.getMessage().contains("did not match the current version"))) {
return false;
}
throw e;
}
}
@Override
public void put(String path, Object body) {
Assert.hasText(path, "Path must not be empty");
doWrite(createDataPath(path), Collections.singletonMap("data", body));
}
}
| 30.688406 | 99 | 0.727745 |
7d14288154f647befd6ae30639d582a2dd351db7 | 5,033 | package com.isco.upc.app.domain;
import java.util.Date;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.format.annotation.DateTimeFormat;
import com.isco.upc.app.email.beans.PersonFunction;
@Document
public class Person {
@Id
private String id;
private String email;
private String firstName;
private String lastName;
private String phone;
private String skype;
private String photoFileId;
private PersonFunction personfunction;
private String status;
//@NotNull
private String job;
private Integer yearsExperience;
private String education;
private String homeAddress;
private String jobAddress;
private String certifications;
private List<Skill> skills;
private String mission;
private String rate;
@DateTimeFormat(style = "M-")
private Date lastCvUpdate;
private String cvFileId;
@DateTimeFormat(style = "M-")
private Date workPermitExpirationDate;
@DateTimeFormat(style = "M-")
private Date startingDateDate;
private List<History> histories;
private List<PersonDocument> documents;
public Person(){}
public Person(String email, String firstName, String lastName){
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSkype() {
return skype;
}
public void setSkype(String skype) {
this.skype = skype;
}
public String getPhotoFileId() {
return photoFileId;
}
public void setPhotoFileId(String photoFileId) {
this.photoFileId = photoFileId;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Integer getYearsExperience() {
return yearsExperience;
}
public void setYearsExperience(Integer yearsExperience) {
this.yearsExperience = yearsExperience;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public String getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(String homeAddress) {
this.homeAddress = homeAddress;
}
public String getJobAddress() {
return jobAddress;
}
public void setJobAddress(String jobAddress) {
this.jobAddress = jobAddress;
}
public String getCertifications() {
return certifications;
}
public void setCertifications(String certifications) {
this.certifications = certifications;
}
public String getMission() {
return mission;
}
public void setMission(String mission) {
this.mission = mission;
}
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
public List<Skill> getSkills() {
return skills;
}
public void setSkills(List<Skill> skills) {
this.skills = skills;
}
public Date getLastCvUpdate() {
return lastCvUpdate;
}
public void setLastCvUpdate(Date lastCvUpdate) {
this.lastCvUpdate = lastCvUpdate;
}
public String getCvFileId() {
return cvFileId;
}
public void setCvFileId(String cvFileId) {
this.cvFileId = cvFileId;
}
public Date getWorkPermitExpirationDate() {
return workPermitExpirationDate;
}
public void setWorkPermitExpirationDate(Date workPermitExpirationDate) {
this.workPermitExpirationDate = workPermitExpirationDate;
}
public Date getStartingDateDate() {
return startingDateDate;
}
public void setStartingDateDate(Date startingDateDate) {
this.startingDateDate = startingDateDate;
}
public PersonFunction getPersonfunction() {
return personfunction;
}
public void setPersonfunction(PersonFunction personfunction) {
this.personfunction = personfunction;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<History> getHistories() {
return histories;
}
public void setHistories(List<History> histories) {
this.histories = histories;
}
public List<PersonDocument> getDocuments() {
return documents;
}
public void setDocuments(List<PersonDocument> documents) {
this.documents = documents;
}
}
| 17.003378 | 74 | 0.687065 |
484a2c0de886a03518d57bd7c246ddcffee545a5 | 2,503 | /*
* Fabric3
* Copyright (c) 2009-2015 Metaform Systems
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fabric3.fabric.container.builder.channel;
import java.net.URI;
import org.fabric3.api.host.Fabric3Exception;
import org.fabric3.fabric.model.physical.ChannelTarget;
import org.fabric3.spi.container.builder.TargetConnectionAttacher;
import org.fabric3.spi.container.channel.Channel;
import org.fabric3.spi.container.channel.ChannelConnection;
import org.fabric3.fabric.container.channel.ChannelManager;
import org.fabric3.spi.model.physical.ChannelSide;
import org.fabric3.spi.model.physical.PhysicalConnectionSource;
import org.oasisopen.sca.annotation.EagerInit;
import org.oasisopen.sca.annotation.Reference;
/**
* Attaches the target side of a channel connection to a channel.
*/
@EagerInit
public class ChannelTargetAttacher implements TargetConnectionAttacher<ChannelTarget> {
private ChannelManager channelManager;
public ChannelTargetAttacher(@Reference ChannelManager channelManager) {
this.channelManager = channelManager;
}
public void attach(PhysicalConnectionSource source, ChannelTarget target, ChannelConnection connection) {
if (source.isDirectConnection()) {
// no event stream to attach since this is a direct connection
return;
}
URI uri = target.getUri();
Channel channel = getChannel(uri, target.getChannelSide());
channel.attach(connection);
connection.setCloseable(() -> { // no-op
});
}
public void detach(PhysicalConnectionSource source, ChannelTarget target) {
// no-op since channel do not maintain references to incoming handlers
}
private Channel getChannel(URI uri, ChannelSide channelSide) {
Channel channel = channelManager.getChannel(uri, channelSide);
if (channel == null) {
throw new Fabric3Exception("Channel not found");
}
return channel;
}
} | 36.808824 | 109 | 0.733919 |
769a8097d3d37100230ad2e0159d18742e49031e | 3,076 | /*
* Copyright © 2011-2012 Philipp Eichhorn
*
* 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.eclipse.handlers.replace;
import lombok.eclipse.handlers.ast.EclipseMethod;
import org.eclipse.jdt.internal.compiler.ast.*;
import org.eclipse.jdt.internal.compiler.lookup.*;
public abstract class StatementReplaceVisitor extends ReplaceVisitor<Statement> {
protected StatementReplaceVisitor(final EclipseMethod method, final lombok.ast.pg.Statement<?> replacement) {
super(method, replacement);
}
@Override
public boolean visit(final ConstructorDeclaration constructorDeclaration, final ClassScope scope) {
replace(constructorDeclaration.statements);
return true;
}
@Override
public boolean visit(final MethodDeclaration methodDeclaration, final ClassScope scope) {
replace(methodDeclaration.statements);
return true;
}
@Override
public boolean visit(final Block block, final BlockScope scope) {
replace(block.statements);
return true;
}
@Override
public boolean visit(final DoStatement doStatement, final BlockScope scope) {
doStatement.action = replace(doStatement.action);
return true;
}
@Override
public boolean visit(final ForeachStatement forStatement, final BlockScope scope) {
forStatement.action = replace(forStatement.action);
return true;
}
@Override
public boolean visit(final ForStatement forStatement, final BlockScope scope) {
forStatement.action = replace(forStatement.action);
return true;
}
@Override
public boolean visit(final IfStatement ifStatement, final BlockScope scope) {
ifStatement.thenStatement = replace(ifStatement.thenStatement);
ifStatement.elseStatement = replace(ifStatement.elseStatement);
return true;
}
@Override
public boolean visit(final SwitchStatement switchStatement, final BlockScope scope) {
replace(switchStatement.statements);
return true;
}
@Override
public boolean visit(final WhileStatement whileStatement, final BlockScope scope) {
whileStatement.action = replace(whileStatement.action);
return true;
}
}
| 34.177778 | 110 | 0.781209 |
f4072c4c348ca897fb737e3f8e9507a81758e3f2 | 876 | package com.lichkin.framework.db.beans;
/**
* 数据库资源定义类
* @author SuZhou LichKin Information Technology Co., Ltd.
*/
public interface SysPssPurchaseReturnStockInOrderR {
public static final int id = 0x50700000;
public static final int usingStatus = 0x50700001;
public static final int insertTime = 0x50700002;
public static final int compId = 0x50700003;
public static final int approvalStatus = 0x50700004;
public static final int approvalTime = 0x50700005;
public static final int orderNo = 0x50700006;
public static final int billDate = 0x50700007;
public static final int remarks = 0x50700008;
public static final int storageId = 0x50700009;
public static final int orderType = 0x50700010;
public static final int supplierId = 0x50700011;
public static final int purchaserId = 0x50700012;
public static final int orderAmount = 0x50700013;
} | 23.675676 | 58 | 0.777397 |
c98f32a4aa0857dcba3f39fdf53434b59bf43e85 | 599 | package web.svg;
import java.util.Locale;
public class Rectangle extends Tag {
private final double x;
private final double y;
private final double width;
private final double height;
protected Rectangle(double x, double y, double width, double height) {
super("rect");
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
@Override
protected String renderAttributes() {
return String.format(Locale.US, "x=\"%f\" y=\"%f\" width=\"%f\" height=\"%f\"",
x, y, width, height);
}
}
| 21.392857 | 87 | 0.582638 |
71d94ca7572da5537b0568e3c684f3abf49a0ff3 | 193 | package com.caiwen.runner;
import com.caiwen.core.Runnable;
import com.caiwen.web.domain.testcase.TestCase;
public class TestCaseRunner implements Runnable {
public void run() {
}
}
| 12.866667 | 49 | 0.751295 |
e1f62bd338ec624bd7a0097a7c529274ed0e3281 | 526 | package com.yito0000.videochat.backend.InMemoryInfrastructure.datamodel;
import lombok.*;
@ToString
public class RoomData {
@Getter
private final String roomId;
@Getter
private final String sessionId;
@Getter
private final String apiKey;
@Getter
private final String name;
public RoomData(String roomId, String sessionId, String apiKey, String name) {
this.roomId = roomId;
this.sessionId = sessionId;
this.apiKey = apiKey;
this.name = name;
}
}
| 19.481481 | 82 | 0.673004 |
e222b3c0ffab0536c377f9d5bf31ac433eb12549 | 3,201 | package frc.robot.subsystems;
import com.ctre.phoenix.motorcontrol.can.WPI_TalonFX;
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkMaxLowLevel.MotorType;
import edu.wpi.first.wpilibj.SpeedControllerGroup;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.controller.ProfiledPIDController;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj.trajectory.TrapezoidProfile;
import edu.wpi.first.wpilibj.util.Units;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants.CANDevices;
import frc.robot.Constants.SuperstructureConstants;
public class ShooterSubsystem extends SubsystemBase {
/**
* Subsystem that controls the shooter of the robot
*/
private final WPI_TalonFX leftFlywheelMotor = new WPI_TalonFX(CANDevices.leftFlywheelMotorId);
private final WPI_TalonFX rightFlywheelMotor = new WPI_TalonFX(CANDevices.rightFlywheelMotorId);
private final CANSparkMax kickerMotor = new CANSparkMax(CANDevices.kickerMotorId, MotorType.kBrushless);
private final SpeedControllerGroup flywheel = new SpeedControllerGroup(leftFlywheelMotor, rightFlywheelMotor);
private final ProfiledPIDController controller = new ProfiledPIDController(
0.005, 0.005, 0,
new TrapezoidProfile.Constraints(
Units.rotationsPerMinuteToRadiansPerSecond(6380) * SuperstructureConstants.flywheelGearRatio,
Units.rotationsPerMinuteToRadiansPerSecond(2000)
)
);
private Timer timer = new Timer();
private double desiredSpeed = 0;
public ShooterSubsystem() {
rightFlywheelMotor.setInverted(true);
controller.setTolerance(Units.rotationsPerMinuteToRadiansPerSecond(20));
timer.start();
timer.reset();
}
@Override
public void periodic() {
if (!(Math.abs(desiredSpeed - getFlywheelVelRadPerSec()) < 50)) timer.reset();
}
public double getFlywheelVelRadPerSec() {
return (((leftFlywheelMotor.getSelectedSensorVelocity()
/ 2048 * (2 * Math.PI) * 10) * SuperstructureConstants.flywheelGearRatio));
// raw sensor unit/100ms * 1 rotation/2048 units Talon * 2pi rad/1 rotation / 10 100ms/sec = rad/sec
}
public void runVelocityProfileController(double desiredSpeedRadPerSec) {
desiredSpeed = desiredSpeedRadPerSec;
double powerOut = controller.calculate(
getFlywheelVelRadPerSec(),
desiredSpeedRadPerSec
);
flywheel.set(powerOut);
SmartDashboard.putNumber("current", Units.radiansPerSecondToRotationsPerMinute(getFlywheelVelRadPerSec()));
}
public void runShooterPercent(double speed) {
flywheel.set(speed);
}
public void stopShooter() {
flywheel.set(0);
}
public void runKicker() {
kickerMotor.set(SuperstructureConstants.kickerPower);
}
public void stopKicker() {
kickerMotor.set(0);
}
public void reverseKicker() {
kickerMotor.set(-SuperstructureConstants.kickerPower);
}
public boolean atGoal() {
return timer.get() >= 0.25;
}
}
| 26.675 | 115 | 0.712902 |
b4db40710872d022ce5d6bb536c9d247536865df | 1,085 | package donjinkrawler.items;
import donjinkrawler.visitor.ItemVisitor;
import krawlercommon.items.DamagePotionData;
public class DamagePotion extends BaseItem {
private double multiplier;
public DamagePotion(DamagePotionData data) {
this(data, 1.5);
}
public DamagePotion(DamagePotionData data, double multiplier) {
this.itemData = data;
super.loadImage("items/damage_potion_distinct.png");
this.multiplier = multiplier;
}
@Override
public DamagePotionData getData() {
return (DamagePotionData) itemData;
}
@Override
public String getDescription() {
return "Adds some damage buff.";
}
@Override
public void accept(ItemVisitor visitor) {
visitor.visit(this);
}
@Override
public DamagePotion deepCopy() throws CloneNotSupportedException {
return (DamagePotion) super.clone();
}
public double getMultiplier() {
return multiplier;
}
public void setMultiplier(double multiplier) {
this.multiplier = multiplier;
}
}
| 22.604167 | 70 | 0.672811 |
86809394c21ec74bd86a46026258d2ce5ffe040c | 995 | package com.lloyd.strategygenerator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
@RunWith(SpringRunner.class)
@SpringBootTest
public class StrategyGeneratorApplicationTest {
@Autowired
private RouterFunction<ServerResponse> routerFunction;
private WebTestClient webTestClient;
@Before
public void setUp() {
webTestClient = WebTestClient.bindToRouterFunction(routerFunction).build();
}
@Test
public void should_generate_strategy() {
webTestClient.get().uri("/strategy").exchange().expectStatus().is2xxSuccessful().expectBody(String.class);
}
}
| 31.09375 | 108 | 0.825126 |
6bfcf1e42118c9f072d2eaa467e67a8bd8ba6be6 | 2,429 | package xyz.discordboats.Boats4J;
import java.util.Objects;
public class UserInfo {
private String id;
private String name;
private String website;
private String twitter;
private String github;
private String instagram;
private String reddit;
private String bio;
UserInfo(String id, String name, String website, String twitter, String github, String instagram, String reddit, String bio) {
this.id = id;
this.name = name;
this.website = website;
this.twitter = twitter;
this.github = github;
this.instagram = instagram;
this.reddit = reddit;
this.bio = bio;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getWebsite() {
return website;
}
public String getTwitter() {
return twitter;
}
public String getGithub() {
return github;
}
public String getInstagram() {
return instagram;
}
public String getReddit() {
return reddit;
}
public String getBio() {
return bio;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserInfo userInfo = (UserInfo) o;
return Objects.equals(id, userInfo.id) &&
Objects.equals(name, userInfo.name) &&
Objects.equals(website, userInfo.website) &&
Objects.equals(twitter, userInfo.twitter) &&
Objects.equals(github, userInfo.github) &&
Objects.equals(instagram, userInfo.instagram) &&
Objects.equals(reddit, userInfo.reddit) &&
Objects.equals(bio, userInfo.bio);
}
@Override
public int hashCode() {
return Objects.hash(id, name, website, twitter, github, instagram, reddit, bio);
}
@Override
public String toString() {
return "UserInfo{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", website='" + website + '\'' +
", twitter='" + twitter + '\'' +
", github='" + github + '\'' +
", instagram='" + instagram + '\'' +
", reddit='" + reddit + '\'' +
", bio='" + bio + '\'' +
'}';
}
}
| 26.402174 | 130 | 0.527789 |
6737deb634d06d60209a82959342a403ee0e4f93 | 2,238 | package org.jeecf.engine.mysql.model.update;
import java.util.List;
import org.jeecf.common.enums.SplitCharEnum;
import org.jeecf.engine.mysql.model.BaseTable;
import org.jeecf.engine.mysql.utils.JniValidate;
import org.jeecf.engine.mysql.utils.SqlHelper;
/**
* 更新表
*
* @author jianyiming
*
*/
public class UpdateTable extends BaseTable {
protected UpdateTable() {
}
/**
* 主键
*/
private Object id;
public Object getId() {
return id;
}
public void setId(Object id) {
this.id = id;
}
private List<UpdateTableColumn> updateTableColumns;
public List<UpdateTableColumn> getUpdateTableColumns() {
return updateTableColumns;
}
public void setUpdateTableColumns(List<UpdateTableColumn> updateTableColumns) {
this.updateTableColumns = updateTableColumns;
}
public static class Builder {
public static UpdateTable build(String name, String tableName) {
UpdateTable updateTable = new UpdateTable();
updateTable.setName(JniValidate.columnValidate(name));
updateTable.setTableName(JniValidate.columnValidate(tableName));
return updateTable;
}
}
/**
* 更新表sql
*
* @return
*/
public String toSql() {
List<UpdateTableColumn> updateTableColumns = this.getUpdateTableColumns();
StringBuilder builder = new StringBuilder("UPDATE ");
builder.append(this.getTableName() + SplitCharEnum.BLANK.getName());
builder.append(this.getName() + SplitCharEnum.BLANK.getName());
for (int i = 0; i < updateTableColumns.size(); i++) {
UpdateTableColumn updateTableColumn = updateTableColumns.get(i);
builder.append(updateTableColumn.getColumnName());
builder.append(" = ");
builder.append(SqlHelper.toJdbcValue(updateTableColumn.getName()) + SplitCharEnum.BLANK.getName());
if (i < updateTableColumns.size() - 1) {
builder.append(SplitCharEnum.COMMA.getName());
}
}
builder.append(" WHERE id = ");
builder.append(SqlHelper.toJdbcValue(this.getId().toString()));
return builder.toString();
}
}
| 27.975 | 111 | 0.644772 |
ee51619e7db69e3705ab37c0645443a221edc13d | 774 | package com.example.android.sunshine.ui.list;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModel;
import com.example.android.sunshine.data.SunshineRepository;
import com.example.android.sunshine.data.database.ListViewWeatherEntry;
import com.example.android.sunshine.data.database.WeatherEntry;
import java.util.Date;
import java.util.List;
public class MainActivityViewModel extends ViewModel {
// Weather forecasts the user is looking at
private LiveData<List<ListViewWeatherEntry>> mForecasts;
public MainActivityViewModel(SunshineRepository repository) {
mForecasts = repository.getCurrentWeatherForecasts();
}
public LiveData<List<ListViewWeatherEntry>> getForecast() {
return mForecasts;
}
}
| 30.96 | 71 | 0.789406 |
e1744f78aa275d1ddc118c6682a6b1afc347c124 | 7,358 | package logic.util;
import java.util.ArrayList;
import game.GameMap;
import game.Site;
import game.Stats;
import logic.Constants;
import logic.Constants.A;
import logic.Constants.D;
import logic.Constants.F;
import logic.Constants.P;
import logic.Constants.S;
public class Actions {
public static boolean commitMove(Site a, Site b) {
if (a.isNot(S.USED) && (a != b)) {
a.outgoing += a.units;
b.incoming += a.units;
// b.accumulate(P.ALLOWED_UNITS, -a.units);
// if (a.action != A.BUMP) {
float decay = ((b.incoming + b.units - b.outgoing) / Constants.MAX_UNITS);
for (Site n : b.neighbors.values())
n.scale(F.DAMAGE, 1f - (0.35f * decay));
for (Site n : a.neighbors.values())
n.scale(F.REINFORCE, 1f - (0.0125f * decay));
// }
a.set(S.USED);
return true;
}
return false;
}
public static void joint(Site s) {
ArrayList<D> ambushers = new ArrayList<D>();
for (D d : Constants.CARDINALS) {
Site n = s.neighbors.get(d);
if (n.is(S.MINE) && n.isNot(S.USED) && (n.v(F.REINFORCE) <= s.v(F.EXPLORE)) && (n.v(F.DAMAGE) == 0))
ambushers.add(d);
}
if (ambushers.size() > 1) {
int setSize = 1 << ambushers.size();
float lowest = Float.MAX_VALUE;
ArrayList<D> lowestAmbushers = new ArrayList<D>();
for (int selection = 1; selection < setSize; selection++) {
int cursor = selection;
ArrayList<D> temp = new ArrayList<D>();
if ((cursor & 1) == 1)
temp.add(ambushers.get(0));
if ((cursor & 2) == 2)
temp.add(ambushers.get(1));
if ((cursor & 4) == 4)
temp.add(ambushers.get(2));
if ((cursor & 8) == 8)
temp.add(ambushers.get(3));
float tempTotal = 0;
for (D d : temp)
tempTotal += s.neighbors.get(d).units;
tempTotal += s.incoming - s.units;
if ((tempTotal > 0) && (tempTotal <= Constants.MAX_UNITS) && (tempTotal < lowest)) {
lowestAmbushers = temp;
lowest = tempTotal;
}
}
for (D d : lowestAmbushers) {
Site neighbor = s.neighbors.get(d);
neighbor.heading = Site.reverse(d);
Actions.commitMove(neighbor, s);
neighbor.action = A.JOINT;
}
}
}
public static void claim(Site s) {
for (D d : Constants.CARDINALS) {
Site neighbor = s.neighbors.get(d);
if (ValidateAction.claim(s, neighbor) && (s.v(F.REINFORCE) <= neighbor.v(F.EXPLORE))) {
if (s.target() == s)
s.heading = d;
else {
if (((s.target().v(F.EXPLORE) == neighbor.v(F.EXPLORE)) &&
(s.target().v(P.EXPLORE_VALUE) < neighbor.v(P.EXPLORE_VALUE))) ||
(s.target().v(F.EXPLORE) < neighbor.v(F.EXPLORE)))
s.heading = d;
}
}
}
if (s.moving())
s.action = A.CLAIM;
}
public static void explore(Site s) {
for (D d : Constants.CARDINALS) {
Site neighbor = s.neighbors.get(d);
if (ValidateAction.explore(s, neighbor) && (s.v(F.REINFORCE) <= neighbor.v(F.EXPLORE))) {
if (s.target() == s)
s.heading = d;
else {
if (((s.target().v(F.EXPLORE) == neighbor.v(F.EXPLORE)) &&
(s.target().v(P.EXPLORE_VALUE) < neighbor.v(P.EXPLORE_VALUE))) ||
(s.target().v(F.EXPLORE) < neighbor.v(F.EXPLORE)))
s.heading = d;
}
}
}
if (s.moving())
s.action = A.EXPLORE;
}
public static void assist(Site s) {
Site target = s;
ArrayList<D> help = new ArrayList<D>();
for (D d : Constants.CARDINALS) {
Site neighbor = s.neighbors.get(d);
if (neighbor.is(S.MINE)) {
if (!neighbor.is(S.USED) && (s.v(F.REINFORCE) >= neighbor.v(F.REINFORCE)) && (neighbor.v(F.DAMAGE) == 0))
help.add(d);
} else if (neighbor.is(S.UNEXPLORED))
if ((target.v(F.EXPLORE) <= neighbor.v(F.EXPLORE)) && (s.v(F.REINFORCE) <= neighbor.v(F.EXPLORE)))
target = neighbor;
}
if ((target != s) && ((s.incoming + s.units + s.v(P.GENERATOR)) < target.units) && (s.outgoing == 0)) {
int setSize = 1 << help.size();
float lowest = Float.MAX_VALUE;
ArrayList<D> lowestHelp = new ArrayList<D>();
for (int selection = 1; selection < setSize; selection++) {
int cursor = selection;
ArrayList<D> temp = new ArrayList<D>();
if ((cursor & 1) == 1)
temp.add(help.get(0));
if ((cursor & 2) == 2)
temp.add(help.get(1));
if ((cursor & 4) == 4)
temp.add(help.get(2));
if ((cursor & 8) == 8)
temp.add(help.get(3));
float tempTotal = 0;
for (D d : temp)
tempTotal += s.neighbors.get(d).units;
tempTotal += s.incoming + s.units + s.v(P.GENERATOR) - target.units;
if ((tempTotal > 0) && (tempTotal <= Constants.MAX_UNITS) && (tempTotal < lowest)) {
lowestHelp = temp;
lowest = tempTotal;
}
}
for (D d : lowestHelp) {
Site neighbor = s.neighbors.get(d);
neighbor.heading = Site.reverse(d);
Actions.commitMove(neighbor, s);
neighbor.action = A.ASSIST;
}
if (lowestHelp.size() > 0)
s.set(S.USED);
}
}
public static void reinforce(Site s, F field) {
D bump = null;
for (D d : Constants.CARDINALS) {
Site neighbor = s.neighbors.get(d);
if (ValidateAction.move(s, neighbor) && (s.target().v(field) < neighbor.v(field))) {
s.heading = d;
bump = null;
}
if (ValidateAction.bump(s, neighbor) && (s.target().v(field) < neighbor.v(field))) {
s.heading = d;
bump = d;
}
}
if (bump != null) {
Site target = s.target();
target.heading = Site.reverse(bump);
commitMove(target, s);
target.action = A.BUMP;
}
if (s.moving())
s.action = A.REINFORCE;
}
public static void attack(Site s) {
int lowestCount = Integer.MAX_VALUE;
for (D d : Constants.CARDINALS) {
Site neighbor = s.neighbors.get(d);
int count = 0;
for (Site n : neighbor.neighbors.values())
if (n.is(S.MINE))
count++;
else if (n.is(S.ENEMY))
count--;
else
count -= 0.5f;
if (ValidateAction.attack(s, neighbor) &&
(count <= lowestCount) &&
(s.target().v(F.DAMAGE) <= neighbor.v(F.DAMAGE))) {
lowestCount = count;
s.heading = d;
}
}
if (s.moving())
s.action = A.ATTACK;
}
public static void breach(Site s, GameMap map) {
for (D d : Constants.CARDINALS) {
Site neighbor = s.neighbors.get(d);
if (ValidateAction.breach(s, neighbor, map) &&
(s.target().v(F.DAMAGE) <= neighbor.v(F.DAMAGE))) {
s.heading = d;
}
}
if (s.moving())
s.action = A.BREACH;
}
public static void capture(Site s) {
int lowestCount = Integer.MAX_VALUE;
for (D d : Constants.CARDINALS) {
Site neighbor = s.neighbors.get(d);
int count = 0;
for (Site n : neighbor.neighbors.values())
if (n.is(S.MINE))
count++;
else if (n.is(S.ENEMY))
count--;
if (ValidateAction.capture(s, neighbor) &&
(count <= lowestCount) &&
((s.target().v(F.DAMAGE) <= neighbor.v(F.DAMAGE)) || (s.units <= Stats.maxGenerator))) {
lowestCount = count;
s.heading = d;
}
}
if (s.moving())
s.action = A.CAPTURE;
}
public static void lock(Site s, float mapScaling) {
if (s.moving() && (s.units > Stats.maxGenerator)) {
float unitBuildUp = 0;
for (Site n : s.target().neighbors.values())
if (n.is(S.ENEMY))
unitBuildUp += n.units * 0.7f;
float units = s.units + s.incoming - s.outgoing;
if (unitBuildUp < units * 1.1f)
for (Site n : s.target().neighbors.values())
n.set(P.ALLOWED_UNITS, 0);
}
}
}
| 28.191571 | 107 | 0.584126 |
3a6d88bcf6aa670114ba3f8575b6b860e3e2f45d | 926 | package com.sequenceiq.sdx.api;
import org.junit.jupiter.api.Test;
import com.sequenceiq.sdx.api.model.ModelDescriptions;
import com.sequenceiq.sdx.api.model.SdxClusterDetailResponse;
import com.sequenceiq.sdx.api.model.SdxClusterDetailResponseTest;
import com.sequenceiq.sdx.api.model.diagnostics.docs.DiagnosticsOperationDescriptions;
import com.sequenceiq.cloudbreak.apiformat.ApiFormatValidator;
public class ApiFormatTest {
@Test
public void testApiFormat() {
ApiFormatValidator.builder()
.modelPackage("com.sequenceiq.sdx.api.model")
.excludedClasses(
SdxClusterDetailResponseTest.class,
SdxClusterDetailResponse.Builder.class,
ModelDescriptions.class,
DiagnosticsOperationDescriptions.class
)
.build()
.validate();
}
}
| 34.296296 | 86 | 0.663067 |
04744c13c19835acc2d02d9a29b2af4a80a8bfcb | 1,875 | package com.believeyourself.leetcode.wordPattern;
import java.util.HashMap;
import java.util.Map;
/**
* 290. Word Pattern
* Given a pattern and a string str, find if str follows the same pattern.
*
* Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
*
* Example 1:
*
* Input: pattern = "abba", str = "dog cat cat dog"
* Output: true
* Example 2:
*
* Input:pattern = "abba", str = "dog cat cat fish"
* Output: false
* Example 3:
*
* Input: pattern = "aaaa", str = "dog cat cat dog"
* Output: false
* Example 4:
*
* Input: pattern = "abba", str = "dog dog dog dog"
* Output: false
* Notes:
* You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space.
*/
public class WordPattern {
/**
* 要注意两个方向都要判断,如Example 4
* @param pattern
* @param str
* @return
*/
public boolean wordPattern(String pattern, String str) {
if(pattern == null || str == null){
return false;
}
char [] patterns = pattern.toCharArray();
String[] strs = str.split(" ");
if(patterns.length!= strs.length){
return false;
}
Map<Character, String> char2Str = new HashMap<>();
Map<String, Character> str2Char = new HashMap<>();
for(int i = 0; i < patterns.length; i++){
if(char2Str.containsKey(patterns[i])){
if(!char2Str.get(patterns[i]).equals(strs[i])){
return false;
}
}else{
if(str2Char.containsKey(strs[i])){
return false;
}
char2Str.put(patterns[i], strs[i]);
str2Char.put(strs[i], patterns[i]);
}
}
return true;
}
}
| 27.985075 | 134 | 0.565867 |
057e60f67a569600d12567f801310c00761ebc52 | 566 | package web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AdminServlet extends HttpServlet {
/**
* The method handles the admin login before user can upload any data file
*/
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
req.getRequestDispatcher("/admin/adminupload.jsp").forward(req, resp);
}
}
| 28.3 | 108 | 0.772085 |
6d1d130b00762b3334280375aed91f19a20d0b4e | 1,811 | package com.kenshoo.pl.entity.spi.helpers;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.kenshoo.jooq.DataTable;
import com.kenshoo.jooq.TempTableHelper;
import com.kenshoo.jooq.TempTableResource;
import com.kenshoo.pl.data.ImpersonatorTable;
import com.kenshoo.pl.entity.EntityField;
import com.kenshoo.pl.entity.EntityType;
import com.kenshoo.pl.entity.FieldsValueMap;
import org.jooq.DSLContext;
import java.util.Collection;
import java.util.stream.Stream;
public class EntitiesTempTableCreator {
private final DSLContext dslContext;
public EntitiesTempTableCreator(DSLContext dslContext) {
this.dslContext = dslContext;
}
public <E extends EntityType<E>> TempTableResource<ImpersonatorTable> createTempTable(final Collection<? extends EntityField<E, ?>> fields, final Collection<? extends FieldsValueMap<E>> fieldsValueMaps) {
Preconditions.checkArgument(!fields.isEmpty(), "fields is empty");
//noinspection ConstantConditions
DataTable primaryTable = Iterables.getFirst(fields, null).getDbAdapter().getTable();
ImpersonatorTable impersonatorTable = new ImpersonatorTable(primaryTable);
fields.stream().flatMap(field -> field.getDbAdapter().getTableFields()).forEach(impersonatorTable::createField);
return TempTableHelper.tempInMemoryTable(dslContext, impersonatorTable, batchBindStep -> {
fieldsValueMaps.forEach(entityChange -> batchBindStep.bind(fields.stream().flatMap(field -> getDbValues(entityChange, field)).toArray()));
});
}
private <E extends EntityType<E>, T> Stream<Object> getDbValues(FieldsValueMap<E> fieldsValueMap, EntityField<E, T> field) {
return field.getDbAdapter().getDbValues(fieldsValueMap.get(field));
}
}
| 45.275 | 208 | 0.764219 |
5e4dd913a8fcbb3ff185e7922131c4cfc76b6fbd | 1,562 | /**
* Project Name:EHealthData
* File Name:WorkFlow.java
* Package Name:com.ghit.wf.model
* Date:2016年8月28日下午10:09:58
*/
package com.haojiankang.framework.provider.sysmanager.api.service.wf;
import java.util.List;
import java.util.Map;
import com.haojiankang.framework.commons.utils.security.model.IUser;
import com.haojiankang.framework.provider.sysmanager.api.model.vo.wf.Activity;
import com.haojiankang.framework.provider.sysmanager.api.model.vo.wf.BPD;
import com.haojiankang.framework.provider.sysmanager.api.model.vo.wf.BPN;
import com.haojiankang.framework.provider.sysmanager.api.model.vo.wf.BPNAction;
import com.haojiankang.framework.provider.sysmanager.api.model.vo.wf.WFProcess;
/**
* ClassName:WorkFlow <br/>
* Function: TODO ADD FUNCTION. <br/>
* Date: 2016年8月28日 下午10:09:58 <br/>
*
* @author ren7wei
* @version
* @since JDK 1.6
* @see
*/
public interface WorkFlow {
WFProcess getFlowState(String id);
WFProcess StartUpProcess(String bpdCode, IUser user);
WFProcess ExecutiveAction(String processId, String actionCode, String message, IUser user);
BPD getBPD(String code);
BPN getBPN(String code);
BPNAction getAction(String code);
Activity getActivity(String id);
Map<String, List<Activity>> getActivityByProcessId(String... processId);
Map<String, List<Activity>> getActivityByProcessId(ActivitiesFilter filter, String... processId);
Map<String, Activity> getActivityByProcessId(ActivityFilter filter, String... processId);
Map<String, String> actionNodeMapping();
}
| 29.471698 | 101 | 0.756722 |
6a3be91c79068b96a4bd3a30712f5f7e0e075935 | 8,247 | package network.datahop.blediscovery;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattServerCallback;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.os.ParcelUuid;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static network.datahop.blediscovery.Constants.CLIENT_CONFIGURATION_DESCRIPTOR_UUID;
/**
* GattServerCallback extends BluetoothGattServerCallback and overwrites all functions required to
* accept GATT connections and read/write characteristics.
*/
public class GattServerCallback extends BluetoothGattServerCallback {
private BluetoothGattServer mGattServer;
private List<BluetoothDevice> mDevices;
private Map<String, byte[]> mClientConfigurations;
String network, password;
private Context mContext;
BluetoothGattCharacteristic mCharacteristic;
ParcelUuid mServiceUUID;
private static final String TAG = "GattServerCallback";
private HashMap<UUID, String> advertisingInfo;
DiscoveryListener listener;
public GattServerCallback(Context context, String parcelUuid, HashMap<UUID, String> advertisingInfo, DiscoveryListener listener) {//WifiDirectHotSpot hotspot, HashMap<UUID,ContentAdvertisement> ca, ParcelUuid service_uuid,StatsHandler stats,List<String> groups) {
mDevices = new ArrayList<>();
mClientConfigurations = new HashMap<>();
mContext = context;
network = null;
mServiceUUID = new ParcelUuid(UUID.nameUUIDFromBytes(parcelUuid.getBytes()));
this.advertisingInfo = advertisingInfo;
Log.d(TAG, "Service uuid:" + mServiceUUID + " " + parcelUuid);
this.listener = listener;
}
public void stop() {
if(mGattServer!=null)mGattServer.close();
network = password = null;
mGattServer = null;
}
public void setServer(BluetoothGattServer gattServer) {
mGattServer = gattServer;
}
@Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
super.onConnectionStateChange(device, status, newState);
if (newState == BluetoothProfile.STATE_CONNECTED) {
mDevices.add(device);
// int con = stats.getBtConnections();
// stats.setBtConnections(++con);
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
mDevices.remove(device);
mClientConfigurations.remove(device.getAddress());
mCharacteristic = null;
}
}
@Override
public void onCharacteristicReadRequest(BluetoothDevice device,
int requestId,
int offset,
BluetoothGattCharacteristic characteristic) {
super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
if (BluetoothUtils.requiresResponse(characteristic)) {
// Unknown read characteristic requiring response, send failure
mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, 0, null);
}
}
@Override
public void onCharacteristicWriteRequest(BluetoothDevice device,
int requestId,
BluetoothGattCharacteristic characteristic,
boolean preparedWrite,
boolean responseNeeded,
int offset,
byte[] value) {
super.onCharacteristicWriteRequest(device,
requestId,
characteristic,
preparedWrite,
responseNeeded,
offset,
value);
List<UUID> groups = new ArrayList<>();
groups.addAll(advertisingInfo.keySet());
Log.d(TAG, "onCharacteristicWriteRequest");
if (BluetoothUtils.matchAnyCharacteristic(characteristic.getUuid(), groups)) {
mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, null);
String valueString = new String(value).split(":")[0];
String peerId = new String(value).split(":")[1];
String valueString2 = new String(advertisingInfo.get(characteristic.getUuid()));
Log.d(TAG, "Characteristic check " + characteristic.getUuid().toString() + " " + network + " " + valueString2 + " " + valueString);
if (!valueString.equals(valueString2)) {
Log.d(TAG, "Connecting");
listener.differentStatusDiscovered(value,characteristic.getUuid(),peerId);
} else {
Log.d(TAG, "Not Connecting");
listener.sameStatusDiscovered(characteristic.getUuid());
}
}
}
@Override
public void onDescriptorReadRequest(BluetoothDevice device,
int requestId,
int offset,
BluetoothGattDescriptor descriptor) {
super.onDescriptorReadRequest(device, requestId, offset, descriptor);
}
@Override
public void onDescriptorWriteRequest(BluetoothDevice device,
int requestId,
BluetoothGattDescriptor descriptor,
boolean preparedWrite,
boolean responseNeeded,
int offset,
byte[] value) {
super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite, responseNeeded, offset, value);
Log.d(TAG,"onDescriptorWriteRequest");
if (CLIENT_CONFIGURATION_DESCRIPTOR_UUID.equals(descriptor.getUuid())) {
Log.d(TAG,"onDescriptorWriteRequest");
mClientConfigurations.put(device.getAddress(), value);
mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, null);
}
}
@Override
public void onNotificationSent(BluetoothDevice device, int status) {
super.onNotificationSent(device, status);
}
public void notifyCharacteristic(byte[] value, UUID uuid) {
BluetoothGattService service = mGattServer.getService(mServiceUUID.getUuid());
BluetoothGattCharacteristic characteristic = service.getCharacteristic(uuid);
characteristic.setValue(value);
boolean confirm = BluetoothUtils.requiresConfirmation(characteristic);
for (BluetoothDevice device : mDevices) {
if (clientEnabledNotifications(device, characteristic)) {
mGattServer.notifyCharacteristicChanged(device, characteristic, confirm);
}
}
}
private boolean clientEnabledNotifications(BluetoothDevice device, BluetoothGattCharacteristic characteristic) {
List<BluetoothGattDescriptor> descriptorList = characteristic.getDescriptors();
BluetoothGattDescriptor descriptor = BluetoothUtils.findClientConfigurationDescriptor(descriptorList);
if (descriptor == null) {
return true;
}
String deviceAddress = device.getAddress();
byte[] clientConfiguration = mClientConfigurations.get(deviceAddress);
if (clientConfiguration == null) {
return false;
}
byte[] notificationEnabled = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
return clientConfiguration.length == notificationEnabled.length
&& (clientConfiguration[0] & notificationEnabled[0]) == notificationEnabled[0]
&& (clientConfiguration[1] & notificationEnabled[1]) == notificationEnabled[1];
}
}
| 41.029851 | 267 | 0.637201 |
aa4dccf55c4743c0419c6daeb592e5cd39233685 | 577 | package entidades;
public abstract class ContribuenteEntidade {
private String nome;
protected Double rendaAnual;
public ContribuenteEntidade() {
}
public ContribuenteEntidade(String nome, double rendaAnual) {
this.nome = nome;
this.rendaAnual = rendaAnual;
}
public abstract Double calcImposto();
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public double getRendaAnual() {
return rendaAnual;
}
public void setRendaAnual(double rendaAnual) {
this.rendaAnual = rendaAnual;
}
}
| 14.794872 | 62 | 0.717504 |
880da3419f44666313021b81140dfd20f7e3cd10 | 3,129 | package com.dasa.splitspends.controller;
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.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import com.dasa.splitspends.SplitspendsApplication;
import com.dasa.splitspends.config.DBConfiguration;
import com.dasa.splitspends.model.User;
import com.dasa.splitspends.payload.LoginRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { SplitspendsApplication.class, DBConfiguration.class })
@ActiveProfiles("web")
@AutoConfigureMockMvc
public class ControllerTestBase {
String jwt;
@Autowired
MockMvc mvc;
@Autowired
ObjectMapper objectMapper;
User nsagar;
User nsahas;
User sirimm;
User nsanvi;
User sneham;
@Before
public void setUp() throws Exception {
jwt = obtainAccessToken("nsahas@gmail.com", "splitspends");
nsagar = getUser(1002l);
nsahas = getUser(1001l);
sirimm = getUser(1003l);
sneham = getUser(1004l);
nsanvi = getUser(1008l);
}
private User getUser(Long id) throws Exception {
MvcResult result = mvc
.perform(get("/users/{id}",id.toString()).header("Authorization", "Bearer " + jwt).contentType(MediaType.APPLICATION_JSON))
.andDo(print()).andExpect(status().isOk()).andReturn();
return objectMapper.readValue(result.getResponse().getContentAsString(), User.class);
}
protected String obtainAccessToken(String email, String password) throws Exception {
LoginRequest loginRequest = new LoginRequest();
loginRequest.setEmail(email);
loginRequest.setPassword(password);
ResultActions result = mvc
.perform(post("/auth/login").contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(loginRequest))
.accept("application/json;charset=UTF-8"))
.andDo(print()).andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"));
String resultString = result.andReturn().getResponse().getContentAsString();
JacksonJsonParser jsonParser = new JacksonJsonParser();
return jsonParser.parseMap(resultString).get("accessToken").toString();
}
}
| 36.383721 | 130 | 0.787472 |
ef9bd6c35c63f374b8b4c084681c8b953420107a | 1,524 | package velascogculebras.personalizedfitworkouts.Controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import velascogculebras.personalizedfitworkouts.Repositories.EntrenadorRepository;
import velascogculebras.personalizedfitworkouts.Repositories.UsuarioReporsitory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Principal;
@Controller
public class LoggedController {
@Autowired
public EntrenadorRepository entrenadorRepository;
@Autowired
public UsuarioReporsitory usuarioReporsitory;
@RequestMapping("/login")
private String login() {
return "login";
}
@GetMapping("/logged")
private String logged(HttpSession session, HttpServletRequest request) {
Principal user = request.getUserPrincipal();
if (request.isUserInRole("ROLE_TRAINER")) {
session.setAttribute("user", entrenadorRepository.findByMail(user.getName()));
} else {
session.setAttribute("user", usuarioReporsitory.findByMail(user.getName()));
}
return "redirect:/";
}
@RequestMapping("/loginerror")
private String loginError(Model model) {
model.addAttribute("error", "Email or password incorrect");
return "login";
}
}
| 31.102041 | 90 | 0.748688 |
3a7da45d43391b3693cefb092f69a316f7297593 | 1,806 | package br.com.zupacademy.gabrielamartins.ecommerce.controller;
import br.com.zupacademy.gabrielamartins.ecommerce.service.Emails;
import br.com.zupacademy.gabrielamartins.ecommerce.model.Pergunta;
import br.com.zupacademy.gabrielamartins.ecommerce.model.Produto;
import br.com.zupacademy.gabrielamartins.ecommerce.model.Usuario;
import br.com.zupacademy.gabrielamartins.ecommerce.repository.PerguntaRepository;
import br.com.zupacademy.gabrielamartins.ecommerce.repository.ProdutoRepository;
import br.com.zupacademy.gabrielamartins.ecommerce.requestDto.PerguntaRequestDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import javax.transaction.Transactional;
import javax.validation.Valid;
import java.util.Optional;
@RestController
public class PerguntaController {
@Autowired
PerguntaRepository perguntaRepository;
@Autowired
ProdutoRepository produtoRepository;
@Autowired
Emails emails;
@PostMapping(value = "/produtos/{id}/perguntas")
@Transactional
public ResponseEntity<?> cadastrarPergunta(@Valid @RequestBody PerguntaRequestDto request, @PathVariable Long id, @AuthenticationPrincipal Usuario usuario){
Optional<Produto> produtoObject = produtoRepository.findById(id);
if(produtoObject.isPresent()){
Produto produto = produtoObject.get();
Pergunta pergunta = request.converteParaPergunta(produto, usuario);
perguntaRepository.save(pergunta);
emails.novaPergunta(pergunta);
return ResponseEntity.ok().build();
}
return ResponseEntity.badRequest().build();
}
}
| 36.857143 | 161 | 0.781285 |
6b331f873388f162570018dd4389e90664be8e93 | 13,854 | package it.polimi.deib.blackboard_mediator;
import it.polimi.deib.blackboard_mediator.utilities.Recommendation;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.query.DatasetAccessor;
import com.hp.hpl.jena.query.DatasetAccessorFactory;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.Syntax;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.impl.PropertyImpl;
import com.hp.hpl.jena.rdf.model.impl.ResourceImpl;
import com.hp.hpl.jena.vocabulary.RDF;
public class BlackboardMediator {
protected Logger logger = LoggerFactory.getLogger(BlackboardMediator.class);
private String agent;
private DatasetAccessor da;
private String prefixes = "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> . "
+ "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . "
+ "@prefix prov: <http://www.w3.org/ns/prov#> . "
+ "@prefix cpsma: <http://www.streamreasoning.com/demos/mdw14/fuseki/data/cpsma/> . ";
@SuppressWarnings("serial")
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") {
public StringBuffer format(Date date, StringBuffer toAppendTo,
java.text.FieldPosition pos) {
StringBuffer toFix = super.format(date, toAppendTo, pos);
return toFix.insert(toFix.length() - 2, ':');
};
};
private String serverURL = "http://www.streamreasoning.com/demos/mdw14/fuseki/blackboard/";
private String dataServerURL = serverURL + "data";
private String queryServerURL = serverURL + "query";
private String baseIRI = "http://www.streamreasoning.com/demos/mdw14/fuseki/data/";
public BlackboardMediator(String agent){
this.agent = agent;
this.baseIRI += agent+"/";
this.prefixes += "@prefix "+agent+": <http://www.streamreasoning.com/demos/mdw14/fuseki/data/"+agent+"/> . ";
this.da = DatasetAccessorFactory.createHTTP(dataServerURL);
}
public BlackboardMediator(String agent, String serverURL, String baseIRI) {
this(agent);
this.baseIRI = baseIRI+agent+"/";
this.serverURL=serverURL;
dataServerURL = serverURL + "data";
queryServerURL = serverURL + "query";
this.da = DatasetAccessorFactory.createHTTP(dataServerURL);
}
private String createGraphMetadata(long timestamp, String graphName) {
String content = prefixes;
content += agent + ":" + graphName
+ " a prov:Entity ; prov:wasAttributedTo cpsma:" + agent + ";";
Date d = new Date(timestamp);
content += "prov:generatedAtTime \"" + sdf.format(d)
+ "\"^^xsd:dateTime . ";
return content;
}
private Model createGraphMetadataDatasetAccessor(long timestamp, String graphName) throws DatatypeConfigurationException {
Model tempMetadataGraph = ModelFactory.createDefaultModel();
tempMetadataGraph.add(new ResourceImpl(graphName), RDF.type, new ResourceImpl("http://www.w3.org/ns/prov#Entity"));
tempMetadataGraph.add(new ResourceImpl(graphName), new PropertyImpl("http://www.w3.org/ns/prov#wasAttributedTo"), new ResourceImpl("http://www.streamreasoning.com/demos/mdw14/fuseki/data/cpsma/" + agent));
GregorianCalendar gc = new GregorianCalendar();
gc.setTimeInMillis(timestamp);
XMLGregorianCalendar xmlCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
tempMetadataGraph.add(new ResourceImpl(graphName), new PropertyImpl("http://www.w3.org/ns/prov#generatedAtTime"), tempMetadataGraph.createTypedLiteral(xmlCalendar.toXMLFormat(), XSDDatatype.XSDdateTime));
return tempMetadataGraph;
}
public void putNewGraph(Date date, String model) throws BlackboardException {
HttpClient client = HttpClientBuilder.create().build();
RequestBuilder rb = RequestBuilder.put();
rb.setUri(dataServerURL);
rb.addHeader("Content-Type", "text/turtle");
rb.addParameter("graph", baseIRI + date.getTime());
try {
rb.setEntity(new StringEntity(model));
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(),e);
throw new BlackboardException("Unable to put new graph",e);
}
HttpUriRequest putRequest = rb.build();
HttpResponse putResponse;
try {
putResponse = client.execute(putRequest);
logger.debug(putResponse.toString());
} catch (ClientProtocolException e) {
logger.error(e.getMessage(),e);
throw new BlackboardException("Unable to put new graph",e);
} catch (IOException e) {
logger.error(e.getMessage(),e);
throw new BlackboardException("Unable to put new graph", e);
}
String content = createGraphMetadata(date.getTime(), String.valueOf(date.getTime()));
client = HttpClientBuilder.create().build();
rb = RequestBuilder.post();
rb.setUri(dataServerURL);
rb.addHeader("Content-Type", "text/turtle");
rb.addParameter("graph", "default");
try {
rb.setEntity(new StringEntity(content));
} catch (UnsupportedEncodingException e) {
// TODO delete the graph just added
logger.error(e.getMessage(),e);
throw new BlackboardException("Graph put, unable to add its metadata",e);
}
HttpUriRequest postRequest = rb.build();
try {
HttpResponse postResponse = client.execute(postRequest);
logger.debug(postResponse.toString());
} catch (ClientProtocolException e) {
// TODO delete the graph just added
logger.error(e.getMessage(),e);
throw new BlackboardException("Graph put, unable to add its metadata",e);
} catch (IOException e) {
// TODO delete the graph just added
logger.error(e.getMessage(),e);
throw new BlackboardException("Graph put, unable to add its metadata",e);
}
}
public void putNewGraph(Date date, String userId, String model) throws BlackboardException {
if(agent.equals(Agents.VM)){
try {
String graphName = userId + "_" + date.getTime();
HttpClient client = HttpClientBuilder.create().build();
RequestBuilder rb = RequestBuilder.put();
rb.setUri(dataServerURL);
rb.addHeader("Content-Type", "text/turtle");
rb.addParameter("graph", baseIRI + graphName);
rb.setEntity(new StringEntity(model));
HttpUriRequest m = rb.build();
HttpResponse response;
response = client.execute(m);
logger.debug(response.toString());
String content = createGraphMetadata(date.getTime(), graphName);
client = HttpClientBuilder.create().build();
rb = RequestBuilder.post();
rb.setUri(dataServerURL);
rb.addHeader("Content-Type", "text/turtle");
rb.addParameter("graph", "default");
rb.setEntity(new StringEntity(content));
m = rb.build();
response = client.execute(m);
logger.debug(response.toString());
} catch (ClientProtocolException e) {
logger.error(e.getMessage(),e);
throw new BlackboardException("Unable to put new graph",e);
} catch (IOException e) {
logger.error(e.getMessage(),e);
throw new BlackboardException("Unable to put new graph", e);
}
} else {
logger.error("This method could be executed only by the Visitor Modeler. Please try to use putNewGraph(Date date, String model). ");
throw new BlackboardException("This method could be executed only by the Visitor Modeler. Please try to use putNewGraph(Date date, String model). ");
}
}
public void putNewGraphDatasetAccessor(Date date, Model model) throws BlackboardException {
// if(agent.equals(Agents.SL)){
try {
da.add(createGraphMetadataDatasetAccessor(date.getTime(), baseIRI + date.getTime()));
da.putModel(baseIRI + date.getTime(), model);
} catch (DatatypeConfigurationException e) {
logger.error(e.getMessage(),e);
throw new BlackboardException(e.getMessage(),e);
}
// } else {
// logger.error("This method could be executed only by the Social Listener. Please try to use putNewGraph(Date date, String model) or putNewGraph(Date date, String userID, String model). ");
// throw new BlackboardException("This method could be executed only by the Social Listener. Please try to use putNewGraph(Date date, String model) or putNewGraph(Date date, String userID, String model). ");
// }
}
public List<String> getRecentGraphNames(Date date) {
String query = "prefix xsd: <http://www.w3.org/2001/XMLSchema#> "
+ "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "
+ "prefix prov: <http://www.w3.org/ns/prov#> "
+ "prefix cpsma: <http://www.streamreasoning.com/demos/mdw14/fuseki/data/cpsma/> "
+ "SELECT " + "?g " + "WHERE { " + "?g a prov:Entity ; "
+ " prov:wasAttributedTo cpsma:" + agent + " ; "
+ " prov:generatedAtTime ?t . " + "FILTER (?t >= \""
+ sdf.format(date.getTime()) + "\"^^xsd:dateTime) " + "}";
logger.debug(query);
List<String> l = new LinkedList<String>();
Query q = QueryFactory.create(query, Syntax.syntaxSPARQL_11);
QueryExecution qexec = QueryExecutionFactory.sparqlService(
queryServerURL, q);
ResultSet r = qexec.execSelect();
for (; r.hasNext();) {
QuerySolution soln = r.nextSolution();
l.add(soln.get("g").toString());
}
return l;
}
public List<String> getRecentGraphNames(Date startDate, Date endDate) {
String query = "prefix xsd: <http://www.w3.org/2001/XMLSchema#> "
+ "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "
+ "prefix prov: <http://www.w3.org/ns/prov#> "
+ "prefix cpsma: <http://www.streamreasoning.com/demos/mdw14/fuseki/data/cpsma/> "
+ "SELECT " + "?g "
+ "WHERE { "
+ "?g a prov:Entity ; "
+ "prov:wasAttributedTo cpsma:" + agent + " ; "
+ "prov:generatedAtTime ?t . "
+ "FILTER (?t >= \"" + sdf.format(startDate.getTime()) + "\"^^xsd:dateTime && ?t <= \"" + sdf.format(endDate.getTime()) + "\"^^xsd:dateTime ) "
+ "}";
logger.debug(query);
List<String> l = new LinkedList<String>();
Query q = QueryFactory.create(query, Syntax.syntaxSPARQL_11);
QueryExecution qexec = QueryExecutionFactory.sparqlService(queryServerURL, q);
ResultSet r = qexec.execSelect();
for (; r.hasNext();) {
QuerySolution soln = r.nextSolution();
l.add(soln.get("g").toString());
}
return l;
}
public String getGraph(String graphName) throws BlackboardException {
HttpClient client = HttpClientBuilder.create().build();
RequestBuilder rb = RequestBuilder.get();
rb.setUri(dataServerURL);
rb.addHeader("Accept", "text/turtle; charset=utf-8");
rb.addParameter("graph", graphName);
HttpUriRequest m = rb.build();
HttpResponse response;
try {
response = client.execute(m);
logger.debug(response.toString());
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
logger.error(e.getMessage(),e);
throw new BlackboardException("Unable to get recent graph",e);
} catch (IOException e) {
logger.error(e.getMessage(),e);
throw new BlackboardException("Unable to get recent graph",e);
}
}
public Model getGraphModelDatasetAccessor(String graphName) throws BlackboardException {
// if(agent.equals(Agents.SL)){
return da.getModel(graphName);
// } else {
// logger.error("This method could be executed only by the Social Listener. Please try to use getGraph(String graphName). ");
// throw new BlackboardException("This method could be executed only by the Social Listener. Please try to use getGraph(String graphName). ");
// }
}
public Map<Long, Recommendation> retrieveAllRecommendations(String model){
HashMap<Long, Recommendation> reccomendations = new HashMap<Long, Recommendation>();
StringReader sr = new StringReader(model);
Model m = ModelFactory.createDefaultModel();
m.read(sr,null,"TURTLE");
String queryText = "PREFIX user:<http://www.streamreasoning.com/demos/mdw14/fuseki/data/user/> "
+ "PREFIX venue:<http://www.streamreasoning.com/demos/mdw14/fuseki/data/venue> "
+ "PREFIX sma:<http://www.citydatafusion.org/ontology/2014/1/sma#> "
+ "SELECT ?user ?obj ?prob "
+ "WHERE { "
+ "?user sma:shows_interest ?interest . "
+ "?interest sma:about ?obj ; "
+ "sma:has_probability ?prob . "
+ "}";
Query q = QueryFactory.create(queryText, Syntax.syntaxSPARQL_11);
QueryExecution qexec = QueryExecutionFactory.create(q,m);
ResultSet rs = qexec.execSelect();
String user;
Recommendation recommendation;
while (rs.hasNext()) {
QuerySolution querySolution = (QuerySolution) rs.next();
recommendation = new Recommendation();
user = querySolution.getResource("user").toString();
user = user.substring(user.lastIndexOf("/") + 1, user.length());
recommendation.setObjectName(querySolution.getResource("obj").toString());
recommendation.setRecommandationProbability(Float.parseFloat(querySolution.getLiteral("prob").getLexicalForm()));
reccomendations.put(Long.parseLong(user), recommendation);
}
return reccomendations;
}
}
| 37.142091 | 211 | 0.718421 |
cd774aae02ecb3941b6d363544457457c9656cd6 | 7,922 | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Aion-Lightning is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License
* along with Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.model.stats.calc.functions;
import com.aionemu.gameserver.model.gameobjects.Item;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.model.stats.calc.Stat2;
import com.aionemu.gameserver.model.stats.container.StatEnum;
import com.aionemu.gameserver.model.templates.item.ItemTemplate;
import java.util.ArrayList;
import java.util.List;
import static ch.lambdaj.Lambda.*;
/**
* @author ATracer
*/
public class PlayerStatFunctions {
private static final List<IStatFunction> FUNCTIONS = new ArrayList<IStatFunction>();
static {
FUNCTIONS.add(new PhysicalAttackFunction());
FUNCTIONS.add(new MagicalAttackFunction());
FUNCTIONS.add(new AttackSpeedFunction());
FUNCTIONS.add(new BoostCastingTimeFunction());
FUNCTIONS.add(new PvPAttackRatioFunction());
FUNCTIONS.add(new PDefFunction());
FUNCTIONS.add(new MaxHpFunction());
FUNCTIONS.add(new MaxMpFunction());
FUNCTIONS.add(new AgilityModifierFunction(StatEnum.BLOCK, 0.25f));
FUNCTIONS.add(new AgilityModifierFunction(StatEnum.PARRY, 0.25f));
FUNCTIONS.add(new AgilityModifierFunction(StatEnum.EVASION, 0.3f));
}
public static final List<IStatFunction> getFunctions() {
return FUNCTIONS;
}
public static final void addPredefinedStatFunctions(Player player) {
player.getGameStats().addEffectOnly(null, FUNCTIONS);
}
}
class PhysicalAttackFunction extends StatFunction {
PhysicalAttackFunction() {
stat = StatEnum.PHYSICAL_ATTACK;
}
@Override
public void apply(Stat2 stat) {
float power = stat.getOwner().getGameStats().getPower().getCurrent();
stat.setBase(Math.round(stat.getBase() * power / 100f));
}
@Override
public int getPriority() {
return 30;
}
}
class AgilityModifierFunction extends StatFunction {
private float modifier;
AgilityModifierFunction(StatEnum stat, float modifier) {
this.stat = stat;
this.modifier = modifier;
}
@Override
public void apply(Stat2 stat) {
float agility = stat.getOwner().getGameStats().getAgility().getCurrent();
stat.setBase(Math.round(stat.getBase() + stat.getBase() * (agility - 100) * modifier / 100f));
}
@Override
public int getPriority() {
return 30;
}
}
class MaxHpFunction extends StatFunction {
MaxHpFunction() {
stat = StatEnum.MAXHP;
}
@Override
public void apply(Stat2 stat) {
float health = stat.getOwner().getGameStats().getHealth().getCurrent();
stat.setBase(Math.round(stat.getBase() * health / 100f));
}
@Override
public int getPriority() {
return 30;
}
}
class MaxMpFunction extends StatFunction {
MaxMpFunction() {
stat = StatEnum.MAXMP;
}
@Override
public void apply(Stat2 stat) {
float will = stat.getOwner().getGameStats().getWill().getCurrent();
stat.setBase(Math.round(stat.getBase() * will / 100f));
}
@Override
public int getPriority() {
return 30;
}
}
class MagicalAttackFunction extends StatFunction {
MagicalAttackFunction() {
stat = StatEnum.MAGICAL_ATTACK;
}
@Override
public void apply(Stat2 stat) {
float knowledge = stat.getOwner().getGameStats().getKnowledge().getCurrent();
stat.setBase(Math.round(stat.getBase() * knowledge / 100f));
}
@Override
public int getPriority() {
return 30;
}
}
class PDefFunction extends StatFunction {
PDefFunction() {
stat = StatEnum.PHYSICAL_DEFENSE;
}
@Override
public void apply(Stat2 stat) {
if (stat.getOwner().isInFlyingState()) {
stat.setBonus(stat.getBonus() - (stat.getBase() / 2));
}
}
@Override
public int getPriority() {
return 60;
}
}
class AttackSpeedFunction extends DuplicateStatFunction {
AttackSpeedFunction() {
stat = StatEnum.ATTACK_SPEED;
}
}
class BoostCastingTimeFunction extends DuplicateStatFunction {
BoostCastingTimeFunction() {
stat = StatEnum.BOOST_CASTING_TIME;
}
}
class PvPAttackRatioFunction extends DuplicateStatFunction {
PvPAttackRatioFunction() {
stat = StatEnum.PVP_ATTACK_RATIO;
}
}
class DuplicateStatFunction extends StatFunction {
@Override
public void apply(Stat2 stat) {
Item mainWeapon = ((Player) stat.getOwner()).getEquipment().getMainHandWeapon();
Item offWeapon = ((Player) stat.getOwner()).getEquipment().getOffHandWeapon();
if (mainWeapon != null) {
StatFunction func1 = null;
StatFunction func2 = null;
List<StatFunction> functions = new ArrayList<StatFunction>();
List<StatFunction> functions1 = mainWeapon.getItemTemplate().getModifiers();
if (functions1 != null) {
List<StatFunction> f1 = getFunctions(functions1, stat, mainWeapon);
if (!f1.isEmpty()) {
func1 = f1.get(0);
functions.addAll(f1);
}
}
if (mainWeapon.hasFusionedItem()) {
ItemTemplate template = mainWeapon.getFusionedItemTemplate();
List<StatFunction> functions2 = template.getModifiers();
if (functions2 != null) {
List<StatFunction> f2 = getFunctions(functions2, stat, mainWeapon);
if (!f2.isEmpty()) {
func2 = f2.get(0);
functions.addAll(f2);
}
}
} else if (offWeapon != null) {
List<StatFunction> functions2 = offWeapon.getItemTemplate().getModifiers();
if (functions2 != null) {
functions.addAll(getFunctions(functions2, stat, offWeapon));
}
}
if (func1 != null && func2 != null) { // for fusioned weapons
if (Math.abs(func1.getValue()) >= Math.abs(func2.getValue())) {
functions.remove(func2);
} else {
functions.remove(func1);
}
}
if (!functions.isEmpty()) {
if (getName() == StatEnum.PVP_ATTACK_RATIO) {
forEach(functions).apply(stat);
} else {
((StatFunction) selectMax(functions, on(StatFunction.class).getValue())).apply(stat);
}
functions.clear();
}
}
}
private List<StatFunction> getFunctions(List<StatFunction> list, Stat2 stat, Item item) {
List<StatFunction> functions = new ArrayList<StatFunction>();
for (StatFunction func : list) {
StatFunctionProxy func2 = new StatFunctionProxy(item, func);
if (func.getName() == getName() && func2.validate(stat, func2)) {
functions.add(func);
}
}
return functions;
}
@Override
public int getPriority() {
return 60;
}
}
| 29.781955 | 105 | 0.618026 |
1252079c8d6cada851afa46ef8fac756c77bfd41 | 1,051 | package com.lbibera.tradebutler.datacore.stock.model;
/**
* Types of Issued Stocks
* http://www.investopedia.com/university/stocks/stocks2.asp
*/
public enum IssueType {
/**
* When people talk about stocks they are usually referring to common stock.
* In fact, the great majority of stock is issued is in this form.
* Common shares represent a claim on profits (dividends) and confer voting rights.
*
* Investors most often get one vote per share-owned to elect board members
* who oversee the major decisions made by management
*/
COMMON,
/**
* Preferred stock functions similarly to bonds,
* and usually doesn't come with the voting rights.
*
* With preferred shares, investors are usually guaranteed a fixed dividend in perpetuity.
* This is different from common stock which has variable dividends that are declared by the board of directors
* and never guaranteed. In fact, many companies do not pay out dividends to common stock at all.
*/
PREFERRED,
}
| 36.241379 | 115 | 0.707897 |
dd2de4219c9624ac16dba5b728548c2c3ecdeeb4 | 1,110 | package carte;
import joueur.Joueur;
import joueur.ListeJoueur;
import partie.Manche;
/**
* Classe modelisant la carte inversion
* @author ikounga_marvel
*
*/
public class Inversion extends CarteSpeciale {
/**
* Constructeur de la classe
* @param couleur couleur de la carte
* @param image image de la carte
*/
public Inversion(String couleur, String image) {
super(couleur, 20, "inversion", image);
}
/* (non-Javadoc)
* @see carte.CarteSpeciale#agir(partie.Manche, joueur.Joueur, int)
*/
@Override
public Joueur agir(Manche manche, Joueur joueurActuel, int tourDeJeu) {
ListeJoueur joueurs = manche.getJoueurs();
Joueur joueurSuivant;
boolean sens = manche.isSens();
if (joueurs.compterJoueurs() == 2) {
System.out.println("Mode 2 joueurs c'est toujours a "+joueurActuel.getPseudonyme()+" de jouer");
joueurSuivant = joueurActuel;
} else {
joueurSuivant = joueurs.joueurPrecedent(joueurActuel,sens);
System.out.println("Changement du sens de la manche. Cest a "+joueurSuivant.getPseudonyme());
}
manche.changerSens();
return joueurSuivant;
}
} | 25.227273 | 99 | 0.715315 |
e21db3dc1c6c397eef2a11828e36bfaf8ace57c3 | 1,388 | /**
* Copyright 2004-present, Facebook, Inc.
*
* <p>Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.profilo.provider.stacktrace;
import android.os.Process;
import com.facebook.proguard.annotations.DoNotStrip;
import com.facebook.soloader.SoLoader;
public class StackTraceWhitelist {
static {
SoLoader.loadLibrary("profilo_stacktrace");
}
public static void add(int threadId) {
nativeAddToWhitelist(threadId);
}
public static void remove(int threadId) {
if (threadId != Process.myPid()) {
// When in wall clock mode, we always profile the main thread, so we don't
// support de-whitelisting it.
nativeRemoveFromWhitelist(threadId);
}
}
@DoNotStrip
private static native void nativeAddToWhitelist(int targetThread);
@DoNotStrip
private static native void nativeRemoveFromWhitelist(int targetThread);
}
| 32.27907 | 99 | 0.743516 |
14bbf7810b6f4d5cb2f4c8090cb21bd95477a949 | 155 | package godofjava.java;
/**
* Create file : ${FILE_NAME}
* Creator : KimBangHyun
* Create time : 2017. 3. 3. 오전 8:06
*/
public class JavaPackage {
}
| 14.090909 | 36 | 0.645161 |
81ac172444d9fbf32100d8fcc4bdf4dd50cf81b1 | 1,760 |
package com.commercetools.api.models.extension;
import java.time.*;
import java.util.*;
import java.util.function.Function;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.*;
import io.vrap.rmf.base.client.utils.Generated;
@Generated(value = "io.vrap.rmf.codegen.rendring.CoreCodeGenerator", comments = "https://github.com/vrapio/rmf-codegen")
@JsonDeserialize(as = ExtensionChangeDestinationActionImpl.class)
public interface ExtensionChangeDestinationAction extends ExtensionUpdateAction {
String CHANGE_DESTINATION = "changeDestination";
@NotNull
@Valid
@JsonProperty("destination")
public ExtensionDestination getDestination();
public void setDestination(final ExtensionDestination destination);
public static ExtensionChangeDestinationAction of() {
return new ExtensionChangeDestinationActionImpl();
}
public static ExtensionChangeDestinationAction of(final ExtensionChangeDestinationAction template) {
ExtensionChangeDestinationActionImpl instance = new ExtensionChangeDestinationActionImpl();
instance.setDestination(template.getDestination());
return instance;
}
public static ExtensionChangeDestinationActionBuilder builder() {
return ExtensionChangeDestinationActionBuilder.of();
}
public static ExtensionChangeDestinationActionBuilder builder(final ExtensionChangeDestinationAction template) {
return ExtensionChangeDestinationActionBuilder.of(template);
}
default <T> T withExtensionChangeDestinationAction(Function<ExtensionChangeDestinationAction, T> helper) {
return helper.apply(this);
}
}
| 34.509804 | 120 | 0.785227 |
dc3f2e3ed0454420a3c2bf711170ef12d75d8a00 | 8,723 | /*
* The MIT License (MIT)
*
* Copyright (c) 2020 Ziver Koc
*
* 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 zutil.net.http;
import zutil.StringUtil;
import zutil.io.IOUtil;
import zutil.io.StringInputStream;
import zutil.parser.URLDecoder;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
public class HttpHeaderParser {
private static final Pattern PATTERN_COLON = Pattern.compile(":");
private static final Pattern PATTERN_EQUAL = Pattern.compile("=");
private static final Pattern PATTERN_AND = Pattern.compile("&");
private InputStream in;
private boolean skipStatusLine;
/**
* Parses the HTTP header information from a stream
*
* @param in is the stream
*/
public HttpHeaderParser(InputStream in) {
this.in = in;
this.skipStatusLine = false;
}
/**
* Parses the HTTP header information from a String
*
* @param in is the String
*/
public HttpHeaderParser(String in) {
this(new StringInputStream(in));
}
public HttpHeader read() throws IOException {
HttpHeader header = new HttpHeader();
String line;
// First line
if (!skipStatusLine) {
if ((line = IOUtil.readLine(in)) != null && !line.isEmpty())
parseStatusLine(header, line);
else
return null;
}
// Read header body
while ((line = IOUtil.readLine(in)) != null && !line.isEmpty()) {
parseHeaderLine(header.getHeaderMap(), line);
}
// Post processing
parseCookieValues(header.getCookieMap(), header.getHeader(HttpHeader.HEADER_COOKIE));
header.setInputStream(in);
return header;
}
/**
* @param skipStatusLine indicates if the parser should expect a http status lines. (default: true)
*/
public void skipStatusLine(boolean skipStatusLine) {
this.skipStatusLine = skipStatusLine;
}
/**
* Parses the first line of a http request/response and stores the values in a HttpHeader object
*
* @param header the header object where the cookies will be stored.
* @param statusLine the status line String
*/
private static void parseStatusLine(HttpHeader header, String statusLine) {
String[] lineArr = statusLine.split(" ", 3);
if (lineArr.length != 3)
return;
// Server Response
if (lineArr[0].contains("/")) {
header.setIsRequest(false);
header.setProtocol(lineArr[0].substring(0, lineArr[0].indexOf('/')));
header.setProtocolVersion(Float.parseFloat(lineArr[0].substring(lineArr[0].indexOf('/')+1)));
header.setResponseStatusCode(Integer.parseInt(lineArr[1]));
header.getResponseStatusString(lineArr[2]);
}
// Client Request
else {
header.setIsRequest(true);
header.setRequestType(lineArr[0]);
header.setProtocol(lineArr[2].substring(0, lineArr[2].indexOf('/')));
header.setProtocolVersion(Float.parseFloat(lineArr[2].substring(lineArr[2].indexOf('/')+1)));
String url = lineArr[1];
// parse URL and attributes
int paramStartIndex = url.indexOf('?');
if (paramStartIndex >= 0) {
parseURLParameters(header.getURLAttributeMap(), url.substring(paramStartIndex + 1));
url = url.substring(0, paramStartIndex);
}
header.setRequestURL(url.trim());
}
}
/**
* Parses a http key value paired header line.
* Note that all header keys will be stored with
* uppercase notation to make them case insensitive.
*
* @param map a map where the header key(Uppercase) and value will be stored.
* @param line is the next line in the header
*/
public static void parseHeaderLine(Map<String, String> map, String line) {
String[] data = PATTERN_COLON.split(line, 2);
map.put(
data[0].trim().toUpperCase(), // Key
(data.length > 1 ? data[1] : "").trim()); //Value
}
/**
* Parses a raw cookie header into key and value pairs
*
* @param map the Map where the cookies will be stored.
* @param cookieValue the raw cookie header value String that will be parsed
*/
public static void parseCookieValues(Map<String, String> map, String cookieValue) {
parseHeaderValues(map, cookieValue, ";");
}
/**
* Parses a header value string that contains key and value paired data and
* stores them in a HashMap. If a pair only contain a key then the value
* will be set as a empty string.
* <p>
* TODO: method is not quote aware
*
* @param headerValue the raw header value String that will be parsed.
* @param delimiter the delimiter that separates key and value pairs (e.g. ';' for Cookies or ',' for Cache-Control)
*/
public static HashMap<String, String> parseHeaderValues(String headerValue, String delimiter) {
HashMap<String, String> map = new HashMap<>();
parseHeaderValues(map, headerValue, delimiter);
return map;
}
/**
* Parses a header value string that contains key and value paired data and
* stores them in a HashMap. If a pair only contain a key then the value
* will be set as a empty string.
* <p>
* TODO: method is not quote aware
*
* @param map the Map where key and values will be stored.
* @param headerValue the raw header value String that will be parsed.
* @param delimiter the delimiter that separates key and value pairs (e.g. ';' for Cookies or ',' for Cache-Control)
*/
public static void parseHeaderValues(Map<String, String> map, String headerValue, String delimiter) {
if (headerValue != null && !headerValue.isEmpty()) {
String[] tmpArr = headerValue.split(delimiter);
for (String cookie : tmpArr) {
String[] tmpStr = PATTERN_EQUAL.split(cookie, 2);
map.put(
tmpStr[0].trim(), // Key
StringUtil.trim((tmpStr.length > 1 ? tmpStr[1] : "").trim(), '\"')); //Value
}
}
}
/**
* Parses a string with variables from a get or post request that was sent from a client
*
* @param header the header object where the url attributes key and value will be stored.
* @param urlAttributes is the String containing all the attributes
*/
public static void parseURLParameters(HttpHeader header, String urlAttributes) {
parseURLParameters(header.getURLAttributeMap(), urlAttributes);
}
/**
* Parses a string with variables from a get or post request that was sent from a client
*
* @param map a map where the url attributes key and value will be stored.
* @param urlAttributes is the String containing all the attributes
*/
public static void parseURLParameters(Map<String, String> map, String urlAttributes) {
String[] tmp;
urlAttributes = URLDecoder.decode(urlAttributes);
// get the variables
String[] data = PATTERN_AND.split(urlAttributes);
for (String element : data) {
tmp = PATTERN_EQUAL.split(element, 2);
map.put(
tmp[0].trim(), // Key
(tmp.length > 1 ? tmp[1] : "").trim()); //Value
}
}
}
| 37.926087 | 122 | 0.629027 |
9d9048808e542156dc2ea0728c23c6321fa767f1 | 2,365 | package io.playback.client;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.Extension;
import org.junit.jupiter.api.extension.ExtensionContext;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.URL;
public class HttpServerExtension implements AfterAllCallback, BeforeAllCallback, Extension {
private final HttpServer server;
public HttpServerExtension(HttpServer server) {
this.server = server;
}
public URL getBaseUrl() {
try {
return new URL("http", server.getAddress().getHostString(), server.getAddress().getPort(), "");
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Unable to deduct base URL", e);
}
}
@Override
public void beforeAll(ExtensionContext context) {
server.start();
}
@Override
public void afterAll(ExtensionContext context) {
server.stop(0);
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
public HttpServerExtension build() {
try {
return new HttpServerExtension(createServer());
} catch (IOException e) {
throw new UncheckedIOException("Unable to create HttpServer", e);
}
}
private HttpServer createServer() throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", findFreePort()), 0);
server.createContext("/").setHandler(createHandler());
return server;
}
private HttpHandler createHandler() {
return he -> {
he.sendResponseHeaders(200, 0);
he.close();
};
}
private int findFreePort() {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
} catch (IOException e) {
throw new UncheckedIOException("Unable to find a free port", e);
}
}
}
}
| 30.320513 | 107 | 0.637209 |
4e6caf35dbcade6b7023e6988ae8c3a8874b00b6 | 560 | package io.quantis;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("keystore")
@Getter
@Setter
public class KeystoreManagerConfig {
private String location;
private String type;
private String password ;
}
| 24.347826 | 81 | 0.830357 |
551de2bcf75621985141f419dd273bdf8ad5a35a | 2,618 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.faces.context;
import javax.faces.component.UIComponent;
import java.io.IOException;
import java.io.Writer;
/**
* see Javadoc of <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/index.html">JSF Specification</a>
*
* @author Manfred Geiler (latest modification by $Author: bommel $)
* @version $Revision: 1187701 $ $Date: 2011-10-22 07:21:54 -0500 (Sat, 22 Oct 2011) $
*/
public abstract class ResponseWriter extends Writer
{
public abstract String getContentType();
public abstract String getCharacterEncoding();
@Override
public abstract void flush() throws IOException;
public abstract void startDocument() throws IOException;
public abstract void endDocument() throws IOException;
public abstract void startElement(String name, UIComponent component) throws IOException;
public abstract void endElement(String name) throws IOException;
public void startCDATA() throws IOException
{
write ("<![CDATA[");
}
public void endCDATA() throws IOException
{
write ("]]>");
}
public abstract void writeAttribute(String name, Object value, String property) throws IOException;
public abstract void writeURIAttribute(String name, Object value, String property) throws IOException;
public abstract void writeComment(Object comment) throws IOException;
public abstract void writeText(Object text, String property) throws IOException;
public abstract void writeText(char[] text, int off, int len) throws IOException;
public abstract ResponseWriter cloneWithWriter(Writer writer);
/**
* @since 1.2
*/
public void writeText(Object object, UIComponent component, String string) throws IOException
{
writeText(object, string);
}
}
| 33.564103 | 116 | 0.729183 |
76d407c5001dcdb19e904b031ebc5cf62f6d81f9 | 4,026 | /**
*/
package org.ecore.component.performanceExtension.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.ecore.component.componentDefinition.ComponentSubNode;
import org.ecore.component.performanceExtension.DefaultObservedElementTrigger;
import org.ecore.component.performanceExtension.PerformanceExtensionPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Default Observed Element Trigger</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.ecore.component.performanceExtension.impl.DefaultObservedElementTriggerImpl#getElement <em>Element</em>}</li>
* </ul>
*
* @generated
*/
public class DefaultObservedElementTriggerImpl extends DefaultTriggerImpl implements DefaultObservedElementTrigger {
/**
* The cached value of the '{@link #getElement() <em>Element</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getElement()
* @generated
* @ordered
*/
protected ComponentSubNode element;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DefaultObservedElementTriggerImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return PerformanceExtensionPackage.Literals.DEFAULT_OBSERVED_ELEMENT_TRIGGER;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ComponentSubNode getElement() {
if (element != null && element.eIsProxy()) {
InternalEObject oldElement = (InternalEObject) element;
element = (ComponentSubNode) eResolveProxy(oldElement);
if (element != oldElement) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE,
PerformanceExtensionPackage.DEFAULT_OBSERVED_ELEMENT_TRIGGER__ELEMENT, oldElement,
element));
}
}
return element;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ComponentSubNode basicGetElement() {
return element;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setElement(ComponentSubNode newElement) {
ComponentSubNode oldElement = element;
element = newElement;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET,
PerformanceExtensionPackage.DEFAULT_OBSERVED_ELEMENT_TRIGGER__ELEMENT, oldElement, element));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case PerformanceExtensionPackage.DEFAULT_OBSERVED_ELEMENT_TRIGGER__ELEMENT:
if (resolve)
return getElement();
return basicGetElement();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case PerformanceExtensionPackage.DEFAULT_OBSERVED_ELEMENT_TRIGGER__ELEMENT:
setElement((ComponentSubNode) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case PerformanceExtensionPackage.DEFAULT_OBSERVED_ELEMENT_TRIGGER__ELEMENT:
setElement((ComponentSubNode) null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case PerformanceExtensionPackage.DEFAULT_OBSERVED_ELEMENT_TRIGGER__ELEMENT:
return element != null;
}
return super.eIsSet(featureID);
}
} //DefaultObservedElementTriggerImpl
| 24.851852 | 129 | 0.692002 |
a91d41c1ccea0034645a1ddc992f9fd08a57546a | 515 | package com.azat.myretro.exception;
import javax.servlet.http.HttpServletResponse;
public class ForbiddenException extends GeneralException {
private static final long serialVersionUID = -8726247459147448419L;
public ForbiddenException() {
super(HttpServletResponse.SC_FORBIDDEN);
}
public ForbiddenException(String message) {
super(HttpServletResponse.SC_FORBIDDEN, message);
}
public ForbiddenException(com.azat.myretro.enums.Error error) {
super(HttpServletResponse.SC_FORBIDDEN, error);
}
}
| 23.409091 | 68 | 0.805825 |
b73b1dde4203594c993f3ba33f6c1eb567f6e9de | 12,047 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.heron.metricsmgr.sink;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.apache.heron.spi.metricsmgr.metrics.ExceptionInfo;
import org.apache.heron.spi.metricsmgr.metrics.MetricsInfo;
import org.apache.heron.spi.metricsmgr.metrics.MetricsRecord;
import org.apache.heron.spi.metricsmgr.sink.SinkContext;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public class PrometheusSinkTests {
private static final long NOW = System.currentTimeMillis();
private final class PrometheusTestSink extends PrometheusSink {
private PrometheusTestSink() {
}
@Override
protected void startHttpServer(String path, int port) {
// no need to start the server for tests
}
public Map<String, Map<String, Double>> getMetrics() {
return getMetricsCache().asMap();
}
long currentTimeMillis() {
return NOW;
}
}
private Map<String, Object> defaultConf;
private SinkContext context;
private List<MetricsRecord> records;
@Before
public void before() throws IOException {
defaultConf = new HashMap<>();
defaultConf.put("port", "9999");
defaultConf.put("path", "test");
defaultConf.put("flat-metrics", "true");
defaultConf.put("include-topology-name", "false");
context = Mockito.mock(SinkContext.class);
Mockito.when(context.getTopologyName()).thenReturn("testTopology");
Mockito.when(context.getSinkId()).thenReturn("testId");
/*
# example: metrics.yaml
rules:
- pattern: kafka.(\w+)<type=(.+), name=(.+)PerSec\w*, (.+)=(.+)><>Count
name: kafka_$1_$2_$3_total
attrNameSnakeCase: true
type: COUNTER
labels:
"$4": "$5"
type: COUNTER
*/
/*
example: metrics
kafkaOffset/nginx-lfp-beacon/totalSpoutLag
kafkaOffset/lads_event_meta_backfill_data/partition_10/spoutLag
*/
List<Map<String, Object>> rules = Lists.newArrayList();
defaultConf.put("rules", rules);
Map<String, Object> rule1 = Maps.newHashMap();
Map<String, Object> labels1 = Maps.newHashMap();
rules.add(rule1);
rule1.put("pattern", "kafkaOffset/(.+)/(.+)");
rule1.put("name", "kafka_offset_$2");
rule1.put("type", "COUNTER");
rule1.put("attrNameSnakeCase", true);
rule1.put("labels", labels1);
labels1.put("topic", "$1");
Map<String, Object> rule2 = Maps.newHashMap();
Map<String, Object> labels2 = Maps.newHashMap();
rules.add(rule2);
rule2.put("pattern", "kafkaOffset/(.+)/partition_(\\d+)/(.+)");
rule2.put("name", "kafka_offset_partition_$3");
rule2.put("type", "COUNTER");
rule2.put("labels", labels2);
rule2.put("attrNameSnakeCase", true);
labels2.put("topic", "$1");
labels2.put("partition", "$2");
Iterable<MetricsInfo> infos = Arrays.asList(new MetricsInfo("metric_1", "1.0"),
new MetricsInfo("metric_2", "2.0"));
records = Arrays.asList(
newRecord("machine/component/instance_1", infos, Collections.emptyList()),
newRecord("machine/component/instance_2", infos, Collections.emptyList()));
}
@Test
public void testMetricsGrouping() {
PrometheusTestSink sink = new PrometheusTestSink();
sink.init(defaultConf, context);
for (MetricsRecord r : records) {
sink.processRecord(r);
}
final Map<String, Map<String, Double>> metrics = sink.getMetrics();
assertTrue(metrics.containsKey("testTopology/component/instance_1"));
assertTrue(metrics.containsKey("testTopology/component/instance_2"));
}
@Test
public void testResponse() throws IOException {
PrometheusTestSink sink = new PrometheusTestSink();
sink.init(defaultConf, context);
for (MetricsRecord r : records) {
sink.processRecord(r);
}
final String topology = "testTopology";
final List<String> expectedLines = Arrays.asList(
createMetric(topology, "component", "instance_1", "metric_1", "1.0"),
createMetric(topology, "component", "instance_1", "metric_2", "2.0"),
createMetric(topology, "component", "instance_1", "metric_1", "1.0"),
createMetric(topology, "component", "instance_1", "metric_2", "2.0")
);
final Set<String> generatedLines =
new HashSet<>(Arrays.asList(new String(sink.generateResponse()).split("\n")));
assertEquals(expectedLines.size(), generatedLines.size());
expectedLines.forEach((String line) -> {
assertTrue(generatedLines.contains(line));
});
}
@Test
public void testResponseWhenMetricNamesHaveAnInstanceId() throws IOException {
Iterable<MetricsInfo> infos = Arrays.asList(
new MetricsInfo("__connection_buffer_by_instanceid/container_1_word_5/packets", "1.0"),
new MetricsInfo("__time_spent_back_pressure_by_compid/container_1_exclaim1_1", "1.0"),
new MetricsInfo("__client_stmgr-92/__ack_tuples_to_stmgrs", "1.0"),
new MetricsInfo("__instance_bytes_received/1", "1.0")
);
records = Arrays.asList(
newRecord("machine/__stmgr__/stmgr-1", infos, Collections.emptyList())
);
PrometheusTestSink sink = new PrometheusTestSink();
sink.init(defaultConf, context);
for (MetricsRecord r : records) {
sink.processRecord(r);
}
final String topology = "testTopology";
final List<String> expectedLines = Arrays.asList(
createMetric(topology, "__stmgr__", "stmgr-1",
"connection_buffer_by_instanceid_packets",
"container_1_word_5", "1.0"),
createMetric(topology, "__stmgr__", "stmgr-1",
"time_spent_back_pressure_by_compid",
"container_1_exclaim1_1", "1.0"),
createMetric(topology, "__stmgr__", "stmgr-1",
"client_stmgr_ack_tuples_to_stmgrs", "stmgr-92", "1.0"),
createMetric(topology, "__stmgr__", "stmgr-1",
"instance_bytes_received", "1", "1.0")
);
final Set<String> generatedLines =
new HashSet<>(Arrays.asList(new String(sink.generateResponse()).split("\n")));
assertEquals(expectedLines.size(), generatedLines.size());
expectedLines.forEach((String line) -> {
assertTrue(generatedLines.contains(line));
});
}
@Test
public void testApacheStormKafkaMetrics() throws IOException {
Iterable<MetricsInfo> infos = Arrays.asList(
new MetricsInfo("kafkaOffset/event_data/partition_0/spoutLag", "1.0"),
new MetricsInfo("kafkaOffset/event_data/partition_10/spoutLag", "1.0"),
new MetricsInfo("kafkaOffset/event_data/partition_0/earliestTimeOffset", "1.0"),
new MetricsInfo("kafkaOffset/event_data/totalRecordsInPartitions", "1.0"),
new MetricsInfo("kafkaOffset/event_data/totalSpoutLag", "1.0"),
new MetricsInfo("kafkaOffset/event_data/partition_2/spoutLag", "1.0")
);
records = Arrays.asList(
newRecord("shared-aurora-036:31/spout-release-1/container_1_spout-release-1_31",
infos, Collections.emptyList())
);
PrometheusTestSink sink = new PrometheusTestSink();
sink.init(defaultConf, context);
for (MetricsRecord r : records) {
sink.processRecord(r);
}
final String topology = "testTopology";
final List<String> expectedLines = Arrays.asList(
createOffsetMetric(topology, "spout-release-1", "container_1_spout-release-1_31",
"kafka_offset_partition_spout_lag", "event_data", "0", "1.0"),
createOffsetMetric(topology, "spout-release-1", "container_1_spout-release-1_31",
"kafka_offset_partition_spout_lag", "event_data", "10", "1.0"),
createOffsetMetric(topology, "spout-release-1", "container_1_spout-release-1_31",
"kafka_offset_partition_earliest_time_offset", "event_data", "0", "1.0"),
createOffsetMetric(topology, "spout-release-1", "container_1_spout-release-1_31",
"kafka_offset_total_records_in_partitions", "event_data", null, "1.0"),
createOffsetMetric(topology, "spout-release-1", "container_1_spout-release-1_31",
"kafka_offset_total_spout_lag", "event_data", null, "1.0"),
createOffsetMetric(topology, "spout-release-1", "container_1_spout-release-1_31",
"kafka_offset_partition_spout_lag", "event_data", "2", "1.0")
);
final Set<String> generatedLines =
new HashSet<>(Arrays.asList(new String(sink.generateResponse()).split("\n")));
assertEquals(expectedLines.size(), generatedLines.size());
expectedLines.forEach((String line) -> {
assertTrue(generatedLines.contains(line));
});
}
@Test
public void testComponentType() {
Map<String, Double> metrics = new HashMap<>();
metrics.put("__execute-time-ns/default", 1d);
assertEquals("bolt", PrometheusSink.getComponentType(metrics));
metrics = new HashMap<>();
metrics.put("__execute-time-ns/stream1", 1d);
assertEquals("bolt", PrometheusSink.getComponentType(metrics));
metrics = new HashMap<>();
metrics.put("__next-tuple-count", 1d);
assertEquals("spout", PrometheusSink.getComponentType(metrics));
metrics = new HashMap<>();
assertNull(PrometheusSink.getComponentType(metrics));
}
private String createMetric(String topology, String component, String instance,
String metric, String value) {
return createMetric(topology, component, instance, metric, null, value);
}
private String createMetric(String topology, String component, String instance,
String metric, String metricNameInstanceId, String value) {
if (metricNameInstanceId != null) {
return String.format("heron_%s"
+ "{component=\"%s\",instance_id=\"%s\",metric_instance_id=\"%s\",topology=\"%s\"}"
+ " %s %d",
metric, component, instance, metricNameInstanceId, topology, value, NOW);
} else {
return String.format("heron_%s{component=\"%s\",instance_id=\"%s\",topology=\"%s\"} %s %d",
metric, component, instance, topology, value, NOW);
}
}
private String createOffsetMetric(String topology, String component, String instance,
String metric, String topic, String partition, String value) {
if (partition != null) {
return String.format("heron_%s"
+ "{component=\"%s\",instance_id=\"%s\",partition=\"%s\","
+ "topic=\"%s\",topology=\"%s\"}"
+ " %s %d",
metric, component, instance, partition, topic, topology, value, NOW);
} else {
return String.format("heron_%s"
+ "{component=\"%s\",instance_id=\"%s\",topic=\"%s\",topology=\"%s\"} %s %d",
metric, component, instance, topic, topology, value, NOW);
}
}
private MetricsRecord newRecord(String source, Iterable<MetricsInfo> metrics,
Iterable<ExceptionInfo> exceptions) {
return new MetricsRecord(source, metrics, exceptions);
}
}
| 37.182099 | 97 | 0.675687 |
825a97d014303487debd69c46b2a2dd7335277ea | 482 | package com.mastertheboss.amq;
import org.eclipse.microprofile.reactive.messaging.Incoming;
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class MessageConsumer {
@Incoming("queueA-transformed")
public void sinkA(Long msg) {
System.out.println("Message from Transformer: "+msg);;
}
@Incoming("queueB-transformed")
public void sinkB(String msg) {
System.out.println("Message from Transformer: "+msg);
}
} | 20.956522 | 62 | 0.715768 |
1c74ff2e096b7d2e74da0702d86b1c4d0edf4001 | 5,062 | /*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.transaction.interceptor;
import java.lang.reflect.Method;
import junit.framework.TestCase;
import org.springframework.transaction.TransactionDefinition;
/**
* Format is
* <code>FQN.Method=tx attribute representation</code>
*
* @author Rod Johnson
* @since 26.04.2003
*/
public class TransactionAttributeSourceEditorTests extends TestCase {
public void testNull() throws Exception {
TransactionAttributeSourceEditor pe = new TransactionAttributeSourceEditor();
pe.setAsText(null);
TransactionAttributeSource tas = (TransactionAttributeSource) pe.getValue();
Method m = Object.class.getMethod("hashCode", (Class[]) null);
assertTrue(tas.getTransactionAttribute(m, null) == null);
}
public void testInvalid() throws Exception {
TransactionAttributeSourceEditor pe = new TransactionAttributeSourceEditor();
try {
pe.setAsText("foo=bar");
fail();
}
catch (IllegalArgumentException ex) {
// Ok
}
}
public void testMatchesSpecific() throws Exception {
TransactionAttributeSourceEditor pe = new TransactionAttributeSourceEditor();
// TODO need FQN?
pe.setAsText(
"java.lang.Object.hashCode=PROPAGATION_REQUIRED\n" +
"java.lang.Object.equals=PROPAGATION_MANDATORY\n" +
"java.lang.Object.*it=PROPAGATION_SUPPORTS\n" +
"java.lang.Object.notify=PROPAGATION_SUPPORTS\n" +
"java.lang.Object.not*=PROPAGATION_REQUIRED");
TransactionAttributeSource tas = (TransactionAttributeSource) pe.getValue();
checkTransactionProperties(tas, Object.class.getMethod("hashCode", (Class[]) null),
TransactionDefinition.PROPAGATION_REQUIRED);
checkTransactionProperties(tas, Object.class.getMethod("equals", new Class[] { Object.class }),
TransactionDefinition.PROPAGATION_MANDATORY);
checkTransactionProperties(tas, Object.class.getMethod("wait", (Class[]) null),
TransactionDefinition.PROPAGATION_SUPPORTS);
checkTransactionProperties(tas, Object.class.getMethod("wait", new Class[] { long.class }),
TransactionDefinition.PROPAGATION_SUPPORTS);
checkTransactionProperties(tas, Object.class.getMethod("wait", new Class[] { long.class, int.class }),
TransactionDefinition.PROPAGATION_SUPPORTS);
checkTransactionProperties(tas, Object.class.getMethod("notify", (Class[]) null),
TransactionDefinition.PROPAGATION_SUPPORTS);
checkTransactionProperties(tas, Object.class.getMethod("notifyAll", (Class[]) null),
TransactionDefinition.PROPAGATION_REQUIRED);
checkTransactionProperties(tas, Object.class.getMethod("toString", (Class[]) null), -1);
}
public void testMatchesAll() throws Exception {
TransactionAttributeSourceEditor pe = new TransactionAttributeSourceEditor();
pe.setAsText("java.lang.Object.*=PROPAGATION_REQUIRED");
TransactionAttributeSource tas = (TransactionAttributeSource) pe.getValue();
checkTransactionProperties(tas, Object.class.getMethod("hashCode", (Class[]) null),
TransactionDefinition.PROPAGATION_REQUIRED);
checkTransactionProperties(tas, Object.class.getMethod("equals", new Class[] { Object.class }),
TransactionDefinition.PROPAGATION_REQUIRED);
checkTransactionProperties(tas, Object.class.getMethod("wait", (Class[]) null),
TransactionDefinition.PROPAGATION_REQUIRED);
checkTransactionProperties(tas, Object.class.getMethod("wait", new Class[] { long.class }),
TransactionDefinition.PROPAGATION_REQUIRED);
checkTransactionProperties(tas, Object.class.getMethod("wait", new Class[] { long.class, int.class }),
TransactionDefinition.PROPAGATION_REQUIRED);
checkTransactionProperties(tas, Object.class.getMethod("notify", (Class[]) null),
TransactionDefinition.PROPAGATION_REQUIRED);
checkTransactionProperties(tas, Object.class.getMethod("notifyAll", (Class[]) null),
TransactionDefinition.PROPAGATION_REQUIRED);
checkTransactionProperties(tas, Object.class.getMethod("toString", (Class[]) null),
TransactionDefinition.PROPAGATION_REQUIRED);
}
private void checkTransactionProperties(TransactionAttributeSource tas, Method method, int propagationBehavior) {
TransactionAttribute ta = tas.getTransactionAttribute(method, null);
if (propagationBehavior >= 0) {
assertTrue(ta != null);
assertTrue(ta.getIsolationLevel() == TransactionDefinition.ISOLATION_DEFAULT);
assertTrue(ta.getPropagationBehavior() == propagationBehavior);
}
else {
assertTrue(ta == null);
}
}
}
| 42.898305 | 114 | 0.761952 |
3adcc39a4d865b1bd017eb1b3f75ce7440e7ce14 | 14,422 | /**
* Copyright (C) 2014-2018 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.genericode;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.Nonempty;
import com.helger.commons.annotation.ReturnsMutableCopy;
import com.helger.commons.collection.CollectionHelper;
import com.helger.commons.collection.impl.CommonsArrayList;
import com.helger.commons.collection.impl.ICommonsList;
import com.helger.commons.lang.ClassHelper;
import com.helger.commons.string.StringHelper;
import com.helger.genericode.v10.Column;
import com.helger.genericode.v10.ColumnRef;
import com.helger.genericode.v10.ColumnSet;
import com.helger.genericode.v10.Data;
import com.helger.genericode.v10.Key;
import com.helger.genericode.v10.KeyColumnRef;
import com.helger.genericode.v10.LongName;
import com.helger.genericode.v10.ObjectFactory;
import com.helger.genericode.v10.Row;
import com.helger.genericode.v10.ShortName;
import com.helger.genericode.v10.SimpleValue;
import com.helger.genericode.v10.UseType;
import com.helger.genericode.v10.Value;
/**
* Helper class for Genericode 1.0 reading
*
* @author Philip Helger
*/
@Immutable
public final class Genericode10Helper
{
private static final ObjectFactory s_aFactory = new ObjectFactory ();
private Genericode10Helper ()
{}
/**
* Get the ID of the passed column element.
*
* @param aColumnElement
* The column element to use. Must be either a {@link ColumnRef} or a
* {@link Column}.
* @return The ID of the object
*/
@Nonnull
public static String getColumnElementID (@Nonnull final Object aColumnElement)
{
if (aColumnElement instanceof ColumnRef)
return ((ColumnRef) aColumnElement).getId ();
if (aColumnElement instanceof Column)
return ((Column) aColumnElement).getId ();
if (aColumnElement instanceof Key)
{
final List <KeyColumnRef> aKeyColumnRefs = ((Key) aColumnElement).getColumnRef ();
final KeyColumnRef aKeyColumnRef = CollectionHelper.getFirstElement (aKeyColumnRefs);
if (aKeyColumnRef == null)
throw new IllegalArgumentException ("Key contains not KeyColumnRef!!");
final Object aRef = aKeyColumnRef.getRef ();
if (aRef instanceof Column)
return ((Column) aRef).getId ();
throw new IllegalArgumentException ("Unsupported referenced object: " +
aRef +
" - " +
ClassHelper.getSafeClassName (aRef));
}
throw new IllegalArgumentException ("Illegal column element: " +
aColumnElement +
" - " +
ClassHelper.getSafeClassName (aColumnElement));
}
/**
* Get the value of a column identified by an ID within a specified row. This
* method only handles simple values.
*
* @param aRow
* The row to scan. May not be <code>null</code>.
* @param sColumnID
* The ID of the column to search. May not be <code>null</code>.
* @return <code>null</code> if no such column is contained
*/
@Nullable
public static String getRowValue (@Nonnull final Row aRow, @Nonnull final String sColumnID)
{
for (final Value aValue : aRow.getValue ())
{
final String sID = getColumnElementID (aValue.getColumnRef ());
if (sID.equals (sColumnID))
{
final SimpleValue aSimpleValue = aValue.getSimpleValue ();
return aSimpleValue != null ? aSimpleValue.getValue () : null;
}
}
return null;
}
/**
* Get all contained columns
*
* @param aColumnSet
* The column set to scan. May not be <code>null</code>.
* @return A non-<code>null</code> list of all columns. Never
* <code>null</code> but maybe empty.
*/
@Nonnull
@ReturnsMutableCopy
public static ICommonsList <Column> getAllColumns (@Nonnull final ColumnSet aColumnSet)
{
final ICommonsList <Column> ret = new CommonsArrayList<> ();
getAllColumns (aColumnSet, ret);
return ret;
}
/**
* Get all contained columns
*
* @param aColumnSet
* The column set to scan. May not be <code>null</code>.
* @param aTarget
* A non-<code>null</code> list where all columns should be added. May
* not be <code>null</code>.
*/
public static void getAllColumns (@Nonnull final ColumnSet aColumnSet, @Nonnull final Collection <Column> aTarget)
{
CollectionHelper.findAll (aColumnSet.getColumnChoice (), o -> o instanceof Column, o -> aTarget.add ((Column) o));
}
/**
* Get the IDs of all contained columns
*
* @param aColumnSet
* The column set to scan. May not be <code>null</code>.
* @return A non-<code>null</code> list of all column IDs. Never
* <code>null</code> but maybe empty.
*/
@Nonnull
@ReturnsMutableCopy
public static ICommonsList <String> getAllColumnIDs (@Nonnull final ColumnSet aColumnSet)
{
final ICommonsList <String> ret = new CommonsArrayList<> ();
getAllColumnIDs (aColumnSet, ret);
return ret;
}
/**
* Get the IDs of all contained columns
*
* @param aColumnSet
* The column set to scan. May not be <code>null</code>.
* @param aTarget
* The target collection to be filled. May not be <code>null</code>.
*/
public static void getAllColumnIDs (@Nonnull final ColumnSet aColumnSet, @Nonnull final Collection <String> aTarget)
{
CollectionHelper.findAll (aColumnSet.getColumnChoice (),
o -> o instanceof Column,
o -> aTarget.add (((Column) o).getId ()));
}
/**
* Get the column with the specified ID.
*
* @param aColumnSet
* The column set to scan. May not be <code>null</code>.
* @param sID
* The ID to search. May be <code>null</code>.
* @return <code>null</code> if no such column exists.
*/
@Nullable
public static Column getColumnOfID (@Nonnull final ColumnSet aColumnSet, @Nullable final String sID)
{
if (sID != null)
for (final Column aColumn : getAllColumns (aColumnSet))
if (aColumn.getId ().equals (sID))
return aColumn;
return null;
}
/**
* Get all contained keys
*
* @param aColumnSet
* The column set to scan. May not be <code>null</code>.
* @return A non-<code>null</code> list of all keys. Never <code>null</code>
* but maybe empty.
*/
@Nonnull
@ReturnsMutableCopy
public static ICommonsList <Key> getAllKeys (@Nonnull final ColumnSet aColumnSet)
{
final ICommonsList <Key> ret = new CommonsArrayList<> ();
getAllKeys (aColumnSet, ret);
return ret;
}
/**
* Get all contained keys
*
* @param aColumnSet
* The column set to scan. May not be <code>null</code>.
* @param aTarget
* The target collection to be filled. May not be <code>null</code>.
*/
public static void getAllKeys (@Nonnull final ColumnSet aColumnSet, @Nonnull final Collection <Key> aTarget)
{
CollectionHelper.findAll (aColumnSet.getKeyChoice (), o -> o instanceof Key, o -> aTarget.add ((Key) o));
}
/**
* Get the IDs of all contained keys
*
* @param aColumnSet
* The column set to scan. May not be <code>null</code>.
* @return A non-<code>null</code> list of all key IDs. Never
* <code>null</code> but maybe empty.
*/
@Nonnull
@ReturnsMutableCopy
public static ICommonsList <String> getAllKeyIDs (@Nonnull final ColumnSet aColumnSet)
{
final ICommonsList <String> ret = new CommonsArrayList<> ();
getAllKeyIDs (aColumnSet, ret);
return ret;
}
/**
* Get the IDs of all contained keys
*
* @param aColumnSet
* The column set to scan. May not be <code>null</code>.
* @param aTarget
* The target collection to be filled. May not be <code>null</code>.
*/
public static void getAllKeyIDs (@Nonnull final ColumnSet aColumnSet, @Nonnull final Collection <String> aTarget)
{
CollectionHelper.findAll (aColumnSet.getKeyChoice (), o -> o instanceof Key, o -> aTarget.add (((Key) o).getId ()));
}
/**
* Get the key with the specified ID.
*
* @param aColumnSet
* The column set to scan. May not be <code>null</code>.
* @param sID
* The ID to search. May be <code>null</code>.
* @return <code>null</code> if no such key exists.
*/
@Nullable
public static Key getKeyOfID (@Nonnull final ColumnSet aColumnSet, @Nullable final String sID)
{
if (sID != null)
for (final Key aKey : getAllKeys (aColumnSet))
if (aKey.getId ().equals (sID))
return aKey;
return null;
}
/**
* Check if the passed column ID is a key column in the specified column set
*
* @param aColumnSet
* The column set to scan. May not be <code>null</code>.
* @param sColumnID
* The column ID to search. May be <code>null</code>.
* @return <code>true</code> if the passed column ID is a key column
*/
public static boolean isKeyColumn (@Nonnull final ColumnSet aColumnSet, @Nullable final String sColumnID)
{
if (sColumnID != null)
for (final Key aKey : getAllKeys (aColumnSet))
for (final KeyColumnRef aColumnRef : aKey.getColumnRef ())
if (aColumnRef.getRef () instanceof Column)
if (((Column) aColumnRef.getRef ()).getId ().equals (sColumnID))
return true;
return false;
}
/**
* Create a {@link ShortName} object
*
* @param sValue
* The value to assign
* @return Never <code>null</code>.
*/
@Nonnull
public static ShortName createShortName (@Nullable final String sValue)
{
final ShortName aShortName = s_aFactory.createShortName ();
aShortName.setValue (sValue);
return aShortName;
}
/**
* Create a {@link LongName} object
*
* @param sValue
* The value to assign
* @return Never <code>null</code>.
*/
@Nonnull
public static LongName createLongName (@Nullable final String sValue)
{
final LongName aLongName = s_aFactory.createLongName ();
aLongName.setValue (sValue);
return aLongName;
}
/**
* Create a {@link SimpleValue} object
*
* @param sValue
* The value to assign
* @return Never <code>null</code>.
*/
@Nonnull
public static SimpleValue createSimpleValue (@Nullable final String sValue)
{
final SimpleValue aSimpleValue = s_aFactory.createSimpleValue ();
aSimpleValue.setValue (sValue);
return aSimpleValue;
}
/**
* Create a {@link KeyColumnRef} object
*
* @param aColumn
* The column to reference
* @return Never <code>null</code>.
*/
@Nonnull
public static KeyColumnRef createKeyColumnRef (@Nullable final Column aColumn)
{
final KeyColumnRef aColumnRef = s_aFactory.createKeyColumnRef ();
// Important: reference the object itself and not just the ID!!!
aColumnRef.setRef (aColumn);
return aColumnRef;
}
/**
* Create a new column to be added to a column set
*
* @param sColumnID
* The ID of the column
* @param eUseType
* The usage type (optional or required)
* @param sShortName
* The short name of the column
* @param sLongName
* The long name of the column
* @param sDataType
* The data type to use
* @return Never <code>null</code>.
*/
@Nonnull
public static Column createColumn (@Nonnull @Nonempty final String sColumnID,
@Nonnull final UseType eUseType,
@Nonnull @Nonempty final String sShortName,
@Nullable final String sLongName,
@Nonnull @Nonempty final String sDataType)
{
ValueEnforcer.notEmpty (sColumnID, "ColumnID");
ValueEnforcer.notNull (eUseType, "useType");
ValueEnforcer.notEmpty (sShortName, "ShortName");
ValueEnforcer.notEmpty (sDataType, "DataType");
final Column aColumn = s_aFactory.createColumn ();
aColumn.setId (sColumnID);
aColumn.setUse (eUseType);
aColumn.setShortName (createShortName (sShortName));
if (StringHelper.hasText (sLongName))
aColumn.getLongName ().add (createLongName (sLongName));
final Data aData = s_aFactory.createData ();
aData.setType (sDataType);
aColumn.setData (aData);
return aColumn;
}
/**
* Create a new key to be added to a column set
*
* @param sColumnID
* The ID of the column
* @param sShortName
* The short name of the column
* @param sLongName
* The long name of the column
* @param aColumn
* The referenced column. May not be <code>null</code>.
* @return Never <code>null</code>.
*/
@Nonnull
public static Key createKey (@Nonnull @Nonempty final String sColumnID,
@Nonnull @Nonempty final String sShortName,
@Nullable final String sLongName,
@Nonnull final Column aColumn)
{
ValueEnforcer.notEmpty (sColumnID, "ColumnID");
ValueEnforcer.notEmpty (sShortName, "ShortName");
ValueEnforcer.notNull (aColumn, "Column");
final Key aKey = s_aFactory.createKey ();
aKey.setId (sColumnID);
aKey.setShortName (createShortName (sShortName));
if (StringHelper.hasText (sLongName))
aKey.getLongName ().add (createLongName (sLongName));
aKey.getColumnRef ().add (createKeyColumnRef (aColumn));
return aKey;
}
}
| 33.230415 | 120 | 0.646027 |
4f2b9f4185006e652debd84c2f47ebc5f2f5ccef | 1,674 | /*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.web.header.writers;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.web.header.HeaderWriter;
import org.springframework.util.Assert;
/**
* A {@link HeaderWriter} that delegates to several other {@link HeaderWriter}s.
*
* @author Ankur Pathak
* @since 5.2
*/
public class CompositeHeaderWriter implements HeaderWriter {
private final List<HeaderWriter> headerWriters;
/**
* Creates a new instance.
* @param headerWriters the {@link HeaderWriter} instances to write out headers to the
* {@link HttpServletResponse}.
*/
public CompositeHeaderWriter(List<HeaderWriter> headerWriters) {
Assert.notEmpty(headerWriters, "headerWriters cannot be empty");
this.headerWriters = headerWriters;
}
@Override
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
this.headerWriters.forEach((headerWriter) -> headerWriter.writeHeaders(request, response));
}
}
| 31.584906 | 93 | 0.765233 |
5287f368088969490516c4b285edbad98793c7ac | 8,976 | /*
* Copyright 2000-2021 JetBrains s.r.o.
*
* 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 jetbrains.buildServer.server.rest.data.problem.tree;
import java.util.*;
import java.util.function.IntSupplier;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jetbrains.buildServer.server.rest.errors.InvalidStateException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class ScopeTree<DATA, COUNTERS extends TreeCounters<COUNTERS>> {
private final Node<DATA, COUNTERS> myRoot;
private final Map<String, Node<DATA, COUNTERS>> myIdToNodesMap = new HashMap<>();
public ScopeTree(@NotNull Scope rootScope,
@NotNull COUNTERS rootCounters,
@NotNull Iterable<? extends LeafInfo<DATA, COUNTERS>> leafs) {
myRoot = new Node<>(rootScope.getId(), rootScope, rootCounters, null);
myIdToNodesMap.put(myRoot.getId(), myRoot);
buildTree(leafs);
}
private void buildTree(@NotNull Iterable<? extends LeafInfo<DATA, COUNTERS>> leafs) {
for (LeafInfo<DATA, COUNTERS> leafInfo : leafs) {
COUNTERS counters = leafInfo.getCounters();
Node<DATA, COUNTERS> parent = myRoot;
parent.merge(counters);
for (Scope scope : leafInfo.getPath()) {
if(scope.equals(myRoot.getScope())) {
continue;
}
if(scope.isLeaf()) {
Node<DATA, COUNTERS> leaf = new Node<>(scope.getId(), scope, leafInfo.getData(), leafInfo.getCounters(), parent);
myIdToNodesMap.put(leaf.getId(), leaf);
parent.putChild(leaf);
break;
}
parent = getOrCreateNode(scope, counters, parent);
}
}
}
private Node<DATA, COUNTERS> getOrCreateNode(@NotNull Scope scope, @NotNull COUNTERS counters, @NotNull Node<DATA, COUNTERS> parent) {
Node<DATA, COUNTERS> child = parent.getChild(scope.getId());
if (child != null) {
child.merge(counters);
return child;
}
child = new Node<>(scope.getId(), scope, counters, parent);
myIdToNodesMap.put(child.getId(), child);
parent.putChild(child);
return child;
}
@NotNull
public List<Node<DATA, COUNTERS>> getSlicedOrderedTree(int maxChildren, @NotNull Comparator<DATA> dataComparator, @Nullable Comparator<Node<DATA, COUNTERS>> nodeComparator) {
return getSlicedOrderedSubtree(myRoot, maxChildren, dataComparator, nodeComparator);
}
@NotNull
public List<Node<DATA, COUNTERS>> getFullNodeAndSlicedOrderedSubtree(@NotNull String nodeId, int maxChildren, @NotNull Comparator<DATA> dataComparator, @Nullable Comparator<Node<DATA, COUNTERS>> nodeComparator) {
Node<DATA, COUNTERS> node = myIdToNodesMap.get(nodeId);
if(node == null) {
return Collections.emptyList();
}
if(node.getScope().isLeaf()) {
// We still need children to be sorted, so passing maxChildren = data.size()
return Collections.singletonList(sliceLeaf(node, node.getData().size(), dataComparator));
}
List<Node<DATA, COUNTERS>> immediateChildren = new ArrayList<>(node.getChildren());
if(nodeComparator != null) {
immediateChildren.sort(nodeComparator);
}
List<Node<DATA, COUNTERS>> result = new ArrayList<>();
result.add(node);
for(Node<DATA, COUNTERS> child : immediateChildren) {
getSlicedOrderedSubtree(child, maxChildren, dataComparator, nodeComparator).forEach(result::add);
}
return result;
}
@NotNull
private List<Node<DATA, COUNTERS>> getSlicedOrderedSubtree(@NotNull Node<DATA, COUNTERS> subTreeRoot, int maxChildren, @NotNull Comparator<DATA> dataComparator, @Nullable Comparator<Node<DATA, COUNTERS>> nodeComparator) {
Queue<Node<DATA, COUNTERS>> nodeQueue = new ArrayDeque<>(maxChildren + 1);
nodeQueue.add(subTreeRoot);
List<Node<DATA, COUNTERS>> result = new ArrayList<>();
while (!nodeQueue.isEmpty()) {
Node<DATA, COUNTERS> node = nodeQueue.poll();
final boolean isLeaf = node.getScope().isLeaf();
if(isLeaf) {
result.add(sliceLeaf(node, maxChildren, dataComparator));
continue;
}
result.add(node);
Stream<Node<DATA, COUNTERS>> children = node.getChildren().stream();
if (nodeComparator != null) {
children = children.sorted(nodeComparator);
}
children.limit(maxChildren)
.forEach(nodeQueue::add);
}
return result;
}
/**
* Slices a leaf node and returns a new one.<br/>
* <b>Important:</b> modifies parent, replacing <code>node</code> with a new sliced one.
*/
private Node<DATA, COUNTERS> sliceLeaf(@NotNull Node<DATA, COUNTERS> node, int maxChildren, @NotNull Comparator<DATA> dataComparator) {
// Actually, it shouldn't be the root node, so there should always be a parent, but just to be safe.
if(!node.getScope().isLeaf() || node.getParent() == null) {
throw new InvalidStateException("Can't slice a non-leaf.");
}
List<DATA> slicedData = node.getData().stream()
.sorted(dataComparator)
.limit(maxChildren)
.collect(Collectors.toList());
Node<DATA, COUNTERS> slicedLeaf = new Node<>(node.getId(), node.getScope(), slicedData, node.getCounters(), node.getParent());
node.getParent().putChild(slicedLeaf);
return slicedLeaf;
}
@NotNull
public List<Node<DATA, COUNTERS>> getTopTreeSliceUpTo(@Nullable Comparator<Node<DATA, COUNTERS>> order, @NotNull Predicate<Scope> isIncludedLevel) {
Queue<Node<DATA, COUNTERS>> nodeQueue = new ArrayDeque<>();
nodeQueue.add(myRoot);
List<Node<DATA, COUNTERS>> slicedNodes = new ArrayList<>();
while (!nodeQueue.isEmpty()) {
Node<DATA, COUNTERS> node = nodeQueue.poll();
if(!isIncludedLevel.test(node.getScope())) {
continue;
}
slicedNodes.add(node);
if(order != null) {
node.getChildren().stream()
.sorted(order)
.forEach(nodeQueue::add);
} else {
nodeQueue.addAll(node.getChildren());
}
}
return slicedNodes;
}
public static class Node<DATA, COUNTERS extends TreeCounters<COUNTERS>> {
@Nullable
private final Node<DATA, COUNTERS> myParent;
@NotNull
private final Scope myScope;
@NotNull
private final List<DATA> myTestRuns;
@NotNull
private COUNTERS myCountersData;
@NotNull
private final Map<String, Node<DATA, COUNTERS>> myChildren; // id -> node
@NotNull
private final String myId;
/** Construct a non-leaf node. It has zero testRuns and may contain children. */
Node(@NotNull String id, @NotNull Scope scope, @NotNull COUNTERS counters, @Nullable Node<DATA, COUNTERS> parent) {
myId = id;
myParent = parent;
myScope = scope;
myCountersData = counters;
myChildren = new LinkedHashMap<>();
myTestRuns = Collections.emptyList();
}
/** Construct a leaf node. It is always a node of type CLASS and has zero children. */
Node (@NotNull String id,
@NotNull Scope scope,
@NotNull Collection<DATA> sTestRuns,
@NotNull COUNTERS counters,
@Nullable Node<DATA, COUNTERS> parent) {
myId = id;
myParent = parent;
myScope = scope;
myCountersData = counters;
myTestRuns = new ArrayList<>(sTestRuns);
myChildren = Collections.emptyMap();
}
@NotNull
public String getId() {
return myId;
}
@NotNull
public Scope getScope() {
return myScope;
}
@NotNull
public COUNTERS getCounters() {
return myCountersData;
}
@NotNull
public List<DATA> getData() {
return myTestRuns;
}
@NotNull
public Collection<Node<DATA, COUNTERS>> getChildren() {
return myChildren.values();
}
@Nullable
public Node<DATA, COUNTERS> getChild(@NotNull String childScopeName) {
return myChildren.get(childScopeName);
}
@Nullable
public Node<DATA, COUNTERS> getParent() {
return myParent;
}
public void merge(@NotNull COUNTERS counters) {
myCountersData = myCountersData.combinedWith(counters);
}
public void putChild(@NotNull Node<DATA, COUNTERS> child) {
myChildren.put(child.getId(), child);
}
@Override
public String toString() {
return "Node{id=" + myId + ", scope=" + myScope + "}";
}
}
}
| 33 | 223 | 0.662322 |
4229f59678d44dab6b2b86457c16541d31317a8a | 1,979 | package org.hac.natives;
import org.hac.env.Environment;
import org.hac.exception.HacException;
import org.hac.function.NativeFunction;
import java.lang.reflect.Method;
public class Natives {
public Environment environment(Environment env) {
appendNatives(env);
return env;
}
protected void appendNatives(Environment env) {
// Print
append(env, "print", Print.class, "print",
Object.class);
// Util
append(env, "length", Util.class, "length",
Object.class);
// Input
append(env, "input", Input.class, "input");
// Convert
append(env, "toInt", Convert.class, "toInt",
Object.class);
append(env, "toStr", Convert.class, "toStr",
Object.class);
// Time
append(env, "currentTime", Time.class, "currentTime");
append(env, "formatTime", Time.class, "formatTime");
// File
append(env, "readFile", File.class, "readFile",
String.class);
append(env, "writeFile", File.class, "writeFile",
String.class, String.class);
// Collection
append(env, "newMap", Collection.class, "newMap");
append(env, "putMap", Collection.class, "putMap",
Object.class, Object.class, Object.class);
append(env, "getMap", Collection.class, "getMap",
Object.class, Object.class);
append(env, "clearMap", Collection.class, "clearMap",
Object.class);
}
protected void append(Environment env, String name, Class<?> clazz,
String methodName, Class<?>... params) {
Method m;
try {
m = clazz.getMethod(methodName, params);
} catch (Exception e) {
throw new HacException("cannot find a native function: " + methodName);
}
env.put(name, new NativeFunction(methodName, m));
}
}
| 30.921875 | 83 | 0.566953 |
c04db3af76fbd6b32072ebb802e86e978ada2789 | 5,285 | package com.gps.imp.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by leogps on 11/27/14.
*/
public class YoutubeUrlFetcher {
public static List<YoutubeLink> fetch(String videoUrl) throws IOException, URLFetchException {
InputStream inStream = null;
BufferedReader in = null;
List<YoutubeLink> youtubeLinks = new ArrayList<YoutubeLink>();
try {
Map<String, String> videoQueryMap = getQueryMapFromURL(videoUrl);
String vid = videoQueryMap.get("v");
if(vid == null) {
throw new URLFetchException("video param 'v' not found in the url");
}
URL url = new URL("http://www.youtube.com/get_video_info?video_id=" + vid);
inStream = url.openStream();
in = new BufferedReader(new InputStreamReader(inStream));
String response = "", temp;
while ((temp = in.readLine()) != null) {
response += temp;
}
Map<String, String> parameters = getQueryMap(response);
if (parameters.containsKey("reason")) {
throw new URLFetchException(URLDecoder.decode(parameters.get("reason"), "UTF-8"));
}
String title = parameters.get("title");
// String thubnailUrl = parameters.get("thumbnail_url");
// links.setThumbnailUrl(URLDecoder.decode(thubnailUrl, "UTF-8"));
title = URLDecoder.decode(title, "UTF-8");
title = title.replaceAll("[^a-zA-Z0-9\\s]+", "");
String url_encoded_fmt_stream_map = parameters.get("url_encoded_fmt_stream_map");
url_encoded_fmt_stream_map = URLDecoder.decode(url_encoded_fmt_stream_map, "UTF-8");
String[] urls = url_encoded_fmt_stream_map.split(",");
for (String u : urls) {
Map<String, String> urlParameters = getQueryMap(u);
String quality = urlParameters.get("quality");
quality = URLDecoder.decode(quality, "UTF-8");
String type = urlParameters.get("type");
type = URLDecoder.decode(type, "UTF-8");
YoutubeLink.Extension extension = YoutubeLink.Extension.getExtension(type);
String fileName = title + "." + extension.getName();
String ul = urlParameters.get("url");
ul = URLDecoder.decode(ul, "UTF-8");
YoutubeLink youtubeLink = new YoutubeLink(ul, YoutubeLink.Quality.getQuality(quality), extension, fileName);
youtubeLinks.add(youtubeLink);
}
} catch (Exception ex) {
throw new URLFetchException(ex);
}
return youtubeLinks;
}
private static Map<String, String> getQueryMapFromURL(String url) {
String query = url.substring(url.indexOf("?") + 1);
return getQueryMap(query);
}
private static Map<String, String> getQueryMap(String query) {
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params) {
String[] values = param.split("=");
if (values.length > 1) {
map.put(values[0], values[1]);
} else {
map.put(values[0], "NA");
}
}
return map;
}
public static void main(String args[]) throws IOException, URLFetchException {
List<YoutubeLink> youtubeLinks = new YoutubeUrlFetcher().fetch("https://www.youtube.com/watch?v=snzDwACffzs");
System.out.println(youtubeLinks);
System.out.println("Best link: " + getBest(youtubeLinks));
}
public static YoutubeLink getBest(List<YoutubeLink> youtubeLinkList) {
YoutubeLink best = null;
for(YoutubeLink youtubeLink : youtubeLinkList) {
if(best == null) {
best = youtubeLink;
continue;
}
if(compare(youtubeLink.getQuality(), best.getQuality())) {
best = youtubeLink;
}
}
return best;
}
private static boolean compare(YoutubeLink.Quality quality, YoutubeLink.Quality bestQuality) {
if(bestQuality == YoutubeLink.Quality.THOUSAND_80_P) {
return false;
}
if(bestQuality == YoutubeLink.Quality.SEVEN_20_P && quality != YoutubeLink.Quality.THOUSAND_80_P) {
return false;
}
if(bestQuality == YoutubeLink.Quality.FOUR_80_P && quality != YoutubeLink.Quality.SEVEN_20_P) {
return false;
}
if(bestQuality == YoutubeLink.Quality.THREE_60_P && quality != YoutubeLink.Quality.FOUR_80_P && quality != YoutubeLink.Quality.SEVEN_20_P) {
return false;
}
if(bestQuality == YoutubeLink.Quality.TWO_40_P && quality != YoutubeLink.Quality.THREE_60_P && quality != YoutubeLink.Quality.FOUR_80_P && quality != YoutubeLink.Quality.SEVEN_20_P) {
return false;
}
return true;
}
}
| 35.233333 | 191 | 0.598297 |
b89fad2978202cd6943220d565f63a1d5a65dc44 | 11,311 | package com.demo.io.niotest;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.*;
import java.sql.SQLOutput;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public class AppMain {
// https://blog.csdn.net/u011381576/article/details/79876754
public static void main(String[] args) throws IOException {
}
public static void method() throws IOException{
// 设置输入源 & 输出地 = 文件
String infile = "E:\\copy.sql";
String outfile = "E:\\copy.txt";
// 1. 获取数据源 和 目标传输地的输入输出流(此处以数据源 = 文件为例)
FileInputStream fin = new FileInputStream(infile);
FileOutputStream fout = new FileOutputStream(outfile);
// 2. 获取数据源的输入输出通道
FileChannel fcin = fin.getChannel();
FileChannel fcout = fout.getChannel();
// 3. 创建 缓冲区 对象:Buffer(共有2种方法)
// 方法1:使用allocate()静态方法
ByteBuffer buff = ByteBuffer.allocate(256);
// 上述方法创建1个容量为256字节的ByteBuffer
// 注:若发现创建的缓冲区容量太小,则重新创建一个大小合适的缓冲区
// 方法2:通过包装一个已有的数组来创建
// 注:通过包装的方法创建的缓冲区保留了被包装数组内保存的数据
//ByteBuffer buff = ByteBuffer.wrap(byteArray);
// 额外:若需将1个字符串存入ByteBuffer,则如下
String sendString="你好,服务器. ";
ByteBuffer sendBuff = ByteBuffer.wrap(sendString.getBytes("UTF-16"));
while (true) {
// 4. 从通道读取数据 & 写入到缓冲区
// 注:若 以读取到该通道数据的末尾,则返回-1
int r = fcin.read(buff);
if (r == -1) {
break;
}
// 5. 传出数据准备:调用flip()方法 将缓存区的写模式 转换->> 读模式
buff.flip();
// 6. 从 Buffer 中读取数据 & 传出数据到通道
fcout.write(buff);
// 7. 重置缓冲区
// 目的:重用现在的缓冲区,即 不必为了每次读写都创建新的缓冲区,在再次读取之前要重置缓冲区
// 注:不会改变缓冲区的数据,只是重置缓冲区的主要索引值
buff.clear();
}
}
// java nio
public static void method1(){
RandomAccessFile aFile = null;
try{
aFile = new RandomAccessFile("src/nio.txt","rw");
FileChannel fileChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1024);
int bytesRead = fileChannel.read(buf);
System.out.println(bytesRead);
while(bytesRead != -1)
{
buf.flip();
while(buf.hasRemaining())
{
System.out.print((char)buf.get());
}
buf.compact();
bytesRead = fileChannel.read(buf);
}
}catch (IOException e){
e.printStackTrace();
}finally{
try{
if(aFile != null){
aFile.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
// java io
public static void method2(){
InputStream in = null;
try{
in = new BufferedInputStream(new FileInputStream("src/nomal_io.txt"));
byte [] buf = new byte[1024];
int bytesRead = in.read(buf);
while(bytesRead != -1)
{
for(int i=0;i<bytesRead;i++)
System.out.print((char)buf[i]);
bytesRead = in.read(buf);
}
}catch (IOException e)
{
e.printStackTrace();
}finally{
try{
if(in != null){
in.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
// java BIO
public static void server1(){
ServerSocket serverSocket = null;
InputStream in = null;
try
{
serverSocket = new ServerSocket(8080);
int recvMsgSize = 0;
byte[] recvBuf = new byte[1024];
while(true){
Socket clntSocket = serverSocket.accept();
SocketAddress clientAddress = clntSocket.getRemoteSocketAddress();
System.out.println("Handling client at "+clientAddress);
in = clntSocket.getInputStream();
while((recvMsgSize=in.read(recvBuf))!=-1){
byte[] temp = new byte[recvMsgSize];
System.arraycopy(recvBuf, 0, temp, 0, recvMsgSize);
System.out.println(new String(temp));
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally{
try{
if(serverSocket!=null){
serverSocket.close();
}
if(in!=null){
in.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
// java NIO
public static void client1(){
ByteBuffer buffer = ByteBuffer.allocate(1024);
SocketChannel socketChannel = null;
// open
// connect
// ...write
// close
try
{
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("127.0.0.1",8080));
if(socketChannel.finishConnect())
{
int i=0;
while(true)
{
TimeUnit.SECONDS.sleep(1);
String info = "I'm "+i+++"-th information from client";
buffer.clear();
buffer.put(info.getBytes());
buffer.flip();
while(buffer.hasRemaining()){
System.out.println(buffer);
socketChannel.write(buffer);
}
}
}
}
catch (IOException | InterruptedException e)
{
e.printStackTrace();
}
finally{
try{
if(socketChannel!=null){
socketChannel.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
// java NIO
public static void server() throws IOException {
// 1. 创建Selector对象
Selector sel = Selector.open();
// 2. 向Selector对象绑定通道
// a. 创建可选择通道,并配置为非阻塞模式
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
// b. 绑定通道到指定端口
ServerSocket socket = server.socket();
InetSocketAddress address = new InetSocketAddress(8083);
socket.bind(address);
// c. 向Selector中注册感兴趣的事件(四种)
SelectionKey selectionKey = server.register(sel, SelectionKey.OP_ACCEPT);
//1. SelectionKey.OP_CONNECT
//2. SelectionKey.OP_ACCEPT
//3. SelectionKey.OP_READ
//4. SelectionKey.OP_WRITE
// 与Selector一起使用时,Channel必须处于非阻塞模式下。这意味着不能将FileChannel与Selector一起使用,因为FileChannel不能切换到非阻塞模式。而套接字通道都可以。
//selectionKey.isAcceptable();
//selectionKey.isConnectable();
//selectionKey.isReadable();
//selectionKey.isWritable();
//Channel channel = selectionKey.channel();
//Selector selector = selectionKey.selector();
//可以将一个对象或者更多信息附着到SelectionKey上,这样就能方便的识别某个给定的通道。例如,可以附加 与通道一起使用的Buffer,或是包含聚集数据的某个对象。使用方法如下:
//
//selectionKey.attach(theObject);
//Object attachedObj = selectionKey.attachment();
//还可以在用register()方法向Selector注册Channel的时候附加对象。如:
//
//SelectionKey key = channel.register(selector, SelectionKey.OP_READ, theObject);
// 3. 处理事件
try {
while(true) {
// 该调用会阻塞,直到至少有一个事件就绪、准备发生
sel.select();
// 一旦上述方法返回,线程就可以处理这些事件
Set<SelectionKey> keys = sel.selectedKeys();
Iterator<SelectionKey> iter = keys.iterator();
while (iter.hasNext()) {
SelectionKey key = (SelectionKey) iter.next();
iter.remove();
System.out.println(key);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
// ByteBuffer
public static void method4(){
RandomAccessFile aFile = null;
FileChannel fc = null;
try{
aFile = new RandomAccessFile("src/1.ppt","rw");
fc = aFile.getChannel();
long timeBegin = System.currentTimeMillis();
ByteBuffer buff = ByteBuffer.allocate((int) aFile.length());
buff.clear();
fc.read(buff);
//System.out.println((char)buff.get((int)(aFile.length()/2-1)));
//System.out.println((char)buff.get((int)(aFile.length()/2)));
//System.out.println((char)buff.get((int)(aFile.length()/2)+1));
long timeEnd = System.currentTimeMillis();
System.out.println("Read time: "+(timeEnd-timeBegin)+"ms");
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(aFile!=null){
aFile.close();
}
if(fc!=null){
fc.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
// MappedByteBuffer 读取大文件有绝对的优势
public static void method3(){
RandomAccessFile aFile = null;
FileChannel fc = null;
try{
aFile = new RandomAccessFile("src/1.ppt","rw");
fc = aFile.getChannel();
long timeBegin = System.currentTimeMillis();
MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, aFile.length());
//READ_ONLY,(只读): 试图修改得到的缓冲区将导致抛出 ReadOnlyBufferException.(MapMode.READ_ONLY)
//
//READ_WRITE(读/写): 对得到的缓冲区的更改最终将传播到文件;该更改对映射到同一文件的其他程序不一定是可见的。 (MapMode.READ_WRITE)
//
//PRIVATE(专用): 对得到的缓冲区的更改不会传播到文件,并且该更改对映射到同一文件的其他程序也不是可见的;相反,会创建缓冲区已修改部分的专用副本。 (MapMode.PRIVATE)
//
//MappedByteBuffer是ByteBuffer的子类,其扩充了三个方法:
// mbb.force();
//force():缓冲区是READ_WRITE模式下,此方法对缓冲区内容的修改强行写入文件;
// mbb.load();
//load():将缓冲区的内容载入内存,并返回该缓冲区的引用;
// mbb.isLoaded();
//isLoaded():如果缓冲区的内容在物理内存中,则返回真,否则返回假;
// System.out.println((char)mbb.get((int)(aFile.length()/2-1)));
// System.out.println((char)mbb.get((int)(aFile.length()/2)));
//System.out.println((char)mbb.get((int)(aFile.length()/2)+1));
long timeEnd = System.currentTimeMillis();
System.out.println("Read time: "+(timeEnd-timeBegin)+"ms");
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(aFile!=null){
aFile.close();
}
if(fc!=null){
fc.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
| 32.976676 | 110 | 0.512775 |
55d93be22f994deb219365fef98068e82a12ad30 | 1,667 | package br.com.webApp.servletpt1.modelo;
import br.com.webApp.servletpt1.controler.Nome;
import br.com.webApp.servletpt1.controler.Usuario;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class BD {
public static ArrayList<Nome> listNomes = new ArrayList<Nome>();
public static ArrayList<Usuario> usuarios = new ArrayList<>();
private Date dataCadastro;
public BD (){
Usuario daniel = new Usuario("daniel", "123");
usuarios.add(daniel);
}
public void adicionarNaLista (Nome nome){
BD.listNomes.add(nome);
}
public List<Nome> getListNomes (){
return BD.listNomes;
}
public Nome getListNomeByID(int index){
return BD.listNomes.get(index);
}
public int getIndex (int id) throws RuntimeException{
int i = 0;
for (Nome nome: listNomes) {
if (listNomes.get(i).getId() == id){
return i;
}
i++;
}
return -1;
}
public void deletaNome (int index){
BD.listNomes.remove(index);
}
public void editarNome (int index, String nome, Date data){
BD.listNomes.set(index, new Nome(nome, data));
}
public void adicionarUsuario (String nome, String password){
Usuario usuario = new Usuario(nome, password);
usuarios.add(usuario);
}
public Usuario verificaLogin (String nome, String passowrd){
for (Usuario user: usuarios) {
if (user.getNome().equals(nome) & user.getPassword().equals(passowrd)){
return user;
}
}
return null;
}
}
| 23.814286 | 83 | 0.60228 |
8e487719521416015616d175e5389ec9704890b4 | 4,629 | package com.facebook.common.memory;
import com.facebook.common.internal.Preconditions;
import com.facebook.common.logging.FLog;
import com.facebook.common.references.ResourceReleaser;
import java.io.IOException;
import java.io.InputStream;
import kotlin.UByte;
public class PooledByteArrayBufferedInputStream extends InputStream {
private static final String TAG = "PooledByteInputStream";
private int mBufferOffset = 0;
private int mBufferedSize = 0;
private final byte[] mByteArray;
private boolean mClosed = false;
private final InputStream mInputStream;
private final ResourceReleaser<byte[]> mResourceReleaser;
/* JADX WARNING: type inference failed for: r3v0, types: [com.facebook.common.references.ResourceReleaser<byte[]>, java.lang.Object] */
/* JADX WARNING: Unknown variable types count: 1 */
/* Code decompiled incorrectly, please refer to instructions dump. */
public PooledByteArrayBufferedInputStream(java.io.InputStream r1, byte[] r2, com.facebook.common.references.ResourceReleaser<byte[]> r3) {
/*
r0 = this;
r0.<init>()
java.lang.Object r1 = com.facebook.common.internal.Preconditions.checkNotNull(r1)
java.io.InputStream r1 = (java.io.InputStream) r1
r0.mInputStream = r1
java.lang.Object r1 = com.facebook.common.internal.Preconditions.checkNotNull(r2)
byte[] r1 = (byte[]) r1
r0.mByteArray = r1
java.lang.Object r1 = com.facebook.common.internal.Preconditions.checkNotNull(r3)
com.facebook.common.references.ResourceReleaser r1 = (com.facebook.common.references.ResourceReleaser) r1
r0.mResourceReleaser = r1
r1 = 0
r0.mBufferedSize = r1
r0.mBufferOffset = r1
r0.mClosed = r1
return
*/
throw new UnsupportedOperationException("Method not decompiled: com.facebook.common.memory.PooledByteArrayBufferedInputStream.<init>(java.io.InputStream, byte[], com.facebook.common.references.ResourceReleaser):void");
}
public int read() throws IOException {
Preconditions.checkState(this.mBufferOffset <= this.mBufferedSize);
ensureNotClosed();
if (!ensureDataInBuffer()) {
return -1;
}
byte[] bArr = this.mByteArray;
int i = this.mBufferOffset;
this.mBufferOffset = i + 1;
return bArr[i] & UByte.MAX_VALUE;
}
public int read(byte[] bArr, int i, int i2) throws IOException {
Preconditions.checkState(this.mBufferOffset <= this.mBufferedSize);
ensureNotClosed();
if (!ensureDataInBuffer()) {
return -1;
}
int min = Math.min(this.mBufferedSize - this.mBufferOffset, i2);
System.arraycopy(this.mByteArray, this.mBufferOffset, bArr, i, min);
this.mBufferOffset += min;
return min;
}
public int available() throws IOException {
Preconditions.checkState(this.mBufferOffset <= this.mBufferedSize);
ensureNotClosed();
return (this.mBufferedSize - this.mBufferOffset) + this.mInputStream.available();
}
public void close() throws IOException {
if (!this.mClosed) {
this.mClosed = true;
this.mResourceReleaser.release(this.mByteArray);
super.close();
}
}
public long skip(long j) throws IOException {
Preconditions.checkState(this.mBufferOffset <= this.mBufferedSize);
ensureNotClosed();
int i = this.mBufferedSize;
int i2 = this.mBufferOffset;
long j2 = (long) (i - i2);
if (j2 >= j) {
this.mBufferOffset = (int) (((long) i2) + j);
return j;
}
this.mBufferOffset = i;
return j2 + this.mInputStream.skip(j - j2);
}
private boolean ensureDataInBuffer() throws IOException {
if (this.mBufferOffset < this.mBufferedSize) {
return true;
}
int read = this.mInputStream.read(this.mByteArray);
if (read <= 0) {
return false;
}
this.mBufferedSize = read;
this.mBufferOffset = 0;
return true;
}
private void ensureNotClosed() throws IOException {
if (this.mClosed) {
throw new IOException("stream already closed");
}
}
/* access modifiers changed from: protected */
public void finalize() throws Throwable {
if (!this.mClosed) {
FLog.m64e(TAG, "Finalized without closing");
close();
}
super.finalize();
}
}
| 37.330645 | 226 | 0.63275 |
13cb3009b73d159be54e91676c2a2db2c4ef0ff6 | 53,348 | package com.github.mschroeder.github.jasgl.editor;
import com.github.mschroeder.github.jasgl.util.EditorUtils;
import com.github.mschroeder.github.jasgl.util.PNGUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.table.AbstractTableModel;
/**
*
* @author Markus Schröder
*/
public class MapTilesetSpriteFrame extends javax.swing.JFrame implements TileListener {
private final String TILESET_EXT = ".tileset.png";
private final String MAP_EXT = ".map.png";
//where maps and tilesets and sprites are stored
private File projectFolder;
public MapTilesetSpriteFrame(File projectFolder) {
this.projectFolder = projectFolder;
initComponents();
//size
Dimension size = new Dimension(1700, 900);
setSize(size);
setPreferredSize(size);
setLocationRelativeTo(null);
//different types
getTilesetRenderPanel().setMode(EditorRenderPanel.Mode.Tileset);
getMapRenderPanel().setMode(EditorRenderPanel.Mode.Map);
//list of files
jTableTileset.setModel(new TilesetTableModel());
jTableMap.setModel(new MapTableModel());
//tileset z change
jSpinnerTilesetZ.addChangeListener((e) -> {
jSpinnerTilesetZValueChanged(e);
});
((JSpinner.DefaultEditor)jSpinnerTilesetZ.getEditor()).getTextField().addKeyListener(new KeyListener(){
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
getTilesetRenderPanel().setZforSelected((int)jSpinnerTilesetZ.getValue());
}
}
@Override
public void keyReleased(KeyEvent e) {
}
});
//init render based on GUI (tileset)
getTilesetRenderPanel().setShowBlock(jCheckBoxTilesetShowBlock.isSelected());
getTilesetRenderPanel().setShowGrid(jCheckBoxTilesetShowGrid.isSelected());
getTilesetRenderPanel().setShowZ(jCheckBoxTilesetShowZ.isSelected());
getTilesetRenderPanel().setShowLayers(jCheckBoxTilesetShowLayers.isSelected());
//init render based on GUI (map)
getMapRenderPanel().setShowBlock(jCheckBoxMapShowBlock.isSelected());
getMapRenderPanel().setShowGrid(jCheckBoxMapShowGrid.isSelected());
getMapRenderPanel().setShowZ(jCheckBoxMapShowZ.isSelected());
getMapRenderPanel().setFillPencil(jCheckBoxPencilFill.isSelected());
getMapRenderPanel().addListener(this);
DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) jComboBoxEraseLayer.getModel();
model.removeAllElements();
model.addElement(Stamp.ALL);
model.addElement(Stamp.GROUND);
model.addElement(Stamp.OBJECT);
model.setSelectedItem(Stamp.ALL);
getMapRenderPanel().setEraseLayer((String) jComboBoxEraseLayer.getSelectedItem());
}
private void updateTilesetTable() {
jTableTileset.clearSelection();
jTableTileset.updateUI();
}
private void updateMapTable() {
jTableMap.clearSelection();
jTableMap.updateUI();
}
private List<File> getTilesetFilesSorted() {
return EditorUtils.getSortedFiles(projectFolder, f -> f.getName().endsWith(TILESET_EXT));
}
private List<File> getMapFilesSorted() {
return EditorUtils.getSortedFiles(projectFolder, f -> f.getName().endsWith(MAP_EXT));
}
@Override
public void selected(List<JsonObject> tiles) {
jTabbedPaneTile.removeAll();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
for(JsonObject tile : tiles) {
int gx = tile.get("gx").getAsInt();
int gy = tile.get("gy").getAsInt();
int gz = tile.get("gz").getAsInt();
JTextArea area = new JTextArea(gson.toJson(tile));
JScrollPane scroll = new JScrollPane(area);
jTabbedPaneTile.addTab(String.format("(%d,%d,%d)", gx, gy, gz), scroll);
}
}
private class TilesetTableModel extends AbstractTableModel {
@Override
public int getRowCount() {
return getTilesetFilesSorted().size();
}
@Override
public int getColumnCount() {
return 1;
}
@Override
public String getColumnName(int column) {
return "Tileset";
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
File f = getTilesetFilesSorted().get(rowIndex);
return f.getName();
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
File f = getTilesetFilesSorted().get(rowIndex);
String name = (String) aValue;
rename(f, name);
}
}
private class MapTableModel extends AbstractTableModel {
@Override
public int getRowCount() {
return getMapFilesSorted().size();
}
@Override
public int getColumnCount() {
return 1;
}
@Override
public String getColumnName(int column) {
return "Map";
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
File f = getMapFilesSorted().get(rowIndex);
return f.getName();
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
File f = getMapFilesSorted().get(rowIndex);
String name = (String) aValue;
rename(f, name);
}
}
private void rename(File f, String name) {
File newFile = new File(f.getParentFile(), name);
if (!(newFile.getName().endsWith(TILESET_EXT) || newFile.getName().endsWith(MAP_EXT))) {
return;
}
if (!newFile.exists()) {
f.renameTo(newFile);
updateTilesetTable();
}
}
private void openTilesetFile(File f) {
getTilesetRenderPanel().setFile(f);
}
private void openMapFile(File f) {
getMapRenderPanel().setFile(f);
}
private EditorRenderPanel getTilesetRenderPanel() {
return (EditorRenderPanel) jPanelTilesetRender;
}
private EditorRenderPanel getMapRenderPanel() {
return (EditorRenderPanel) jPanelMapRender;
}
private JsonObject createTile(int x, int y, int w, int h) {
JsonObject tile = new JsonObject();
tile.addProperty("x", x);
tile.addProperty("y", y);
tile.addProperty("w", w);
tile.addProperty("h", h);
tile.addProperty("z", 0);
tile.addProperty("l", false);
tile.addProperty("r", false);
tile.addProperty("u", false);
tile.addProperty("d", false);
return tile;
}
private void cutTileset() {
if(jTableTileset.getSelectedRow() == -1)
return;
File file = getTilesetFilesSorted().get(jTableTileset.getSelectedRow());
if(JOptionPane.showConfirmDialog(this, "Cut " + file.getName() + "?") != JOptionPane.OK_OPTION) {
return;
}
String cut = JOptionPane.showInputDialog(this, "Cut", "16x16");
String[] split = cut.split("x");
int w = Integer.parseInt(split[0]);
int h = Integer.parseInt(split[1]);
BufferedImage image;
try {
image = ImageIO.read(file);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
JsonArray array = new JsonArray();
for(int y = 0; y < image.getHeight(); y += h) {
for(int x = 0; x < image.getWidth(); x += w) {
array.add(createTile(x, y, w, h));
}
}
JsonObject data = new JsonObject();
data.add("tiles", array);
PNGUtils.write(file, data.toString());
openTilesetFile(file);
}
private void removeTileset() {
List<File> files = new ArrayList<>();
List<File> all = getTilesetFilesSorted();
for(int i : jTableTileset.getSelectedRows()) {
files.add(all.get(i));
}
if(JOptionPane.showConfirmDialog(this, "Remove " + files.size() + "?") != JOptionPane.OK_OPTION) {
return;
}
for(File f : all) {
f.delete();
}
updateTilesetTable();
}
private void removeMap() {
List<File> files = new ArrayList<>();
List<File> all = getMapFilesSorted();
for(int i : jTableMap.getSelectedRows()) {
files.add(all.get(i));
}
if(JOptionPane.showConfirmDialog(this, "Remove " + files.size() + "?") != JOptionPane.OK_OPTION) {
return;
}
for(File f : all) {
f.delete();
}
updateMapTable();
}
private void jSpinnerTilesetZValueChanged(ChangeEvent e) {
getTilesetRenderPanel().setZforSelected((int)jSpinnerTilesetZ.getValue());
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroupMapMode = new javax.swing.ButtonGroup();
buttonGroupDrawMode = new javax.swing.ButtonGroup();
jSplitPaneMain = new javax.swing.JSplitPane();
jTabbedPaneTilesetSprite = new javax.swing.JTabbedPane();
jPanelTileset = new javax.swing.JPanel();
jSplitPaneTileset = new javax.swing.JSplitPane();
jPanel1 = new javax.swing.JPanel();
jToolBar1 = new javax.swing.JToolBar();
jSpinnerTilesetZ = new javax.swing.JSpinner();
jCheckBoxTilesetShowLayers = new javax.swing.JCheckBox();
jCheckBoxTilesetShowGrid = new javax.swing.JCheckBox();
jCheckBoxTilesetShowZ = new javax.swing.JCheckBox();
jCheckBoxTilesetShowBlock = new javax.swing.JCheckBox();
jScrollPaneTileset = new javax.swing.JScrollPane();
jPanelTilesetRender = new com.github.mschroeder.github.jasgl.editor.EditorRenderPanel();
jPanelTilesetList = new javax.swing.JPanel();
jToolBarTileset = new javax.swing.JToolBar();
jButtonTilesetCut = new javax.swing.JButton();
jButtonTilesetRemove = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTableTileset = new javax.swing.JTable();
jPanelSprite = new javax.swing.JPanel();
jTabbedPaneMap = new javax.swing.JTabbedPane();
jPanelMap = new javax.swing.JPanel();
jSplitPaneMap = new javax.swing.JSplitPane();
jPanel2 = new javax.swing.JPanel();
jToolBar2 = new javax.swing.JToolBar();
jButtonMapNew = new javax.swing.JButton();
jButtonDuplicate = new javax.swing.JButton();
jButtonRemove = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTableMap = new javax.swing.JTable();
jPanel3 = new javax.swing.JPanel();
jToolBar3 = new javax.swing.JToolBar();
jRadioButtonMapDraw = new javax.swing.JRadioButton();
jRadioButtonMapSelect = new javax.swing.JRadioButton();
jRadioButtonMapErase = new javax.swing.JRadioButton();
jCheckBoxMapShowGrid = new javax.swing.JCheckBox();
jCheckBoxMapShowZ = new javax.swing.JCheckBox();
jCheckBoxMapShowBlock = new javax.swing.JCheckBox();
jScrollPaneMapRender = new javax.swing.JScrollPane();
jPanelMapRender = new EditorRenderPanel();
jToolBar4 = new javax.swing.JToolBar();
jRadioButtonPoint = new javax.swing.JRadioButton();
jRadioButtonLine = new javax.swing.JRadioButton();
jRadioButtonRect = new javax.swing.JRadioButton();
jRadioButtonCircle = new javax.swing.JRadioButton();
jCheckBoxPencilFill = new javax.swing.JCheckBox();
jComboBoxEraseLayer = new javax.swing.JComboBox<>();
jTabbedPaneTile = new javax.swing.JTabbedPane();
jMenuBarMain = new javax.swing.JMenuBar();
jMenuMap = new javax.swing.JMenu();
jMenuItemResetTilesetCache = new javax.swing.JMenuItem();
jMenuTileset = new javax.swing.JMenu();
jMenuItemTilesetPasteImage = new javax.swing.JMenuItem();
jMenuItemBlock = new javax.swing.JMenuItem();
jMenuItemPass = new javax.swing.JMenuItem();
jMenuItemGround = new javax.swing.JMenuItem();
jMenuItemResetLayer = new javax.swing.JMenuItem();
jMenuSprite = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Editor");
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
jSplitPaneMain.setDividerLocation(800);
jSplitPaneMain.setResizeWeight(1.0);
jSplitPaneTileset.setDividerLocation(400);
jSplitPaneTileset.setResizeWeight(1.0);
jToolBar1.setFloatable(false);
jToolBar1.setRollover(true);
jSpinnerTilesetZ.setModel(new javax.swing.SpinnerNumberModel(0, null, 10, 1));
jToolBar1.add(jSpinnerTilesetZ);
jCheckBoxTilesetShowLayers.setSelected(true);
jCheckBoxTilesetShowLayers.setText("Show Layers");
jCheckBoxTilesetShowLayers.setFocusable(false);
jCheckBoxTilesetShowLayers.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
jCheckBoxTilesetShowLayers.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
jCheckBoxTilesetShowLayers.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jCheckBoxTilesetShowLayers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxTilesetShowLayersActionPerformed(evt);
}
});
jToolBar1.add(jCheckBoxTilesetShowLayers);
jCheckBoxTilesetShowGrid.setSelected(true);
jCheckBoxTilesetShowGrid.setText("Show Grid");
jCheckBoxTilesetShowGrid.setFocusable(false);
jCheckBoxTilesetShowGrid.setHideActionText(true);
jCheckBoxTilesetShowGrid.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
jCheckBoxTilesetShowGrid.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jCheckBoxTilesetShowGrid.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxTilesetShowGridActionPerformed(evt);
}
});
jToolBar1.add(jCheckBoxTilesetShowGrid);
jCheckBoxTilesetShowZ.setSelected(true);
jCheckBoxTilesetShowZ.setText("Show Z");
jCheckBoxTilesetShowZ.setToolTipText("");
jCheckBoxTilesetShowZ.setFocusable(false);
jCheckBoxTilesetShowZ.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
jCheckBoxTilesetShowZ.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jCheckBoxTilesetShowZ.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxTilesetShowZActionPerformed(evt);
}
});
jToolBar1.add(jCheckBoxTilesetShowZ);
jCheckBoxTilesetShowBlock.setSelected(true);
jCheckBoxTilesetShowBlock.setText("Show Block");
jCheckBoxTilesetShowBlock.setFocusable(false);
jCheckBoxTilesetShowBlock.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
jCheckBoxTilesetShowBlock.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jCheckBoxTilesetShowBlock.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxTilesetShowBlockActionPerformed(evt);
}
});
jToolBar1.add(jCheckBoxTilesetShowBlock);
jPanelTilesetRender.setLayout(null);
jScrollPaneTileset.setViewportView(jPanelTilesetRender);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPaneTileset, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPaneTileset, javax.swing.GroupLayout.DEFAULT_SIZE, 547, Short.MAX_VALUE))
);
jSplitPaneTileset.setLeftComponent(jPanel1);
jToolBarTileset.setFloatable(false);
jToolBarTileset.setRollover(true);
jButtonTilesetCut.setText("Cut");
jButtonTilesetCut.setFocusable(false);
jButtonTilesetCut.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonTilesetCut.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jButtonTilesetCut.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonTilesetCutActionPerformed(evt);
}
});
jToolBarTileset.add(jButtonTilesetCut);
jButtonTilesetRemove.setText("Remove");
jButtonTilesetRemove.setToolTipText("");
jButtonTilesetRemove.setFocusable(false);
jButtonTilesetRemove.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonTilesetRemove.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jButtonTilesetRemove.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonTilesetRemoveActionPerformed(evt);
}
});
jToolBarTileset.add(jButtonTilesetRemove);
jTableTileset.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jTableTileset.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTableTilesetMouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTableTileset);
javax.swing.GroupLayout jPanelTilesetListLayout = new javax.swing.GroupLayout(jPanelTilesetList);
jPanelTilesetList.setLayout(jPanelTilesetListLayout);
jPanelTilesetListLayout.setHorizontalGroup(
jPanelTilesetListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToolBarTileset, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
);
jPanelTilesetListLayout.setVerticalGroup(
jPanelTilesetListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelTilesetListLayout.createSequentialGroup()
.addComponent(jToolBarTileset, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 547, Short.MAX_VALUE))
);
jSplitPaneTileset.setRightComponent(jPanelTilesetList);
javax.swing.GroupLayout jPanelTilesetLayout = new javax.swing.GroupLayout(jPanelTileset);
jPanelTileset.setLayout(jPanelTilesetLayout);
jPanelTilesetLayout.setHorizontalGroup(
jPanelTilesetLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPaneTileset)
);
jPanelTilesetLayout.setVerticalGroup(
jPanelTilesetLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPaneTileset)
);
jTabbedPaneTilesetSprite.addTab("Tileset", jPanelTileset);
javax.swing.GroupLayout jPanelSpriteLayout = new javax.swing.GroupLayout(jPanelSprite);
jPanelSprite.setLayout(jPanelSpriteLayout);
jPanelSpriteLayout.setHorizontalGroup(
jPanelSpriteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 579, Short.MAX_VALUE)
);
jPanelSpriteLayout.setVerticalGroup(
jPanelSpriteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 586, Short.MAX_VALUE)
);
jTabbedPaneTilesetSprite.addTab("Sprite", jPanelSprite);
jSplitPaneMain.setRightComponent(jTabbedPaneTilesetSprite);
jSplitPaneMap.setDividerLocation(170);
jToolBar2.setFloatable(false);
jToolBar2.setRollover(true);
jButtonMapNew.setText("New");
jButtonMapNew.setFocusable(false);
jButtonMapNew.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonMapNew.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jButtonMapNew.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonMapNewActionPerformed(evt);
}
});
jToolBar2.add(jButtonMapNew);
jButtonDuplicate.setText("Dupl.");
jButtonDuplicate.setFocusable(false);
jButtonDuplicate.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonDuplicate.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jButtonDuplicate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonDuplicateActionPerformed(evt);
}
});
jToolBar2.add(jButtonDuplicate);
jButtonRemove.setText("Remove");
jButtonRemove.setFocusable(false);
jButtonRemove.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jButtonRemove.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jButtonRemove.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonRemoveActionPerformed(evt);
}
});
jToolBar2.add(jButtonRemove);
jTableMap.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jTableMap.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTableMapMouseClicked(evt);
}
});
jScrollPane2.setViewportView(jTableMap);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(0, 0, 0)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToolBar2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 553, Short.MAX_VALUE))
);
jSplitPaneMap.setLeftComponent(jPanel2);
jToolBar3.setFloatable(false);
jToolBar3.setRollover(true);
buttonGroupMapMode.add(jRadioButtonMapDraw);
jRadioButtonMapDraw.setSelected(true);
jRadioButtonMapDraw.setText("Draw");
jRadioButtonMapDraw.setFocusable(false);
jRadioButtonMapDraw.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
jRadioButtonMapDraw.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jRadioButtonMapDraw.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jRadioButtonMapDrawItemStateChanged(evt);
}
});
jToolBar3.add(jRadioButtonMapDraw);
buttonGroupMapMode.add(jRadioButtonMapSelect);
jRadioButtonMapSelect.setText("Select");
jRadioButtonMapSelect.setFocusable(false);
jRadioButtonMapSelect.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
jRadioButtonMapSelect.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jRadioButtonMapSelect.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jRadioButtonMapSelectItemStateChanged(evt);
}
});
jToolBar3.add(jRadioButtonMapSelect);
buttonGroupMapMode.add(jRadioButtonMapErase);
jRadioButtonMapErase.setText("Erase");
jRadioButtonMapErase.setFocusable(false);
jRadioButtonMapErase.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
jRadioButtonMapErase.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jRadioButtonMapErase.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jRadioButtonMapEraseItemStateChanged(evt);
}
});
jToolBar3.add(jRadioButtonMapErase);
jCheckBoxMapShowGrid.setSelected(true);
jCheckBoxMapShowGrid.setText("Show Grid");
jCheckBoxMapShowGrid.setFocusable(false);
jCheckBoxMapShowGrid.setHideActionText(true);
jCheckBoxMapShowGrid.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
jCheckBoxMapShowGrid.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jCheckBoxMapShowGrid.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxMapShowGridActionPerformed(evt);
}
});
jToolBar3.add(jCheckBoxMapShowGrid);
jCheckBoxMapShowZ.setSelected(true);
jCheckBoxMapShowZ.setText("Show Z");
jCheckBoxMapShowZ.setToolTipText("");
jCheckBoxMapShowZ.setFocusable(false);
jCheckBoxMapShowZ.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
jCheckBoxMapShowZ.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jCheckBoxMapShowZ.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxMapShowZActionPerformed(evt);
}
});
jToolBar3.add(jCheckBoxMapShowZ);
jCheckBoxMapShowBlock.setSelected(true);
jCheckBoxMapShowBlock.setText("Show Block");
jCheckBoxMapShowBlock.setFocusable(false);
jCheckBoxMapShowBlock.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
jCheckBoxMapShowBlock.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jCheckBoxMapShowBlock.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxMapShowBlockActionPerformed(evt);
}
});
jToolBar3.add(jCheckBoxMapShowBlock);
jPanelMapRender.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseExited(java.awt.event.MouseEvent evt) {
jPanelMapRenderMouseExited(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jPanelMapRenderMouseEntered(evt);
}
});
jPanelMapRender.setLayout(null);
jScrollPaneMapRender.setViewportView(jPanelMapRender);
jToolBar4.setFloatable(false);
jToolBar4.setRollover(true);
buttonGroupDrawMode.add(jRadioButtonPoint);
jRadioButtonPoint.setSelected(true);
jRadioButtonPoint.setText("·");
jRadioButtonPoint.setToolTipText("Dot");
jRadioButtonPoint.setFocusable(false);
jRadioButtonPoint.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
jRadioButtonPoint.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jRadioButtonPoint.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jRadioButtonPointItemStateChanged(evt);
}
});
jToolBar4.add(jRadioButtonPoint);
buttonGroupDrawMode.add(jRadioButtonLine);
jRadioButtonLine.setText("/");
jRadioButtonLine.setToolTipText("Line");
jRadioButtonLine.setFocusable(false);
jRadioButtonLine.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
jRadioButtonLine.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jRadioButtonLine.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jRadioButtonLineItemStateChanged(evt);
}
});
jToolBar4.add(jRadioButtonLine);
buttonGroupDrawMode.add(jRadioButtonRect);
jRadioButtonRect.setText("☐");
jRadioButtonRect.setToolTipText("Rectangle");
jRadioButtonRect.setFocusable(false);
jRadioButtonRect.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
jRadioButtonRect.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jRadioButtonRect.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jRadioButtonRectItemStateChanged(evt);
}
});
jToolBar4.add(jRadioButtonRect);
buttonGroupDrawMode.add(jRadioButtonCircle);
jRadioButtonCircle.setText("○");
jRadioButtonCircle.setToolTipText("Circle");
jRadioButtonCircle.setFocusable(false);
jRadioButtonCircle.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
jRadioButtonCircle.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jRadioButtonCircle.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jRadioButtonCircleItemStateChanged(evt);
}
});
jToolBar4.add(jRadioButtonCircle);
jCheckBoxPencilFill.setSelected(true);
jCheckBoxPencilFill.setText("FIlled");
jCheckBoxPencilFill.setFocusable(false);
jCheckBoxPencilFill.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
jCheckBoxPencilFill.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
jCheckBoxPencilFill.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCheckBoxPencilFillActionPerformed(evt);
}
});
jToolBar4.add(jCheckBoxPencilFill);
jComboBoxEraseLayer.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBoxEraseLayer.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBoxEraseLayerItemStateChanged(evt);
}
});
jToolBar4.add(jComboBoxEraseLayer);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jToolBar3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPaneMapRender)
.addComponent(jToolBar4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTabbedPaneTile)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jToolBar3, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jToolBar4, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPaneMapRender, javax.swing.GroupLayout.DEFAULT_SIZE, 401, Short.MAX_VALUE)
.addGap(9, 9, 9)
.addComponent(jTabbedPaneTile, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jSplitPaneMap.setRightComponent(jPanel3);
javax.swing.GroupLayout jPanelMapLayout = new javax.swing.GroupLayout(jPanelMap);
jPanelMap.setLayout(jPanelMapLayout);
jPanelMapLayout.setHorizontalGroup(
jPanelMapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPaneMap)
);
jPanelMapLayout.setVerticalGroup(
jPanelMapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPaneMap)
);
jTabbedPaneMap.addTab("Map", jPanelMap);
jSplitPaneMain.setLeftComponent(jTabbedPaneMap);
jMenuMap.setText("Map");
jMenuItemResetTilesetCache.setText("Reset Tileset Cache");
jMenuItemResetTilesetCache.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemResetTilesetCacheActionPerformed(evt);
}
});
jMenuMap.add(jMenuItemResetTilesetCache);
jMenuBarMain.add(jMenuMap);
jMenuTileset.setText("Tileset");
jMenuItemTilesetPasteImage.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK));
jMenuItemTilesetPasteImage.setText("Paste Image");
jMenuItemTilesetPasteImage.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemTilesetPasteImageActionPerformed(evt);
}
});
jMenuTileset.add(jMenuItemTilesetPasteImage);
jMenuItemBlock.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, java.awt.event.InputEvent.CTRL_MASK));
jMenuItemBlock.setText("Set Block");
jMenuItemBlock.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemBlockActionPerformed(evt);
}
});
jMenuTileset.add(jMenuItemBlock);
jMenuItemPass.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
jMenuItemPass.setText("Set Pass");
jMenuItemPass.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemPassActionPerformed(evt);
}
});
jMenuTileset.add(jMenuItemPass);
jMenuItemGround.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, java.awt.event.InputEvent.CTRL_MASK));
jMenuItemGround.setText("Set Ground Layer");
jMenuItemGround.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemGroundActionPerformed(evt);
}
});
jMenuTileset.add(jMenuItemGround);
jMenuItemResetLayer.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.CTRL_MASK));
jMenuItemResetLayer.setText("Reset Layer");
jMenuItemResetLayer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemResetLayerActionPerformed(evt);
}
});
jMenuTileset.add(jMenuItemResetLayer);
jMenuBarMain.add(jMenuTileset);
jMenuSprite.setText("Sprite");
jMenuBarMain.add(jMenuSprite);
setJMenuBar(jMenuBarMain);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPaneMain)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPaneMain)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jMenuItemTilesetPasteImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemTilesetPasteImageActionPerformed
BufferedImage img = EditorUtils.getImageFromClipboard();
if(img == null)
return;
String name = JOptionPane.showInputDialog("Name (without extension)");
if(name == null)
return;
File imgFile = new File(projectFolder, name + TILESET_EXT);
try {
ImageIO.write(img, "png", imgFile);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
updateTilesetTable();
}//GEN-LAST:event_jMenuItemTilesetPasteImageActionPerformed
private void jTableTilesetMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableTilesetMouseClicked
if(SwingUtilities.isLeftMouseButton(evt) && jTableTileset.getSelectedRow() != -1) {
File f = getTilesetFilesSorted().get(jTableTileset.getSelectedRow());
openTilesetFile(f);
}
}//GEN-LAST:event_jTableTilesetMouseClicked
private void jButtonTilesetCutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTilesetCutActionPerformed
cutTileset();
}//GEN-LAST:event_jButtonTilesetCutActionPerformed
private void jButtonTilesetRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTilesetRemoveActionPerformed
removeTileset();
}//GEN-LAST:event_jButtonTilesetRemoveActionPerformed
private void jCheckBoxTilesetShowGridActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxTilesetShowGridActionPerformed
getTilesetRenderPanel().setShowGrid(jCheckBoxTilesetShowGrid.isSelected());
}//GEN-LAST:event_jCheckBoxTilesetShowGridActionPerformed
private void jCheckBoxTilesetShowZActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxTilesetShowZActionPerformed
getTilesetRenderPanel().setShowZ(jCheckBoxTilesetShowZ.isSelected());
}//GEN-LAST:event_jCheckBoxTilesetShowZActionPerformed
private void jCheckBoxTilesetShowBlockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxTilesetShowBlockActionPerformed
getTilesetRenderPanel().setShowBlock(jCheckBoxTilesetShowBlock.isSelected());
}//GEN-LAST:event_jCheckBoxTilesetShowBlockActionPerformed
private void jMenuItemPassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemPassActionPerformed
getTilesetRenderPanel().setBlockforSelected(false);
}//GEN-LAST:event_jMenuItemPassActionPerformed
private void jMenuItemBlockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemBlockActionPerformed
getTilesetRenderPanel().setBlockforSelected(true);
}//GEN-LAST:event_jMenuItemBlockActionPerformed
private void jCheckBoxMapShowGridActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMapShowGridActionPerformed
getMapRenderPanel().setShowGrid(jCheckBoxMapShowGrid.isSelected());
}//GEN-LAST:event_jCheckBoxMapShowGridActionPerformed
private void jCheckBoxMapShowZActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMapShowZActionPerformed
getMapRenderPanel().setShowZ(jCheckBoxMapShowZ.isSelected());
}//GEN-LAST:event_jCheckBoxMapShowZActionPerformed
private void jCheckBoxMapShowBlockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxMapShowBlockActionPerformed
getMapRenderPanel().setShowBlock(jCheckBoxMapShowBlock.isSelected());
}//GEN-LAST:event_jCheckBoxMapShowBlockActionPerformed
private void jButtonMapNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonMapNewActionPerformed
String name = JOptionPane.showInputDialog("Name (without extension)");
if(name == null)
return;
File imgFile = new File(projectFolder, name + MAP_EXT);
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
try {
ImageIO.write(img, "png", imgFile);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
updateMapTable();
}//GEN-LAST:event_jButtonMapNewActionPerformed
private void jButtonDuplicateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDuplicateActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButtonDuplicateActionPerformed
private void jButtonRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRemoveActionPerformed
removeMap();
}//GEN-LAST:event_jButtonRemoveActionPerformed
private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
jSplitPaneMain.setDividerLocation(0.5);
SwingUtilities.invokeLater(() -> {
jSplitPaneMap.setDividerLocation(0.25);
jSplitPaneTileset.setDividerLocation(0.75);
});
}//GEN-LAST:event_formComponentShown
private void jTableMapMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableMapMouseClicked
if(SwingUtilities.isLeftMouseButton(evt) && jTableMap.getSelectedRow() != -1) {
File f = getMapFilesSorted().get(jTableMap.getSelectedRow());
openMapFile(f);
}
}//GEN-LAST:event_jTableMapMouseClicked
private void jPanelMapRenderMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanelMapRenderMouseEntered
Stamp stamp = getTilesetRenderPanel().getTilesetStamp();
getMapRenderPanel().setMapStamp(stamp);
}//GEN-LAST:event_jPanelMapRenderMouseEntered
private void jPanelMapRenderMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanelMapRenderMouseExited
getMapRenderPanel().setMapStamp(null);
}//GEN-LAST:event_jPanelMapRenderMouseExited
private void jMenuItemGroundActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemGroundActionPerformed
getTilesetRenderPanel().setLayerForSelected(Stamp.GROUND);
}//GEN-LAST:event_jMenuItemGroundActionPerformed
private void jMenuItemResetLayerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemResetLayerActionPerformed
getTilesetRenderPanel().setLayerForSelected(null);
}//GEN-LAST:event_jMenuItemResetLayerActionPerformed
private void jCheckBoxTilesetShowLayersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxTilesetShowLayersActionPerformed
getTilesetRenderPanel().setShowLayers(jCheckBoxTilesetShowLayers.isSelected());
}//GEN-LAST:event_jCheckBoxTilesetShowLayersActionPerformed
private void jRadioButtonMapDrawItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRadioButtonMapDrawItemStateChanged
if(evt.getStateChange() == ItemEvent.SELECTED)
getMapRenderPanel().setDrawMode(EditorRenderPanel.DrawMode.Draw);
}//GEN-LAST:event_jRadioButtonMapDrawItemStateChanged
private void jRadioButtonMapSelectItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRadioButtonMapSelectItemStateChanged
if(evt.getStateChange() == ItemEvent.SELECTED)
getMapRenderPanel().setDrawMode(EditorRenderPanel.DrawMode.Select);
}//GEN-LAST:event_jRadioButtonMapSelectItemStateChanged
private void jRadioButtonMapEraseItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRadioButtonMapEraseItemStateChanged
if(evt.getStateChange() == ItemEvent.SELECTED)
getMapRenderPanel().setDrawMode(EditorRenderPanel.DrawMode.Erase);
}//GEN-LAST:event_jRadioButtonMapEraseItemStateChanged
private void jRadioButtonPointItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRadioButtonPointItemStateChanged
if(evt.getStateChange() == ItemEvent.SELECTED)
getMapRenderPanel().setPencilMode(EditorRenderPanel.PencilMode.Point);
}//GEN-LAST:event_jRadioButtonPointItemStateChanged
private void jRadioButtonLineItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRadioButtonLineItemStateChanged
if(evt.getStateChange() == ItemEvent.SELECTED)
getMapRenderPanel().setPencilMode(EditorRenderPanel.PencilMode.Line);
}//GEN-LAST:event_jRadioButtonLineItemStateChanged
private void jRadioButtonRectItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRadioButtonRectItemStateChanged
if(evt.getStateChange() == ItemEvent.SELECTED)
getMapRenderPanel().setPencilMode(EditorRenderPanel.PencilMode.Rect);
}//GEN-LAST:event_jRadioButtonRectItemStateChanged
private void jRadioButtonCircleItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRadioButtonCircleItemStateChanged
if(evt.getStateChange() == ItemEvent.SELECTED)
getMapRenderPanel().setPencilMode(EditorRenderPanel.PencilMode.Circle);
}//GEN-LAST:event_jRadioButtonCircleItemStateChanged
private void jCheckBoxPencilFillActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBoxPencilFillActionPerformed
getMapRenderPanel().setFillPencil(jCheckBoxPencilFill.isSelected());
}//GEN-LAST:event_jCheckBoxPencilFillActionPerformed
private void jComboBoxEraseLayerItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxEraseLayerItemStateChanged
getMapRenderPanel().setEraseLayer((String) jComboBoxEraseLayer.getSelectedItem());
}//GEN-LAST:event_jComboBoxEraseLayerItemStateChanged
private void jMenuItemResetTilesetCacheActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemResetTilesetCacheActionPerformed
getMapRenderPanel().resetTilesetCache();
}//GEN-LAST:event_jMenuItemResetTilesetCacheActionPerformed
public static void showGUI(File projectFolder) {
java.awt.EventQueue.invokeLater(() -> {
new MapTilesetSpriteFrame(projectFolder).setVisible(true);
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.ButtonGroup buttonGroupDrawMode;
private javax.swing.ButtonGroup buttonGroupMapMode;
private javax.swing.JButton jButtonDuplicate;
private javax.swing.JButton jButtonMapNew;
private javax.swing.JButton jButtonRemove;
private javax.swing.JButton jButtonTilesetCut;
private javax.swing.JButton jButtonTilesetRemove;
private javax.swing.JCheckBox jCheckBoxMapShowBlock;
private javax.swing.JCheckBox jCheckBoxMapShowGrid;
private javax.swing.JCheckBox jCheckBoxMapShowZ;
private javax.swing.JCheckBox jCheckBoxPencilFill;
private javax.swing.JCheckBox jCheckBoxTilesetShowBlock;
private javax.swing.JCheckBox jCheckBoxTilesetShowGrid;
private javax.swing.JCheckBox jCheckBoxTilesetShowLayers;
private javax.swing.JCheckBox jCheckBoxTilesetShowZ;
private javax.swing.JComboBox<String> jComboBoxEraseLayer;
private javax.swing.JMenuBar jMenuBarMain;
private javax.swing.JMenuItem jMenuItemBlock;
private javax.swing.JMenuItem jMenuItemGround;
private javax.swing.JMenuItem jMenuItemPass;
private javax.swing.JMenuItem jMenuItemResetLayer;
private javax.swing.JMenuItem jMenuItemResetTilesetCache;
private javax.swing.JMenuItem jMenuItemTilesetPasteImage;
private javax.swing.JMenu jMenuMap;
private javax.swing.JMenu jMenuSprite;
private javax.swing.JMenu jMenuTileset;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanelMap;
private javax.swing.JPanel jPanelMapRender;
private javax.swing.JPanel jPanelSprite;
private javax.swing.JPanel jPanelTileset;
private javax.swing.JPanel jPanelTilesetList;
private javax.swing.JPanel jPanelTilesetRender;
private javax.swing.JRadioButton jRadioButtonCircle;
private javax.swing.JRadioButton jRadioButtonLine;
private javax.swing.JRadioButton jRadioButtonMapDraw;
private javax.swing.JRadioButton jRadioButtonMapErase;
private javax.swing.JRadioButton jRadioButtonMapSelect;
private javax.swing.JRadioButton jRadioButtonPoint;
private javax.swing.JRadioButton jRadioButtonRect;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPaneMapRender;
private javax.swing.JScrollPane jScrollPaneTileset;
private javax.swing.JSpinner jSpinnerTilesetZ;
private javax.swing.JSplitPane jSplitPaneMain;
private javax.swing.JSplitPane jSplitPaneMap;
private javax.swing.JSplitPane jSplitPaneTileset;
private javax.swing.JTabbedPane jTabbedPaneMap;
private javax.swing.JTabbedPane jTabbedPaneTile;
private javax.swing.JTabbedPane jTabbedPaneTilesetSprite;
private javax.swing.JTable jTableMap;
private javax.swing.JTable jTableTileset;
private javax.swing.JToolBar jToolBar1;
private javax.swing.JToolBar jToolBar2;
private javax.swing.JToolBar jToolBar3;
private javax.swing.JToolBar jToolBar4;
private javax.swing.JToolBar jToolBarTileset;
// End of variables declaration//GEN-END:variables
}
| 45.635586 | 158 | 0.698508 |
29d6829b189ea66dfe00edcc7155396a09fe63f4 | 853 | package ns.coco.cocolabel.utils;
import com.alibaba.fastjson.JSON;
import java.util.Base64;
public class ByteUtils {
//private static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToBase64(byte[] bytes) {
// String encodedText = JSON.toJSONString(bytes);
// return encodedText.substring(1,encodedText.length()-2);
final Base64.Encoder encoder = Base64.getEncoder();
//编码
final String encodedText = encoder.encodeToString(bytes);
return encodedText;
}
public static byte[] base64ToBytes(String encodedText) {
final Base64.Decoder decoder = Base64.getDecoder();
//解码
return decoder.decode(encodedText);
}
public static void main(String[] args) {
System.out.println(bytesToBase64("iojwe98".getBytes()));
}
}
| 25.848485 | 72 | 0.669402 |
dae0a75636dd2a8a64868186bf3474f1e65a3ed1 | 755 | package co.edu.udistrital.VirtualLabs.jschematic.messages;
import co.edu.udistrital.VirtualLabs.jschematic.VLSchematicBoard;
import co.edu.udistrital.VirtualLabs.jschematic.comm.*;
/**
*
* @author Oscar E. Cala W.
*/
public class StartProblem extends AbstractStartProblem{
public static boolean waitingForStartStateEndMessage = false;
@Override
public void dispatch() {
if (!waitingForStartStateEndMessage) {
VLSchematicBoard.getInstance().clearBoard();
waitingForStartStateEndMessage = true;
}
}
@Override
protected void extractToolProperties() {
}
public static void setStartStateEndMessageReceived(){
waitingForStartStateEndMessage = false;
}
}
| 23.59375 | 65 | 0.700662 |
3d3675f741198ede68d3acf3a58963f8c066acc4 | 169 | package com.android.albert.base;
/**
* @author zhanglei
* @date 2018/6/20
* @brief 公共activity
*/
public class BaseSimpleActivity extends BaseActionBarActivity {
}
| 15.363636 | 63 | 0.733728 |
9e402f8fbc2a13dd32802c4896475de1a827fcd5 | 221 | package cn.dustlight.datacenter.amqp.sync;
import cn.dustlight.datacenter.amqp.entities.RecodeEvent;
import reactor.core.publisher.Mono;
public interface SyncHandler {
Mono<Void> sync(RecodeEvent eventMessage);
}
| 20.090909 | 57 | 0.800905 |
c99118fc9ed0096a4bcfbf71325a53fbe54df340 | 3,013 | /*
* Copyright 2017 ~ 2025 the original author or authors. <wanglsir@gmail.com, 983708408@qq.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wl4g.iam.session;
import static com.google.common.base.Charsets.UTF_8;
import static com.wl4g.iam.common.constant.ServiceIAMConstants.CACHE_SESSION;
import java.io.IOException;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.wl4g.StandaloneIam;
import com.wl4g.component.support.cache.jedis.JedisService;
import com.wl4g.component.support.cache.jedis.ScanCursor;
import com.wl4g.component.support.cache.jedis.ScanCursor.ClusterScanParams;
import com.wl4g.iam.core.session.IamSession;
import com.wl4g.iam.core.session.mgt.IamSessionDAO;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = StandaloneIam.class)
@FixMethodOrder(MethodSorters.JVM)
public class IamSessionDAOTests {
@Autowired
private JedisService jedisService;
@Autowired
private IamSessionDAO sessionDAO;
@Test
public void setSerializeTest() {
IamSession s = new IamSession();
s.setId("abcd123");
String res = jedisService.setObjectT("iam:session:1c315080e64b4731b011a14551a54c92", s, 0);
System.out.println("setSerializeTest result: " + res);
}
@Test
public void getDeserializeTest() {
IamSession s = jedisService.getObjectT("iam:session:1c315080e64b4731b011a14551a54c92", IamSession.class);
System.out.println("getDeserializeTest IamSession: " + s);
}
@Test
public void scanCursorTest() throws IOException {
byte[] pattern = ("iam_" + CACHE_SESSION + "*").getBytes(UTF_8);
ClusterScanParams params = new ClusterScanParams(200, pattern);
ScanCursor<IamSession> sc = new ScanCursor<IamSession>(jedisService.getJedisClient(), null, params) {
}.open();
System.out.println("ScanResult: " + sc);
while (sc.hasNext()) {
System.out.println("IamSession: " + sc.next());
}
}
@Test
public void getAccessSessionsTests() {
ScanCursor<IamSession> ss = sessionDAO.getAccessSessions(200);
while (ss.hasNext()) {
IamSession s = ss.next();
System.out.println(s);
}
}
} | 34.632184 | 113 | 0.721208 |
d8bcce0555060fff78bfb943398067b2ac6e4dc1 | 9,676 | /*
* MIT License
*
* Copyright (c) 2018 Asynchronous Game Query Library
*
* 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 com.ibasco.agql.core;
import com.google.gson.*;
import com.ibasco.agql.core.client.AbstractRestClient;
import com.ibasco.agql.core.exceptions.*;
import com.ibasco.agql.core.reflect.types.CollectionParameterizedType;
import io.netty.handler.codec.http.HttpStatusClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* <p>An API Interface containing a set/group of methods that are usually defined by the publisher</p>
*
* @param <T> Any class extending {@link AbstractRestClient}
* @param <Req> Any class extending {@link AbstractWebRequest}
*/
abstract public class AbstractWebApiInterface<T extends AbstractRestClient,
Req extends AbstractWebApiRequest,
Res extends AbstractWebApiResponse<JsonElement>> {
private static final Logger log = LoggerFactory.getLogger(AbstractWebApiInterface.class);
private T client;
private GsonBuilder gsonBuilder = new GsonBuilder();
private Gson jsonBuilder;
/**
* Used by the underlying concrete classes for api versioning
*/
public static final int VERSION_1 = 1, VERSION_2 = 2, VERSION_3 = 3;
/**
* <p>Default Constructor</p>
*
* @param client A {@link AbstractRestClient} instance
*/
public AbstractWebApiInterface(T client) {
this.client = client;
}
/**
* Lazy-Inititalization
*
* @return A {@link Gson} instance
*/
protected Gson builder() {
if (jsonBuilder == null) {
configureBuilder(gsonBuilder);
jsonBuilder = gsonBuilder.create();
}
return jsonBuilder;
}
protected <V> V fromJson(JsonElement element, Type typeOf) {
return builder().fromJson(element, typeOf);
}
protected <V> V fromJson(JsonElement element, Class<V> classTypeOf) {
return builder().fromJson(element, classTypeOf);
}
/**
* <p>Similar to {@link #asCollectionOf(Class, String, JsonObject, Class, boolean)} minus the Collection class argument. This also returns a {@link List} collection type instead.</p>
*
* @param itemType The {@link Class} type of the item in the {@link Collection}
* @param searchKey The name of the {@link JsonArray} element that we will convert
* @param searchElement The {@link JsonObject} that will be used to search for the {@link JsonArray} element
* @param strict If <code>true</code> an exception will be thrown if the listName is not found within the search element specified.
* Otherwise no exceptions will be raised and an empty {@link Collection} instance will be returned.
* @param <A> The type of the List to be returned
*
* @return A {@link List} containing the parsed json entities
*/
protected <A> List<A> asListOf(Class itemType, String searchKey, JsonObject searchElement, boolean strict) {
return asCollectionOf(itemType, searchKey, searchElement, ArrayList.class, strict);
}
/**
* <p>A Utility function that retrieves the specified json element and converts it to a Parameterized {@link java.util.Collection} instance.</p>
*
* @param itemType The {@link Class} type of the item in the {@link Collection}
* @param searchKey The name of the {@link JsonArray} element that we will convert
* @param searchElement The {@link JsonObject} that will be used to search for the {@link JsonArray} element
* @param collectionClass A {@link Class} representing the concrete implementation of the {@link Collection}
* @param strict If <code>true</code> an exception will be thrown if the listName is not found within the search element specified. Otherwise no exceptions will be raised and an empty {@link Collection} instance will be returned.
* @param <A> The internal type of the {@link Collection} to be returned
*
* @return A {@link Collection} containing the type specified by collectionClass argument
*/
protected <A extends Collection> A asCollectionOf(Class itemType, String searchKey, JsonObject searchElement, Class<? extends Collection> collectionClass, boolean strict) {
if (searchElement.has(searchKey) && searchElement.get(searchKey).isJsonArray()) {
return fromJson(searchElement.getAsJsonArray(searchKey), new CollectionParameterizedType(itemType, collectionClass));
}
if (strict)
throw new JsonElementNotFoundException(searchElement, String.format("Unable to find a JsonArray element '%s' from the search element", searchKey));
else {
return null;
}
}
/**
* <p>Sends a requests to the internal client.</p>
*
* @param request An instance of {@link AbstractWebRequest}
* @param <A> The return type
*
* @return A {@link CompletableFuture} that will hold the expected value once a response has been received by the server
*/
@SuppressWarnings("unchecked")
protected <A> CompletableFuture<A> sendRequest(Req request) {
CompletableFuture<Res> responseFuture = client.sendRequest(request);
return responseFuture.whenComplete(this::interceptResponse).thenApply(this::postProcessConversion);
}
/**
* <p>Override this method if you need to perform additional configurations against the builder (e.g. Register custom deserializers)</p>
*
* @param builder A {@link GsonBuilder} instance that will be accessed and configured by a concrete {@link AbstractWebApiInterface} implementation
*/
protected void configureBuilder(GsonBuilder builder) {
//no implementation
}
/**
* The default error handler. Override this if needed.
*
* @param response An instance of {@link AbstractWebApiResponse} or <code>null</code> if an exception was thrown.
* @param error A {@link Throwable} instance or <code>null</code> if no error has occured.
*
* @throws WebException thrown if a server/client error occurs
*/
protected void interceptResponse(Res response, Throwable error) {
if (error != null)
throw new WebException(error);
log.debug("Handling response for {}, with status code = {}", response.getMessage().getUri(), response.getMessage().getStatusCode());
if (response.getStatus() == HttpStatusClass.SERVER_ERROR ||
response.getStatus() == HttpStatusClass.CLIENT_ERROR) {
switch (response.getMessage().getStatusCode()) {
case 400:
throw new BadRequestException("Incorrect parameters provided for request");
case 403:
throw new AccessDeniedException("Access denied, either because of missing/incorrect credentials or used API token does not grant access to the requested resource.");
case 404:
throw new ResourceNotFoundException("Resource was not found.");
case 429:
throw new TooManyRequestsException("Request was throttled, because amount of requests was above the threshold defined for the used API token.");
case 500:
throw new UnknownWebException("An internal error occured in server");
case 503:
throw new ServiceUnavailableException("Service is temprorarily unavailable. Possible maintenance on-going.");
default:
throw new WebException("Unknown error occured on request send");
}
}
}
/**
* Converts the underlying processed content to a {@link com.google.gson.JsonObject} instance
*/
@SuppressWarnings("unchecked")
private <A> A postProcessConversion(Res response) {
log.debug("ConvertToJson for Response = {}, {}", response.getMessage().getStatusCode(), response.getMessage().getHeaders());
JsonElement processedElement = response.getProcessedContent();
if (processedElement != null) {
if (processedElement.isJsonObject())
return (A) processedElement.getAsJsonObject();
else if (processedElement.isJsonArray())
return (A) processedElement.getAsJsonArray();
}
throw new AsyncGameLibUncheckedException("No parsed content found for response" + response);
}
}
| 48.139303 | 242 | 0.68396 |
64ab1323f942ddd708d7cfcc84f68b4fafabc0a8 | 21,078 | package com.jokls.jok.dataset;
import com.jokls.jok.event.field.Field;
import com.jokls.jok.event.field.FieldCreator;
import com.jokls.jok.event.field.FieldValue;
import com.jokls.jok.exception.DatasetRuntimeException;
import com.jokls.jok.exception.EventRuntimeException;
import java.util.Arrays;
/**
* Copyright (C) 2019
* All rights reserved
*
* @author: marik.wei
* @mail: marks@126.com
* Date: 2019/6/24 17:13
*/
public class PromptDataset implements IDataset, Cloneable{
private CommonMetadata metadata = new CommonMetadata();
private String dsName;
private int totalCount = -1;
private final FieldCreator fc;
private int workMode = 1;
private FieldValue defaultFieldValue;
private IDatasetAttribute dssa;
private int rowCount = 0;
private int currentLineIndex = 1;
private int colCount = 0;
private int colCapacity = 50;
private int rowCapacity = 10;
private transient FieldValue[] values;
protected PromptDataset(IDatasetAttribute dssa) {
this.dssa = dssa;
this.fc = FieldCreator.getNewInstance(dssa);
this.defaultFieldValue = this.fc.getFieldValue((Object)null);
this.values = new FieldValue[this.colCapacity * this.rowCapacity];
}
protected PromptDataset(int minColCapacity, int minRowCapacity, IDatasetAttribute dssa) {
this.dssa = dssa;
this.fc = FieldCreator.getNewInstance(dssa);
this.defaultFieldValue = this.fc.getFieldValue((Object)null);
this.colCapacity = minColCapacity;
this.rowCapacity = minRowCapacity;
this.values = new FieldValue[this.colCapacity * this.rowCapacity];
}
public PromptDataset clone() {
PromptDataset newDS = new PromptDataset(this.colCapacity, this.rowCapacity, this.dssa);
newDS.metadata = this.metadata.clone();
newDS.rowCount = this.rowCount;
newDS.colCount = this.colCount;
newDS.dsName = this.dsName;
newDS.totalCount = this.totalCount;
newDS.workMode = this.workMode;
System.arraycopy(this.values, 0, newDS.values, 0, this.values.length);
return newDS;
}
public void ensureCapacity(int minColcapacity, int minRowCapacity){
this.ensureColCapacity(minColcapacity);
this.ensureRowCapacity(minRowCapacity);
}
private void ensureColCapacity(int minCapacity){
int oldCapacity = this.colCapacity;
if(oldCapacity < minCapacity){
int newCapacity = oldCapacity * 3 /2 +1;
if(newCapacity < minCapacity){
newCapacity = minCapacity;
}
int totalCapacity = this.rowCapacity * newCapacity;
FieldValue[] oldValues = this.values;
this.values = new FieldValue[totalCapacity];
for(int i = 0 ; i < this.rowCount; i++){
System.arraycopy(oldValues, i* oldCapacity, this.values, i* newCapacity, oldCapacity);
}
oldValues = null;
}
}
private void ensureRowCapacity(int minCapacity){
int oldCapacity = this.rowCapacity;
if (oldCapacity < minCapacity) {
int newCapacity = oldCapacity * 3 / 2 + 1;
if (newCapacity < minCapacity) {
newCapacity = minCapacity;
}
int totalCapacity = this.colCapacity * newCapacity;
FieldValue[] oldValues = this.values;
this.values = new FieldValue[totalCapacity];
System.arraycopy(oldValues, 0, this.values, 0, oldValues.length);
oldValues = null;
}
}
@Override
public String getDatasetName() {
return this.dsName;
}
@Override
public void setDatasetName(String name) {
this.dsName = name;
}
@Override
public int getTotalCount() {
return this.totalCount;
}
@Override
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
@Override
public IDatasetMetaData getMetaData() {
return this.metadata;
}
@Override
public void deleteRow(int rowIndex) {
this.checkRowIndex(rowIndex);
if(rowIndex != this.rowCount){
System.arraycopy(this.values, rowIndex * this.colCapacity, this.values, (rowIndex - 1 )* this.colCapacity, this.colCapacity);
}
Arrays.fill(this.values, (rowIndex - 1) * this.colCapacity, rowIndex * this.colCapacity - 1, null);
--this.rowCount;
}
private void checkRowIndex(int rowIndex){
if(rowIndex < 1 || rowIndex > this.rowCount){
throw new DatasetRuntimeException("65", rowIndex, 1, this.rowCount);
}
}
@Override
public int getColumnCount() {
return this.colCount;
}
@Override
public char getColumnType(int column) {
return this.metadata.getColumnType(column);
}
@Override
public int findColumn(String columnName) {
return this.metadata.findColumn(columnName);
}
@Override
public String getColumnName(int column) {
return this.metadata.getColumnName(column);
}
@Override
public int getInt(String columnName) {
FieldValue fv = this.getFieldValue(columnName);
int def = this.dssa.getDefInt();
return this.getInt(fv, def);
}
@Override
public int getInt(int columnIndex) {
FieldValue fv = this.getFieldValue(columnIndex);
int def = this.dssa.getDefInt();
return this.getInt(fv, def);
}
public int getInt(int columnIndex, int def) {
FieldValue fv = this.getFieldValue(columnIndex);
return this.getInt(fv, def);
}
private int getInt(FieldValue fv, int def) {
try {
return fv.getInt(def);
} catch (DatasetRuntimeException e) {
if (this.isExceptionMode()) {
throw e;
} else {
return def;
}
}
}
@Override
public int getInt(String columnName, int def) {
FieldValue fv = this.getFieldValue(columnName);
return this.getInt(fv, def);
}
@Override
public long getLong(String columnName) {
FieldValue fv = this.getFieldValue(columnName);
long def = this.dssa.getDefLong();
return this.getLong(fv, def);
}
@Override
public long getLong(int columnIndex) {
FieldValue fv = this.getFieldValue(columnIndex);
long def = this.dssa.getDefLong();
return this.getLong(fv, def);
}
@Override
public long getLong(String columnName, long def) {
FieldValue fv = this.getFieldValue(columnName);
return this.getLong(fv, def);
}
@Override
public long getLong(int columnIndex, long def) {
FieldValue fv =this.getFieldValue(columnIndex);
return this.getLong(fv, def);
}
private long getLong(FieldValue fv, long def){
try {
return fv.getLong(def);
}catch (DatasetRuntimeException e){
if(this.isExceptionMode()){
throw e;
}else {
return def;
}
}
}
@Override
public double getDouble(String columnName) {
FieldValue fv = this.getFieldValue(columnName);
double def = this.dssa.getDefDouble();
return this.getDouble(fv, def);
}
@Override
public double getDouble(int columnIndex) {
FieldValue fv = this.getFieldValue(columnIndex);
double def = this.dssa.getDefDouble();
return this.getDouble(fv, def);
}
@Override
public double getDouble(String columnName, double def) {
FieldValue fv =this.getFieldValue(columnName);
return this.getDouble(fv, def);
}
@Override
public double getDouble(int columnIndex, double def) {
FieldValue fv =this.getFieldValue(columnIndex);
return this.getDouble(fv, def);
}
private double getDouble(FieldValue fv, double def) {
try {
return fv.getDouble(def);
} catch (DatasetRuntimeException e) {
if (this.isExceptionMode()) {
throw e;
} else {
return def;
}
}
}
@Override
public byte[] getByteArray(String columnName) {
FieldValue fv = this.getFieldValue(columnName);
byte[] def = this.dssa.getDefBytes();
return this.getByteArray(fv, def);
}
@Override
public byte[] getByteArray(int columnIndex) {
FieldValue fv = this.getFieldValue(columnIndex);
byte[] def = this.dssa.getDefBytes();
return this.getByteArray(fv, def);
}
@Override
public byte[] getByteArray(String columnName, byte[] def) {
FieldValue fv =this.getFieldValue(columnName);
return this.getByteArray(fv, def);
}
@Override
public byte[] getByteArray(int columnIndex, byte[] def) {
FieldValue fv =this.getFieldValue(columnIndex);
return this.getByteArray(fv, def);
}
private byte[] getByteArray(FieldValue fv, byte[] def) {
try {
return fv.getByteArray(def);
} catch (DatasetRuntimeException e) {
if (this.isExceptionMode()) {
throw e;
} else {
return def;
}
}
}
@Override
public String getString(String columnName) {
FieldValue fv = this.getFieldValue(columnName);
String def = this.dssa.getDefString();
return this.getString(fv, def);
}
@Override
public String getString(int columnIndex) {
FieldValue fv = this.getFieldValue(columnIndex);
String def = this.dssa.getDefString();
return this.getString(fv, def);
}
@Override
public String getString(String columnName, String def) {
FieldValue fv = this.getFieldValue(columnName);
return this.getString(fv, def);
}
@Override
public String getString(int columnIndex, String def) {
FieldValue fv =this.getFieldValue(columnIndex);
return this.getString(fv, def);
}
private String getString(FieldValue fv, String def) {
try {
return fv.getString(def);
} catch (DatasetRuntimeException e) {
if (this.isExceptionMode()) {
throw e;
} else {
return def;
}
}
}
@Override
public String[] getStringArray(String columnName) {
FieldValue fv = this.getFieldValue(columnName);
String[] def = this.dssa.getDefStrings();
return this.getStrings(fv, def);
}
@Override
public String[] getStringArray(int columnIndex) {
FieldValue fv = this.getFieldValue(columnIndex);
String[] def = this.dssa.getDefStrings();
return this.getStrings(fv, def);
}
@Override
public String[] getStringArray(String columnName, String[] def) {
FieldValue fv = this.getFieldValue(columnName);
return this.getStrings(fv, def);
}
private String[] getStrings(FieldValue fv, String[] def) {
try {
return fv.getStringArray(def);
} catch (DatasetRuntimeException e) {
if (this.isExceptionMode()) {
throw e;
} else {
return def;
}
}
}
@Override
public IDataset getSubDataset(int columnIndex) {
return (IDataset) this.getValue(columnIndex);
}
@Override
public IDataset getSubDataset(String columnName) {
return (IDataset) this.getValue(columnName);
}
@Override
public String[] getStringArray(int columnIndex, String[] def) {
FieldValue fv = this.getFieldValue(columnIndex);
return this.getStrings(fv, def);
}
@Override
public Object getValue(String columnName) {
FieldValue fv = this.getFieldValue(columnName);
return this.getValue(fv, null);
}
@Override
public Object getValue(int columnIndex) {
FieldValue fv = this.getFieldValue(columnIndex);
return this.getValue(fv, null);
}
@Override
public Object getValue(String columnName, Object def) {
FieldValue fv = this.getFieldValue(columnName);
return this.getValue(fv, def);
}
@Override
public Object getValue(int columnIndex, Object def) {
FieldValue fv = this.getFieldValue(columnIndex);
return this.getValue(fv, def);
}
private Object getValue(FieldValue fv, Object def) {
try {
return fv.getValue();
} catch (DatasetRuntimeException e) {
if (this.isExceptionMode()) {
throw e;
} else {
return def;
}
}
}
@Override
public void locateLine(int lineIndex) {
this.checkRowIndex(lineIndex);
this.currentLineIndex = lineIndex;
}
@Override
public void beforeFirst() {
this.currentLineIndex = 0;
}
@Override
public boolean hasNext() {
return this.currentLineIndex < this.rowCount;
}
@Override
public void next() {
++this.currentLineIndex;
}
@Override
public int getMode() {
return this.workMode;
}
@Override
public void setMode(int mode) {
if(MODE_EXCEPTION == mode){
this.workMode = mode;
}else{
this.workMode = MODE_DEFAULT;
}
}
@Override
public int getRowCount() {
return this.rowCount;
}
@Override
public void addColumn(String colName) {
this.addColumn(colName, 83);
}
@Override
public void addColumn(String colName, int type) {
this.ensureColCapacity(this.colCount + 1);
Field field = this.fc.getField(colName, type);
this.metadata.addField(field);
++this.colCount;
}
@Override
public void modifyColumnType(String colName, int type) throws DatasetRuntimeException {
Integer t = FieldCreator.getTypeMap().get(type);
if (t == null) {
throw new EventRuntimeException("69", type);
} else {
int index = this.checkColumnName(colName, true);
Field field = this.metadata.getField(index);
field.setType((char)t.intValue());
}
}
@Override
public void modifyColumnType(int colIndex, int type) throws DatasetRuntimeException {
Integer t = FieldCreator.getTypeMap().get(type);
if (t == null) {
throw new EventRuntimeException("69", type);
} else {
this.checkColumnIndex(colIndex);
Field field = this.metadata.getField(colIndex);
field.setType((char)t.intValue());
}
}
private void updateFieldValue(FieldValue fv, int rowIndex, int colIndex) {
this.checkRowIndex(rowIndex);
this.checkColumnIndex(colIndex);
--rowIndex;
--colIndex;
this.values[rowIndex * this.rowCapacity + colIndex] = fv;
}
private void updateFieldValue(FieldValue fv, int rowIndex, String colName) {
this.checkRowIndex(rowIndex);
int colIndex = this.checkColumnName(colName, this.isExceptionMode());
if (colIndex != 0) {
--rowIndex;
--colIndex;
this.values[rowIndex * this.rowCapacity + colIndex] = fv;
}
}
private void updateFieldValue(FieldValue fv, int colIndex) {
this.updateFieldValue(fv, this.currentLineIndex, colIndex);
}
private void updateFieldValue(FieldValue fv, String colName) {
this.updateFieldValue(fv, this.currentLineIndex, colName);
}
@Override
public void updateByteArray(int columnIndex, byte[] v) throws DatasetRuntimeException {
FieldValue fv = this.fc.getFieldValue(v);
this.updateFieldValue(fv, columnIndex);
}
@Override
public void updateByteArray(String columnName, byte[] v) throws DatasetRuntimeException {
FieldValue fv = this.fc.getFieldValue(v);
this.updateFieldValue(fv, columnName);
}
@Override
public void updateSubDataset(int columnIndex, IDataset v) throws DatasetRuntimeException {
this.updateValue(columnIndex, v);
}
@Override
public void updateSubDataset(String columnName, IDataset v) throws DatasetRuntimeException {
this.updateValue(columnName, v);
}
@Override
public void updateDouble(int columnIndex, double v) throws DatasetRuntimeException {
FieldValue fv = this.fc.getFieldValue(v);
this.updateFieldValue(fv, columnIndex);
}
@Override
public void updateDouble(String columnName, double v) throws DatasetRuntimeException {
FieldValue fv =this.fc.getFieldValue(v);
this.updateFieldValue(fv, columnName);
}
@Override
public void updateInt(int columnIndex, int v) throws DatasetRuntimeException {
FieldValue fv = this.fc.getFieldValue(v);
this.updateFieldValue(fv, columnIndex);
}
@Override
public void updateInt(String columnIndex, int v) throws DatasetRuntimeException {
FieldValue fv = this.fc.getFieldValue(v);
this.updateFieldValue(fv, columnIndex);
}
@Override
public void updateLong(int columnIndex, long v) throws DatasetRuntimeException {
FieldValue fv = this.fc.getFieldValue(v);
this.updateFieldValue(fv, columnIndex);
}
@Override
public void updateLong(String columnName, long v) throws DatasetRuntimeException {
FieldValue fv = this.fc.getFieldValue(v);
this.updateFieldValue(fv, columnName);
}
@Override
public void updateString(int columnIndex, String v) throws DatasetRuntimeException {
FieldValue fv = this.fc.getFieldValue(v);
this.updateFieldValue(fv, columnIndex);
}
@Override
public void updateString(String columnName, String v) throws DatasetRuntimeException {
FieldValue fv = this.fc.getFieldValue(v);
this.updateFieldValue(fv, columnName);
}
@Override
public void updateStringArray(int columnIndex, String[] v) throws DatasetRuntimeException {
FieldValue fv = this.fc.getFieldValue(v);
this.updateFieldValue(fv, columnIndex);
}
@Override
public void updateStringArray(String columnName, String[] v) throws DatasetRuntimeException {
FieldValue fv = this.fc.getFieldValue(v);
this.updateFieldValue(fv, columnName);
}
@Override
public void updateValue(int columnIndex, Object v) {
FieldValue fv = this.fc.getFieldValue(v);
this.updateFieldValue(fv, columnIndex);
}
@Override
public void updateValue(String columnName, Object v) {
FieldValue fv = this.fc.getFieldValue(v);
this.updateFieldValue(fv, columnName);
}
@Override
public boolean appendRow() {
this.ensureRowCapacity(this.rowCount + 1);
++this.rowCount;
this.currentLineIndex = this.rowCount;
return true;
}
@Override
public void clear() {
this.rowCount = 0;
this.colCount = 0;
this.currentLineIndex = 0;
if (this.values != null) {
Arrays.fill(this.values, (Object)null);
}
}
private FieldValue getFieldValue(int colIndex) {
return this.getFieldValue(this.currentLineIndex, colIndex);
}
private FieldValue getFieldValue(String colName) {
return this.getFieldValue(this.currentLineIndex, colName);
}
private FieldValue getFieldValue(int rowIndex, String colName) {
this.checkRowIndex(rowIndex);
int colIndex = this.checkColumnName(colName, this.isExceptionMode());
if (colIndex == 0) {
return this.defaultFieldValue;
} else {
--rowIndex;
--colIndex;
FieldValue value = this.values[rowIndex * this.rowCapacity + colIndex];
if (value == null) {
value = this.defaultFieldValue;
}
return value;
}
}
private FieldValue getFieldValue(int rowIndex, int colIndex) {
this.checkRowIndex(rowIndex);
this.checkColumnIndex(colIndex);
--rowIndex;
--colIndex;
return this.values[rowIndex * this.rowCapacity + colIndex];
}
private int checkColumnName(String columnName, boolean bException) {
int index = this.metadata.findColumn(columnName);
if (index == 0 && bException) {
throw new DatasetRuntimeException("68", columnName);
} else {
return index;
}
}
private void checkColumnIndex(int columnIndex) {
if (columnIndex < 1 || columnIndex > this.colCount) {
throw new DatasetRuntimeException("66", columnIndex, 1, this.colCount);
}
}
protected boolean isExceptionMode() {
return 0 == this.getMode();
}
@Override
public void clearAll() {
this.metadata.clear();
this.clear();
}
}
| 29.47972 | 137 | 0.620268 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.