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
c2fd7351e8aeeeb8d06960cd4204a735f04b6509
814
/* Copyright (c) 2015-2018 Bernd Wengenroth * Licensed under the MIT License. * See LICENSE file for details. */ package bweng.thrift.parser.model; /** * Part of the data model, representing a Thrift Field (e.g. as parameter in a Function). */ public final class ThriftField extends ThriftObject { public String name_; public int id_; public ThriftType type_; @Override public String toString() { return ""+id_+":"+ ((type_ != null) ? ((type_.name_!= null) ?type_.name_ : type_.toString()) : "?" ) + ' ' + name_; } /** * Checks if the field type is valid. * @return true if type is valid. */ @Override final public boolean valid() { return ( type_ != null && type_.valid() ); } }
22.611111
89
0.574939
c135a4adf94c59825e974862620f1ccd6c13b364
8,013
package android.support.v7.widget; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources.Theme; import android.content.res.TypedArray; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewPropertyAnimatorCompat; import android.support.v4.view.ViewPropertyAnimatorListener; import android.support.v7.appcompat.R.attr; import android.support.v7.appcompat.R.styleable; import android.util.AttributeSet; import android.util.TypedValue; import android.view.ContextThemeWrapper; import android.view.MotionEvent; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup; abstract class AbsActionBarView extends ViewGroup { private static final int FADE_DURATION = 200; protected ActionMenuPresenter mActionMenuPresenter; protected int mContentHeight; private boolean mEatingHover; private boolean mEatingTouch; protected ActionMenuView mMenuView; protected final Context mPopupContext; protected final VisibilityAnimListener mVisAnimListener = new VisibilityAnimListener(); protected ViewPropertyAnimatorCompat mVisibilityAnim; AbsActionBarView(Context paramContext) { this(paramContext, null); } AbsActionBarView(Context paramContext, AttributeSet paramAttributeSet) { this(paramContext, paramAttributeSet, 0); } AbsActionBarView(Context paramContext, AttributeSet paramAttributeSet, int paramInt) { super(paramContext, paramAttributeSet, paramInt); TypedValue localTypedValue = new TypedValue(); if ((paramContext.getTheme().resolveAttribute(R.attr.actionBarPopupTheme, localTypedValue, true)) && (resourceId != 0)) { mPopupContext = new ContextThemeWrapper(paramContext, resourceId); return; } mPopupContext = paramContext; } protected static int next(int paramInt1, int paramInt2, boolean paramBoolean) { if (paramBoolean) { return paramInt1 - paramInt2; } return paramInt1 + paramInt2; } public void animateToVisibility(int paramInt) { setupAnimatorToVisibility(paramInt, 200L).start(); } public boolean canShowOverflowMenu() { return (isOverflowReserved()) && (getVisibility() == 0); } public void dismissPopupMenus() { if (mActionMenuPresenter != null) { mActionMenuPresenter.dismissPopupMenus(); } } public int getAnimatedVisibility() { if (mVisibilityAnim != null) { return mVisAnimListener.mFinalVisibility; } return getVisibility(); } public int getContentHeight() { return mContentHeight; } public boolean hideOverflowMenu() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.hideOverflowMenu(); } return false; } public boolean isOverflowMenuShowPending() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.isOverflowMenuShowPending(); } return false; } public boolean isOverflowMenuShowing() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.isOverflowMenuShowing(); } return false; } public boolean isOverflowReserved() { return (mActionMenuPresenter != null) && (mActionMenuPresenter.isOverflowReserved()); } protected int measureChildView(View paramView, int paramInt1, int paramInt2, int paramInt3) { paramView.measure(View.MeasureSpec.makeMeasureSpec(paramInt1, Integer.MIN_VALUE), paramInt2); return Math.max(0, paramInt1 - paramView.getMeasuredWidth() - paramInt3); } protected void onConfigurationChanged(Configuration paramConfiguration) { super.onConfigurationChanged(paramConfiguration); TypedArray localTypedArray = getContext().obtainStyledAttributes(null, R.styleable.ActionBar, R.attr.actionBarStyle, 0); setContentHeight(localTypedArray.getLayoutDimension(R.styleable.ActionBar_height, 0)); localTypedArray.recycle(); if (mActionMenuPresenter != null) { mActionMenuPresenter.onConfigurationChanged(paramConfiguration); } } public boolean onHoverEvent(MotionEvent paramMotionEvent) { int i = MotionEventCompat.getActionMasked(paramMotionEvent); if (i == 9) { mEatingHover = false; } if (!mEatingHover) { boolean bool = super.onHoverEvent(paramMotionEvent); if ((i == 9) && (!bool)) { mEatingHover = true; } } if ((i == 10) || (i == 3)) { mEatingHover = false; } return true; } public boolean onTouchEvent(MotionEvent paramMotionEvent) { int i = MotionEventCompat.getActionMasked(paramMotionEvent); if (i == 0) { mEatingTouch = false; } if (!mEatingTouch) { boolean bool = super.onTouchEvent(paramMotionEvent); if ((i == 0) && (!bool)) { mEatingTouch = true; } } if ((i == 1) || (i == 3)) { mEatingTouch = false; } return true; } protected int positionChild(View paramView, int paramInt1, int paramInt2, int paramInt3, boolean paramBoolean) { int i = paramView.getMeasuredWidth(); int j = paramView.getMeasuredHeight(); int k = paramInt2 + (paramInt3 - j) / 2; if (paramBoolean) { paramView.layout(paramInt1 - i, k, paramInt1, k + j); } for (;;) { if (paramBoolean) { i = -i; } return i; paramView.layout(paramInt1, k, paramInt1 + i, k + j); } } public void postShowOverflowMenu() { post(new Runnable() { public void run() { showOverflowMenu(); } }); } public void setContentHeight(int paramInt) { mContentHeight = paramInt; requestLayout(); } public void setVisibility(int paramInt) { if (paramInt != getVisibility()) { if (mVisibilityAnim != null) { mVisibilityAnim.cancel(); } super.setVisibility(paramInt); } } public ViewPropertyAnimatorCompat setupAnimatorToVisibility(int paramInt, long paramLong) { if (mVisibilityAnim != null) { mVisibilityAnim.cancel(); } if (paramInt == 0) { if (getVisibility() != 0) { ViewCompat.setAlpha(this, 0.0F); } ViewPropertyAnimatorCompat localViewPropertyAnimatorCompat2 = ViewCompat.animate(this).alpha(1.0F); localViewPropertyAnimatorCompat2.setDuration(paramLong); localViewPropertyAnimatorCompat2.setListener(mVisAnimListener.withFinalVisibility(localViewPropertyAnimatorCompat2, paramInt)); return localViewPropertyAnimatorCompat2; } ViewPropertyAnimatorCompat localViewPropertyAnimatorCompat1 = ViewCompat.animate(this).alpha(0.0F); localViewPropertyAnimatorCompat1.setDuration(paramLong); localViewPropertyAnimatorCompat1.setListener(mVisAnimListener.withFinalVisibility(localViewPropertyAnimatorCompat1, paramInt)); return localViewPropertyAnimatorCompat1; } public boolean showOverflowMenu() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.showOverflowMenu(); } return false; } protected class VisibilityAnimListener implements ViewPropertyAnimatorListener { private boolean mCanceled = false; int mFinalVisibility; protected VisibilityAnimListener() {} public void onAnimationCancel(View paramView) { mCanceled = true; } public void onAnimationEnd(View paramView) { if (mCanceled) { return; } mVisibilityAnim = null; AbsActionBarView.this.setVisibility(mFinalVisibility); } public void onAnimationStart(View paramView) { AbsActionBarView.this.setVisibility(0); mCanceled = false; } public VisibilityAnimListener withFinalVisibility(ViewPropertyAnimatorCompat paramViewPropertyAnimatorCompat, int paramInt) { mVisibilityAnim = paramViewPropertyAnimatorCompat; mFinalVisibility = paramInt; return this; } } }
27.726644
133
0.701111
a78232cf1dd97c51bfe448392db82cb1258329dd
12,570
package de.uniks.networkparser.parser; import de.uniks.networkparser.DateTimeEntity; import de.uniks.networkparser.EntityCreator; import de.uniks.networkparser.EntityUtil; import de.uniks.networkparser.IdMap; import de.uniks.networkparser.Pos; import de.uniks.networkparser.buffer.Buffer; import de.uniks.networkparser.buffer.CharacterBuffer; import de.uniks.networkparser.interfaces.BaseItem; import de.uniks.networkparser.interfaces.Entity; import de.uniks.networkparser.interfaces.EntityList; import de.uniks.networkparser.interfaces.SendableEntityCreator; import de.uniks.networkparser.list.SimpleKeyValueList; import de.uniks.networkparser.list.SimpleList; import de.uniks.networkparser.xml.XMLEntity; import de.uniks.networkparser.xml.XMLTokener; public class ExcelParser { public static final String ROW = "row"; public static final String CELL = "c"; public static final String CELL_TYPE = "t"; public static final String REF = "ref"; public static final String CELL_TYPE_REFERENCE = "s"; public static final char SEMICOLON = ';'; public ExcelWorkBook parseSheets(CharSequence stringFile, CharSequence... sheetFile) { ExcelWorkBook excelWorkBook = new ExcelWorkBook(); if (sheetFile == null) { return excelWorkBook; } for (CharSequence sheet : sheetFile) { excelWorkBook.add(parseSheet(stringFile, sheet)); } return excelWorkBook; } public ExcelSheet parseSheet(CharSequence stringFile, CharSequence sheetFile) { ExcelSheet data = new ExcelSheet(); SimpleKeyValueList<String, ExcelCell> cells = new SimpleKeyValueList<String, ExcelCell>(); SimpleKeyValueList<String, String> mergeCellPos = new SimpleKeyValueList<String, String>(); IdMap map = new IdMap(); map.add(new ExcelCell()); XMLTokener tokener = new XMLTokener().withMap(map); tokener.withDefaultFactory(EntityCreator.createXML()); CharacterBuffer buffer = null; if (sheetFile instanceof CharacterBuffer) { buffer = (CharacterBuffer) sheetFile; } else { buffer = new CharacterBuffer().with(sheetFile.toString()); } XMLEntity sheet = (XMLEntity) map.decode(tokener, buffer, map.getFilter()); XMLEntity sharedStrings = null; if (stringFile != null) { sharedStrings = (XMLEntity) map.decode(stringFile.toString()); } if (sheet != null) { EntityList mergeCells = sheet.getElementsBy(XMLEntity.PROPERTY_TAG, "mergeCells"); /* <mergeCells count="1"><mergeCell ref="A2:A3"/></mergeCells> */ if (mergeCells != null) { for (int i = 0; i < mergeCells.sizeChildren(); i++) { BaseItem mergeCell = mergeCells.getChild(i); if (mergeCell == null) { continue; } SimpleList<Pos> excelRange = EntityUtil.getExcelRange(((Entity) mergeCell).getString(REF)); for (Pos item : excelRange) { if (item == null || item.x < 0 || item.y < 0) { continue; } mergeCellPos.add(item.toString(), excelRange.first().toString()); } } } EntityList sheetData = sheet.getElementsBy(XMLEntity.PROPERTY_TAG, "sheetData"); if (sheetData != null) { for (int i = 0; i < sheetData.sizeChildren(); i++) { BaseItem child = sheetData.getChild(i); if (child == null || child instanceof XMLEntity == false) { continue; } XMLEntity row = (XMLEntity) child; if (ROW.equalsIgnoreCase(row.getTag()) == false) { continue; } ExcelRow dataRow = new ExcelRow(); /* <c r="A1" t="s"><v>2</v></c> */ for (int c = 0; c < row.size(); c++) { BaseItem item = row.getChild(c); if (item == null || item instanceof ExcelCell == false) { continue; } ExcelCell cell = (ExcelCell) item; if (CELL.equalsIgnoreCase(cell.getTag()) == false) { continue; } ExcelCell excelCell = (ExcelCell) cell; if (CELL_TYPE_REFERENCE.equalsIgnoreCase(excelCell.getType())) { /* <v>2</v> */ EntityList element = cell.getChild(0); if (element != null) { String ref = ((XMLEntity) element).getValue(); if (sharedStrings != null) { XMLEntity refString = (XMLEntity) sharedStrings.getChild(Integer.valueOf(ref)); String text = ((XMLEntity) refString.getChild(0)).getValue(); excelCell.setContent(text); } } } else if (excelCell.sizeChildren() < 1) { String pos = mergeCellPos.get(excelCell.getReferenz().toString()); if (pos != null && cells.contains(pos)) { ExcelCell firstCell = cells.get(pos); excelCell.setReferenceCell(firstCell); } } cells.add(excelCell.getReferenz().toString(), excelCell); dataRow.add(excelCell); } if (dataRow.size() > 0) { data.add(dataRow); } } } } return data; } public CharacterBuffer writeCSV(SimpleList<SimpleList<ExcelCell>> data) { CharacterBuffer result = new CharacterBuffer(); if (data == null) { return result; } for (SimpleList<ExcelCell> row : data) { boolean first = true; for (ExcelCell cell : row) { if (first == false) { result.with(SEMICOLON); } result.with(cell.getContentAsString()); first = false; } result.with(BaseItem.CRLF); } return result; } public SimpleList<Object> readCSV(Buffer data, SendableEntityCreator creator) { SimpleList<Object> result = new SimpleList<Object>(); if (data == null || creator == null) { return result; } SimpleList<String> header = new SimpleList<String>(); CharacterBuffer line = data.readLine(); if (line == null || line.length() < 1) { return result; } int start = 0; for (int i = 0; i < line.length(); i++) { if (line.charAt(i) == SEMICOLON) { header.add(line.substring(start, i)); start = i + 1; } } do { line = data.readLine(); int column = 0; start = 0; /* Parsing data */ Object item = creator.getSendableInstance(false); for (int i = 0; i < line.length(); i++) { if (line.charAt(i) == SEMICOLON) { String value = line.substring(start, i); creator.setValue(item, header.get(column), value, SendableEntityCreator.NEW); column++; if (column > header.size()) { break; } start = i + 1; } } result.add(item); if (data.isEnd()) { break; } } while (line != null); return result; } private final static String HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r\n"; private final static String APP = "<Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties\" xmlns:vt=\"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes\"><TotalTime>0</TotalTime><Application>NetworkParser</Application><DocSecurity>0</DocSecurity><ScaleCrop>false</ScaleCrop><AppVersion>1.42</AppVersion></Properties>"; private final static String RELS = "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\"><Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\" Target=\"xl/workbook.xml\"/><Relationship Id=\"rId2\" Type=\"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties\" Target=\"docProps/core.xml\"/><Relationship Id=\"rId3\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties\" Target=\"docProps/app.xml\"/></Relationships>"; public SimpleKeyValueList<String, String> createExcelContent(ExcelWorkBook content) { int id = 4; SimpleKeyValueList<String, String> fileContent = new SimpleKeyValueList<String, String>(); fileContent.add("[Content_Types].xml", getContentTypes(content)); fileContent.add("docProps/app.xml", HEADER + APP); fileContent.add("_rels/.rels", HEADER + RELS); fileContent.add("xl/_rels/workbook.xml.rels", this.getHeaderWorkbookRel(content, id)); fileContent.add("xl/workbook.xml", this.getHeaderWorkbook(content, id)); fileContent.add("docProps/core.xml", this.getHeader(content)); for (int i = 0; i < content.size(); i++) { ExcelSheet sheet = content.get(i); if (sheet == null) { continue; } fileContent.add("xl/worksheets/sheet" + (i + 1) + ".xml", this.getSheet(sheet, id)); } return fileContent; } private String getContentTypes(ExcelWorkBook content) { CharacterBuffer data = new CharacterBuffer().with(HEADER); data.with( "<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\"><Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/><Default Extension=\"xml\" ContentType=\"application/xml\"/><Override PartName=\"/xl/workbook.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml\"/><Override PartName=\"/docProps/app.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.extended-properties+xml\"/><Override PartName=\"/docProps/core.xml\" ContentType=\"application/vnd.openxmlformats-package.core-properties+xml\"/>"); for (int i = 1; i <= content.size(); i++) { data.with("<Override PartName=\"/xl/worksheets/sheet" + i + ".xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml\"/>"); } data.with("</Types>"); return data.toString(); } private String getHeaderWorkbook(ExcelWorkBook content, int id) { CharacterBuffer data = new CharacterBuffer().with(HEADER); data.with( "<workbook xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\">\r\n <sheets>\r\n"); for (int i = 0; i < content.size(); i++) { ExcelSheet sheet = content.get(i); if (sheet == null) { continue; } data.with(" <sheet name=\""); if (sheet.getName() == null) { data.with("Table" + (i + 1)); } else { data.with(sheet.getName()); } data.with("\" sheetId=\"", "" + (i + 1), "\" r:id=\"rId", "" + (i + id), "\"/>\r\n"); } data.with(" </sheets>\r\n</workbook>"); return data.toString(); } private String getSheet(ExcelSheet sheet, int id) { int rowPos; CharacterBuffer data = new CharacterBuffer().with(HEADER); data.with( "<worksheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\">\r\n"); data.with("<sheetData>\r\n"); for (rowPos = 0; rowPos <= sheet.size(); rowPos++) { ExcelRow row = sheet.get(rowPos); if (row == null) { continue; } data.with(" <row r=\"" + row.getRowPos() + "\">"); for (ExcelCell cell : row) { data.with(cell.toString()); } data.with("</row>\r\n"); } data.with("</sheetData>"); data.with("</worksheet>"); return data.toString(); }; private String getHeaderWorkbookRel(ExcelWorkBook content, int id) { CharacterBuffer data = new CharacterBuffer().with(HEADER); data.with("<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">"); for (int i = 0; i < content.size(); i++) { data.with("<Relationship Id=\"rId", "" + (id + i), "\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet\" Target=\"worksheets/sheet", "" + (i + 1), ".xml\"/>"); } data.with("</Relationships>"); return data.toString(); } private String getHeader(ExcelWorkBook content) { if (content.getAuthor() == null) { content.withAuthor(System.getProperty("user.name")); } CharacterBuffer data = new CharacterBuffer().with(HEADER); DateTimeEntity date = new DateTimeEntity(); String string = date.toString("yyyy-mm-dd'T'HZ:MM:SS'Z'"); data.with( "<cp:coreProperties xmlns:cp=\"http://schemas.openxmlformats.org/package/2006/metadata/core-properties\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:dcmitype=\"http://purl.org/dc/dcmitype/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"); data.with("<dc:creator>", content.getAuthor(), "</dc:creator>"); data.with("<cp:lastModifiedBy>", content.getAuthor(), "</cp:lastModifiedBy>"); data.with("<dcterms:created xsi:type=\"dcterms:W3CDTF\">", string, "</dcterms:created>"); data.with("<dcterms:modified xsi:type=\"dcterms:W3CDTF\">", string, "</dcterms:modified>"); data.with("</cp:coreProperties>"); return data.toString(); } /** Parse WorkBook to Model * @return success */ public boolean parseModel() { return false; } }
40.811688
626
0.677168
b4220e7a47d0a0ae7d3c20f07a1593c7495073f0
1,144
package com.gentics.mesh.core.data.search.request; import com.gentics.mesh.search.SearchProvider; import io.reactivex.Completable; import io.reactivex.functions.Action; import java.util.function.Function; import static com.gentics.mesh.util.RxUtil.NOOP; /** * Contains all information to execute a search request to elasticsearch. */ public interface SearchRequest { /** * The amount of requests that will be executed. * @return */ int requestCount(); /** * Executes the request. * @param searchProvider * @return */ Completable execute(SearchProvider searchProvider); /** * An action that will be executed after the request was successful * @return */ default Action onComplete() { return NOOP; } /** * Creates a new search request from the given function. * @param function * @return */ static SearchRequest create(Function<SearchProvider, Completable> function) { return new SearchRequest() { @Override public int requestCount() { return 1; } @Override public Completable execute(SearchProvider searchProvider) { return function.apply(searchProvider); } }; } }
20.8
78
0.716783
1803df2b60c91a463be2a690bb5c2c03a4503e9f
2,334
/* * (c) Copyright 2021 Felipe Orozco, Robert Kruszewski. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gradlets.gradle.typescript.shim; import static org.assertj.core.api.Assertions.assertThat; import java.util.Optional; import org.junit.jupiter.api.Test; class IvyPatternsTest { @Test void converts_typescript() { Optional<ModuleIdentifier> maybeId = IvyPatterns.parseArtifactPath(getPath("typescript", "3.7.5")); assertThat(maybeId).hasValue(ModuleIdentifier.of("typescript", "3.7.5")); } @Test void converts_plain_package() { Optional<ModuleIdentifier> maybeId = IvyPatterns.parseArtifactPath(getPath("conjure-client", "1.0.0")); assertThat(maybeId).hasValue(ModuleIdentifier.of("conjure-client", "1.0.0")); } @Test void converts_scoped_requests() { Optional<ModuleIdentifier> maybeId = IvyPatterns.parseArtifactPath(getPath("foundry/conjure-fe-lib", "1.0.0")); assertThat(maybeId).hasValueSatisfying(id -> { assertThat(id.packageName()).isEqualTo("@foundry/conjure-fe-lib"); assertThat(id.packageVersion()).isEqualTo("1.0.0"); }); } @Test void converts_weird_versions() { Optional<ModuleIdentifier> maybeId = IvyPatterns.parseArtifactPath(getPath("foundry/conjure-fe-lib", "1.0.0-rc1-foo-bar.npm.sucks")); assertThat(maybeId).hasValueSatisfying(id -> { assertThat(id.packageName()).isEqualTo("@foundry/conjure-fe-lib"); assertThat(id.packageVersion()).isEqualTo("1.0.0-rc1-foo-bar.npm.sucks"); }); } private static String getPath(String packageName, String packageVersion) { return String.format("/%s/-/%s-%s.tgz", packageName, packageName, packageVersion); } }
38.262295
119
0.691088
9e5e5990abd7d8e63ce8ce11ea168d80f077ae0f
1,975
package org.specnaz.params.testng; import org.specnaz.impl.SpecsRegistryViolation; import org.specnaz.params.SpecnazParams; import org.specnaz.testng.SpecnazFactoryTestNG; import org.specnaz.testng.SpecnazTests; import org.specnaz.testng.impl.SpecnazTestNgSpecFactory; import org.testng.annotations.Factory; import java.util.function.Consumer; /** * The main interface for writing parametrized Specnaz specs that execute using * <a href="https://testng.org">TestNG</a>. * <p> * You use it identically as {@link SpecnazFactoryTestNG}: * your class must implement this interface * (it has one, default, method) * and be annotated with {@link org.testng.annotations.Test}. * The specification itself looks like any other * {@link SpecnazParams} spec: the {@link SpecnazParams#describes} * method is called in the public, no-argument constructor exactly once, * with the body of the specification. * * @see SpecnazParams * @see #specs */ public interface SpecnazParamsFactoryTestNG extends SpecnazParams { /** * The parametrized equivalent of {@link SpecnazFactoryTestNG#specs}. * Same notes apply to this method as they do to * {@link SpecnazFactoryTestNG#specs}. * * @return an array of {@link SpecnazTests} instances, * one for each test in the specification implementing this interface * @throws IllegalStateException if the {@link SpecnazParams#describes} * method was never called in the public, no-argument * constructor of the implementing class * @see SpecnazParams#describes * @see SpecnazFactoryTestNG#specs */ @Factory default Object[] specs() { try { return SpecnazTestNgSpecFactory.specs(this); } catch (SpecsRegistryViolation e) { throw new IllegalStateException("SpecnazParams.describes() was never called in the " + "no-argument constructor of " + this.getClass().getSimpleName()); } } }
37.980769
98
0.71443
9b07c09999b7ae336743a44d27d1821070aa72e4
1,112
package com.kgc.oop.io.byte_stream; import java.io.*; /** * @author:杨涛 */ public class DateInputStream_1 { public static void main(String[] args) { FileInputStream fis = null; FileOutputStream fos = null; DataInputStream dis = null; DataOutputStream dos = null; try { fis =new FileInputStream("D:\\picture.jpg"); System.out.println("可读取到的字节数:"+fis.available()); dis = new DataInputStream(fis); byte[] bytes = dis.readAllBytes(); System.out.println("读取完成"); fos = new FileOutputStream("C:\\Users\\yangtao\\Desktop\\1.jpg"); dos = new DataOutputStream(fos); dos.write(bytes); dos.flush(); } catch (IOException e) { e.printStackTrace(); }finally { try { assert dos != null; dos.close(); fos.close(); dis.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
25.272727
77
0.493705
8f4ff9882066c8cbdfa48ea331fab15edc3055b3
1,128
/* * Copyright © 2015 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.http; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponseStatus; /** * Handles exceptions and provides a response via the {@link HttpResponder}. */ public class ExceptionHandler { public void handle(Throwable t, HttpRequest request, HttpResponder responder) { String message = String.format("Exception encountered while processing request : %s", t.getMessage()); responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR, message); } }
36.387097
106
0.756206
61be7c8d8f8227dbbd8cf738dd3d30274f2ff857
12,295
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.cloudsearchdomain.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Information about a document that matches the search request. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class Hit implements Serializable, Cloneable, StructuredPojo { /** * <p> * The document ID of a document that matches the search request. * </p> */ private String id; /** * <p> * The fields returned from a document that matches the search request. * </p> */ private com.amazonaws.internal.SdkInternalMap<String, java.util.List<String>> fields; /** * <p> * The expressions returned from a document that matches the search request. * </p> */ private com.amazonaws.internal.SdkInternalMap<String, String> exprs; /** * <p> * The highlights returned from a document that matches the search request. * </p> */ private com.amazonaws.internal.SdkInternalMap<String, String> highlights; /** * <p> * The document ID of a document that matches the search request. * </p> * * @param id * The document ID of a document that matches the search request. */ public void setId(String id) { this.id = id; } /** * <p> * The document ID of a document that matches the search request. * </p> * * @return The document ID of a document that matches the search request. */ public String getId() { return this.id; } /** * <p> * The document ID of a document that matches the search request. * </p> * * @param id * The document ID of a document that matches the search request. * @return Returns a reference to this object so that method calls can be chained together. */ public Hit withId(String id) { setId(id); return this; } /** * <p> * The fields returned from a document that matches the search request. * </p> * * @return The fields returned from a document that matches the search request. */ public java.util.Map<String, java.util.List<String>> getFields() { if (fields == null) { fields = new com.amazonaws.internal.SdkInternalMap<String, java.util.List<String>>(); } return fields; } /** * <p> * The fields returned from a document that matches the search request. * </p> * * @param fields * The fields returned from a document that matches the search request. */ public void setFields(java.util.Map<String, java.util.List<String>> fields) { this.fields = fields == null ? null : new com.amazonaws.internal.SdkInternalMap<String, java.util.List<String>>(fields); } /** * <p> * The fields returned from a document that matches the search request. * </p> * * @param fields * The fields returned from a document that matches the search request. * @return Returns a reference to this object so that method calls can be chained together. */ public Hit withFields(java.util.Map<String, java.util.List<String>> fields) { setFields(fields); return this; } /** * Add a single Fields entry * * @see Hit#withFields * @returns a reference to this object so that method calls can be chained together. */ public Hit addFieldsEntry(String key, java.util.List<String> value) { if (null == this.fields) { this.fields = new com.amazonaws.internal.SdkInternalMap<String, java.util.List<String>>(); } if (this.fields.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.fields.put(key, value); return this; } /** * Removes all the entries added into Fields. * * @return Returns a reference to this object so that method calls can be chained together. */ public Hit clearFieldsEntries() { this.fields = null; return this; } /** * <p> * The expressions returned from a document that matches the search request. * </p> * * @return The expressions returned from a document that matches the search request. */ public java.util.Map<String, String> getExprs() { if (exprs == null) { exprs = new com.amazonaws.internal.SdkInternalMap<String, String>(); } return exprs; } /** * <p> * The expressions returned from a document that matches the search request. * </p> * * @param exprs * The expressions returned from a document that matches the search request. */ public void setExprs(java.util.Map<String, String> exprs) { this.exprs = exprs == null ? null : new com.amazonaws.internal.SdkInternalMap<String, String>(exprs); } /** * <p> * The expressions returned from a document that matches the search request. * </p> * * @param exprs * The expressions returned from a document that matches the search request. * @return Returns a reference to this object so that method calls can be chained together. */ public Hit withExprs(java.util.Map<String, String> exprs) { setExprs(exprs); return this; } /** * Add a single Exprs entry * * @see Hit#withExprs * @returns a reference to this object so that method calls can be chained together. */ public Hit addExprsEntry(String key, String value) { if (null == this.exprs) { this.exprs = new com.amazonaws.internal.SdkInternalMap<String, String>(); } if (this.exprs.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.exprs.put(key, value); return this; } /** * Removes all the entries added into Exprs. * * @return Returns a reference to this object so that method calls can be chained together. */ public Hit clearExprsEntries() { this.exprs = null; return this; } /** * <p> * The highlights returned from a document that matches the search request. * </p> * * @return The highlights returned from a document that matches the search request. */ public java.util.Map<String, String> getHighlights() { if (highlights == null) { highlights = new com.amazonaws.internal.SdkInternalMap<String, String>(); } return highlights; } /** * <p> * The highlights returned from a document that matches the search request. * </p> * * @param highlights * The highlights returned from a document that matches the search request. */ public void setHighlights(java.util.Map<String, String> highlights) { this.highlights = highlights == null ? null : new com.amazonaws.internal.SdkInternalMap<String, String>(highlights); } /** * <p> * The highlights returned from a document that matches the search request. * </p> * * @param highlights * The highlights returned from a document that matches the search request. * @return Returns a reference to this object so that method calls can be chained together. */ public Hit withHighlights(java.util.Map<String, String> highlights) { setHighlights(highlights); return this; } /** * Add a single Highlights entry * * @see Hit#withHighlights * @returns a reference to this object so that method calls can be chained together. */ public Hit addHighlightsEntry(String key, String value) { if (null == this.highlights) { this.highlights = new com.amazonaws.internal.SdkInternalMap<String, String>(); } if (this.highlights.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.highlights.put(key, value); return this; } /** * Removes all the entries added into Highlights. * * @return Returns a reference to this object so that method calls can be chained together. */ public Hit clearHighlightsEntries() { this.highlights = null; return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getId() != null) sb.append("Id: ").append(getId()).append(","); if (getFields() != null) sb.append("Fields: ").append(getFields()).append(","); if (getExprs() != null) sb.append("Exprs: ").append(getExprs()).append(","); if (getHighlights() != null) sb.append("Highlights: ").append(getHighlights()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Hit == false) return false; Hit other = (Hit) obj; if (other.getId() == null ^ this.getId() == null) return false; if (other.getId() != null && other.getId().equals(this.getId()) == false) return false; if (other.getFields() == null ^ this.getFields() == null) return false; if (other.getFields() != null && other.getFields().equals(this.getFields()) == false) return false; if (other.getExprs() == null ^ this.getExprs() == null) return false; if (other.getExprs() != null && other.getExprs().equals(this.getExprs()) == false) return false; if (other.getHighlights() == null ^ this.getHighlights() == null) return false; if (other.getHighlights() != null && other.getHighlights().equals(this.getHighlights()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode()); hashCode = prime * hashCode + ((getFields() == null) ? 0 : getFields().hashCode()); hashCode = prime * hashCode + ((getExprs() == null) ? 0 : getExprs().hashCode()); hashCode = prime * hashCode + ((getHighlights() == null) ? 0 : getHighlights().hashCode()); return hashCode; } @Override public Hit clone() { try { return (Hit) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.cloudsearchdomain.model.transform.HitMarshaller.getInstance().marshall(this, protocolMarshaller); } }
31.852332
137
0.607645
4b7f60a7b7f5ea55f28aacfafbc989dddb76808a
1,188
/* * Copyright 2021-2022 Aklivity Inc. * * Aklivity 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 io.aklivity.zilla.manager.internal.settings; import java.util.Objects; public final class ZpmSecurity { public String secret; @Override public int hashCode() { return Objects.hash(secret); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof ZpmSecurity)) { return false; } ZpmSecurity that = (ZpmSecurity) obj; return Objects.equals(this.secret, that.secret); } }
25.276596
78
0.659933
e91549fe0a0f5dc0a3cc56be9f7f240aa69b0575
4,469
package app.roana0229.org.screentracker; import android.app.Activity; import android.app.Application; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; public class ScreenTrackingLifecycleHandler extends FragmentManager.FragmentLifecycleCallbacks implements Application.ActivityLifecycleCallbacks { private final ScreenTrackingCallBack callBack; private long activityStartedTime; private long fragmentStartedTime; public ScreenTrackingLifecycleHandler(ScreenTrackingCallBack callBack) { this.callBack = callBack; } // ================================================================ // Application.ActivityLifecycleCallbacks // ================================================================ @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (!(activity instanceof AppCompatActivity)) { return; } ((AppCompatActivity) activity).getSupportFragmentManager().registerFragmentLifecycleCallbacks(this, true); } @Override public void onActivityStarted(Activity activity) { } @Override public void onActivityResumed(Activity activity) { if (activity instanceof TrackingMarker) { activityStartedTime = System.currentTimeMillis(); callBack.trackStarted((TrackingMarker) activity); } } @Override public void onActivityPaused(Activity activity) { if (activity instanceof TrackingMarker) { long exposureTime = System.currentTimeMillis() - activityStartedTime; callBack.trackEnded((TrackingMarker) activity, exposureTime); } } @Override public void onActivityStopped(Activity activity) { } @Override public void onActivitySaveInstanceState(Activity activity, Bundle bundle) { } @Override public void onActivityDestroyed(Activity activity) { if (!(activity instanceof AppCompatActivity)) { return; } ((AppCompatActivity) activity).getSupportFragmentManager().unregisterFragmentLifecycleCallbacks(this); } // ================================================================ // FragmentManager.FragmentLifecycleCallbacks // ================================================================ @Override public void onFragmentResumed(FragmentManager fm, Fragment f) { super.onFragmentResumed(fm, f); if (f instanceof TrackingMarker) { if (!(f instanceof DialogFragment)) { if (f.getView() == null || f.getView().getParent() == null) { return; } if (f.getView().getParent() instanceof ViewPager) { ViewPager viewPager = (ViewPager) f.getView().getParent(); if (!(viewPager instanceof TrackingViewPager)) { return; } if (((TrackingViewPager) viewPager).indexOfFragment(f) != viewPager.getCurrentItem()) { return; } ((TrackingViewPager) viewPager).resume(); } } fragmentStartedTime = System.currentTimeMillis(); callBack.trackStarted((TrackingMarker) f); } } @Override public void onFragmentPaused(FragmentManager fm, Fragment f) { super.onFragmentPaused(fm, f); if (f instanceof TrackingMarker) { if (!(f instanceof DialogFragment)) { if (f.getView() == null || f.getView().getParent() == null) { return; } if (f.getView().getParent() instanceof ViewPager) { ViewPager viewPager = (ViewPager) f.getView().getParent(); if (!(viewPager instanceof TrackingViewPager)) { return; } if (viewPager.indexOfChild(f.getView()) != viewPager.getCurrentItem()) { return; } } } long exposureTime = System.currentTimeMillis() - fragmentStartedTime; callBack.trackEnded((TrackingMarker) f, exposureTime); } } }
33.601504
146
0.576639
887082e1d4aeccff6a8b4e56d07c7907cc08fa49
2,473
package com.delivery.common.util; import com.fasterxml.jackson.databind.annotation.JsonAppend; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; /** * @author finderlo * @date 21/04/2017 */ @Component public class TimerImpl implements Timer, Runnable { private Map<Long, List<Task>> tasks = new HashMap<>(1000); private ExceptionHandler exceptionHandler; public TimerImpl() { this.exceptionHandler = new ExceptionHandler() { @Override public void handle(Throwable e, Task task) { //todo 定时器执行的异常处理器 } }; ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间 // 每秒执行一次run()方法,非阻塞 service.scheduleAtFixedRate(this, 1, 1, java.util.concurrent.TimeUnit.SECONDS); } @Override public void submit(Task task, int delay, TimeUnit unit) { //校对参数 if (delay <= 0) { throw new IllegalArgumentException(); } //秒为单位,获取当前时间 long time = System.currentTimeMillis() / 1000; //计算截止时间 time = time + delay * unit.getWeight(); //将时间放入队列中 List<Task> taskQueue = tasks.getOrDefault(time, new ArrayList<>()); taskQueue.add(task); } @Override public void run() { long time = System.currentTimeMillis() / 1000; List<Task> task = tasks.remove(time); new Thread(new Executor(task,exceptionHandler)).run(); } private static class Executor implements Runnable { List<Task> tasks; ExceptionHandler handler; Executor(List<Task> tasks,ExceptionHandler handler) { this.handler = handler; this.tasks = tasks; } public void run() { if (tasks == null) return; for (Task task : tasks) { try { task.run(); } catch (Exception e) { //do nothing //定时任务出现异常 handler.handle(e,task); } } } } public interface ExceptionHandler{ void handle(Throwable e,Task task); } }
26.591398
88
0.599677
88aaa2a1146480017b322ec96717c248dea73154
1,045
package com.boom.pojo; public class DbWaysign { private Integer wid; private String longitude; private String latitude; private String radius; private Integer mode; private String mac; private Integer state; public Integer getWid() { return wid; } public void setWid(Integer wid) { this.wid = wid; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getRadius() { return radius; } public void setRadius(String radius) { this.radius = radius; } public Integer getMode() { return mode; } public void setMode(Integer mode) { this.mode = mode; } public String getMac() { return mac; } public void setMac(String mac) { this.mac = mac; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } }
13.571429
45
0.68134
85d604c3f6723438b9fa37f48b423e331c4605f9
7,798
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.javascript.grunt.ui.actions; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JMenuItem; import org.netbeans.api.annotations.common.NullAllowed; import org.netbeans.api.options.OptionsDisplayer; import org.netbeans.api.project.Project; import org.netbeans.modules.javascript.grunt.GruntBuildTool; import org.netbeans.modules.javascript.grunt.GruntBuildToolSupport; import org.netbeans.modules.javascript.grunt.file.GruntTasks; import org.netbeans.modules.javascript.grunt.ui.options.GruntOptionsPanelController; import org.netbeans.modules.web.clientproject.api.build.BuildTools; import org.netbeans.spi.project.ui.support.ProjectConvertors; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.awt.ActionRegistration; import org.openide.awt.Actions; import org.openide.awt.DynamicMenuContent; import org.openide.filesystems.FileObject; import org.openide.loaders.DataObject; import org.openide.util.ContextAwareAction; import org.openide.util.Lookup; import org.openide.util.NbBundle; import org.openide.util.actions.Presenter; @ActionID(id = "org.netbeans.modules.javascript.grunt.ui.actions.RunGruntTaskAction", category = "Build") @ActionRegistration(displayName = "#RunGruntTaskAction.name", lazy = false) @ActionReferences({ @ActionReference(path = "Editors/text/grunt+javascript/Popup", position = 790), @ActionReference(path = "Loaders/text/grunt+javascript/Actions", position = 150), @ActionReference(path = "Projects/org-netbeans-modules-web-clientproject/Actions", position = 180), @ActionReference(path = "Projects/org-netbeans-modules-php-project/Actions", position = 130), @ActionReference(path = "Projects/org-netbeans-modules-web-project/Actions", position = 670), @ActionReference(path = "Projects/org-netbeans-modules-maven/Actions", position = 770), }) @NbBundle.Messages("RunGruntTaskAction.name=Grunt Tasks") public final class RunGruntTaskAction extends AbstractAction implements ContextAwareAction, Presenter.Popup { static final Logger LOGGER = Logger.getLogger(RunGruntTaskAction.class.getName()); @NullAllowed private final Project project; @NullAllowed private final FileObject gruntfile; public RunGruntTaskAction() { this(null); } private RunGruntTaskAction(Project project) { this(project, null); } private RunGruntTaskAction(Project project, FileObject gruntfile) { this.project = project; this.gruntfile = gruntfile; setEnabled(project != null); putValue(DynamicMenuContent.HIDE_WHEN_DISABLED, true); // hide this action in IDE Options > Keymap putValue(Action.NAME, null); } @Override public void actionPerformed(ActionEvent e) { assert false; } @Override public Action createContextAwareInstance(Lookup context) { Project contextProject = context.lookup(Project.class); if (contextProject != null) { // project action return createAction(contextProject); } // gruntfile directly FileObject file = context.lookup(FileObject.class); if (file == null) { DataObject dataObject = context.lookup(DataObject.class); if (dataObject != null) { file = dataObject.getPrimaryFile(); } } if (file == null) { return this; } contextProject = ProjectConvertors.getNonConvertorOwner(file); if (contextProject == null) { return this; } if (file.getParent().equals(contextProject.getProjectDirectory())) { return createAction(contextProject); } return createAction(contextProject, file); } private Action createAction(Project contextProject) { return createAction(contextProject, null); } private Action createAction(Project contextProject, @NullAllowed FileObject gruntfile) { assert contextProject != null; GruntBuildTool gruntBuildTool = GruntBuildTool.inProject(contextProject); if (gruntBuildTool == null) { return this; } if (gruntfile != null) { return new RunGruntTaskAction(contextProject, gruntfile); } if (!gruntBuildTool.getProjectGruntfile().exists()) { return this; } return new RunGruntTaskAction(contextProject); } @Override public JMenuItem getPopupPresenter() { if (project == null) { return new Actions.MenuItem(this, false); } return BuildTools.getDefault().createTasksMenu(new TasksMenuSupportImpl(project, gruntfile)); } //~ Inner classes private static final class TasksMenuSupportImpl extends GruntBuildToolSupport implements BuildTools.TasksMenuSupport { public TasksMenuSupportImpl(Project project, @NullAllowed FileObject gruntfile) { super(project, gruntfile); } @NbBundle.Messages({ "TasksMenuSupportImpl.tasks.label=&Task(s)", "TasksMenuSupportImpl.tasks.loading=Loading Tasks...", "TasksMenuSupportImpl.tasks.manage.advanced=Manage Task(s)", "TasksMenuSupportImpl.grunt.configure=Configure Grunt...", }) @Override public String getTitle(Title title) { switch (title) { case MENU: return Bundle.RunGruntTaskAction_name(); case LOADING_TASKS: return Bundle.TasksMenuSupportImpl_tasks_loading(); case CONFIGURE_TOOL: return Bundle.TasksMenuSupportImpl_grunt_configure(); case MANAGE_ADVANCED: return Bundle.TasksMenuSupportImpl_tasks_manage_advanced(); case TASKS_LABEL: return Bundle.TasksMenuSupportImpl_tasks_label(); default: assert false : "Unknown title: " + title; } return null; } @Override public String getDefaultTaskName() { return GruntTasks.DEFAULT_TASK; } @Override public void reloadTasks() { assert !EventQueue.isDispatchThread(); gruntTasks.reset(); try { gruntTasks.loadTasks(null, null); } catch (ExecutionException | TimeoutException ex) { LOGGER.log(Level.INFO, null, ex); } } @Override public void configure() { OptionsDisplayer.getDefault().open(GruntOptionsPanelController.OPTIONS_PATH); } } }
37.671498
122
0.681457
59c756b9af80e0239088525c8f6727af9b613513
3,926
/* * This file is part of adventure, licensed under the MIT License. * * Copyright (c) 2017-2022 KyoriPowered * * 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 net.kyori.adventure.text; import java.util.stream.Stream; import net.kyori.examination.ExaminableProperty; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * A component that can display NBT fetched from different locations, optionally trying to interpret the NBT as JSON * using the {@code net.kyori.adventure.text.serializer.gson.GsonComponentSerializer} to convert the JSON to a {@link Component}. * Sending interpreted NBT to the chat would be similar to using {@code /tellraw}. * * <p>This component consists of:</p> * <dl> * <dt>nbtPath</dt> * <dd>a path to specify which parts of the nbt you want displayed(<a href="https://minecraft.gamepedia.com/NBT_path_format#Examples">examples</a>).</dd> * <dt>interpret</dt> * <dd>a boolean telling adventure if the fetched NBT value should be parsed as JSON</dd> * </dl> * * <p>This component is rendered serverside and can therefore receive platform-defined * context. See the documentation for your respective * platform for more info</p> * * @param <C> component type * @param <B> builder type * @since 4.0.0 * @sinceMinecraft 1.14 */ public interface NBTComponent<C extends NBTComponent<C, B>, B extends NBTComponentBuilder<C, B>> extends BuildableComponent<C, B> { /** * Gets the NBT path. * * @return the NBT path * @since 4.0.0 */ @NotNull String nbtPath(); /** * Sets the NBT path. * * @param nbtPath the NBT path * @return an NBT component * @since 4.0.0 */ @Contract(pure = true) @NotNull C nbtPath(final @NotNull String nbtPath); /** * Gets if we should be interpreting. * * @return if we should be interpreting * @since 4.0.0 */ boolean interpret(); /** * Sets if we should be interpreting. * * @param interpret if we should be interpreting. * @return an NBT component * @since 4.0.0 */ @Contract(pure = true) @NotNull C interpret(final boolean interpret); /** * Gets the separator. * * @return the separator * @since 4.8.0 */ @Nullable Component separator(); /** * Sets the separator. * * @param separator the separator * @return the separator * @since 4.8.0 */ @NotNull C separator(final @Nullable ComponentLike separator); @Override default @NotNull Stream<? extends ExaminableProperty> examinableProperties() { return Stream.concat( Stream.of( ExaminableProperty.of("nbtPath", this.nbtPath()), ExaminableProperty.of("interpret", this.interpret()), ExaminableProperty.of("separator", this.separator()) ), BuildableComponent.super.examinableProperties() ); } }
32.716667
155
0.705298
3061206eef6d0e8335cf55409798d76c01e69324
488
package nl.esciencecenter.computeservice.model; public class StatePreconditionException extends Exception { private static final long serialVersionUID = 7561477622540055275L; public StatePreconditionException() { super(); } public StatePreconditionException(String string) { super(string); } public StatePreconditionException(String message, Throwable cause) { super(message, cause); } public StatePreconditionException(Throwable cause) { super(cause); } }
22.181818
69
0.772541
47eda1d3f2d83670e3aa18cad3e212e16d12f880
4,647
package net.myscloud.open.apollo.client.file; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import net.myscloud.open.apollo.common.kits.CollectionKits; import net.myscloud.open.apollo.common.kits.StringKits; import net.myscloud.open.apollo.common.Response; import okhttp3.OkHttpClient; import okhttp3.Request; import org.springframework.beans.factory.config.PropertiesFactoryBean; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PropertiesLoaderUtils; import java.io.IOException; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Properties; /** * 允许通过HTTP从远程加载配置,并将加载的配置保持到ClassPath下 * 当远程服务器出现问题时,允许从本地ClassPath中加载配置文件 * * @since 1.0 */ @Getter @Setter @Slf4j public class HttpPropertiesFactoryBean extends PropertiesFactoryBean { private String name; private List<String> names; @Override protected void loadProperties(Properties props) throws IOException { Properties apolloProp = PropertiesLoaderUtils.loadAllProperties("apollo.properties"); if (apolloProp.size() == 0) { log.warn("请检查ClassPath下是否存在配置文件[apollo.properties]"); } if (!apolloProp.containsKey("apollo.config.file.api")) { log.warn("找不到配置项[apollo.config.file.api]"); } if (!apolloProp.containsKey("apollo.project")) { log.warn("找不到配置项[apollo.project]"); } if (!apolloProp.containsKey("apollo.env")) { log.warn("找不到配置项[apollo.env]"); } OkHttpClient client = new OkHttpClient(); List<Resource> resources = Lists.newArrayList(); if (StringKits.isNotEmpty(name)) { resources.add(loadRemoteProperties(client, name, apolloProp)); } if (CollectionKits.isNotEmpty(names)) { names.stream() .filter(StringKits::isNotEmpty) .forEach(item -> resources.add(loadRemoteProperties(client, item, apolloProp))); } Resource[] tmp = new Resource[resources.size()]; resources.toArray(tmp); super.setLocations(tmp); super.loadProperties(props); } private Resource loadRemoteProperties(OkHttpClient client, String name, Properties apolloProp) { String mode = apolloProp.getProperty("apollo.mode"); if (StringKits.isEmpty(mode) || !"local".equals(mode)) { //非本地模式运行 String url = Joiner.on("/").skipNulls() .join(apolloProp.getProperty("apollo.config.file.api") , apolloProp.getProperty("apollo.project") , apolloProp.getProperty("apollo.env") , name); log.info("加载远程配置文件... Url:[{}]", url); Request request = new Request.Builder() .header("certification", apolloProp.getProperty("apollo.certification", "")) .url(url).build(); URL pathUrl = Thread.currentThread().getContextClassLoader().getResource("/"); if (pathUrl == null) { log.warn("获取ClassPath失败"); return new ClassPathResource(name); } //Windows环境获取ClassPath后需特殊处理 String classPath = System.getProperty("os.name").toLowerCase().startsWith("win") ? pathUrl.getPath().substring(1) : pathUrl.getPath(); log.info("获取ClassPath[{}]成功", classPath); try (okhttp3.Response response = client.newCall(request).execute()) { String content = response.body().string(); JSONObject result = JSON.parseObject(content); if (result.getInteger("code") == Response.Status.SUCCESS.getCode()) { String configContent = result.getString("data"); log.info("加载远程配置文件成功 Content:[{}]", configContent); //将配置文件保存到ClassPath Files.write(Paths.get(classPath + name) , configContent.getBytes(Charset.defaultCharset())); } else { log.warn("加载远程配置文件失败,Error:{}", result.getString("msg")); } } catch (IOException e) { log.warn(e.getMessage(), e); } } return new ClassPathResource(name); } }
39.717949
100
0.621691
f060cdee03b2e61a7dbe2d856e44f079224c0ea6
778
package com.lxisoft.service.dto; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import com.lxisoft.web.rest.TestUtil; public class AnswerDTOTest { @Test public void dtoEqualsVerifier() throws Exception { TestUtil.equalsVerifier(AnswerDTO.class); AnswerDTO answerDTO1 = new AnswerDTO(); answerDTO1.setId(1L); AnswerDTO answerDTO2 = new AnswerDTO(); assertThat(answerDTO1).isNotEqualTo(answerDTO2); answerDTO2.setId(answerDTO1.getId()); assertThat(answerDTO1).isEqualTo(answerDTO2); answerDTO2.setId(2L); assertThat(answerDTO1).isNotEqualTo(answerDTO2); answerDTO1.setId(null); assertThat(answerDTO1).isNotEqualTo(answerDTO2); } }
32.416667
57
0.708226
6cc97508ec2d033bceed074ae5cca7897b476494
1,687
package org.cloudfoundry.identity.uaa.test; import org.junit.jupiter.api.extension.*; import org.springframework.context.ApplicationContext; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.*; public class ZoneSeederExtension implements AfterEachCallback, ParameterResolver, BeforeTestExecutionCallback { private Map<Object, ZoneSeeder> zoneSeeders = new HashMap<>(); @Override public void afterEach(ExtensionContext extensionContext) { for (ZoneSeeder zoneSeeder : zoneSeeders.values()) { zoneSeeder.destroy(); } zoneSeeders.clear(); } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { return parameterContext.getParameter().getType() == ZoneSeeder.class; } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { Object testInstance = extensionContext.getTestInstance().get(); ApplicationContext applicationContext = SpringExtension.getApplicationContext(extensionContext); ZoneSeeder zoneSeeder = new ZoneSeeder(applicationContext); zoneSeeders.put(testInstance, zoneSeeder); return zoneSeeder; } @Override public void beforeTestExecution(ExtensionContext extensionContext) throws Exception { Object testInstance = extensionContext.getTestInstance().get(); ZoneSeeder zoneSeeder = zoneSeeders.get(testInstance); if (zoneSeeder != null) { zoneSeeder.seed(); } } }
38.340909
144
0.744517
b67a72698248a2c5a216dc264b633c5fc1fffee6
100
package fr.ignishky.mtgcollection.domain.card; public record CardImage( String image ) { }
14.285714
46
0.72
d680da0253ae757ffb175a80113443bd8eaed8ff
1,772
/* MazeRunnerII: A Maze-Solving Game Copyright (C) 2008-2012 Eric Ahnell Any questions should be directed to the author via email at: [email protected] */ package com.puttysoftware.mazerunner3.maze.objects; import com.puttysoftware.mazerunner3.Application; import com.puttysoftware.mazerunner3.Game; import com.puttysoftware.mazerunner3.loader.ObjectImageConstants; import com.puttysoftware.mazerunner3.loader.SoundConstants; import com.puttysoftware.mazerunner3.loader.SoundLoader; import com.puttysoftware.mazerunner3.maze.abc.AbstractMazeObject; import com.puttysoftware.mazerunner3.maze.abc.AbstractTeleport; import com.puttysoftware.mazerunner3.maze.utilities.MazeObjectInventory; public class ControllableTeleport extends AbstractTeleport { // Constructors public ControllableTeleport() { super(0, 0, 0, false, ObjectImageConstants.OBJECT_IMAGE_CONTROLLABLE); } // Scriptability @Override public void postMoveAction(final boolean ie, final int dirX, final int dirY, final MazeObjectInventory inv) { final Application app = Game.getApplication(); SoundLoader.playSound(SoundConstants.SOUND_WALK); app.getGameManager().controllableTeleport(); } @Override public String getName() { return "Controllable Teleport"; } @Override public String getPluralName() { return "Controllable Teleports"; } @Override public void editorProbeHook() { Game.getApplication().showMessage(this.getName()); } @Override public AbstractMazeObject editorPropertiesHook() { return null; } @Override public String getDescription() { return "Controllable Teleports let you choose the place you teleport to."; } @Override public int getCustomFormat() { return 0; } }
29.533333
113
0.764673
d52889615afbe6468137855e2e605e5b2057b899
1,475
package com.ruoyi.ext.mapper; import com.ruoyi.ext.database.SqlParam; import com.ruoyi.ext.domain.SysRoleMenu; import org.beetl.sql.core.mapper.BaseMapper; import java.util.List; /** * 角色与菜单关联表 数据层 * * @author ruoyi */ public interface SysRoleMenuMapper extends BaseMapper<SysRoleMenu> { /** * 通过角色ID删除角色和菜单关联 * * @param roleId 角色ID * @return 结果 */ public default int deleteRoleMenuByRoleId(Long roleId) { return this.getSQLManager().executeUpdate("delete from sys_role_menu where role_id=#roleId#", SqlParam.create().set("roleId", roleId)); } /** * 批量删除角色菜单关联信息 * * @param ids 需要删除的数据ID * @return 结果 */ public default int deleteRoleMenu(Long[] ids) { return this.getSQLManager().executeUpdate("delete from sys_role_menu where role_id in (#join(ids)#)", SqlParam.create().set("ids", ids)); } /** * 查询菜单使用数量 * * @param menuId 菜单ID * @return 结果 */ public default int selectCountRoleMenuByMenuId(Long menuId) { SysRoleMenu sysRoleMenu = new SysRoleMenu(); sysRoleMenu.setMenuId(menuId); Long count = this.templateCount(sysRoleMenu); return count.intValue(); } /** * 批量新增角色菜单信息 * * @param roleMenuList 角色菜单列表 * @return 结果 */ public default int batchRoleMenu(List<SysRoleMenu> roleMenuList) { this.insertBatch(roleMenuList); return roleMenuList.size(); } }
24.583333
145
0.640678
0d4f28fbdd6dd42d851289c9e9b72d62c854ef16
1,514
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package davy; /** * * @author mars */ public class WhileLoop { private static final java.util.Scanner sc = new java.util.Scanner(System.in); public static void main(String[] args) { int sum = 0; System.out.println("Enter an integer " + "(the input ends if it is 0)"); int number = getInput(); while (number != 0) { sum += number; System.out.println("Enter an integer " + "(the input ends if it is 0)"); number = getInput(); } } /** * The conditional expression in the while statement calls the hasNextInt * method of the Scanner to see if the next value is an integer. The while * loop repeats as long as this call returns false, indicating that the next * value is not a valid integer. The body of the loop calls nextLine to * discard the bad data and displays an error message. The loop ends only * when you know you have good data in the input stream, so the return * statement calls nextInt to parse the data to an integer and return the * resulting value. * */ private static int getInput() { while (!sc.hasNextInt()) { sc.nextLine(); System.out.println("That's not an integer..Try again!"); } return sc.nextInt(); } }
32.913043
84
0.624835
c88394e73174219d60c97372e8efe27de74150b7
758
import java.text.MessageFormat; /** * Word is a custom object for holding a sub-string value and its start and end indices in a string. */ public class Word implements Comparable<Word> { private String value; private long startIndex; public String getValue() { return value; } public long getStartIndex() { return startIndex; } public Word(String value, long startIndex) { this.value = value; this.startIndex = startIndex; } @Override public String toString() { return MessageFormat.format("{0} [{1}:{2}]", value, String.valueOf(startIndex), value.length()); } @Override public int compareTo(Word w) { return value.compareTo(w.getValue()); } }
21.657143
104
0.633245
998d497d5641929c0e4d3ea518fe88370eb33225
660
package com.achais.leetcode; import java.util.LinkedList; import java.util.Queue; public class Solution190 { public int reverseBits(int n) { int[] arr = new int[32]; for (int i = 0; i < 32; i++) { arr[i] = n & 1; n >>= 1; } int ans = 0; for (int i : arr) { ans <<= 1; ans += i; } return ans; } public static void main(String[] args) { int stdin = 0b11111111111111111111111111111101; Solution190 solution = new Solution190(); Integer stdout = solution.reverseBits(stdin); System.out.println(stdout); } }
22
55
0.522727
bccbf2646982eb552613f69ccde05cecb1412513
6,736
package com.v5ent.xiubit.fragment.main; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.FragmentManager; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.RelativeLayout; import com.flyco.tablayout.SlidingTabLayout; import com.toobei.common.view.MyShowTipsView; import com.v5ent.xiubit.R; import com.v5ent.xiubit.activity.MainActivity; import com.v5ent.xiubit.data.pageadapter.OrgAndProductPagerAdapter; import com.v5ent.xiubit.event.FundListBackRefreshEvent; import com.v5ent.xiubit.event.OpenFundSearchEvent; import com.v5ent.xiubit.fragment.FragmentBase; import com.umeng.analytics.MobclickAgent; import org.greenrobot.eventbus.EventBus; import org.xsl781.utils.Logger; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * 公司: tophlc * 类说明: * * @author yangLin * @time 2017/6/21 */ public class FragmentOrgAndProduct extends FragmentBase { @BindView(R.id.tabLayout) SlidingTabLayout mTabLayout; @BindView(R.id.vPager) ViewPager mVPager; @BindView(R.id.headViewLi) RelativeLayout headViewLi; @BindView(R.id.status_bar) View mStatusBar; @BindView(R.id.searchIv) ImageView mSearchIv; private int defaultTabIndex; private MyShowTipsView mMyShowTipsView2; private MainActivity mMainActivity; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = LayoutInflater.from(ctx) .inflate(R.layout.fragment_org_and_product, null); ButterKnife.bind(this, rootView); mMainActivity = (MainActivity)ctx; initView(); return rootView; } @Override public void onHiddenChanged(boolean hidden) { super.onHiddenChanged(hidden); if (mVPager == null) return; if (!hidden && mVPager.getCurrentItem() == 2){ EventBus.getDefault().post(new FundListBackRefreshEvent(true)); initShowTip(); } } private void initView() { setHeadViewCoverStateBar(mStatusBar); FragmentManager fragmentManager = getChildFragmentManager(); mVPager.setAdapter(new OrgAndProductPagerAdapter(ctx, fragmentManager)); mVPager.setOffscreenPageLimit(1); // String[] title = {"网贷" ,"超级返","基金","保险"}; String[] title = {"网贷" ,"超级返"}; mTabLayout.setViewPager(mVPager, title); mVPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { switch (position){ case 0: MobclickAgent.onEvent(ctx,"T_2_1"); break; case 1: MobclickAgent.onEvent(ctx,"T_5_1"); break; case 2: MobclickAgent.onEvent(ctx,"T_3_1"); break; case 3: MobclickAgent.onEvent(ctx,"T_4_1"); break; } mSearchIv.setVisibility(position == 2 ?View.VISIBLE:View.INVISIBLE); } @Override public void onPageScrollStateChanged(int state) { } }); mVPager.setCurrentItem(defaultTabIndex); initShowTip(); } public void initShowTip() { mTabLayout.getViewTreeObserver() .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { initShowTipsView(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { mTabLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this); } } }); } /** * 新手引导图片 */ private void initShowTipsView() { // MyShowTipsView myShowTipsView1 = new MyShowTipsView(ctx, mTabLayout, GuideViewType.FRAGMENT_HOME_INVEST_GUIDE1 // .getValue(), // DisplayUtil.dip2px(ctx, -5), DisplayUtil.dip2px(ctx, 0), GuideViewType.FRAGMENT_HOME_INVEST_GUIDE1 // .toString()); // // myShowTipsView1.setLocationOffset(DisplayUtil.dip2px(ctx, 190), 0); // myShowTipsView1.setExpandSize(-DisplayUtil.dip2px(ctx, 190), 0); //// myShowTipsView1.setDisplayOneTime(false); // myShowTipsView1.show(ctx); // // // // mMyShowTipsView2 = new MyShowTipsView(ctx, mTabLayout, GuideViewType.FRAGMENT_HOME_INVEST_GUIDE1 // .getValue(),// // PixelUtil.dip2px(ctx, -5), PixelUtil.dip2px(ctx, 0), GuideViewType.FRAGMENT_HOME_INVEST_GUIDE1 // .toString()); //// mMyShowTipsView2.setDisplayOneTime(false); // mMyShowTipsView2.setLocationOffset(PixelUtil.dip2px(ctx, 190), 0); // mMyShowTipsView2.setExpandSize(-PixelUtil.dip2px(ctx, 190), 0); // // mMyShowTipsView2.setOnShowTipHideListener(new MyShowTipsView.onShowTipHideListener() { // @Override // public void onShowTipHide() { // // mMyShowTipsView1.show(ctx); // } // }); //// mMyShowTipsView1.setDisplayOneTime(false); // if (mMainActivity.curIndex == 1) { // 当前在当前才显示新手引导 // mMyShowTipsView2.show(ctx); // } } @OnClick(R.id.searchIv) public void onViewClicked() { Logger.e("OpenFundSearchEvent-post"); //弹出搜索页面 EventBus.getDefault().post(new OpenFundSearchEvent()); } public void skipTab(int tabIndext) { // 0 、1网贷 2基金 3保险 4限时抢 int pageIndex = 0; switch (tabIndext){ case 0: case 1: pageIndex = 0; break; case 2: pageIndex = 2; break; case 3: pageIndex = 3; break; case 4: pageIndex = 1; break; } if (mVPager != null){ mVPager.setCurrentItem(pageIndex); }else { defaultTabIndex = pageIndex; } } }
33.182266
123
0.600356
eb52063e09c246cf738b70dfd4e68e9c7a816820
9,012
package com.hsq.client; import com.hsq.bean.User; import java.math.BigInteger; import java.util.Scanner; /** * @author concise */ public class InformationAndAccountView { private static Scanner input = new Scanner(System.in); // 首页 public static User indexView() { System.out.println("******************************************************************"); System.out.println("*******************\t\t 学生信息管理系统\t\t**************************"); System.out.println("**********************\t\t 请根据提示操作\t\t*************************"); System.out.println("**********************\t\t 请输入账号\t\t***************************"); String uname = input.nextLine(); System.out.println("**********************\t\t 请输入密码\t\t***************************"); String upass = input.nextLine(); System.out.println("******************************************************************"); System.out.println("******************************************************************"); User user = new User(uname, upass); System.out.println(user); return user; } // 管理员菜单 public static int managerMenuView() { System.out.println("***********************************************************************"); System.out.println("************************\t\t 欢迎管理员回家 \t\t**************************"); System.out.println("*************************\t\t 请根据提示操作 \t\t*************************"); System.out.println("**************************\t\t 0. 退出 \t\t*****************************"); System.out.println("**********************\t\t 1. 增加学生信息 \t\t***************************"); System.out.println("**********************\t\t 2. 删除学生信息 \t\t***************************"); System.out.println("**********************\t\t 3. 修改学生信息 \t\t***************************"); System.out.println("**********************\t\t 4. 查询学生信息 \t\t***************************"); String type = input.nextLine(); int item = Integer.parseInt(type); if (item < 0 || item > 4) { System.out.println("输入有误!请重新输入"); return managerMenuView(); } System.out.println("******************************************************************"); return item; } // 教师 public static int teacherMenuView() { System.out.println("***********************************************************************"); System.out.println("*************************\t\t 欢迎老师回家 \t\t**************************"); System.out.println("*************************\t\t 请根据提示操作 \t\t*************************"); System.out.println("**************************\t\t 0. 退出 \t\t*****************************"); System.out.println("**********************\t\t 1. 增加学生信息 \t\t***************************"); System.out.println("**********************\t\t 2. 修改学生信息 \t\t***************************"); System.out.println("**********************\t\t 3. 查询学生信息 \t\t***************************"); String type = input.nextLine(); int ietm = Integer.parseInt(type); if (ietm < 0 || ietm > 3) { System.out.println("输入有误!请重新输入"); return teacherMenuView(); } System.out.println("******************************************************************"); return ietm; } public static int studentMenuView() { System.out.println("***********************************************************************"); System.out.println("*************************\t\t 欢迎同学回家 \t\t**************************"); System.out.println("*************************\t\t 请根据提示操作 \t\t*************************"); System.out.println("**************************\t\t 0. 退出 \t\t*****************************"); System.out.println("**********************\t\t 1. 增加学生信息 \t\t***************************"); System.out.println("**********************\t\t 2. 修改学生信息 \t\t***************************"); System.out.println("**********************\t\t 3. 查询学生信息 \t\t***************************"); String type = input.nextLine(); int ietm = Integer.parseInt(type); if (ietm < 0 || ietm > 3) { System.out.println("输入有误!请重新输入"); return studentMenuView(); } System.out.println("******************************************************************"); return ietm; } /** * 添加学生信息视图 * * @return new User object */ public static User addMenuView() { System.out.println("******************************************************************"); System.out.println("**********************\t\t 请根据提示操作\t\t*************************"); System.out.println("**********************\t\t 请输入新添加的账号\t\t***************************"); String uname = input.nextLine(); System.out.println("**********************\t\t 请输入新添加的密码\t\t***************************"); String upass = input.nextLine(); System.out.println("**********************\t\t 请输入新添加人员类型\t\t***************************"); int type = Integer.parseInt(input.nextLine()); System.out.println("**********************\t\t 请输入新添加人员的性别\t\t***************************"); String sex = input.nextLine(); System.out.println("**********************\t\t 请输入新添加人员的学号\t\t***************************"); BigInteger number = input.nextBigInteger(); System.out.println("**********************\t\t 请输入新添加人员的入学年份\t\t***************************"); Long year = input.nextLong(); String a = input.nextLine(); System.out.println("**********************\t\t 请输入新添加人员的学院\t\t***************************"); String academy = input.nextLine(); System.out.println("**********************\t\t 请输入新添加人员的专业\t\t***************************"); String major = input.nextLine(); System.out.println("*****************************************************************************"); return new User(uname, upass, type, sex, number, year, academy, major); } /** * 删除学生信息视图 * * @return new User object */ public static User deleteMenuView() { System.out.println("******************************************************************"); System.out.println("**********************\t\t 请根据提示操作\t\t*************************"); System.out.println("**********************\t\t 请输入需删除的账号\t\t***************************"); String uname = input.nextLine(); System.out.println("**********************\t\t 删除账号需要确认密码\t\t***************************"); String upass = input.nextLine(); System.out.println("******************************************************************"); return new User(uname, upass); } /** * 修改学生信息视图 * * @return new User object */ public static User changeMenuView() { System.out.println("******x************************************************************"); System.out.println("**********************\t\t 请根据提示操作\t\t*************************"); System.out.println("**********************\t\t 请输入需修改的账号\t\t***************************"); String uname = input.nextLine(); System.out.println("**********************\t\t 请输入新的密码\t\t***************************"); String upass = input.nextLine(); System.out.println("******************************************************************"); return new User(uname, upass); } /** * 查询学生信息视图 * * @return new User object */ public static User selectMenuView() { System.out.println("******************************************************************"); System.out.println("**********************\t\t 请根据提示操作\t\t*************************"); System.out.println("**********************\t\t 请输入需查询的账号\t\t***************************"); String uname = input.nextLine(); System.out.println("**********************\t\t 查询账号需要确认密码\t\t***************************"); String upass = input.nextLine(); System.out.println("******************************************************************"); return new User(uname, upass); } /** * 输出学生信息 * * @param user * @author concise */ public static void printUser(User user) { System.out.println("id: " + user.getId()); System.out.println("name: " + user.getUname()); System.out.println("password: " + user.getUpass()); if (user.getType() == 1) { System.out.println("用户权限:管理员" + user.getType()); } else if (user.getType() == 2) { System.out.println("用户权限:教师" + user.getType()); } else if (user.getType() == 3) { System.out.println("用户权限:学生" + user.getType()); } } }
47.93617
108
0.353418
4c49d9245dcf055265b7b50cb90b236fb40febc9
3,167
package se.eris.notnull.instrumentation; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class ClassMatcherTest { @Test public void fromPlainMarcher() { final ClassMatcher matcher = ClassMatcher.namePattern("se.eris.A"); assertThat(matcher.matches("se.A"), is(false)); assertThat(matcher.matches("se.eris.A"), is(true)); assertThat(matcher.matches("se.eris.B"), is(false)); assertThat(matcher.matches("se.eris.test.A"), is(false)); } @Test public void fromSingleWildcard() { final ClassMatcher matcher = ClassMatcher.namePattern("se.*"); assertThat(matcher.matches("se.A"), is(true)); assertThat(matcher.matches("se.eris.A"), is(false)); assertThat(matcher.matches("se.eris.Test"), is(false)); assertThat(matcher.matches("sea"), is(false)); } @Test public void fromDoubleWildcardAtEnd() { final ClassMatcher matcher = ClassMatcher.namePattern("se.**"); assertThat(matcher.matches("se"), is(true)); assertThat(matcher.matches("se.eris"), is(true)); assertThat(matcher.matches("se.eris.Test"), is(true)); assertThat(matcher.matches("sea"), is(false)); assertThat(matcher.matches("sea.Test"), is(false)); } @Test public void fromDoubleWildcard() { final ClassMatcher matcher = ClassMatcher.namePattern("se.**.Test"); assertThat(matcher.matches("se"), is(false)); assertThat(matcher.matches("se.eris"), is(false)); assertThat(matcher.matches("se.Test"), is(true)); assertThat(matcher.matches("se.eris.Test"), is(true)); assertThat(matcher.matches("se.eris.other.Test"), is(true)); assertThat(matcher.matches("se.eris.Test.more"), is(false)); assertThat(matcher.matches("sea.eris.Test"), is(false)); } @Test public void fromWildcardFirst() { final ClassMatcher matcher = ClassMatcher.namePattern("*.Test"); assertThat(matcher.matches("se"), is(false)); assertThat(matcher.matches("se.Test"), is(true)); assertThat(matcher.matches("se.eris.Test"), is(false)); } @Test public void fromDoubleWildcardFirst() { final ClassMatcher matcher = ClassMatcher.namePattern("**.Test"); assertThat(matcher.matches("se"), is(false)); assertThat(matcher.matches("se.Test"), is(true)); assertThat(matcher.matches("se.eris.Test"), is(true)); } @Test public void currencyDollar_shouldWork() { final ClassMatcher matcher = ClassMatcher.namePattern("**.Test$1"); assertThat(matcher.matches("se.Test"), is(false)); assertThat(matcher.matches("se.Test$1"), is(true)); assertThat(matcher.matches("se.Test$12"), is(false)); } @Test public void regexp_shouldWork() { final ClassMatcher matcher = ClassMatcher.namePattern("**.Test($[0-9]+)?"); assertThat(matcher.matches("se.Test"), is(true)); assertThat(matcher.matches("se.Test$1"), is(true)); assertThat(matcher.matches("se.Test$12"), is(true)); } }
38.621951
83
0.641617
98353f5df63629aa20164cd6e75a5f1df72e61d0
404
package com.liangxiaoqiao.leetcode.day.hard; /* * English * id: 431 * title: Encode N-ary Tree to Binary Tree * href: https://leetcode.com/problems/encode-n-ary-tree-to-binary-tree * desc: * <p> * 中文 * 序号: 431 * 标题: 将 N 叉树编码为二叉树 * 链接: https://leetcode-cn.com/problems/encode-n-ary-tree-to-binary-tree * 描述: * <p> * acceptance: 68.5% * difficulty: Hard * private: False */ //TODO init
16.833333
72
0.65099
2d21067372e7c62113ed48c03fb7e4dda4f72683
3,012
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // This file is a part of the 'coroutines' project. // Copyright 2018 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany // // 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 de.esoco.coroutine; import de.esoco.coroutine.Coroutine.Subroutine; import org.junit.Test; import static de.esoco.coroutine.Coroutine.first; import static de.esoco.coroutine.CoroutineScope.launch; import static de.esoco.coroutine.step.CallSubroutine.call; import static de.esoco.coroutine.step.CodeExecution.apply; import static de.esoco.coroutine.step.CodeExecution.supply; import static de.esoco.coroutine.step.Condition.doIf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /******************************************************************** * Test of {@link Subroutine}. * * @author eso */ public class SubroutineTest { //~ Methods ---------------------------------------------------------------- /*************************************** * Test of subroutine invocations. */ @Test public void testSubroutine() { Coroutine<String, Integer> cr = Coroutine.first(call(CoroutineTest.CONVERT_INT)) .then(apply(i -> i + 10)); launch( scope -> { Continuation<Integer> ca = cr.runAsync(scope, "test1234"); Continuation<Integer> cb = cr.runBlocking(scope, "test1234"); assertEquals(Integer.valueOf(12355), ca.getResult()); assertEquals(Integer.valueOf(12355), cb.getResult()); assertTrue(ca.isFinished()); assertTrue(cb.isFinished()); }); } /*************************************** * Test of early subroutine termination. */ @Test public void testSubroutineTermination() { Coroutine<Boolean, String> cr = first( call( first( doIf( (Boolean b) -> b == Boolean.TRUE, supply(() -> "TRUE"))))); launch( scope -> { Continuation<String> ca = cr.runAsync(scope, false); Continuation<String> cb = cr.runBlocking(scope, false); assertEquals(null, ca.getResult()); assertEquals(null, cb.getResult()); assertTrue(ca.isFinished()); assertTrue(cb.isFinished()); ca = cr.runAsync(scope, true); cb = cr.runBlocking(scope, true); assertEquals("TRUE", ca.getResult()); assertEquals("TRUE", cb.getResult()); assertTrue(ca.isFinished()); assertTrue(cb.isFinished()); }); } }
29.821782
78
0.615206
0c40e712480bf6796befb1a3ee7bedcb512c802c
4,522
//| Copyright - The University of Edinburgh 2011 | //| | //| 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 uk.ac.ed.epcc.webapp.jdbc.filter; /** Helper classes to convert generic filters into {@link SQLFilter}s. * Unlike {@link FilterConverter} this returns the original filter if * conversion is not possible * * @author spb * */ public class OptionalFilterConverter<T> implements FilterVisitor<BaseFilter<T>, T> { public static <X> BaseFilter<X> convert(BaseFilter<X> fil) { if( fil instanceof SQLFilter || fil == null){ return (SQLFilter<X>) fil; } OptionalFilterConverter<X> conv = new OptionalFilterConverter<>(); try { return fil.acceptVisitor(conv); } catch (Exception e) { return fil; } } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.jdbc.filter.FilterVisitor#visitPatternFilter(uk.ac.ed.epcc.webapp.jdbc.filter.PatternFilter) */ @Override public BaseFilter<T> visitPatternFilter(PatternFilter<T> fil) throws NoSQLFilterException { return fil; } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.jdbc.filter.FilterVisitor#visitSQLCombineFilter(uk.ac.ed.epcc.webapp.jdbc.filter.BaseSQLCombineFilter) */ @Override public BaseFilter<T> visitSQLCombineFilter( BaseSQLCombineFilter<T> fil) throws NoSQLFilterException { return fil; } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.jdbc.filter.FilterVisitor#visitAndFilter(uk.ac.ed.epcc.webapp.jdbc.filter.AndFilter) */ @Override public BaseFilter<T> visitAndFilter(AndFilter<T> fil) throws NoSQLFilterException { if( ! fil.hasAcceptFilters()) { return fil.getSQLFilter(); } return fil; } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.jdbc.filter.FilterVisitor#visitOrderFilter(uk.ac.ed.epcc.webapp.jdbc.filter.OrderFilter) */ @Override public BaseFilter<T> visitOrderFilter(SQLOrderFilter<T> fil) throws NoSQLFilterException { return fil; } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.jdbc.filter.FilterVisitor#visitAcceptFilter(uk.ac.ed.epcc.webapp.jdbc.filter.AcceptFilter) */ @Override public BaseFilter<T> visitAcceptFilter(AcceptFilter<T> fil) throws NoSQLFilterException { return fil; } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.jdbc.filter.FilterVisitor#visitJoinFilter(uk.ac.ed.epcc.webapp.jdbc.filter.JoinFilter) */ @Override public BaseFilter<T> visitJoinFilter(JoinFilter<T> fil) throws NoSQLFilterException { return fil; } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.jdbc.filter.FilterVisitor#visitOrFiler(uk.ac.ed.epcc.webapp.jdbc.filter.OrFilter) */ @Override public BaseFilter<T> visitOrFilter(OrFilter<T> fil) throws NoSQLFilterException { if( fil.nonSQL()) { return fil; } return fil.getSQLFilter(); } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.jdbc.filter.FilterVisitor#visitBinaryFilter(uk.ac.ed.epcc.webapp.jdbc.filter.BinaryFilter) */ @Override public BaseFilter<T> visitBinaryFilter(BinaryFilter<T> fil) { if( fil instanceof SQLFilter){ return fil; } return new GenericBinaryFilter<>((Class<T>) fil.getTarget(), fil.getBooleanResult()); } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.jdbc.filter.FilterVisitor#visitDualFilter(uk.ac.ed.epcc.webapp.jdbc.filter.DualFilter) */ @Override public BaseFilter<T> visitDualFilter(DualFilter<T> fil) { return fil.getSQLFilter(); } /* (non-Javadoc) * @see uk.ac.ed.epcc.webapp.jdbc.filter.FilterVisitor#visitBinaryAcceptFilter(uk.ac.ed.epcc.webapp.jdbc.filter.BinaryAcceptFilter) */ @Override public BaseFilter<T> visitBinaryAcceptFilter(BinaryAcceptFilter<T> fil) throws Exception { return visitBinaryFilter(fil); } }
35.054264
132
0.670942
4f6d0b6493c8fa307fe715d56331fbcce693cb33
902
package me.giraffetree.java.boomjava.alg.sort.merge; import me.giraffetree.java.boomjava.alg.sort.Element; import java.util.Arrays; import static me.giraffetree.java.boomjava.alg.sort.SortUtils.generateObj; /** * 自底向上的归并排序 * * @author GiraffeTree * @date 2020-01-04 */ public class MergeObjectSort2 { public static void sort(Comparable[] a) { int N = a.length; Comparable[] aux = new Comparable[N]; for (int sz = 1; sz < N; sz = sz + sz) { for (int lo = 0; lo < N - sz; lo += sz + sz) { MergeObjectSort.merge(a, aux, lo, lo + sz - 1, Math.min(lo + sz + sz - 1, N - 1)); } } } public static void main(String[] args) { Element[] elements = generateObj(); System.out.println(Arrays.toString(elements)); sort(elements); System.out.println(Arrays.toString(elements)); } }
23.736842
98
0.594235
de48e3beee8c81b8396b5b33940a1bac7ebb798a
1,096
package action.testcases; import org.junit.Test; import com.xceptance.xlt.api.actions.AbstractHtmlPageAction; import com.xceptance.xlt.api.engine.scripting.AbstractHtmlUnitScriptTestCase; import action.testcases.OpenCloseOpen_actions.OpenCloseOpenAction; import action.testcases.OpenCloseOpen_actions.OpenCloseOpenAction0; import action.testcases.OpenCloseOpen_actions.OpenCloseOpenAction1; /** * Related to #1728 Close the last open window/tab and open new page. */ public class OpenCloseOpen extends AbstractHtmlUnitScriptTestCase { /** * Constructor. */ public OpenCloseOpen() { super("http://localhost:8080"); } @Test public void test() throws Throwable { AbstractHtmlPageAction lastAction = null; lastAction = new OpenCloseOpenAction(lastAction, "/testpages/examplePage_1.html"); lastAction.run(); lastAction = new OpenCloseOpenAction0(lastAction); lastAction.run(); lastAction = new OpenCloseOpenAction1(lastAction, "/testpages/examplePage_1.html"); lastAction.run(); } }
26.095238
91
0.729927
f801995edeff74a303ae4b9ed9e07c914633466d
1,326
/* * Copyright 2002-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.springframework.util.function; import java.util.function.Supplier; import org.springframework.lang.Nullable; /** * Convenience utilities for {@link java.util.function.Supplier} handling. * * @author Juergen Hoeller * @since 5.1 * @see SingletonSupplier */ public abstract class SupplierUtils { /** * Resolve the given {@code Supplier}, getting its result or immediately * returning {@code null} if the supplier itself was {@code null}. * @param supplier the supplier to resolve * @return the supplier's result, or {@code null} if none */ @Nullable public static <T> T resolve(@Nullable Supplier<T> supplier) { return (supplier != null ? supplier.get() : null); } }
30.136364
75
0.726244
387b89ba233e13974e0b0733a7b87a63641c0b79
2,268
package ch.softridge.cardmarket.autopricing.controller; import ch.softridge.cardmarket.autopricing.domain.service.CardService; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; /** * @author Kevin Zellweger * @Date 05.07.20 */ @Controller public class SorterUploadController { private static final Logger log = LoggerFactory.getLogger(SorterUploadController.class); private final String UPLOAD_DIR = "./uploads/"; private final CardService cardService; @Autowired public SorterUploadController(CardService cardService) { this.cardService = cardService; } @GetMapping("/sorterUpload") public String main() { return "sorterUpload"; } @PostMapping("/sorterUpload/upload") public String uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes attributes) { // check if file is empty if (file.isEmpty()) { attributes.addFlashAttribute("message", "Please select a file to upload."); return "redirect:/sorterUpload"; } // normalize the file path String fileName = StringUtils.cleanPath(file.getOriginalFilename()); log.info(fileName); // save the file on the local file system try { Path path = Paths.get(UPLOAD_DIR + fileName); log.info(path.toString()); Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } // return success response attributes.addFlashAttribute("message", "You successfully uploaded " + fileName + '!'); cardService.addAll(cardService.readSorterCSV(fileName)); return "redirect:/sorterUpload"; } }
32.4
91
0.754409
59b375ff2a28e26e886ee43cfa732b77699544d9
4,994
/* * 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.gearpump.streaming.javaapi; import akka.actor.ActorSystem; import org.apache.gearpump.cluster.UserConfig; import org.apache.gearpump.streaming.sink.DataSink; import org.apache.gearpump.streaming.sink.DataSinkProcessor; import org.apache.gearpump.streaming.sink.DataSinkTask; import org.apache.gearpump.streaming.source.DataSource; import org.apache.gearpump.streaming.source.DataSourceProcessor; import org.apache.gearpump.streaming.source.DataSourceTask; /** * Java version of Processor * * See {@link org.apache.gearpump.streaming.Processor} */ public class Processor<T extends org.apache.gearpump.streaming.task.Task> implements org.apache.gearpump.streaming.Processor<T> { private Class<T> _taskClass; private int _parallelism = 1; private String _description = ""; private UserConfig _userConf = UserConfig.empty(); public Processor(Class<T> taskClass) { this._taskClass = taskClass; } public Processor(Class<T> taskClass, int parallelism) { this._taskClass = taskClass; this._parallelism = parallelism; } /** * Creates a Sink Processor * * @param dataSink the data sink itself * @param parallelism the parallelism of this processor * @param description the description for this processor * @param taskConf the configuration for this processor * @param system actor system * @return the new created sink processor */ public static Processor<DataSinkTask> sink(DataSink dataSink, int parallelism, String description, UserConfig taskConf, ActorSystem system) { org.apache.gearpump.streaming.Processor<DataSinkTask> p = DataSinkProcessor.apply(dataSink, parallelism, description, taskConf, system); return new Processor(p); } /** * Creates a Source Processor * * @param source the data source itself * @param parallelism the parallelism of this processor * @param description the description of this processor * @param taskConf the configuration of this processor * @param system actor system * @return the new created source processor */ public static Processor<DataSourceTask> source(DataSource source, int parallelism, String description, UserConfig taskConf, ActorSystem system) { org.apache.gearpump.streaming.Processor<DataSourceTask<Object, Object>> p = DataSourceProcessor.apply(source, parallelism, description, taskConf, system); return new Processor(p); } public Processor(org.apache.gearpump.streaming.Processor<T> processor) { this._taskClass = (Class) (processor.taskClass()); this._parallelism = processor.parallelism(); this._description = processor.description(); this._userConf = processor.taskConf(); } /** * Creates a general processor with user specified task logic. * * @param taskClass task implementation class of this processor (shall be a derived class from {@link Task} * @param parallelism, how many initial tasks you want to use * @param description, some text to describe this processor * @param taskConf, Processor specific configuration */ public Processor(Class<T> taskClass, int parallelism, String description, UserConfig taskConf) { this._taskClass = taskClass; this._parallelism = parallelism; this._description = description; this._userConf = taskConf; } public Processor<T> withParallelism(int parallel) { return new Processor<T>(_taskClass, parallel, _description, _userConf); } public Processor<T> withDescription(String desc) { return new Processor<T>(_taskClass, _parallelism, desc, _userConf); } public Processor<T> withConfig(UserConfig conf) { return new Processor<T>(_taskClass, _parallelism, _description, conf); } @Override public int parallelism() { return _parallelism; } @Override public UserConfig taskConf() { return _userConf; } @Override public String description() { return _description; } @Override public Class<? extends org.apache.gearpump.streaming.task.Task> taskClass() { return _taskClass; } /** * reference equal */ @Override public boolean equals(Object obj) { return (this == obj); } }
35.169014
147
0.737085
f65c4805db87d08cf8ef5f76728fc352db623247
5,956
/* * Copyright 2005 Sun Microsystems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.roller.weblogger.planet.ui; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.roller.planet.business.PlanetManager; import org.apache.roller.planet.pojos.Planet; import org.apache.roller.planet.pojos.PlanetGroup; import org.apache.roller.weblogger.business.Weblogger; import org.apache.roller.weblogger.business.WebloggerFactory; import org.apache.struts2.convention.annotation.AllowedMethods; /** * Manage planet groups. */ // TODO: make this work @AllowedMethods({"execute","save","delete"}) public class PlanetGroups extends PlanetUIAction { private static Log log = LogFactory.getLog(PlanetGroups.class); // a bean to manage submitted data private PlanetGroupsBean bean = new PlanetGroupsBean(); // the planet group we are working on private PlanetGroup group = null; public PlanetGroups() { this.actionName = "planetGroups"; this.desiredMenu = "admin"; this.pageTitle = "planetGroups.pagetitle"; } @Override public boolean isWeblogRequired() { return false; } @Override public void myPrepare() { if(getPlanet() != null && getBean().getId() != null) { try { PlanetManager pmgr = WebloggerFactory.getWeblogger().getPlanetManager(); setGroup(pmgr.getGroupById(getBean().getId())); } catch(Exception ex) { log.error("Error looking up planet group - " + getBean().getId(), ex); } } } /** * Show planet groups page. */ public String execute() { // if we are loading an existing group then populate the bean if(getGroup() != null) { getBean().copyFrom(getGroup()); } return LIST; } /** * Save group. */ public String save() { myValidate(); if (!hasActionErrors()) { try { PlanetManager planetManager = WebloggerFactory.getWeblogger().getPlanetManager(); Planet planet = getPlanet(); PlanetGroup planetGroup = getGroup(); if (planetGroup == null) { planetGroup = new PlanetGroup(); planetGroup.setPlanet(planet); getBean().copyTo(planetGroup); log.debug("Adding New Group: " + planetGroup.getHandle()); planetManager.saveNewPlanetGroup(getPlanet(), planetGroup); } else { log.debug("Updating Existing Group: " + planetGroup.getHandle()); getBean().copyTo(planetGroup); planetManager.saveGroup(planetGroup); } WebloggerFactory.getWeblogger().flush(); addMessage("planetGroups.success.saved"); setGroup(null); } catch (Exception ex) { log.error("Error saving planet group - " + getBean().getId(), ex); addError("planetGroups.error.saved"); } } return LIST; } /** * Delete group, reset form */ public String delete() { if(getGroup() != null) { try { PlanetManager pmgr = WebloggerFactory.getWeblogger().getPlanetManager(); pmgr.deleteGroup(getGroup()); WebloggerFactory.getWeblogger().flush(); addMessage("planetSubscription.success.deleted"); setGroup(null); } catch(Exception ex) { log.error("Error deleting planet group - "+getBean().getId()); addError("Error deleting planet group"); } } return LIST; } /** * Validate posted group */ private void myValidate() { if(StringUtils.isEmpty(getBean().getTitle())) { addError("planetGroups.error.title"); } if(StringUtils.isEmpty(getBean().getHandle())) { addError("planetGroups.error.handle"); } if(getBean().getHandle() != null && "all".equals(getBean().getHandle())) { addError("planetGroups.error.nameReserved"); } // make sure duplicate group handles are prevented } public List<PlanetGroup> getGroups() { List<PlanetGroup> displayGroups = new ArrayList<PlanetGroup>(); for (PlanetGroup planetGroup : getPlanet().getGroups()) { // The "all" group is considered a special group and cannot be // managed independently if (!planetGroup.getHandle().equals("all")) { displayGroups.add(planetGroup); } } return displayGroups; } public PlanetGroupsBean getBean() { return bean; } public void setBean(PlanetGroupsBean bean) { this.bean = bean; } public PlanetGroup getGroup() { return group; } public void setGroup(PlanetGroup group) { this.group = group; } }
28.634615
97
0.575218
a68f8d2cb23587fa5257d7415612f0d41c4bc012
1,968
package nl.naturalis.oaipmh.api; import static nl.naturalis.oaipmh.api.Argument.FROM; import static nl.naturalis.oaipmh.api.Argument.METADATA_PREFIX; import static nl.naturalis.oaipmh.api.Argument.RESUMPTION_TOKEN; import static nl.naturalis.oaipmh.api.Argument.SET; import static nl.naturalis.oaipmh.api.Argument.UNTIL; import java.util.EnumSet; import java.util.List; import org.domainobject.util.CollectionUtil; import org.openarchives.oai._2.OAIPMHerrorType; import org.openarchives.oai._2.VerbType; /** * An {@link ArgumentChecker} for the {@link VerbType#LIST_RECORDS LIST_RECORDS} * protocol request. * * @author Ayco Holleman * */ public class ListRecordsArgumentChecker extends ArgumentChecker { private static final EnumSet<Argument> required; private static final EnumSet<Argument> optional; static { /* * NB the Argument.RESUMPTION_TOKEN is not included as either an * optional or required argument. Since it is an "exclusive argument" * (it is mutually exclusive with all other arguments except the verb * argument), we deal with it in the beforeCheck() method. */ required = EnumSet.of(METADATA_PREFIX); optional = EnumSet.of(FROM, UNTIL, SET); } public ListRecordsArgumentChecker() { } @Override protected boolean beforeCheck(EnumSet<Argument> arguments, List<OAIPMHerrorType> errors) { if (arguments.contains(RESUMPTION_TOKEN)) { if (arguments.size() != 1) { EnumSet<Argument> copy = EnumSet.copyOf(arguments); copy.remove(RESUMPTION_TOKEN); String illegal = CollectionUtil.implode(copy, "/"); String fmt = "resumptionToken argument cannot be combined with %s argument"; String msg = String.format(fmt, illegal); errors.add(new BadArgumentError(msg)); } return false; } return true; } @Override protected EnumSet<Argument> getRequiredArguments() { return required; } @Override protected EnumSet<Argument> getOptionalArguments() { return optional; } }
26.958904
89
0.751016
c97a31bfba6cb2ed9e5eff0008508e5e11197dbf
836
/* * Copyright (c) 2004, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0, which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package fromjava.handler_simple.server; import jakarta.jws.*; import jakarta.jws.soap.SOAPBinding; /** */ @jakarta.jws.HandlerChain( name="", file="Hello_handler.xml" ) @WebService(name="Hello", serviceName="HelloService", targetNamespace="urn:test") @SOAPBinding(style=SOAPBinding.Style.RPC) public class HelloService_Impl { @WebMethod public int hello(@WebParam(name="x")int x) { System.out.println("HelloService_Impl received: " + x); return x; } }
24.588235
81
0.706938
57c8543c2bb926ff15ec21b477eb30d32c4a3c6f
3,504
package com.wjwu.wpmain.util; import android.content.Context; import android.text.TextUtils; import android.widget.Toast; import com.wjwu.wpmain.lib_base.R; /** * Created by wjwu on 2015/8/28. */ public class ZToastUtils { private static Toast sToast; private static Toast getToast(Context context) { return Toast.makeText(context, "", Toast.LENGTH_SHORT); } /*** * 显示toast内容 * * @param context * @param message */ public static void toastMessage(Context context, String message) { if (context == null) { return; } if (TextUtils.isEmpty(message)) { sToast = null; return; } if (sToast != null) { sToast.cancel(); sToast = null; } sToast = getToast(context); sToast.setDuration(Toast.LENGTH_SHORT); sToast.setText(message); sToast.show(); } /*** * 显示toast内容 * * @param context * @param message */ public static void toastMessageLong(Context context, String message) { if (context == null) { return; } if (TextUtils.isEmpty(message)) { sToast = null; return; } if (sToast != null) { sToast.cancel(); sToast = null; } sToast = getToast(context); sToast.setDuration(Toast.LENGTH_LONG); sToast.setText(message); sToast.show(); } /*** * 根据资源文件显示toast内容 * * @param context * @param resId */ public static void toastMessage(Context context, int resId) { if (context == null) { return; } if (sToast != null) { sToast.cancel(); sToast = null; } sToast = getToast(context); sToast.setDuration(Toast.LENGTH_SHORT); sToast.setText(resId); sToast.show(); } /*** * 加载失败 * * @param context */ public static void toastLoadingFail(Context context) { if (context != null) { toastMessage(context, R.string.z_toast_loading_fail); } } /*** * 网络不可用 * * @param context */ public static void toastNoNetWork(Context context) { if (context != null) { toastMessage(context, R.string.z_toast_error_no_net); } } /*** * 连接超时 * * @param context */ public static void toastTimeout(Context context) { if (context != null) { toastMessage(context, R.string.z_toast_error_timeout); } } /*** * 未连接 * * @param context */ public static void toastUnunited(Context context) { if (context != null) { toastMessage(context, R.string.z_toast_error_ununited); } } /*** * 数据解析错误 * * @param context */ public static void toastDataError(Context context) { if (context != null) { toastMessage(context, R.string.z_toast_error_dataError); } } /*** * 服务器内部错误 * * @param context */ public static void toastServerError(Context context) { if (context != null) { toastMessage(context, R.string.z_toast_error_server_error); } } /*** * 请求失败 * * @param context */ public static void toastRequestError(Context context) { if (context != null) { toastMessage(context, R.string.z_toast_error_request); } } /*** * 未知错误 * * @param context */ public static void toastUnknownError(Context context) { if (context != null) { toastMessage(context, R.string.z_toast_error_unknown); } } /*** * 获取本地缓存失败 * * @param context */ public static void toastCacheError(Context context) { if (context != null) { toastMessage(context, R.string.z_toast_error_cache); } } /*** * 再按一次退出 * * @param context */ public static void toastExitBefore(Context context) { if (context != null) { toastMessage(context, R.string.z_toast_exit_app); } } }
17.69697
71
0.644692
af37dff40b10dad275e6a307a198a2c41982bdc2
80,430
package edu.indiana.d2i.komadu.query.graph; import edu.indiana.d2i.komadu.ingest.db.BaseDBIngesterImplementer; import edu.indiana.d2i.komadu.query.DetailEnumType; import edu.indiana.d2i.komadu.query.PROVSqlQuery; import edu.indiana.d2i.komadu.query.QueryConstants; import edu.indiana.d2i.komadu.query.QueryException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openprovenance.prov.model.*; import org.openprovenance.prov.model.ActedOnBehalfOf; import org.openprovenance.prov.model.Activity; import org.openprovenance.prov.model.Agent; import org.openprovenance.prov.model.AlternateOf; import org.openprovenance.prov.model.Entity; import org.openprovenance.prov.model.HadMember; import org.openprovenance.prov.model.SpecializationOf; import org.openprovenance.prov.model.Statement; import org.openprovenance.prov.model.Used; import org.openprovenance.prov.model.WasAssociatedWith; import org.openprovenance.prov.model.WasAttributedTo; import org.openprovenance.prov.model.WasDerivedFrom; import org.openprovenance.prov.model.WasEndedBy; import org.openprovenance.prov.model.WasGeneratedBy; import org.openprovenance.prov.model.WasInformedBy; import org.openprovenance.prov.model.WasInvalidatedBy; import org.openprovenance.prov.model.WasStartedBy; import org.openprovenance.prov.xml.*; import org.openprovenance.prov.xml.Other; import org.w3.www.ns.prov.Document; import javax.xml.namespace.QName; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.sql.*; import java.util.*; import java.util.Collection; public class ContextGraphGenerator extends GraphGenerator { private static final Log l = LogFactory.getLog(ContextGraphGenerator.class); /** * Computes the PROV graph using the given workflow uri */ protected Document computeProvGraph(Connection connection, String contextWorkflowURI, DetailEnumType.Enum informationDetailLevel) throws QueryException, SQLException { Document provGraph = null; // first we find out all activities, entities and agents HashMap<String, Activity> activities = getActivities(connection, contextWorkflowURI, informationDetailLevel); HashMap<String, Entity> entities = getEntities(connection, contextWorkflowURI); HashMap<String, Agent> agents = getAgents(connection, contextWorkflowURI, informationDetailLevel); Collection<Activity> activityValues = activities.values(); Collection<Entity> entityValues = entities.values(); Collection<Agent> agentValues = agents.values(); // list of relationships List<Statement> relationships = new ArrayList<Statement>(); // adding different kinds of relationships // activity-entity relationships addUsages(connection, activities, entities, relationships, contextWorkflowURI, informationDetailLevel); addGenerations(connection, activities, entities, relationships, contextWorkflowURI, informationDetailLevel); addStarts(connection, activities, entities, relationships, contextWorkflowURI, informationDetailLevel); addEnds(connection, activities, entities, relationships, contextWorkflowURI, informationDetailLevel); addInvalidations(connection, activities, entities, relationships, contextWorkflowURI, informationDetailLevel); // agent-activity relationships addAssociations(connection, activities, agents, relationships, contextWorkflowURI, informationDetailLevel); // agent-entity relationships addAttributions(connection, agents, entities, relationships, contextWorkflowURI, informationDetailLevel); // agent-agent relationships addDelegations(connection, agents, relationships, contextWorkflowURI, informationDetailLevel); // activity-activity relationships addCommunications(connection, activities, relationships, contextWorkflowURI, informationDetailLevel); // entity-entity relationships addDerivations(connection, entities, relationships, contextWorkflowURI, informationDetailLevel); addAlternates(connection, entities, relationships); addSpecializations(connection, entities, relationships); addMemberships(connection, entities, relationships); // create the PROV graph using prov-toolbox library's api org.openprovenance.prov.model.Document graph = pFactory.newDocument( activityValues.toArray(new Activity[activityValues.size()]), entityValues.toArray(new Entity[entityValues.size()]), agentValues.toArray(new Agent[agentValues.size()]), relationships.toArray(new Statement[relationships.size()])); graph.setNamespace(Namespace.gatherNamespaces(graph)); /* * Now we have to serialize the created graph and parse it to the Xmlbean type that * we want to return */ ProvSerialiser serializer = ProvSerialiser.getThreadProvSerialiser(); try { ByteArrayOutputStream os = new ByteArrayOutputStream(); serializer.serialiseDocument(os, graph, true); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); provGraph = org.w3.www.ns.prov.Document.Factory.parse(is); } catch (Exception e) { l.error("Exiting getProvGraph() with SQL errors", e); } return provGraph; } private HashMap<String, Activity> getActivities(Connection connection, String contextWorkflowURI, DetailEnumType.Enum informationDetailLevel) throws SQLException { assert (connection != null); assert (contextWorkflowURI != null); l.debug("Entering getActivities()"); HashMap<String, Activity> activities = new HashMap<String, Activity>(); PreparedStatement getActivitiesStmt = null; PreparedStatement getRegActivitiesStmt = null; ResultSet actResult = null; ResultSet regActResult = null; HashMap<String, String> visitedRegEntity = new HashMap<String, String>(); try { getActivitiesStmt = connection .prepareStatement(PROVSqlQuery.GET_ACTIVITIES_BY_CONTEXT_WORKFLOW_URI); getActivitiesStmt.setString(1, contextWorkflowURI); getActivitiesStmt.setString(2, contextWorkflowURI); actResult = getActivitiesStmt.executeQuery(); // loop through all activities and create corresponding Activity elements while (actResult.next()) { int timestep; String activityType = actResult.getString("activity_type"); int instanceOfID = actResult.getInt("instance_of"); /* create the activity ID */ String activityID = QueryConstants.ACTIVITY_IDENTIFIER + actResult.getInt("activity_id"); // create new prov activity Activity activity = pFactory.newActivity(getIdQName(activityID)); // add current activity into the list activities.put(activityID, activity); if (informationDetailLevel != null && informationDetailLevel .equals(DetailEnumType.FINE)) { // add activity type attribute. note that this is not the prov:type Other typeAtt = pFactory.newOther(getKomaduAttQName("type"), activityType, Name.QNAME_XSD_STRING); pFactory.addAttribute(activity, typeAtt); if (activityType.equals(BaseDBIngesterImplementer.ActivityTypeEnum.WORKFLOW.toString())) { String workflowID = actResult.getString("activity_uri"); // add workflow ID as a Komadu Attribute Other workflowIDAtt = pFactory.newOther(getKomaduAttQName("workflowID"), workflowID, Name.QNAME_XSD_STRING); pFactory.addAttribute(activity, workflowIDAtt); } else if (activityType.equals(BaseDBIngesterImplementer.ActivityTypeEnum.SERVICE.toString()) || activityType.equals(BaseDBIngesterImplementer.ActivityTypeEnum.METHOD.toString())) { String workflowID = actResult.getString("context_workflow_uri"); String serviceID = actResult.getString("activity_uri"); String workflowNodeID = actResult.getString("context_wf_node_id_token"); timestep = actResult.getInt("timestep"); Other workflowIDAtt = pFactory.newOther(getKomaduAttQName("workflowID"), workflowID, Name.QNAME_XSD_STRING); pFactory.addAttribute(activity, workflowIDAtt); Other workflowNodeIdAtt = pFactory.newOther(getKomaduAttQName("workflowNodeID"), workflowNodeID, Name.QNAME_XSD_STRING); pFactory.addAttribute(activity, workflowNodeIdAtt); Other timestepAtt = pFactory.newOther(getKomaduAttQName("timestep"), timestep, Name.QNAME_XSD_INT); pFactory.addAttribute(activity, timestepAtt); if (activityType.equals(BaseDBIngesterImplementer.ActivityTypeEnum.METHOD.toString())) { serviceID = actResult.getString("context_service_uri"); String methodID = actResult.getString("activity_uri"); Other methodIDAtt = pFactory.newOther(getKomaduAttQName("methodID"), methodID, Name.QNAME_XSD_STRING); pFactory.addAttribute(activity, methodIDAtt); } Other serviceIDAtt = pFactory.newOther(getKomaduAttQName("serviceID"), serviceID, Name.QNAME_XSD_STRING); pFactory.addAttribute(activity, serviceIDAtt); } // add external attributes too addCustomAttributes(PROVSqlQuery.GET_EXE_ACTIVITY_ATTRIBUTES_BY_ID, activityID, activity, connection); } if (instanceOfID > 0) { if (visitedRegEntity.get(QueryConstants.REG_ACTIVITY_IDENTIFIER + instanceOfID) == null) { visitedRegEntity.put(QueryConstants.REG_ACTIVITY_IDENTIFIER + instanceOfID, QueryConstants.REG_ACTIVITY_IDENTIFIER + instanceOfID); getRegActivitiesStmt = connection .prepareStatement(PROVSqlQuery.GET_REG_ACTIVITIES_BY_ID); getRegActivitiesStmt.setString(1, instanceOfID + ""); regActResult = getRegActivitiesStmt.executeQuery(); while (regActResult.next()) { /* create the activity ID */ activityID = QueryConstants.REG_ACTIVITY_IDENTIFIER + instanceOfID; // create new prov activity Activity regActivity = pFactory.newActivity(getIdQName(activityID)); // add current activity into the list activities.put(activityID, regActivity); if (informationDetailLevel != null && informationDetailLevel .equals(DetailEnumType.FINE)) { String regActivityType = regActResult.getString("activity_type"); String regActivityName = regActResult.getString("activity_uri"); String regActivityVersion = regActResult.getString("version"); String regActivityCreationTime = regActResult.getString("creation_time"); Other activityTypeAtt = pFactory.newOther(getKomaduAttQName("type"), regActivityType, Name.QNAME_XSD_STRING); pFactory.addAttribute(regActivity, activityTypeAtt); Other activityNameAtt = pFactory.newOther(getKomaduAttQName("name"), regActivityName, Name.QNAME_XSD_STRING); pFactory.addAttribute(regActivity, activityNameAtt); Other activityVersionAtt = pFactory.newOther(getKomaduAttQName("version"), regActivityVersion, Name.QNAME_XSD_STRING); pFactory.addAttribute(regActivity, activityVersionAtt); Other activityTimeAtt = pFactory.newOther(getKomaduAttQName("creationTime"), regActivityCreationTime, Name.QNAME_XSD_STRING); pFactory.addAttribute(regActivity, activityTimeAtt); // TODO : Add reg_activity_attributes } } } } } l.debug("Exiting getActivities()"); return activities; } catch (SQLException e) { l.error("Exiting getActivities() with errors", e); // return an empty array return new HashMap<String, Activity>(); } finally { if (actResult != null) { actResult.close(); } if (regActResult != null) { regActResult.close(); } if (getActivitiesStmt != null) { getActivitiesStmt.close(); } if (getRegActivitiesStmt != null) { getRegActivitiesStmt.close(); } } } private HashMap<String, Entity> getEntities(Connection connection, String contextWorkflowURI) throws SQLException { assert (connection != null); assert (contextWorkflowURI != null); l.debug("Entering getEntities()"); /* * There may be some data products that may be both produced and * consumed hence keep a list of urls which are already added */ ArrayList<String> uris = new ArrayList<String>(); // a list of entities created HashMap<String, Entity> provEntities = new HashMap<String, Entity>(); PreparedStatement getDataObjectStmt = null; ResultSet res = null; try { /* get all the files that were produced */ getDataObjectStmt = connection.prepareStatement(PROVSqlQuery.GET_DATA_FILES_GENERATED); getDataObjectStmt.setString(1, contextWorkflowURI); getDataObjectStmt.setString(2, contextWorkflowURI); res = getDataObjectStmt.executeQuery(); while (res.next()) { String fileURI = res.getString(1); String size = res.getString(2); String fileID = res.getString(3); // add the current entity if it is not already considered if (!uris.contains(fileURI)) { Entity e = newEntity(QueryConstants.FILE_IDENTIFIER + fileID, fileURI, QueryConstants.ENTITY_FILE); // add size as an additional attribute Other sizeAtt = pFactory.newOther(getKomaduAttQName("size"), size, Name.QNAME_XSD_STRING); pFactory.addAttribute(e, sizeAtt); provEntities.put(fileID, e); uris.add(fileURI); } } if (getDataObjectStmt != null) { getDataObjectStmt.close(); getDataObjectStmt = null; } if (res != null) { res.close(); res = null; } /* get all the blocks that were produced */ getDataObjectStmt = connection.prepareStatement(PROVSqlQuery.GET_DATA_BLOCKS_GENERATED); getDataObjectStmt.setString(1, contextWorkflowURI); getDataObjectStmt.setString(2, contextWorkflowURI); res = getDataObjectStmt.executeQuery(); while (res.next()) { String blockID = res.getString(1); String blockURI = res.getString(2); String blockSize = res.getString(3); String blockContent = res.getString(4); if (!uris.contains(blockURI)) { Entity e = newEntity(QueryConstants.BLOCK_IDENTIFIER + blockID, blockURI, QueryConstants.ENTITY_BLOCK); // add size as an additional attribute Other sizeAtt = pFactory.newOther(getKomaduAttQName("size"), blockSize, Name.QNAME_XSD_STRING); pFactory.addAttribute(e, sizeAtt); // add block content as an additional attribute Other contentAtt = pFactory.newOther(getKomaduAttQName("content"), blockContent, Name.QNAME_XSD_STRING); pFactory.addAttribute(e, contentAtt); provEntities.put(blockID, e); uris.add(blockURI); } } if (getDataObjectStmt != null) { getDataObjectStmt.close(); getDataObjectStmt = null; } if (res != null) { res.close(); res = null; } getDataObjectStmt = connection .prepareStatement(PROVSqlQuery.GET_DATA_COLLECTIONS_GENERATED); getDataObjectStmt.setString(1, contextWorkflowURI); getDataObjectStmt.setString(2, contextWorkflowURI); res = getDataObjectStmt.executeQuery(); while (res.next()) { String collectionID = res.getString(1); String collectionURI = res.getString(2); if (!uris.contains(collectionURI)) { Entity e = newEntity(QueryConstants.COLLECTION_IDENTIFIER + collectionID, collectionURI, QueryConstants.ENTITY_COLLECTION); provEntities.put(collectionID, e); uris.add(collectionURI); } } if (getDataObjectStmt != null) { getDataObjectStmt.close(); getDataObjectStmt = null; } if (res != null) { res.close(); res = null; } // TODO : Read Generic Entity /* get all the files that were consumed */ getDataObjectStmt = connection.prepareStatement(PROVSqlQuery.GET_DATA_FILES_USED); getDataObjectStmt.setString(1, contextWorkflowURI); getDataObjectStmt.setString(2, contextWorkflowURI); res = getDataObjectStmt.executeQuery(); while (res.next()) { String fileURI = res.getString(1); String size = res.getString(2); String fileID = res.getString(3); // add the current entity if it is not already considered if (!uris.contains(fileURI)) { Entity e = newEntity(QueryConstants.FILE_IDENTIFIER + fileID, fileURI, QueryConstants.ENTITY_FILE); // add size as an additional attribute Other sizeAtt = pFactory.newOther(getKomaduAttQName("size"), size, Name.QNAME_XSD_STRING); pFactory.addAttribute(e, sizeAtt); provEntities.put(fileID, e); uris.add(fileURI); } } if (getDataObjectStmt != null) { getDataObjectStmt.close(); getDataObjectStmt = null; } if (res != null) { res.close(); res = null; } /* get all the blocks that were consumed */ getDataObjectStmt = connection.prepareStatement(PROVSqlQuery.GET_DATA_BLOCKS_USED); getDataObjectStmt.setString(1, contextWorkflowURI); getDataObjectStmt.setString(2, contextWorkflowURI); res = getDataObjectStmt.executeQuery(); while (res.next()) { String blockID = res.getString(1); String blockURI = res.getString(2); String blockSize = res.getString(3); String blockContent = res.getString(4); if (!uris.contains(blockURI)) { Entity e = newEntity(QueryConstants.BLOCK_IDENTIFIER + blockID, blockURI, QueryConstants.ENTITY_BLOCK); // add size as an additional attribute Other sizeAtt = pFactory.newOther(getKomaduAttQName("size"), blockSize, Name.QNAME_XSD_STRING); pFactory.addAttribute(e, sizeAtt); // add block content as an additional attribute Other contentAtt = pFactory.newOther(getKomaduAttQName("content"), blockContent, Name.QNAME_XSD_STRING); pFactory.addAttribute(e, contentAtt); provEntities.put(blockID, e); uris.add(blockURI); } } if (getDataObjectStmt != null) { getDataObjectStmt.close(); getDataObjectStmt = null; } if (res != null) { res.close(); res = null; } getDataObjectStmt = connection .prepareStatement(PROVSqlQuery.GET_DATA_COLLECTIONS_USED); getDataObjectStmt.setString(1, contextWorkflowURI); getDataObjectStmt.setString(2, contextWorkflowURI); res = getDataObjectStmt.executeQuery(); while (res.next()) { String collectionID = res.getString(1); String collectionURI = res.getString(2); if (!uris.contains(collectionURI)) { Entity e = newEntity(QueryConstants.COLLECTION_IDENTIFIER + collectionID, collectionURI, QueryConstants.ENTITY_COLLECTION); provEntities.put(collectionID, e); uris.add(collectionURI); } } if (getDataObjectStmt != null) { getDataObjectStmt.close(); getDataObjectStmt = null; } if (res != null) { res.close(); res = null; } // TODO : Here we only have considered usages and generations to find activities // TODO : But we have to consider start, end and invalidation too l.debug("Exiting getEntities() with success"); // convert the list into an array and return return provEntities; } catch (SQLException e) { l.error("Exiting getEntities() with errors"); l.error(e.toString()); return new HashMap<String, Entity>(); } finally { if (getDataObjectStmt != null) { getDataObjectStmt.close(); } if (res != null) { res.close(); } } } private HashMap<String, Agent> getAgents(Connection connection, String contextWorkflowURI, DetailEnumType.Enum informationDetailLevel) throws SQLException { assert (connection != null); assert (contextWorkflowURI != null); l.debug("Entering getAgents()"); HashMap<String, Agent> agents = new HashMap<String, Agent>(); PreparedStatement getAgentsStmt = null; ResultSet result = null; try { if (informationDetailLevel != null && informationDetailLevel .equals(DetailEnumType.FINE)) { getAgentsStmt = connection .prepareStatement(PROVSqlQuery.GET_AGENTS_BY_ACTIVITY_URI); getAgentsStmt.setString(1, contextWorkflowURI); getAgentsStmt.setString(2, contextWorkflowURI); result = getAgentsStmt.executeQuery(); while (result.next()) { String id = result.getString("agent_id"); String uri = result.getString("agent_uri"); String type = result.getString("agent_type"); String name = result.getString("name"); String affiliation = result.getString("affiliation"); String email = result.getString("email"); // TODO : Handle role and location later String role = result.getString("role"); String location = result.getString("location"); Agent a = newAgent(QueryConstants.AGENT_IDENTIFIER + id, uri, type); // add name as an additional attribute if (name != null) { Other nameAtt = pFactory.newOther(getKomaduAttQName("name"), name, Name.QNAME_XSD_STRING); pFactory.addAttribute(a, nameAtt); } // add affiliation as an additional attribute if (affiliation != null) { Other affiliationAtt = pFactory.newOther(getKomaduAttQName("affiliation"), affiliation, Name.QNAME_XSD_STRING); pFactory.addAttribute(a, affiliationAtt); } // add email as an additional attribute if (email != null) { Other emailAtt = pFactory.newOther(getKomaduAttQName("email"), email, Name.QNAME_XSD_STRING); pFactory.addAttribute(a, emailAtt); } // add the new agent into list agents.put(QueryConstants.AGENT_IDENTIFIER + id, a); // TODO : Add other kinds of Agents if any } } l.debug("Exiting getOPMAgents() with success"); // convert the list of agents to an array and return return agents; } catch (SQLException e) { l.error("Exiting getOPMAgents() with errors"); l.error(e.toString()); return null; } finally { if (getAgentsStmt != null) { getAgentsStmt.close(); } if (result != null) { result.close(); } } } private void addUsages(Connection connection, HashMap<String, Activity> activities, HashMap<String, Entity> entities, List<Statement> relationships, String contextWorkflowURI, DetailEnumType.Enum informationDetailLevel) throws SQLException { assert (connection != null); assert (contextWorkflowURI != null); l.debug("Entering addUsages()"); PreparedStatement usedStmt = null; ResultSet resultSet = null; try { usedStmt = connection.prepareStatement(PROVSqlQuery.GET_PROV_USAGES); usedStmt.setString(1, contextWorkflowURI); usedStmt.setString(2, contextWorkflowURI); resultSet = usedStmt.executeQuery(); while (resultSet.next()) { String usageID = resultSet.getString(1); String activityID = QueryConstants.ACTIVITY_IDENTIFIER + resultSet.getString(2); String entityID = resultSet.getString(3); String location = resultSet.getString(4); java.sql.Timestamp usedTime = resultSet.getTimestamp(5); Activity usedActivity = activities.get(activityID); Entity usedEntity = entities.get(entityID); Used used = pFactory.newUsed(getIdQName(usageID), usedActivity.getId(), usedEntity.getId()); if (informationDetailLevel != null && informationDetailLevel.equals(DetailEnumType.FINE)) { // add attributes if (location != null) { used.getLocation().add(pFactory.newLocation(location, Name.QNAME_XSD_STRING)); // TODO : check Role } if (usedTime != null) { Other timeAtt = pFactory.newOther(getKomaduAttQName("used-time"), usedTime, Name.QNAME_XSD_DATETIME); pFactory.addAttribute(used, timeAtt); } // add external attributes too addCustomAttributes(PROVSqlQuery.GET_EXE_USAGE_ATTRIBUTES_BY_ID, usageID, used, connection); } // add the used element into the list of relationships relationships.add(used); } l.debug("addUsages() successful"); } catch (SQLException e) { l.error("Exiting addUsages() with error"); l.error(e.toString()); } finally { if (usedStmt != null) { usedStmt.close(); } if (resultSet != null) { resultSet.close(); } } } private void addGenerations(Connection connection, HashMap<String, Activity> activities, HashMap<String, Entity> entities, List<Statement> relationships, String contextWorkflowURI, DetailEnumType.Enum informationDetailLevel) throws SQLException { assert (connection != null); assert (contextWorkflowURI != null); l.debug("Entering addGenerations()"); PreparedStatement generatedStmt = null; ResultSet resultSet = null; try { generatedStmt = connection.prepareStatement(PROVSqlQuery.GET_PROV_GENERATIONS); generatedStmt.setString(1, contextWorkflowURI); generatedStmt.setString(2, contextWorkflowURI); resultSet = generatedStmt.executeQuery(); while (resultSet.next()) { String genID = resultSet.getString(1); String activityID = QueryConstants.ACTIVITY_IDENTIFIER + resultSet.getString(2); String entityID = resultSet.getString(3); String location = resultSet.getString(4); java.sql.Timestamp usedTime = resultSet.getTimestamp(5); Activity activity = activities.get(activityID); Entity entity = entities.get(entityID); if (activity == null || entity == null) { l.error("Activity or Entity is null. Inconsistent WasGeneratedBy relationship.."); return; } WasGeneratedBy wasGeneratedBy = pFactory.newWasGeneratedBy(getIdQName(genID), entity.getId(), activity.getId()); if (informationDetailLevel != null && informationDetailLevel.equals(DetailEnumType.FINE)) { // add attributes if (location != null) { wasGeneratedBy.getLocation().add(pFactory.newLocation(location, Name.QNAME_XSD_STRING)); // TODO : check Role } if (usedTime != null) { Other timeAtt = pFactory.newOther(getKomaduAttQName("generation-time"), usedTime, Name.QNAME_XSD_DATETIME); pFactory.addAttribute(wasGeneratedBy, timeAtt); } // add external attributes too addCustomAttributes(PROVSqlQuery.GET_EXE_GENERATION_ATTRIBUTES_BY_ID, genID, wasGeneratedBy, connection); } // add the used element into the list of relationships relationships.add(wasGeneratedBy); } l.debug("addGenerations() successful"); } catch (SQLException e) { l.error("Exiting addGenerations() with error"); l.error(e.toString()); } finally { if (generatedStmt != null) { generatedStmt.close(); } if (resultSet != null) { resultSet.close(); } } } private void addStarts(Connection connection, HashMap<String, Activity> activities, HashMap<String, Entity> entities, List<Statement> relationships, String contextWorkflowURI, DetailEnumType.Enum informationDetailLevel) throws SQLException { assert (connection != null); assert (contextWorkflowURI != null); l.debug("Entering addStarts()"); PreparedStatement stmt = null; ResultSet resultSet = null; try { stmt = connection.prepareStatement(PROVSqlQuery.GET_PROV_STARTS); stmt.setString(1, contextWorkflowURI); stmt.setString(2, contextWorkflowURI); resultSet = stmt.executeQuery(); while (resultSet.next()) { String startID = resultSet.getString(1); String activityID = QueryConstants.ACTIVITY_IDENTIFIER + resultSet.getString(2); String entityID = resultSet.getString(3); String location = resultSet.getString(4); java.sql.Timestamp usedTime = resultSet.getTimestamp(5); Activity activity = activities.get(activityID); Entity entity = entities.get(entityID); if (activity == null || entity == null) { l.error("Activity or Entity is null. Inconsistent WasStartedBy relationship.."); return; } WasStartedBy wasStartedBy = pFactory.newWasStartedBy(getIdQName(startID), activity.getId(), entity.getId(), null); // TODO : check starter if (informationDetailLevel != null && informationDetailLevel.equals(DetailEnumType.FINE)) { // add attributes if (location != null) { wasStartedBy.getLocation().add(pFactory.newLocation(location, Name.QNAME_XSD_STRING)); // TODO : check Role } if (usedTime != null) { Other timeAtt = pFactory.newOther(getKomaduAttQName("start-time"), usedTime, Name.QNAME_XSD_DATETIME); pFactory.addAttribute(wasStartedBy, timeAtt); } // add external attributes too addCustomAttributes(PROVSqlQuery.GET_EXE_START_ATTRIBUTES_BY_ID, startID, wasStartedBy, connection); } // add the used element into the list of relationships relationships.add(wasStartedBy); } l.debug("addStarts() successful"); } catch (SQLException e) { l.error("Exiting addStarts() with error"); l.error(e.toString()); } finally { if (stmt != null) { stmt.close(); } if (resultSet != null) { resultSet.close(); } } } private void addEnds(Connection connection, HashMap<String, Activity> activities, HashMap<String, Entity> entities, List<Statement> relationships, String contextWorkflowURI, DetailEnumType.Enum informationDetailLevel) throws SQLException { assert (connection != null); assert (contextWorkflowURI != null); l.debug("Entering addEnds()"); PreparedStatement stmt = null; ResultSet resultSet = null; try { stmt = connection.prepareStatement(PROVSqlQuery.GET_PROV_ENDS); stmt.setString(1, contextWorkflowURI); stmt.setString(2, contextWorkflowURI); resultSet = stmt.executeQuery(); while (resultSet.next()) { String endID = resultSet.getString(1); String activityID = QueryConstants.ACTIVITY_IDENTIFIER + resultSet.getString(2); String entityID = resultSet.getString(3); String location = resultSet.getString(4); java.sql.Timestamp endTime = resultSet.getTimestamp(5); Activity activity = activities.get(activityID); Entity entity = entities.get(entityID); if (activity == null || entity == null) { l.error("Activity or Entity is null. Inconsistent WasEndedBy relationship.."); return; } WasEndedBy wasEndedBy = pFactory.newWasEndedBy(getIdQName(endID), activity.getId(), entity.getId(), null); // TODO : check starter if (informationDetailLevel != null && informationDetailLevel.equals(DetailEnumType.FINE)) { // add attributes if (location != null) { wasEndedBy.getLocation().add(pFactory.newLocation(location, Name.QNAME_XSD_STRING)); // TODO : check Role } if (endTime != null) { Other timeAtt = pFactory.newOther(getKomaduAttQName("end-time"), endTime, Name.QNAME_XSD_DATETIME); pFactory.addAttribute(wasEndedBy, timeAtt); } // add external attributes too addCustomAttributes(PROVSqlQuery.GET_EXE_END_ATTRIBUTES_BY_ID, endID, wasEndedBy, connection); } // add the used element into the list of relationships relationships.add(wasEndedBy); } l.debug("addEnds() successful"); } catch (SQLException e) { l.error("Exiting addEnds() with error"); l.error(e.toString()); } finally { if (stmt != null) { stmt.close(); } if (resultSet != null) { resultSet.close(); } } } private void addInvalidations(Connection connection, HashMap<String, Activity> activities, HashMap<String, Entity> entities, List<Statement> relationships, String contextWorkflowURI, DetailEnumType.Enum informationDetailLevel) throws SQLException { assert (connection != null); assert (contextWorkflowURI != null); l.debug("Entering addInvalidations()"); PreparedStatement stmt = null; ResultSet resultSet = null; try { stmt = connection.prepareStatement(PROVSqlQuery.GET_PROV_INVALIDATIONS); stmt.setString(1, contextWorkflowURI); stmt.setString(2, contextWorkflowURI); resultSet = stmt.executeQuery(); while (resultSet.next()) { String invalidationID = resultSet.getString(1); String activityID = QueryConstants.ACTIVITY_IDENTIFIER + resultSet.getString(2); String entityID = resultSet.getString(3); String location = resultSet.getString(4); java.sql.Timestamp usedTime = resultSet.getTimestamp(5); Activity activity = activities.get(activityID); Entity entity = entities.get(entityID); if (activity == null || entity == null) { l.error("Activity or Entity is null. Inconsistent WasInvalidatedBy relationship.."); return; } WasInvalidatedBy wasInvalidatedBy = pFactory.newWasInvalidatedBy(getIdQName(invalidationID), entity.getId(), activity.getId()); // TODO : check starter if (informationDetailLevel != null && informationDetailLevel.equals(DetailEnumType.FINE)) { // add attributes if (location != null) { wasInvalidatedBy.getLocation().add(pFactory.newLocation(location, Name.QNAME_XSD_STRING)); // TODO : check Role } if (usedTime != null) { Other timeAtt = pFactory.newOther(getKomaduAttQName("invalidation-time"), usedTime, Name.QNAME_XSD_DATETIME); pFactory.addAttribute(wasInvalidatedBy, timeAtt); } // add external attributes too addCustomAttributes(PROVSqlQuery.GET_EXE_INVALIDATION_ATTRIBUTES_BY_ID, invalidationID, wasInvalidatedBy, connection); } // add the used element into the list of relationships relationships.add(wasInvalidatedBy); } l.debug("addInvalidations() successful"); } catch (SQLException e) { l.error("Exiting addInvalidations() with error"); l.error(e.toString()); } finally { if (stmt != null) { stmt.close(); } if (resultSet != null) { resultSet.close(); } } } private void addAssociations(Connection connection, HashMap<String, Activity> activities, HashMap<String, Agent> agents, List<Statement> relationships, String contextWorkflowURI, DetailEnumType.Enum informationDetailLevel) throws SQLException { assert (connection != null); assert (contextWorkflowURI != null); l.debug("Entering addAssociations()"); PreparedStatement stmt = null; ResultSet resultSet = null; try { stmt = connection.prepareStatement(PROVSqlQuery.GET_PROV_ASSOCIATIONS); stmt.setString(1, contextWorkflowURI); stmt.setString(2, contextWorkflowURI); resultSet = stmt.executeQuery(); while (resultSet.next()) { String associationID = resultSet.getString(1); String activityID = QueryConstants.ACTIVITY_IDENTIFIER + resultSet.getString(2); String agentID = resultSet.getString(3); String planID = resultSet.getString(4); Activity activity = activities.get(activityID); Agent agent = agents.get(QueryConstants.AGENT_IDENTIFIER + agentID); if (activity == null || agent == null) { l.error("Activity or Agent is null. Inconsistent WasAssociatedWith relationship.."); return; } WasAssociatedWith wasAssociatedWith = pFactory.newWasAssociatedWith(getIdQName(associationID), activity, agent); if (informationDetailLevel != null && informationDetailLevel.equals(DetailEnumType.FINE)) { // add attributes if (planID != null) { // TODO : handle plan } // add external attributes too addCustomAttributes(PROVSqlQuery.GET_EXE_ASSOCIATION_ATTRIBUTES_BY_ID, associationID, wasAssociatedWith, connection); } // add the used element into the list of relationships relationships.add(wasAssociatedWith); } l.debug("addAssociations() successful"); } catch (SQLException e) { l.error("Exiting addAssociations() with error", e); } finally { if (stmt != null) { stmt.close(); } if (resultSet != null) { resultSet.close(); } } } private void addAttributions(Connection connection, HashMap<String, Agent> agents, HashMap<String, Entity> entities, List<Statement> relationships, String contextWorkflowURI, DetailEnumType.Enum informationDetailLevel) throws SQLException { assert (connection != null); assert (contextWorkflowURI != null); l.debug("Entering addAttributions()"); PreparedStatement stmt = null; ResultSet resultSet = null; try { // this query will return the attributions which are related to already considered agents // TODO : We have to consider attributions which are related to already considered entities too, that we introduce new Agents stmt = connection.prepareStatement(PROVSqlQuery.GET_PROV_ATTRIBUTIONS_THROUGH_ASSOCIATIONS); stmt.setString(1, contextWorkflowURI); stmt.setString(2, contextWorkflowURI); resultSet = stmt.executeQuery(); while (resultSet.next()) { String attributionID = resultSet.getString(1); String agentID = resultSet.getString(2); String entityID = resultSet.getString(3); Agent agent = agents.get(QueryConstants.AGENT_IDENTIFIER + agentID); Entity entity = entities.get(entityID); // entity may not already exists. that happens when the entity is only connected to the // graph through the attribution if (entity == null) { entity = createEntity(entityID, connection); } WasAttributedTo wasAttributedTo = pFactory.newWasAttributedTo(getIdQName(attributionID), entity.getId(), agent.getId(), new ArrayList<Attribute>()); if (informationDetailLevel != null && informationDetailLevel.equals(DetailEnumType.FINE)) { // add external attributes too addCustomAttributes(PROVSqlQuery.GET_EXE_ATTRIBUTION_ATTRIBUTES_BY_ID, attributionID, wasAttributedTo, connection); } // add the used element into the list of relationships relationships.add(wasAttributedTo); } l.debug("addAttributions() successful"); } catch (SQLException e) { l.error("Exiting addAttributions() with error"); l.error(e.toString()); } finally { if (stmt != null) { stmt.close(); } if (resultSet != null) { resultSet.close(); } } } private void addDelegations(Connection connection, HashMap<String, Agent> agents, List<Statement> relationships, String contextWorkflowURI, DetailEnumType.Enum informationDetailLevel) throws SQLException { assert (connection != null); assert (contextWorkflowURI != null); l.debug("Entering addDelegations()"); PreparedStatement stmt = null; ResultSet resultSet = null; try { /** * This query finds delegations in which the responsible agent is someone already associated with the * activity identified by the given workflow_uri. */ stmt = connection.prepareStatement(PROVSqlQuery.GET_PROV_DELEGATIONS); stmt.setString(1, contextWorkflowURI); stmt.setString(2, contextWorkflowURI); resultSet = stmt.executeQuery(); while (resultSet.next()) { String delegationID = resultSet.getString(1); String delAgentID = resultSet.getString(2); String resAgentID = resultSet.getString(3); String activityID = resultSet.getString(4); // properties of the new delegate agent // TODO : create a method to be called from here and getAgents() String uri = resultSet.getString("agent_uri"); String type = resultSet.getString("agent_type"); String name = resultSet.getString("name"); String affiliation = resultSet.getString("affiliation"); String email = resultSet.getString("email"); // TODO : Handle role and location later String role = resultSet.getString("role"); String location = resultSet.getString("location"); Agent delAgent = agents.get(QueryConstants.AGENT_IDENTIFIER + delAgentID); Agent resAgent = agents.get(QueryConstants.AGENT_IDENTIFIER + resAgentID); if (delAgent == null) { delAgent = newAgent(QueryConstants.AGENT_IDENTIFIER + delAgentID, uri, type); // add name as an additional attribute if (name != null) { Other nameAtt = pFactory.newOther(getKomaduAttQName("name"), name, Name.QNAME_XSD_STRING); pFactory.addAttribute(delAgent, nameAtt); } // add affiliation as an additional attribute if (affiliation != null) { Other affiliationAtt = pFactory.newOther(getKomaduAttQName("affiliation"), affiliation, Name.QNAME_XSD_STRING); pFactory.addAttribute(delAgent, affiliationAtt); } // add email as an additional attribute if (email != null) { Other emailAtt = pFactory.newOther(getKomaduAttQName("email"), email, Name.QNAME_XSD_STRING); pFactory.addAttribute(delAgent, emailAtt); } agents.put(QueryConstants.AGENT_IDENTIFIER + delAgentID, delAgent); } ActedOnBehalfOf behalfOf = pFactory.newActedOnBehalfOf(getIdQName(delegationID), delAgent.getId(), resAgent.getId()); if (informationDetailLevel != null && informationDetailLevel.equals(DetailEnumType.FINE)) { // add external attributes too addCustomAttributes(PROVSqlQuery.GET_EXE_DELEGATION_ATTRIBUTES_BY_ID, delegationID, behalfOf, connection); } // add the used element into the list of relationships relationships.add(behalfOf); } l.debug("addDelegations() successful"); } catch (SQLException e) { l.error("Exiting addDelegations() with error"); l.error(e.toString()); } finally { if (stmt != null) { stmt.close(); } if (resultSet != null) { resultSet.close(); } } } private void addCommunications(Connection connection, HashMap<String, Activity> activities, List<Statement> relationships, String contextWorkflowURI, DetailEnumType.Enum informationDetailLevel) throws SQLException { assert (connection != null); assert (contextWorkflowURI != null); l.debug("Entering addCommunications()"); PreparedStatement stmt = null; ResultSet resultSet = null; /** * There are 2 possible cases here * 1. activity1 generates entity1 and activity2 uses entity1. We have to build this relationship * by looking at generations and usages. * 2. activity1 invokes activity2. There should be a separate notification and a relation in the * database to handle this case. */ try { // Case 1 stmt = connection.prepareStatement(PROVSqlQuery.GET_PROV_COMMUNICATIONS_BY_ENTITY); stmt.setString(1, contextWorkflowURI); stmt.setString(2, contextWorkflowURI); resultSet = stmt.executeQuery(); while (resultSet.next()) { String informantID = resultSet.getString("gen_id"); // activity by which the entity was generated String informedID = resultSet.getString("used_id"); // activity by which the entity was used Activity infromantActivity = activities.get(informantID); Activity infromedActivity = activities.get(informedID); WasInformedBy informedBy = pFactory.newWasInformedBy(infromantActivity, infromedActivity); // add the used element into the list of relationships relationships.add(informedBy); } if (stmt != null) { stmt.close(); stmt = null; } if (resultSet != null) { resultSet.close(); resultSet = null; } // Case 2 stmt = connection.prepareStatement(PROVSqlQuery.GET_PROV_COMMUNICATIONS); stmt.setString(1, contextWorkflowURI); stmt.setString(2, contextWorkflowURI); resultSet = stmt.executeQuery(); while (resultSet.next()) { String communicationID = resultSet.getString(1); String informedID = resultSet.getString(2); String informantID = resultSet.getString(3); Activity informedActivity = activities.get(informedID); Activity informantActivity = activities.get(informantID); if (informedActivity == null) { informedActivity = createActivityById(connection, informedID, informationDetailLevel); if (informedActivity != null) { activities.put(QueryConstants.ACTIVITY_IDENTIFIER + informedID, informedActivity); } else { l.error("No activity found. Invalid Activity ID : " + informedID); continue; } } if (informantActivity == null) { informantActivity = createActivityById(connection, informantID, informationDetailLevel); if (informantActivity != null) { activities.put(QueryConstants.ACTIVITY_IDENTIFIER + informantID, informantActivity); } else { l.error("No activity found. Invalid Activity ID : " + informantID); continue; } } WasInformedBy informedBy = pFactory.newWasInformedBy(getIdQName(QueryConstants.COMMUNICATION_IDENTIFIER + communicationID), informantActivity, informedActivity); if (informationDetailLevel != null && informationDetailLevel.equals(DetailEnumType.FINE)) { // add external attributes too addCustomAttributes(PROVSqlQuery.GET_EXE_COMMUNICATION_ATTRIBUTES_BY_ID, communicationID, informedBy, connection); } // add the used element into the list of relationships relationships.add(informedBy); } l.debug("addCommunications() successful"); } catch (SQLException e) { l.error("Exiting addCommunications() with error"); l.error(e.toString()); } finally { if (stmt != null) { stmt.close(); } if (resultSet != null) { resultSet.close(); } } } private void addDerivations(Connection connection, HashMap<String, Entity> entities, List<Statement> relationships, String contextWorkflowURI, DetailEnumType.Enum informationDetailLevel) throws SQLException, QueryException { assert (connection != null); assert (contextWorkflowURI != null); l.debug("Entering addDerivations()"); /** * There are 2 possible cases here. * 1. There is a derivation notification in the database relating entity1 and entity2. In this * case we directly map it into a derivation relationship in the graph. At least 1 entity must * be already there in the list of entities. * 2. activity1 uses entity1 and generates entity2. But there's no derivation notification * in the database for entity1 and entity2. In this case, we have to infer the derivation. */ // derivations identified in case 1 should not be duplicated in case 2. therefore we have to // keep track of the pairs of entities considered in case 1 List<String> foundList = new ArrayList<String>(); PreparedStatement stmt = null; ResultSet resultSet = null; try { // Case 1.1 : both entities in context stmt = connection.prepareStatement(PROVSqlQuery.GET_PROV_DERIVATIONS_IN_CONTEXT); stmt.setString(1, contextWorkflowURI); stmt.setString(2, contextWorkflowURI); resultSet = stmt.executeQuery(); while (resultSet.next()) { String derivationId = resultSet.getString("derivation_id"); String usedId = resultSet.getString("used_id"); String generatedId = resultSet.getString("generated_id"); String derivationType = resultSet.getString("derivation_type"); // get entities from list Entity usedEntity = entities.get(usedId); Entity generatedEntity = entities.get(generatedId); // none of the entities can be null for this query if (usedEntity == null || generatedEntity == null) { throw new QueryException("None of the entities can be null for a derivation in context"); } // create the relationship WasDerivedFrom derivedFrom = pFactory.newWasDerivedFrom(getIdQName(QueryConstants.DERIVATION_IDENTIFIER + derivationId), generatedEntity.getId(), usedEntity.getId()); // if this is a revision, quotation or primary source, add type addDerivationType(derivationType, derivedFrom); if (informationDetailLevel != null && informationDetailLevel.equals(DetailEnumType.FINE)) { // add external attributes too addCustomAttributes(PROVSqlQuery.GET_EXE_DERIVATION_ATTRIBUTES_BY_ID, derivationId, derivedFrom, connection); } // add the derivation element into the list of relationships relationships.add(derivedFrom); foundList.add(usedId + "-" + generatedId); } if (stmt != null) { stmt.close(); stmt = null; } if (resultSet != null) { resultSet.close(); resultSet = null; } // Case 1.2 : only the generated entity is in context stmt = connection.prepareStatement(PROVSqlQuery.GET_PROV_DERIVATIONS_GENERATED_IN_CONTEXT); stmt.setString(1, contextWorkflowURI); stmt.setString(2, contextWorkflowURI); resultSet = stmt.executeQuery(); while (resultSet.next()) { String derivationId = resultSet.getString("derivation_id"); String usedId = resultSet.getString("used_id"); String generatedId = resultSet.getString("generated_id"); String derivationType = resultSet.getString("derivation_type"); // get entities from list Entity usedEntity = entities.get(usedId); Entity generatedEntity = entities.get(generatedId); // generated entity must already be in the context if (generatedEntity == null) { throw new QueryException("Generated entity can't be null because it's in the context"); } if (usedEntity == null) { usedEntity = createEntity(usedId, connection); } // create the relationship WasDerivedFrom derivedFrom = pFactory.newWasDerivedFrom(getIdQName(QueryConstants.DERIVATION_IDENTIFIER + derivationId), generatedEntity.getId(), usedEntity.getId()); // if this is a revision, quotation or primary source, add type addDerivationType(derivationType, derivedFrom); if (informationDetailLevel != null && informationDetailLevel.equals(DetailEnumType.FINE)) { // add external attributes too addCustomAttributes(PROVSqlQuery.GET_EXE_DERIVATION_ATTRIBUTES_BY_ID, derivationId, derivedFrom, connection); } // add the used element into the list of relationships relationships.add(derivedFrom); foundList.add(usedId + "-" + generatedId); } if (stmt != null) { stmt.close(); stmt = null; } if (resultSet != null) { resultSet.close(); resultSet = null; } // Case 1.3 : only the used entity is in context stmt = connection.prepareStatement(PROVSqlQuery.GET_PROV_DERIVATIONS_USED_IN_CONTEXT); stmt.setString(1, contextWorkflowURI); stmt.setString(2, contextWorkflowURI); resultSet = stmt.executeQuery(); while (resultSet.next()) { String derivationId = resultSet.getString("derivation_id"); String usedId = resultSet.getString("used_id"); String generatedId = resultSet.getString("generated_id"); String derivationType = resultSet.getString("derivation_type"); // get entities from list Entity usedEntity = entities.get(usedId); Entity generatedEntity = entities.get(generatedId); // used entity can't be null in this case if (usedEntity == null) { throw new QueryException("Used entity can't be null because it's in the context"); } if (generatedEntity == null) { generatedEntity = createEntity(generatedId, connection); } // create the relationship WasDerivedFrom derivedFrom = pFactory.newWasDerivedFrom(getIdQName(QueryConstants.DERIVATION_IDENTIFIER + derivationId), generatedEntity.getId(), usedEntity.getId()); // if this is a revision, quotation or primary source, add type addDerivationType(derivationType, derivedFrom); if (informationDetailLevel != null && informationDetailLevel.equals(DetailEnumType.FINE)) { // add external attributes too addCustomAttributes(PROVSqlQuery.GET_EXE_DERIVATION_ATTRIBUTES_BY_ID, derivationId, derivedFrom, connection); } // add the used element into the list of relationships relationships.add(derivedFrom); foundList.add(usedId + "-" + generatedId); } if (stmt != null) { stmt.close(); stmt = null; } if (resultSet != null) { resultSet.close(); resultSet = null; } // Case 2 stmt = connection.prepareStatement(PROVSqlQuery.GET_PROV_DERIVATIONS_BY_ACTIVITY); stmt.setString(1, contextWorkflowURI); stmt.setString(2, contextWorkflowURI); resultSet = stmt.executeQuery(); while (resultSet.next()) { String generatedId = resultSet.getString("gen_id"); String usedId = resultSet.getString("used_id"); // now we have to check whether we've already considered this pair as a derivation if (!foundList.contains(usedId + "-" + generatedId)) { // get entities from list Entity usedEntity = entities.get(usedId); Entity generatedEntity = entities.get(generatedId); // used entity or generated entity can't be null in this case if (usedEntity == null || generatedEntity == null) { throw new QueryException("None of the entities can be null for a derivation in context"); } // create the relationship WasDerivedFrom derivedFrom = pFactory.newWasDerivedFrom(getIdQName(QueryConstants.DERIVATION_IDENTIFIER + usedId + "_" + generatedId), generatedEntity.getId(), usedEntity.getId()); // add the used element into the list of relationships relationships.add(derivedFrom); } } l.debug("addDerivations() successful"); } catch (SQLException e) { l.error("Exiting addDerivations() with error"); l.error(e.toString()); } finally { if (stmt != null) { stmt.close(); } if (resultSet != null) { resultSet.close(); } } } private void addAlternates(Connection connection, HashMap<String, Entity> entities, List<Statement> relationships) throws SQLException, QueryException { assert (connection != null); assert (entities != null); l.debug("Entering addAlternates()"); // Here we have a problem because we can't query for alternatives using the context // workflow uri. Therefore we have to check for each entity in entities list // TODO : Improve this if possible if (entities.isEmpty()) { return; } PreparedStatement stmt = null; ResultSet resultSet = null; try { // we are going to create the query by considering all entities that we have in the list StringBuilder query = new StringBuilder(); query.append(PROVSqlQuery.GET_PROV_ALTERNATES); Set<String> entityIDs = entities.keySet(); int i = 0; for (String entityId : entityIDs) { query.append("alternate1_id = ").append(entityId).append(" OR "); query.append("alternate2_id = ").append(entityId); if (i < entityIDs.size() - 1) { query.append(" OR "); } i++; } stmt = connection.prepareStatement(query.toString()); resultSet = stmt.executeQuery(); while (resultSet.next()) { String alt1 = resultSet.getString("alternate1_id"); String alt2 = resultSet.getString("alternate2_id"); Entity alt1Entity = entities.get(alt1); Entity alt2Entity = entities.get(alt2); if (alt1Entity == null && alt2Entity == null) { throw new QueryException("At least 1 entity must not be null"); } if (alt1Entity == null) { alt1Entity = createEntity(alt1, connection); } if (alt2Entity == null) { alt2Entity = createEntity(alt2, connection); } // create the relationship AlternateOf alternateOf = pFactory.newAlternateOf(alt1Entity.getId(), alt2Entity.getId()); // add the used element into the list of relationships relationships.add(alternateOf); } l.debug("Exiting addAlternates() with success"); } catch (SQLException e) { l.error("Exiting addAlternates() with error"); l.error(e.toString()); } finally { if (stmt != null) { stmt.close(); } if (resultSet != null) { resultSet.close(); } } } private void addSpecializations(Connection connection, HashMap<String, Entity> entities, List<Statement> relationships) throws SQLException, QueryException { assert (connection != null); assert (entities != null); l.debug("Entering addSpecializations()"); // Here we have a problem because we can't query for specializations using the context // workflow uri. Therefore we have to check for each entity in entities list // TODO : Improve this if possible if (entities.isEmpty()) { return; } PreparedStatement stmt = null; ResultSet resultSet = null; try { // we are going to create the query by considering all entities that we have in the list StringBuilder query = new StringBuilder(); query.append(PROVSqlQuery.GET_PROV_SPECIALIZATIONS); Set<String> entityIDs = entities.keySet(); int i = 0; for (String entityId : entityIDs) { query.append("specific_id = ").append(entityId).append(" OR "); query.append("general_id = ").append(entityId); if (i < entityIDs.size() - 1) { query.append(" OR "); } i++; } stmt = connection.prepareStatement(query.toString()); resultSet = stmt.executeQuery(); while (resultSet.next()) { String specificId = resultSet.getString("specific_id"); String generalId = resultSet.getString("general_id"); Entity specificEntity = entities.get(specificId); Entity generalEntity = entities.get(generalId); if (specificEntity == null && generalEntity == null) { throw new QueryException("At least 1 entity must not be null"); } if (specificEntity == null) { specificEntity = createEntity(specificId, connection); } if (generalEntity == null) { generalEntity = createEntity(generalId, connection); } // create the relationship SpecializationOf specializationOf = pFactory.newSpecializationOf(specificEntity.getId(), generalEntity.getId()); // add the used element into the list of relationships relationships.add(specializationOf); } l.debug("Exiting addSpecializations() with success"); } catch (SQLException e) { l.error("Exiting addSpecializations() with error"); l.error(e.toString()); } finally { if (stmt != null) { stmt.close(); } if (resultSet != null) { resultSet.close(); } } } private void addMemberships(Connection connection, HashMap<String, Entity> entities, List<Statement> relationships) throws SQLException, QueryException { assert (connection != null); assert (entities != null); l.debug("Entering addMemberships()"); if (entities.isEmpty()) { return; } HashMap<Integer, List<QName>> collections = new HashMap<Integer, List<QName>>(); PreparedStatement stmt = null; ResultSet resultSet = null; try { // we are going to create the query by considering all entities that we have in the list StringBuilder query = new StringBuilder(); query.append(PROVSqlQuery.GET_PROV_MEMBERSHIPS); Set<String> entityIDs = entities.keySet(); int i = 0; for (String entityId : entityIDs) { query.append("collection_id = ").append(entityId); if (i < entityIDs.size() - 1) { query.append(" OR "); } i++; } stmt = connection.prepareStatement(query.toString()); resultSet = stmt.executeQuery(); while (resultSet.next()) { int collectionId = resultSet.getInt("collection_id"); int memberId = resultSet.getInt("member_id"); // get entity from list List<QName> collection = collections.get(collectionId); if (collection == null) { collection = new ArrayList<QName>(); collections.put(collectionId, collection); } Entity memberEntity = entities.get("" + memberId); if (memberEntity == null) { memberEntity = createEntity("" + memberId, connection); } collection.add(memberEntity.getId()); } Set<Integer> keys = collections.keySet(); for (Integer key : keys) { List<QName> members = collections.get(key); if (members.size() > 0) { // get the collection entity which must already be in the list Entity collectionEntity = entities.get("" + key); // create the relationship HadMember hadMember = pFactory.newHadMember(collectionEntity.getId(), members); // add the used element into the list of relationships relationships.add(hadMember); } } l.debug("Exiting addMemberships() with success"); } catch (SQLException e) { l.error("Exiting addMemberships() with error"); l.error(e.toString()); } finally { if (stmt != null) { stmt.close(); } if (resultSet != null) { resultSet.close(); } } } /** * Creates a PROV Activity by querying the database using the given db id. */ private Activity createActivityById(Connection connection, String dbId, DetailEnumType.Enum infoDetailLevel) throws SQLException { PreparedStatement stmt = null; ResultSet resultSet = null; Activity activity = null; try { stmt = connection.prepareStatement(PROVSqlQuery.GET_ACTIVITIES_BY_ACTIVITY_ID); stmt.setString(1, dbId); resultSet = stmt.executeQuery(); if (resultSet.next()) { int activityID = resultSet.getInt("activity_id"); String activityUri = resultSet.getString("activity_uri"); String activityType = resultSet.getString("activity_type"); String contextWorkflowUri = resultSet.getString("context_workflow_uri"); String contextServiceUri = resultSet.getString("context_service_uri"); String timestep = resultSet.getString("timestep"); // String location = resultSet.getString("location"); // TODO : Handle location, role String contextWfNodeIdToken = resultSet.getString("context_wf_node_id_token"); // create new prov activity activity = pFactory.newActivity(getIdQName( QueryConstants.ACTIVITY_IDENTIFIER + activityID)); if (infoDetailLevel != null && infoDetailLevel.equals(DetailEnumType.FINE)) { // add attributes // activity uri attribute pFactory.addAttribute(activity, pFactory.newOther(getKomaduAttQName("activityUri"), activityUri, Name.QNAME_XSD_STRING)); // activity type attribute pFactory.addAttribute(activity, pFactory.newOther(getKomaduAttQName("type"), activityType, Name.QNAME_XSD_STRING)); // context WF uri if (contextWorkflowUri != null) { pFactory.addAttribute(activity, pFactory.newOther(getKomaduAttQName("contextWorkflowUri"), contextWorkflowUri, Name.QNAME_XSD_STRING)); } // context Service uri if (contextServiceUri != null) { pFactory.addAttribute(activity, pFactory.newOther(getKomaduAttQName("contextServiceUri"), contextServiceUri, Name.QNAME_XSD_STRING)); } // timestep if (timestep != null) { pFactory.addAttribute(activity, pFactory.newOther(getKomaduAttQName("timestep"), timestep, Name.QNAME_XSD_STRING)); } // node id if (contextWfNodeIdToken != null) { pFactory.addAttribute(activity, pFactory.newOther(getKomaduAttQName("workflowNodeID"), timestep, Name.QNAME_XSD_STRING)); } // add external attributes too addCustomAttributes(PROVSqlQuery.GET_EXE_ACTIVITY_ATTRIBUTES_BY_ID, "" + activityID, activity, connection); } } l.debug("createActivity() successful"); } catch (SQLException e) { l.error("createActivity() with error"); l.error(e.toString()); } finally { if (stmt != null) { stmt.close(); } if (resultSet != null) { resultSet.close(); } } return activity; } }
46.545139
137
0.550603
3b59cf2e96a72b63371ae367fab75570c4be7fc1
1,541
package br.ufs.dcomp.eduard6.disciplinas.ia.projetos.iclass.persistence.pojo; import br.ufs.dcomp.eduard6.disciplinas.ia.projetos.iclass.to.HorarioTO; /** * Representa um Horario no banco de dados. * * @author Eduardo Fillipe da Silva Reis * */ public class HorarioPOJO { private TurmaPOJO turma; private String codigo; private int horarioSequencia; private int numeroHorario; public HorarioPOJO(HorarioTO horarioTO) { super(); if (horarioTO.getTurma() != null) this.turma = new TurmaPOJO(horarioTO.getTurma()); this.codigo = horarioTO.getCodigo(); this.horarioSequencia = horarioTO.getHorarioSequencia().getValor(); this.numeroHorario = horarioTO.getNumeroHorario(); } public HorarioPOJO() { super(); } public HorarioPOJO(TurmaPOJO turma, String codigo, int horarioSequencia, int numeroHorario) { super(); this.turma = turma; this.codigo = codigo; this.horarioSequencia = horarioSequencia; this.numeroHorario = numeroHorario; } public TurmaPOJO getTurma() { return turma; } public void setTurma(TurmaPOJO turma) { this.turma = turma; } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } public int getHorarioSequencia() { return horarioSequencia; } public void setHorarioSequencia(int horarioSequencia) { this.horarioSequencia = horarioSequencia; } public int getNumeroHorario() { return numeroHorario; } public void setNumeroHorario(int numeroHorario) { this.numeroHorario = numeroHorario; } }
22.333333
94
0.739779
bd9b18558f3c5302e4202c32bfae90f19e0d078a
3,549
/** * Licensed to the Austrian Association for Software Tool Integration (AASTI) * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. The AASTI 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.openengsb.loom.java; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.commons.lang.reflect.MethodUtils; import org.openengsb.core.api.remote.MethodCall; import org.openengsb.core.api.remote.MethodResult; import org.openengsb.core.api.remote.MethodResult.ReturnType; import org.openengsb.loom.java.util.JsonUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LocalRequestHandler { private static final Logger LOGGER = LoggerFactory.getLogger(LocalRequestHandler.class); private Object connector; public LocalRequestHandler(Object connector) { this.connector = connector; } public MethodResult process(MethodCall request) { try { return doProcess(request); } catch (Exception e) { return makeExceptionResult(e); } } private MethodResult doProcess(MethodCall request) throws Exception { JsonUtils.convertAllArgs(connector.getClass().getClassLoader(), request); Class<?>[] argTypes = getArgTypes(request); LOGGER.debug("searching for method {} with args {}", request.getMethodName(), argTypes); Method method = MethodUtils .getMatchingAccessibleMethod(connector.getClass(), request.getMethodName(), argTypes); LOGGER.info("invoking method {}", method); Object result; try { result = method.invoke(connector, request.getArgs()); } catch (InvocationTargetException e) { throw (Exception) e.getTargetException(); } if (method.getReturnType().equals(void.class)) { return MethodResult.newVoidResult(); } LOGGER.debug("invocation successful"); return new MethodResult(result); } private Class<?>[] getArgTypes(MethodCall call) { Object[] args = call.getArgs(); if (args == null) { return new Class<?>[0]; } Class<?>[] types = new Class<?>[args.length]; for (int i = 0; i < args.length; i++) { types[i] = args[i].getClass(); if(types[i].getName().contains("$Proxy")){ Class<?>[] interfaces = types[i].getInterfaces(); types[i] = interfaces[interfaces.length - 1]; } } return types; } private MethodResult makeExceptionResult(Exception e) { LOGGER.error("Exception occured, making Exception result"); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); return new MethodResult(sw.toString(), ReturnType.Exception); } }
38.16129
102
0.674556
f072f39c35e4189e54c004ae1145bafa140ed323
10,351
package de.vinado.wicket.participate.ui.event; import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeIconType; import de.vinado.wicket.participate.components.TextAlign; import de.vinado.wicket.participate.components.modals.BootstrapModal; import de.vinado.wicket.participate.components.panels.IconPanel; import de.vinado.wicket.participate.components.panels.SendEmailPanel; import de.vinado.wicket.participate.components.snackbar.Snackbar; import de.vinado.wicket.participate.components.tables.BootstrapAjaxDataTable; import de.vinado.wicket.participate.components.tables.columns.BootstrapAjaxLinkColumn; import de.vinado.wicket.participate.components.tables.columns.EnumColumn; import de.vinado.wicket.participate.email.Email; import de.vinado.wicket.participate.email.EmailBuilderFactory; import de.vinado.wicket.participate.events.AjaxUpdateEvent; import de.vinado.wicket.participate.events.EventUpdateEvent; import de.vinado.wicket.participate.model.Event; import de.vinado.wicket.participate.model.EventDetails; import de.vinado.wicket.participate.model.InvitationStatus; import de.vinado.wicket.participate.model.Participant; import de.vinado.wicket.participate.model.Person; import de.vinado.wicket.participate.model.Voice; import de.vinado.wicket.participate.model.dtos.ParticipantDTO; import de.vinado.wicket.participate.model.filters.ParticipantFilter; import de.vinado.wicket.participate.providers.SimpleDataProvider; import de.vinado.wicket.participate.services.EventService; import de.vinado.wicket.participate.ui.pages.BasePage; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.event.IEvent; import org.apache.wicket.extensions.breadcrumb.IBreadCrumbModel; import org.apache.wicket.extensions.breadcrumb.panel.BreadCrumbPanel; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.basic.MultiLineLabel; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.LoadableDetachableModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.model.ResourceModel; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.util.string.Strings; import java.util.ArrayList; import java.util.List; /** * @author Vincent Nadoll ([email protected]) */ public class EventPanel extends BreadCrumbPanel { @SpringBean @SuppressWarnings("unused") private EventService eventService; @SpringBean private EmailBuilderFactory emailBuilderFactory; private IModel<EventDetails> model; private Form form; private SimpleDataProvider<Participant, String> dataProvider; private BootstrapAjaxDataTable<Participant, String> dataTable; public EventPanel(final String id, final IBreadCrumbModel breadCrumbModel, final IModel<EventDetails> model, final boolean editable) { super(id, breadCrumbModel, model); this.model = model; setOutputMarkupPlaceholderTag(true); form = new Form("form") { @Override protected void onConfigure() { dataProvider.set(eventService.getParticipants(model.getObject().getEvent())); } }; add(form); final WebMarkupContainer wmc = new WebMarkupContainer("wmc"); wmc.setOutputMarkupId(true); form.add(wmc); wmc.add(new Label("name")); wmc.add(new Label("eventType")); wmc.add(new Label("displayDate")); wmc.add(new Label("creationDateTimeIso").add(new RelativeTimePipe())); wmc.add(new Label("location")); wmc.add(new MultiLineLabel("description") { @Override protected void onConfigure() { setVisible(!Strings.isEmpty(model.getObject().getDescription())); } }); final ParticipantFilterPanel filterPanel = new ParticipantFilterPanel("filterPanel", new LoadableDetachableModel<List<Participant>>() { @Override protected List<Participant> load() { return eventService.getParticipants(model.getObject().getEvent()); } }, new CompoundPropertyModel<>(new ParticipantFilter()), new PropertyModel<>(model, "event"), editable) { @Override public SimpleDataProvider<Participant, ?> getDataProvider() { return dataProvider; } @Override public DataTable<Participant, ?> getDataTable() { return dataTable; } }; wmc.add(filterPanel); dataProvider = new SimpleDataProvider<Participant, String>() { @Override public String getDefaultSort() { return "invitationStatus"; } }; final List<IColumn<Participant, String>> columns = new ArrayList<>(); columns.add(new AbstractColumn<Participant, String>(Model.of(""), "invitationStatus") { @Override public void populateItem(final Item<ICellPopulator<Participant>> item, final String componentId, final IModel<Participant> rowModel) { final IconPanel icon = new IconPanel(componentId); final Participant participant = rowModel.getObject(); final InvitationStatus invitationStatus = participant.getInvitationStatus(); icon.setTextAlign(TextAlign.CENTER); if (InvitationStatus.ACCEPTED.equals(invitationStatus)) { icon.setType(FontAwesomeIconType.check); icon.setColor(IconPanel.Color.SUCCESS); } else if (InvitationStatus.DECLINED.equals(invitationStatus)) { icon.setType(FontAwesomeIconType.times); icon.setColor(IconPanel.Color.DANGER); } else if (InvitationStatus.UNINVITED.equals(invitationStatus)) { icon.setType(FontAwesomeIconType.circle_thin); icon.setColor(IconPanel.Color.MUTED); } else { icon.setType(FontAwesomeIconType.circle); icon.setColor(IconPanel.Color.WARNING); } item.add(icon); } @Override public String getCssClass() { return "td-with-btn-xs"; } }); columns.add(new PropertyColumn<>(new ResourceModel("name", "Name"), "singer.sortName", "singer.sortName")); columns.add(new EnumColumn<Participant, String, Voice>(new ResourceModel("voice", "voice"), "singer.voice", "singer.voice")); if (editable) { columns.add(new BootstrapAjaxLinkColumn<Participant, String>(FontAwesomeIconType.pencil, new ResourceModel("invitation.edit", "Edit Invitation")) { @Override public void onClick(final AjaxRequestTarget target, final IModel<Participant> rowModel) { final BootstrapModal modal = ((BasePage) getWebPage()).getModal(); modal.setContent(new EditInvitationPanel(modal, new CompoundPropertyModel<>(new ParticipantDTO(rowModel.getObject()))) { @Override protected void onSaveSubmit(final IModel<ParticipantDTO> savedModel, final AjaxRequestTarget target) { model.setObject(eventService.getEventDetails(eventService.saveParticipant(savedModel.getObject()).getEvent())); dataProvider.set(eventService.getParticipants(model.getObject().getEvent())); Snackbar.show(target, new ResourceModel("edit.success", "The data was saved successfully")); target.add(form); } }); modal.show(target); } }); columns.add(new BootstrapAjaxLinkColumn<Participant, String>(FontAwesomeIconType.envelope, new ResourceModel("email.send", "Send Email")) { @Override public void onClick(final AjaxRequestTarget target, final IModel<Participant> rowModel) { final Person person = rowModel.getObject().getSinger(); Email mailData = emailBuilderFactory.create() .to(person) .build(); final BootstrapModal modal = ((BasePage) getWebPage()).getModal(); modal.setContent(new SendEmailPanel(modal, new CompoundPropertyModel<>(mailData))); modal.show(target); } }); } dataTable = new BootstrapAjaxDataTable<>("dataTable", columns, dataProvider, 15); dataTable.setOutputMarkupId(true); dataTable.hover().condensed(); wmc.add(dataTable); } @Override public void onEvent(final IEvent<?> iEvent) { super.onEvent(iEvent); final Object payload = iEvent.getPayload(); if (payload instanceof EventUpdateEvent) { final EventUpdateEvent updateEvent = (EventUpdateEvent) payload; final AjaxRequestTarget target = updateEvent.getTarget(); final Event event = updateEvent.getEvent(); model.setObject(eventService.getEventDetails(event)); target.add(form); } if (payload instanceof AjaxUpdateEvent) { final AjaxUpdateEvent event = (AjaxUpdateEvent) payload; final AjaxRequestTarget target = event.getTarget(); target.add(form); } } @Override public IModel<String> getTitle() { return new PropertyModel<>(model, "name"); } }
46.41704
159
0.667955
c7cf45bfc39a506e00bff088a208d05d62a6f7a1
11,918
/* */ package com.wtpgaming.omzp.v15.Events.CustomItems.Armor.Helmets; /* */ import com.wtpgaming.omzp.OMZP; /* */ import java.util.Objects; /* */ import org.bukkit.ChatColor; /* */ import org.bukkit.Material; /* */ import org.bukkit.event.EventHandler; /* */ import org.bukkit.event.Listener; /* */ import org.bukkit.event.block.Action; /* */ import org.bukkit.event.inventory.InventoryClickEvent; /* */ import org.bukkit.event.inventory.InventoryType; /* */ import org.bukkit.event.player.PlayerInteractEvent; /* */ import org.bukkit.event.player.PlayerJoinEvent; /* */ import org.bukkit.event.player.PlayerMoveEvent; /* */ import org.bukkit.inventory.meta.ItemMeta; /* */ import org.bukkit.metadata.FixedMetadataValue; /* */ import org.bukkit.metadata.MetadataValue; /* */ import org.bukkit.plugin.Plugin; /* */ import org.bukkit.potion.PotionEffect; /* */ import org.bukkit.potion.PotionEffectType; /* */ /* */ public class MinersLampEvent implements Listener { /* */ OMZP plugin; /* */ /* */ public MinersLampEvent(OMZP plugin) { /* 25 */ this.item = "MinersLamp"; /* */ this.plugin = plugin; /* */ } String item; @EventHandler(ignoreCancelled = true) /* */ public void onPlayerJoin(PlayerJoinEvent event) { /* 29 */ if (event.getPlayer().getInventory().getHelmet() != null) /* */ { /* 31 */ if (event.getPlayer().getInventory().getHelmet().hasItemMeta()) /* */ { /* 33 */ if (event.getPlayer().getInventory().getHelmet().getItemMeta().hasDisplayName()) /* */ { /* 35 */ if (event.getPlayer().getInventory().getHelmet().getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', this.plugin.getConfig().getString(this.item + "-Name")))) /* */ { /* 37 */ if (event.getPlayer().getInventory().getHelmet().getType() == Material.getMaterial(this.plugin.getConfig().getString(this.item + "-Type"))) { /* */ /* 39 */ if (!event.getPlayer().hasPotionEffect(PotionEffectType.NIGHT_VISION)) /* */ { /* 41 */ event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, 999999, 0)); /* */ } /* */ /* 44 */ event.getPlayer().removeMetadata(this.item, (Plugin)this.plugin); /* 45 */ event.getPlayer().setMetadata(this.item, (MetadataValue)new FixedMetadataValue((Plugin)this.plugin, "true")); /* */ } /* */ } /* */ } /* */ } /* */ } /* */ } /* */ /* */ /* */ @EventHandler(ignoreCancelled = true) /* */ public void onInventoryClick(InventoryClickEvent event) { /* 56 */ if (event.getClickedInventory().getType() == InventoryType.PLAYER) /* */ { /* 58 */ if (event.getSlot() == 39) { /* */ /* 60 */ if (event.getWhoClicked().getInventory().getHelmet() == null) { /* */ /* 62 */ if (event.getCursor() != null) /* */ { /* 64 */ if (event.getCursor().hasItemMeta()) /* */ { /* 66 */ if (event.getCursor().getItemMeta().hasDisplayName()) /* */ { /* 68 */ if (event.getCursor().getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', this.plugin.getConfig().getString(this.item + "-Name")))) /* */ { /* 70 */ if (event.getCursor().getType() == Material.getMaterial(this.plugin.getConfig().getString(this.item + "-Type"))) { /* */ /* 72 */ if (!event.getWhoClicked().hasPotionEffect(PotionEffectType.NIGHT_VISION)) /* */ { /* 74 */ event.getWhoClicked().addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, 999999, 0)); /* */ } /* */ /* 77 */ event.getWhoClicked().removeMetadata(this.item, (Plugin)this.plugin); /* 78 */ event.getWhoClicked().setMetadata(this.item, (MetadataValue)new FixedMetadataValue((Plugin)this.plugin, "true")); /* */ } /* */ } /* */ } /* */ } /* */ } /* 84 */ } else if (event.getWhoClicked().getInventory().getHelmet().hasItemMeta()) { /* */ /* 86 */ if (event.getWhoClicked().getInventory().getHelmet().getItemMeta().hasDisplayName()) /* */ { /* 88 */ if (event.getWhoClicked().getInventory().getHelmet().getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', this.plugin.getConfig().getString(this.item + "-Name")))) /* */ { /* 90 */ if (event.getWhoClicked().getInventory().getHelmet().getType() == Material.getMaterial(this.plugin.getConfig().getString(this.item + "-Type"))) /* */ { /* 92 */ if (event.getWhoClicked().hasPotionEffect(PotionEffectType.NIGHT_VISION)) { /* */ /* 94 */ if (event.getWhoClicked().hasPotionEffect(PotionEffectType.NIGHT_VISION)) { /* 95 */ event.getWhoClicked().removePotionEffect(PotionEffectType.NIGHT_VISION); /* */ } /* */ /* 98 */ event.getWhoClicked().removeMetadata(this.item, (Plugin)this.plugin); /* 99 */ event.getWhoClicked().setMetadata(this.item, (MetadataValue)new FixedMetadataValue((Plugin)this.plugin, "false")); /* */ } /* */ } /* */ } /* */ } /* */ } /* 105 */ } else if (event.getWhoClicked().getInventory().getItem(event.getSlot()) != null) { /* */ /* 107 */ if (event.isShiftClick()) /* */ { /* 109 */ if (event.getWhoClicked().getInventory().getItem(event.getSlot()).hasItemMeta()) /* */ { /* 111 */ if (event.getWhoClicked().getInventory().getItem(event.getSlot()).getItemMeta().hasDisplayName()) /* */ { /* 113 */ if (event.getWhoClicked().getInventory().getItem(event.getSlot()).getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', this.plugin.getConfig().getString(this.item + "-Name")))) /* */ { /* 115 */ if (event.getWhoClicked().getInventory().getItem(event.getSlot()).getType() == Material.getMaterial(this.plugin.getConfig().getString(this.item + "-Type"))) /* */ { /* 117 */ if (event.getWhoClicked().getInventory().getHelmet() == null) { /* */ /* 119 */ if (!event.getWhoClicked().hasPotionEffect(PotionEffectType.NIGHT_VISION)) { /* 120 */ event.getWhoClicked().addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, 999999, 0)); /* */ } /* */ /* 123 */ event.getWhoClicked().removeMetadata(this.item, (Plugin)this.plugin); /* 124 */ event.getWhoClicked().setMetadata(this.item, (MetadataValue)new FixedMetadataValue((Plugin)this.plugin, "true")); /* */ } /* */ } /* */ } /* */ } /* */ } /* */ } /* */ } /* */ } /* */ } /* */ /* */ @EventHandler /* */ public void onMove(PlayerMoveEvent event) { /* 137 */ event.getPlayer().removeMetadata(this.item, (Plugin)this.plugin); /* 138 */ event.getPlayer().setMetadata(this.item, (MetadataValue)new FixedMetadataValue((Plugin)this.plugin, "false")); /* */ /* 140 */ if (event.getPlayer().getInventory().getHelmet() != null) /* */ { /* 142 */ if (event.getPlayer().getInventory().getHelmet().hasItemMeta()) /* */ { /* 144 */ if (event.getPlayer().getInventory().getHelmet().getItemMeta().hasDisplayName()) /* */ { /* 146 */ if (event.getPlayer().getInventory().getHelmet().getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', this.plugin.getConfig().getString(this.item + "-Name")))) /* */ { /* 148 */ if (event.getPlayer().getInventory().getHelmet().getType() == Material.getMaterial(this.plugin.getConfig().getString(this.item + "-Type"))) { /* 149 */ event.getPlayer().removeMetadata(this.item, (Plugin)this.plugin); /* 150 */ event.getPlayer().setMetadata(this.item, (MetadataValue)new FixedMetadataValue((Plugin)this.plugin, "true")); /* */ } /* */ } /* */ } /* */ } /* */ } /* */ /* 157 */ if (((MetadataValue)event.getPlayer().getMetadata(this.item).get(0)).asString() == "true") { /* 158 */ if (!event.getPlayer().hasPotionEffect(PotionEffectType.NIGHT_VISION)) { /* 159 */ event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, 999999, 0)); /* */ } /* */ } /* 162 */ else if (event.getPlayer().hasPotionEffect(PotionEffectType.NIGHT_VISION)) { /* 163 */ event.getPlayer().removePotionEffect(PotionEffectType.NIGHT_VISION); /* */ } /* */ } /* */ /* */ /* */ @EventHandler /* */ public void onPlayerInteract(PlayerInteractEvent event) { /* 170 */ if (event.getAction() != Action.LEFT_CLICK_AIR && event.getAction() != Action.LEFT_CLICK_BLOCK && event.getAction() != Action.PHYSICAL) /* */ { /* 172 */ if (event.getPlayer().getInventory().getItemInMainHand().getType() != Material.AIR) /* */ { /* 174 */ if (event.getPlayer().getInventory().getItemInMainHand().hasItemMeta()) /* */ { /* 176 */ if (((ItemMeta)Objects.<ItemMeta>requireNonNull(event.getPlayer().getInventory().getItemInMainHand().getItemMeta())).hasDisplayName()) /* */ { /* 178 */ if (event.getPlayer().getInventory().getItemInMainHand().getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', this.plugin.getConfig().getString(this.item + "-Name")))) /* */ { /* 180 */ if (event.getPlayer().getInventory().getItemInMainHand().getType() == Material.getMaterial(this.plugin.getConfig().getString(this.item + "-Type"))) /* */ { /* 182 */ if (event.getPlayer().getInventory().getHelmet() == null) { /* 183 */ if (!event.getPlayer().hasPotionEffect(PotionEffectType.NIGHT_VISION)) /* */ { /* 185 */ event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, 999999, 0)); /* */ } /* 187 */ event.getPlayer().removeMetadata(this.item, (Plugin)this.plugin); /* 188 */ event.getPlayer().setMetadata(this.item, (MetadataValue)new FixedMetadataValue((Plugin)this.plugin, "true")); /* */ } /* */ } /* */ } /* */ } /* */ } /* */ } /* */ } /* */ } /* */ } /* Location: D:\Austin\Downloads\OMZP-1.1.2.jar!\com\wtpgaming\omzp\v15\Events\CustomItems\Armor\Helmets\MinersLampEvent.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
58.70936
230
0.520557
3b3aae465d7ef87b2320106ba710e1d885d032a0
3,585
import java.util.ArrayList; import java.util.Scanner; import java.util.InputMismatchException; import java.util.NoSuchElementException; public class Main { public static void main(String[] args) throws InputMismatchException { Scanner sc = new Scanner(System.in); // Usar exceção para tratar entradas inválidas para os valores referente a produtos e salário do Funcionario - TODO float valorProduto=0.0f; float salarioFuncionario=0.0f; try { System.out.println("DIGITE O VALOR DO PRODUTO: "); valorProduto = sc.nextFloat(); }catch(InputMismatchException e) { System.out.println("DEU MUITO RUIM"); } Endereco end1 = new Endereco("Av. Costa e Silva", 2001, "Universitário", "Campo Grande", "79070-900"); Endereco end2 = new Endereco("Av. Afonso Pena", 2002, "Centro", "Campo Grande", "79065-555"); Endereco end3 = new Endereco("Rua do Parque", 2003, "Centro", "Campo Grande", "79065-190"); Endereco end4 = new Endereco("Av. Nelly Martins", 2004, "Portal Itayara", "Campo Grande", "79065-190"); Endereco end5 = new Endereco("Rua Coronel Zózimo", 2005, "Monte Castelo", "Campo Grande", "79065-190"); Endereco end6 = new Endereco("Rua Barueri", 2006, "Moreninha II", "Campo Grande", "79065-190"); try { System.out.println("DIGITE O SALÁRIO DO FUNCIONÁRIO: "); //SE ELE COMEU ALGUM INPUT COLOCA ESSE NEXTLINE //TA PASSADA? sc.nextLine(); salarioFuncionario = sc.nextFloat(); System.out.println(salarioFuncionario); }catch(InputMismatchException e) { String r = e.getMessage(); System.out.println(r); } Funcionario func1 = new Funcionario("Everton", "33333333333", end1, "67999464219", 1000, "Feirante"); Funcionario func2 = new Funcionario("Lourdes", "22222222222", end2, "67999898985", salarioFuncionario, "Feirante"); Cliente cli1 = new Cliente("Eduardo", "07435925144", end3, "67999464221"); Cliente cli2 = new Cliente("Thiago", "50093037104", end4, "67999464220"); Fornecedor empresa1 = new Fornecedor("barraca no mercadão municipal", "GOOOL", "52393813000192", end5, "67999464219"); Fornecedor empresa2 = new Fornecedor("barraca na feira central", "TAAAM", "52393813000192", end5, "67999464219"); Produto produto1 = new Produto("Morango", 1.50f, empresa1); Produto produto2 = new Produto("Macadâmia", valorProduto, empresa1); Produto produto3 = new Produto("Manga", 3.50f, empresa1); Produto produto4 = new Produto("Mexerica", 4.50f, empresa1); Produto produto5 = new Produto("Mamão", 5.50f, empresa2); Produto produto6 = new Produto("Mirtilo", 6.50f, empresa2); Produto produto7 = new Produto("Melancia", 7.50f, empresa2); Produto produto8 = new Produto("Melão", 8.50f, empresa2); Produto produto9 = new Produto("Maça", 9.50f, empresa1); Produto produto10 = new Produto("Maracujá", 10.50f, empresa1); Compra compra1 = new Compra(func1, cli1); Compra compra2 = new Compra(func2, cli2); compra1.adicionaProduto(produto1); compra1.adicionaProduto(produto2); compra1.adicionaProduto(produto3); compra1.adicionaProduto(produto4); compra1.adicionaProduto(produto5); compra2.adicionaProduto(produto6); compra2.adicionaProduto(produto7); compra2.adicionaProduto(produto8); compra2.adicionaProduto(produto9); compra2.adicionaProduto(produto10); compra2.listarCompra(); System.out.println("\n*********************SEGUNDA COMPRA\n"); compra1.listarCompra(); } }
41.686047
124
0.68145
47f2a5a830af66ad79092f1e311b6f011dc08493
2,371
package com.ramsarup.ramsarup.Adapter; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import com.ramsarup.ramsarup.R; import com.ramsarup.ramsarup.Storyshow; import java.util.List; public class Successadapter extends RecyclerView.Adapter<Successadapter.MyViewHolder> { private List<Item> itemList; private Context context; public Successadapter(List<Item> itemList, Context context) { this.itemList = itemList; this.context=context; } @SuppressLint("ResourceType") @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int position) { View view; { view = LayoutInflater.from(context).inflate(R.layout.successlayout, parent, false); return new MyViewHolder(view); } } @Override public void onBindViewHolder(Successadapter.MyViewHolder holder, int i) { initLayoutOne((MyViewHolder) holder, i); } private void initLayoutOne(final MyViewHolder holder, final int pos) { holder.storyheading.setText(itemList.get(pos).getSuccess()); holder.parent.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent callstoryclass=new Intent(context, Storyshow.class); callstoryclass.putExtra("success",itemList.get(pos).getSuccess()); context.startActivity(callstoryclass); } }); } @Override public int getItemCount() { return itemList.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { public TextView storyheading; RelativeLayout parent; public MyViewHolder(@NonNull View itemView) { super(itemView); storyheading = itemView.findViewById(R.id.success); parent=itemView.findViewById(R.id.successlayout); } }}
20.982301
96
0.648671
7d4e9393d6f4090e21ea3120337fd44f3e3374b8
4,159
package com.mmorpg.logic.base.login; import com.mmorpg.framework.message.Message; import com.mmorpg.framework.message.MessageId; import com.mmorpg.framework.message.MessageType; import com.mmorpg.framework.net.session.GameSession; import com.mmorpg.framework.net.session.GameSessionStatusUpdateCause; import com.mmorpg.framework.utils.OnlinePlayer; import com.mmorpg.framework.utils.PacketUtils; import com.mmorpg.framework.utils.TimeUtils; import com.mmorpg.framework.utils.Timer; import com.mmorpg.logic.base.Context; import com.mmorpg.logic.base.login.packet.RespLoginAskPacket; import com.mmorpg.logic.base.message.RespMessagePacket; import com.mmorpg.logic.base.scene.creature.player.Player; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Iterator; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; /** * 登录监视器 * * @author Ariescat * @version 2020/2/19 11:32 */ public class LoginWatcher { private final static Logger log = LoggerFactory.getLogger(LoginWatcher.class); /** * 登录等待请求 */ private final ConcurrentLinkedQueue<LoginPendingRequest> pendingQueue = new ConcurrentLinkedQueue<>(); private final static LoginWatcher instance = new LoginWatcher(); public static LoginWatcher getInstance() { return instance; } private LoginWatcher() { } /** * 处理登录逻辑 */ public final void processLogin(Player player, GameSession session, RespLoginAskPacket packet) { final int max = Context.it().configService.getMaxOnlineCount(); if (max > 0 && OnlinePlayer.getInstance().getOnlinePlayerCount() >= max) { RespMessagePacket msgPacket = Message.buildMessagePacket(MessageType.WARN, MessageId.ANOUNCEMENT, "服务器繁忙,请尝试登录其他服务器!"); PacketUtils.sendAndClose(session.getChannel(), msgPacket); return; } if (OnlinePlayer.getInstance().isSameIPMax(session.getIp())) { RespMessagePacket msgPacket = Message.buildMessagePacket(MessageType.WARN, MessageId.ANOUNCEMENT, "相同IP登录超过上限!"); PacketUtils.sendAndClose(session.getChannel(), msgPacket); return; } if (OnlinePlayer.getInstance().registerSession(player, session)) { //首次登录不需要进入等待队列,直接处理掉 handleLoginLogic(player, session, packet); } else { /* * 1)玩家账号被顶号,需要先执行完成旧链接的退出事务,才开启新的登录流程 * 2)玩家正常退出后,由于ReqL ogoutPacket是异步执行,必须保证退出事务处理完毕后才能开启新的登录流程 */ pendingQueue.add(new LoginPendingRequest(player, session, packet)); } } private Timer logTimer = new Timer(1, TimeUnit.SECONDS); public final void heartbeat() { if (pendingQueue.isEmpty()) { return; } if (logTimer.isTimeOut(TimeUtils.getCurrentMillisTime())) { log.info("{} Pending Size:{}", Thread.currentThread().getName(), pendingQueue.size()); } Iterator<LoginPendingRequest> iterator = pendingQueue.iterator(); while (iterator.hasNext()) { LoginPendingRequest request = iterator.next(); if (request.execute()) { iterator.remove(); } else if (request.getCount() > 3) { iterator.remove(); } else if (request.isTimeout()) { request.reset(); } } } private void handleLoginLogic(Player player, GameSession session, RespLoginAskPacket packet) { player.sendPacket(packet.success()); player.login(); // TODO send scene info (sceneId, point, role info) } /** * 登录等待请求 */ public class LoginPendingRequest { private Player player; private GameSession session; private RespLoginAskPacket packet; private long timeout; private int count = 0; public LoginPendingRequest(Player player, GameSession session, RespLoginAskPacket packet) { this.player = player; this.session = session; this.packet = packet; this.timeout = TimeUtils.getCurrentMillisTime() + 20000; } public boolean isTimeout() { return TimeUtils.getCurrentMillisTime() > timeout; } public void reset() { count++; OnlinePlayer.getInstance().timeoutReset(player, GameSessionStatusUpdateCause.TimeoutReset); } public boolean execute() { if (OnlinePlayer.getInstance().registerSession(player, session)) { handleLoginLogic(player, session, packet); return true; } return false; } public int getCount() { return count; } } }
28.486301
122
0.742486
b246baeeb5e22a7220ffbcca2dd1b3f0f6c75289
143
package com.thegongoliers.commands; import edu.wpi.first.wpilibj2.command.CommandBase; public class DoNothingCommand extends CommandBase { }
20.428571
51
0.832168
09978ffef0de0aa034c20bd2315b371e74e6c15a
761
// -*- tab-width: 4 -*- //Title: JET //Version: 1.00 //Copyright: Copyright (c) 2000 //Author: Ralph Grishman //Description: A Java-based Information Extraction Tool package edu.nyu.jet.pat; import edu.nyu.jet.tipster.*; import java.util.*; import javax.swing.tree.DefaultMutableTreeNode; /** * a node in the graph representation of a pattern set. */ public abstract class PatternNode { public Id id; private boolean visited = false; public abstract void eval(Document doc, int posn, HashMap bindings, PatternApplication patap); public abstract void toTree(DefaultMutableTreeNode parent); public void visit() { visited = true; } public boolean visited() { return visited; } }
21.742857
69
0.668857
1e1a053e79372515e65149b00c2c51a47fb3aef6
5,596
/** * Copyright 2017 Goldman Sachs. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.gs.obevocomparer.util; import java.io.IOException; import java.io.Reader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.List; import com.gs.obevocomparer.compare.CatoBreakExcluder; import com.gs.obevocomparer.compare.CatoComparison; import com.gs.obevocomparer.compare.CatoDataSourceComparator; import com.gs.obevocomparer.compare.CatoProperties; import com.gs.obevocomparer.compare.simple.SimpleCatoProperties; import com.gs.obevocomparer.input.CatoDataSource; import com.gs.obevocomparer.input.db.QueryDataSource; import com.gs.obevocomparer.input.text.DelimitedStreamDataSource; import com.gs.obevocomparer.input.text.FixedStreamDataSource; import com.gs.obevocomparer.output.CatoComparisonWriter; import com.gs.obevocomparer.output.CatoMultiComparisonWriter; import com.gs.obevocomparer.spring.CatoSimpleJavaConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CatoBaseUtil { private static final Logger LOG = LoggerFactory.getLogger(CatoBaseUtil.class); public static QueryDataSource createQueryDataSource(String name, String url, String user, String password, String query) throws SQLException { return createQueryDataSource(name, DriverManager.getConnection(url, user, password), query); } public static QueryDataSource createQueryDataSource(String name, Connection connection, String query) { return new QueryDataSource(name, connection, query); } public static DelimitedStreamDataSource createDelimitedStreamDataSource(String name, Reader reader, String delimiter) { return new DelimitedStreamDataSource(name, reader, delimiter); } public static DelimitedStreamDataSource createDelimitedStreamDataSource(String name, Reader reader, List<String> fields, String delimiter) { return new DelimitedStreamDataSource(name, reader, fields, delimiter); } public static FixedStreamDataSource createFixedStreamDataSource(String name, Reader reader, Object... fieldInput) { return new FixedStreamDataSource(name, reader, fieldInput); } public static CatoComparison compare(String name, CatoDataSource leftDataSource, CatoDataSource rightDataSource, List<String> keyFields) { return compare(name, leftDataSource, rightDataSource, new SimpleCatoProperties(keyFields)); } public static CatoComparison compare(String name, CatoDataSource leftDataSource, CatoDataSource rightDataSource, List<String> keyFields, List<String> excludeFields) { return compare(name, leftDataSource, rightDataSource, new SimpleCatoProperties(keyFields, excludeFields)); } public static CatoComparison compare(String name, CatoDataSource leftDataSource, CatoDataSource rightDataSource, CatoProperties properties) { return compare(name, leftDataSource, rightDataSource, new CatoSimpleJavaConfiguration(properties)); } private static CatoComparison compare(String comparisonName, CatoDataSource leftDataSource, CatoDataSource rightDataSource, CatoConfiguration appContext) { LOG.info("Beginning comparison of left data source '{}' to right data source '{}'", leftDataSource.getName(), rightDataSource.getName()); CatoProperties properties = appContext.getProperties(); leftDataSource.setCatoConfiguration(appContext); rightDataSource.setCatoConfiguration(appContext); CatoDataSourceComparator dataSourceComparator = appContext.dataSourceComparator(); CatoBreakExcluder breakExcluder = appContext.breakExcluder(); CatoComparison result = dataSourceComparator.compare(comparisonName, leftDataSource, rightDataSource); if (properties.getBreakExcludes() != null && properties.getBreakExcludes().size() != 0) { breakExcluder.excludeBreaks(result.getBreaks(), properties.getBreakExcludes()); } LOG.info("Completed comparison of left data source '{}' to right data source '{}'", leftDataSource.getName(), rightDataSource.getName()); return result; } public static void writeComparison(CatoComparison comparison, CatoComparisonWriter comparisonWriter) throws IOException { comparisonWriter.writeComparison(comparison); comparisonWriter.close(); } public static void writeComparison(Collection<CatoComparison> comparisons, CatoMultiComparisonWriter comparisonWriter) throws IOException { comparisonWriter.writeComparison(comparisons); comparisonWriter.close(); } public static String getDateStr() { return new SimpleDateFormat("MM-dd-yyyy HH.mm.ss").format(new Date()); } }
45.129032
124
0.742137
051f9c96e1fd42cead2731874e071884c66d5e14
2,681
package view; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; final class GuiCreator { private GuiCreator() {} static JTextArea createTextArea(boolean lineWrap, boolean opaque, boolean editable) { JTextArea textArea = new JTextArea(); textArea.setLineWrap(lineWrap); textArea.setWrapStyleWord(true); textArea.setOpaque(opaque); textArea.setEditable(editable); return textArea; } static JLabel createLabel(String text, int horizontalAlignment, Font font) { JLabel label = new JLabel(text, horizontalAlignment); label.setFont(font); return label; } static JPanel createPanel(LayoutManager layout, Dimension preferredSize, Border border) { JPanel panel = createPanel(layout, preferredSize); panel.setBorder(border); return panel; } static JPanel createPanel(LayoutManager layout, Dimension preferredSize) { JPanel panel = createPanel(layout); panel.setPreferredSize(preferredSize); return panel; } static JPanel createPanel(LayoutManager layout, Border border) { JPanel panel = createPanel(layout); panel.setBorder(border); return panel; } static JPanel createPanel(LayoutManager layout) { JPanel panel = new JPanel(); panel.setLayout(layout); return panel; } static JPanel createPanel(Border border) { JPanel panel = new JPanel(); panel.setBorder(border); return panel; } static LayeredPane createLayeredPane(Dimension dimension, float alignmentX, float alignmentY) { LayeredPane layeredPane = createLayeredPane(dimension, alignmentX); layeredPane.setAlignmentY(alignmentY); return layeredPane; } static LayeredPane createLayeredPane(float alignmentX, float alignmentY) { LayeredPane layeredPane = createLayeredPane(alignmentX); layeredPane.setAlignmentY(alignmentY); return layeredPane; } static LayeredPane createLayeredPane(Dimension dimension, float alignmentX) { LayeredPane layeredPane = createLayeredPane(dimension); layeredPane.setAlignmentX(alignmentX); return layeredPane; } static LayeredPane createLayeredPane(float alignmentX) { LayeredPane layeredPane = new LayeredPane(); layeredPane.setAlignmentX(alignmentX); return layeredPane; } static LayeredPane createLayeredPane(Dimension dimension) { LayeredPane layeredPane = new LayeredPane(); layeredPane.setPreferredSize(dimension); return layeredPane; } }
27.639175
99
0.6837
525b5ff378a327c7b2498a5e9ec60b05579ef50e
2,232
package seedu.savenus.logic.commands; import static java.util.Objects.requireNonNull; import java.util.List; import javafx.collections.ObservableList; import javafx.collections.transformation.SortedList; import seedu.savenus.logic.commands.exceptions.CommandException; import seedu.savenus.model.Model; import seedu.savenus.model.food.Food; import seedu.savenus.model.sort.FoodComparator; //@@author seanlowjk /** * Sorts all the foods in the $aveNUS menu based on given criterion. */ public class SortCommand extends Command { public static final String COMMAND_WORD = "sort"; public static final String EXAMPLE_USAGE = "Example Usage: " + COMMAND_WORD + " PRICE ASC NAME DESC"; public static final String MESSAGE_SUCCESS = "You have successfully sorted the food items!"; public static final String NO_FIELDS_ERROR = "You have keyed in zero fields! " + "You need to key in at least one field."; public static final String AUTO_SORT_WARNING = "Autosort is turned on! \n" + "This command will not work unless you turn autosort off."; private List<String> fields; /** * Create a simple Sort Command. * @param fields the list of fields. */ public SortCommand(List<String> fields) { this.fields = fields; } public List<String> getFields() { return this.fields; } @Override public CommandResult execute(Model model) throws CommandException { requireNonNull(model); if (model.getAutoSortFlag() == true) { return new CommandResult(AUTO_SORT_WARNING); } // Clear the recommendation system (if it was used) model.setRecommendationSystemInUse(false); ObservableList<Food> foodList = model.getFilteredFoodList(); SortedList<Food> sortedList = foodList.sorted(new FoodComparator(fields)); model.setFoods(sortedList); return new CommandResult(MESSAGE_SUCCESS); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof SortCommand // instanceof handles nulls && getFields().equals(((SortCommand) other).getFields())); } }
34.338462
105
0.6931
b85adb86abfad2f67ec2461675895f435a2756f4
5,969
package com.example.android.quakereport; import android.app.Activity; import android.graphics.drawable.GradientDrawable; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; /** * Created by liway on 24/08/2017. * custom adapter to cater to the EarthquakeInfo object */ public class EarthquakeInfoAdapter extends ArrayAdapter<Earthquake> { String locationEstimate, location; private static final String LOCATION_DESCRIPTION = "Near the "; private static final String LOCATION_SEPARATOR = "of"; public EarthquakeInfoAdapter(Activity context, ArrayList<Earthquake> earthquakeInfo){ super(context,0, earthquakeInfo); } // control how the listview items are created @Override public View getView(int position, View convertView, ViewGroup parent) { // Check if the existing view is being reused, otherwise inflate the view View listItemView = convertView; if(listItemView == null) { listItemView = LayoutInflater.from(getContext()).inflate( R.layout.earthquake_list, parent, false); } Earthquake currentEquakeInfo = getItem(position); // Find the TextView in the xml layout with the ID magTextView, and set its value TextView magTextView = (TextView) listItemView.findViewById(R.id.magnitude); magTextView.setText(formatMagnitude(currentEquakeInfo.getMag())); // Set the proper background color on the magnitude circle. // Fetch the background from the TextView, which is a GradientDrawable. GradientDrawable magnitudeCircle = (GradientDrawable) magTextView.getBackground(); // Get the appropriate background color based on the current earthquake magnitude int magnitudeColor = getMagnitudeColor(currentEquakeInfo.getMag()); // Set the color on the magnitude circle magnitudeCircle.setColor(magnitudeColor); // Find the TextView in the xml layout with the ID cityTextView, and set its value TextView cityTextView = (TextView) listItemView.findViewById(R.id.primary_location); TextView locationEstimateTextView = (TextView) listItemView.findViewById(R.id.location_offset); String locationInfo = currentEquakeInfo.getCity(); if(locationInfo.contains(LOCATION_SEPARATOR)){ splitString(locationInfo); locationEstimateTextView.setText(locationEstimate + LOCATION_SEPARATOR); cityTextView.setText(location); } else{ locationEstimateTextView.setText(LOCATION_DESCRIPTION); cityTextView.setText(locationInfo); } // create Date object from the Equake info Date dateObject = new Date(currentEquakeInfo.getDate()); // Find the TextView in the xml layout with the ID dateTextView, and set its value TextView dateTextView = (TextView) listItemView.findViewById(R.id.date); dateTextView.setText(formatDate(dateObject)); // Find the TextView in the xml layout with the ID timeTextView, and set its value TextView timeTextView = (TextView) listItemView.findViewById(R.id.time); timeTextView.setText(formatTime(dateObject)); // Return the whole list item layout so that it can be shown in the ListView return listItemView; } /** * Return the formatted magnitude string showing 1 decimal place (i.e. "3.2") * from a decimal magnitude value. */ private String formatMagnitude(double magnitude) { DecimalFormat magnitudeFormat = new DecimalFormat("0.0"); return magnitudeFormat.format(magnitude); } /** * Return the formatted magnitude string showing 1 decimal place (i.e. "3.2") * from a decimal magnitude value. */ private int getMagnitudeColor(double magnitude) { int magnitudeColor; switch ((int)Math.floor(magnitude)){ case 0: case 1: magnitudeColor = R.color.magnitude1; break; case 2: magnitudeColor = R.color.magnitude2; break; case 3: magnitudeColor = R.color.magnitude3; break; case 4: magnitudeColor = R.color.magnitude4; break; case 5: magnitudeColor = R.color.magnitude5; break; case 6: magnitudeColor = R.color.magnitude6; break; case 7: magnitudeColor = R.color.magnitude7; break; case 8: magnitudeColor = R.color.magnitude8; break; case 9: magnitudeColor = R.color.magnitude9; break; default: magnitudeColor = R.color.magnitude10plus; break; } return ContextCompat.getColor(getContext(), magnitudeColor); } /** * Return the formatted date string (i.e. "Mar 3, 1984") from a Date object. */ private String formatDate(Date dateObject) { SimpleDateFormat dateFormat = new SimpleDateFormat("MMM DD, yyyy"); return dateFormat.format(dateObject); } /** * Return the formatted date string (i.e. "4:30 PM") from a Date object. */ private String formatTime(Date dateObject) { SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a"); return timeFormat.format(dateObject); } private void splitString(String s){ String[] parts = s.split(LOCATION_SEPARATOR); locationEstimate= parts[0]; location = parts[1]; } }
36.396341
92
0.649523
6dd2fb37bf9a26bcaac6792579b03af5869effe5
5,427
package com.raoulvdberge.refinedstorage.screen.widget; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; import com.raoulvdberge.refinedstorage.RS; import com.raoulvdberge.refinedstorage.api.network.grid.IGridTab; import com.raoulvdberge.refinedstorage.apiimpl.render.ElementDrawers; import com.raoulvdberge.refinedstorage.screen.BaseScreen; import com.raoulvdberge.refinedstorage.util.RenderUtils; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.widget.button.Button; import java.util.LinkedList; import java.util.List; import java.util.function.Supplier; public class TabListWidget { public interface ITabListListener { void onSelectionChanged(int tab); void onPageChanged(int page); } private BaseScreen gui; private ElementDrawers drawers; private Supplier<List<IGridTab>> tabs; private int tabHovering; private int tabsPerPage; private Supplier<Integer> pages; private Supplier<Integer> page; private Supplier<Integer> selected; private boolean hadTabs; private List<ITabListListener> listeners = new LinkedList<>(); private Button left; private Button right; public TabListWidget(BaseScreen gui, ElementDrawers drawers, Supplier<List<IGridTab>> tabs, Supplier<Integer> pages, Supplier<Integer> page, Supplier<Integer> selected, int tabsPerPage) { this.gui = gui; this.drawers = drawers; this.tabs = tabs; this.pages = pages; this.page = page; this.selected = selected; this.tabsPerPage = tabsPerPage; } public void init(int width) { this.left = gui.addButton(gui.getGuiLeft(), gui.getGuiTop() - 22, 20, 20, "<", true, pages.get() > 0, btn -> listeners.forEach(t -> t.onPageChanged(page.get() - 1))); this.right = gui.addButton(gui.getGuiLeft() + width - 22, gui.getGuiTop() - 22, 20, 20, ">", true, pages.get() > 0, btn -> listeners.forEach(t -> t.onPageChanged(page.get() + 1))); } public void addListener(ITabListListener listener) { listeners.add(listener); } public void drawForeground(int x, int y, int mouseX, int mouseY, boolean visible) { this.tabHovering = -1; if (visible) { int j = 0; for (int i = page.get() * tabsPerPage; i < (page.get() * tabsPerPage) + tabsPerPage; ++i) { if (i < tabs.get().size()) { drawTab(tabs.get().get(i), true, x, y, i, j); if (RenderUtils.inBounds(x + getXOffset() + ((IGridTab.TAB_WIDTH + 1) * j), y, IGridTab.TAB_WIDTH, IGridTab.TAB_HEIGHT - (i == selected.get() ? 2 : 7), mouseX, mouseY)) { this.tabHovering = i; } j++; } } } } public void update() { boolean hasTabs = !tabs.get().isEmpty(); if (this.hadTabs != hasTabs) { this.hadTabs = hasTabs; gui.init(); } if (page.get() > pages.get()) { listeners.forEach(t -> t.onPageChanged(pages.get())); } left.visible = pages.get() > 0; right.visible = pages.get() > 0; left.active = page.get() > 0; right.active = page.get() < pages.get(); } public void drawBackground(int x, int y) { int j = 0; for (int i = page.get() * tabsPerPage; i < (page.get() * tabsPerPage) + tabsPerPage; ++i) { if (i < tabs.get().size()) { drawTab(tabs.get().get(i), false, x, y, i, j++); } } } public int getHeight() { return !tabs.get().isEmpty() ? IGridTab.TAB_HEIGHT - 4 : 0; } private int getXOffset() { if (pages.get() > 0) { return 24; } return 0; } private void drawTab(IGridTab tab, boolean foregroundLayer, int x, int y, int index, int num) { boolean isSelected = index == selected.get(); if ((foregroundLayer && !isSelected) || (!foregroundLayer && isSelected)) { return; } int tx = x + getXOffset() + ((IGridTab.TAB_WIDTH + 1) * num); int ty = y; RenderSystem.enableAlphaTest(); gui.bindTexture(RS.ID, "icons.png"); if (!isSelected) { ty += 3; } int uvx; int uvy = 225; int tbw = IGridTab.TAB_WIDTH; int otx = tx; if (isSelected) { uvx = 227; if (num > 0 || getXOffset() != 0) { uvx = 226; uvy = 194; tbw++; tx--; } } else { uvx = 199; } gui.blit(tx, ty, uvx, uvy, tbw, IGridTab.TAB_HEIGHT); tab.drawIcon(otx + 6, ty + 9 - (!isSelected ? 3 : 0), drawers.getItemDrawer(), drawers.getFluidDrawer()); } public void drawTooltip(FontRenderer fontRenderer, int mouseX, int mouseY) { if (tabHovering >= 0 && tabHovering < tabs.get().size()) { tabs.get().get(tabHovering).drawTooltip(mouseX, mouseY, gui.width, gui.height, fontRenderer); } } public boolean mouseClicked() { if (tabHovering >= 0 && tabHovering < tabs.get().size()) { listeners.forEach(t -> t.onSelectionChanged(tabHovering)); return true; } return false; } }
30.835227
191
0.573982
cdd031f8c625809a664036c085011f7443ddded2
716
/** * */ package com.inicu.hl7.data.acquisition; import java.util.Map; import ca.uhn.hl7v2.HL7Exception; import ca.uhn.hl7v2.protocol.ReceivingApplicationExceptionHandler; /** * @author sanoob * iNICU * 24-Feb-2017 */ public class HL7ExceptionHandler implements ReceivingApplicationExceptionHandler { @Override public String processException(String inComingMessage, Map<String, Object> metadataMap, String outgoingMessage, Exception excp) throws HL7Exception { /* * Here you can do any processing you like. If you want to change the * response (NAK) message which will be returned you may do so, or just * return the default NAK (outgoingMessage) */ return outgoingMessage; } }
22.375
128
0.747207
0d134a9c8f7e9274c63a108f72257e5a99383e7c
4,631
/** * Copyright (c) 2014, Sebastian Sdorra All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. 2. Redistributions in * binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. 3. Neither the name of SCM-Manager; * nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * http://bitbucket.org/sdorra/scm-manager * */ package sonia.scm.repository.api; //~--- non-JDK imports -------------------------------------------------------- import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; import sonia.scm.repository.Changeset; import sonia.scm.repository.spi.HookChangesetProvider; import sonia.scm.repository.spi.HookChangesetRequest; import sonia.scm.repository.spi.javahg.AbstractChangesetCommand; import sonia.scm.util.Util; //~--- JDK imports ------------------------------------------------------------ import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Mercurial hook branch provider implementation. * * @author Sebastian Sdorra */ public class HgHookBranchProvider implements HookBranchProvider { private static final Logger logger = LoggerFactory.getLogger(HgHookBranchProvider.class); private static final HookChangesetRequest REQUEST = new HookChangesetRequest(); //~--- constructors --------------------------------------------------------- /** * Constructs a new instance. * * * @param changesetProvider changeset provider */ public HgHookBranchProvider(HookChangesetProvider changesetProvider) { this.changesetProvider = changesetProvider; } //~--- get methods ---------------------------------------------------------- @Override public List<String> getCreatedOrModified() { if (createdOrModified == null) { collect(); } return createdOrModified; } @Override public List<String> getDeletedOrClosed() { if (deletedOrClosed == null) { collect(); } return deletedOrClosed; } //~--- methods -------------------------------------------------------------- private List<String> appendBranches(Builder<String> builder, Changeset c) { List<String> branches = c.getBranches(); if (Util.isEmpty(branches)) { builder.add(AbstractChangesetCommand.BRANCH_DEFAULT); } else { builder.addAll(branches); } return branches; } private Iterable<Changeset> changesets() { return changesetProvider.handleRequest(REQUEST).getChangesets(); } private void collect() { Builder<String> createdOrModifiedBuilder = ImmutableList.builder(); Builder<String> deletedOrClosedBuilder = ImmutableList.builder(); logger.trace("collecting branches from hook changesets"); for (Changeset c : changesets()) { if (c.getProperty(AbstractChangesetCommand.PROPERTY_CLOSE) != null) { appendBranches(deletedOrClosedBuilder, c); } else { appendBranches(createdOrModifiedBuilder, c); } } createdOrModified = createdOrModifiedBuilder.build(); deletedOrClosed = deletedOrClosedBuilder.build(); } //~--- fields --------------------------------------------------------------- private final HookChangesetProvider changesetProvider; private List<String> createdOrModified; private List<String> deletedOrClosed; }
29.685897
91
0.6748
1a41ccb8e80d27e730507d90e50314b73f4beb6d
1,907
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 油站信息 * * @author auto create * @since 1.0, 2019-11-25 16:22:33 */ public class OilStationDetails extends AlipayObject { private static final long serialVersionUID = 5345526333663841952L; /** * 油站详细地址 */ @ApiField("address") private String address; /** * 直降金额 */ @ApiField("discount_price") private String discountPrice; /** * 油站名称 */ @ApiField("oil_station_name") private String oilStationName; /** * 油品 */ @ApiField("oil_type") private String oilType; /** * 高德 poi_id */ @ApiField("poi_id") private String poiId; /** * 油价,以元为单位 */ @ApiField("sale_price") private String salePrice; /** * 油站门店ID */ @ApiField("shop_id") private String shopId; public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; } public String getDiscountPrice() { return this.discountPrice; } public void setDiscountPrice(String discountPrice) { this.discountPrice = discountPrice; } public String getOilStationName() { return this.oilStationName; } public void setOilStationName(String oilStationName) { this.oilStationName = oilStationName; } public String getOilType() { return this.oilType; } public void setOilType(String oilType) { this.oilType = oilType; } public String getPoiId() { return this.poiId; } public void setPoiId(String poiId) { this.poiId = poiId; } public String getSalePrice() { return this.salePrice; } public void setSalePrice(String salePrice) { this.salePrice = salePrice; } public String getShopId() { return this.shopId; } public void setShopId(String shopId) { this.shopId = shopId; } }
17.657407
68
0.65915
3a9f7b8c2b5c51dd0344097ee6d6ee178f44a502
2,563
package com.ray3k.stripe.test; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application; import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.utils.viewport.ScreenViewport; import com.badlogic.gdx.utils.viewport.StretchViewport; import com.badlogic.gdx.utils.viewport.Viewport; import com.ray3k.stripe.ResizeWidget; import com.ray3k.stripe.ViewportWidget; public class ViewportWidgetTest extends ApplicationAdapter { private Skin skin; private Stage stage; private Viewport gameViewport; private SpriteBatch spriteBatch; @Override public void create() { skin = new Skin(Gdx.files.internal("resize-widget/skin.json")); spriteBatch = new SpriteBatch(); stage = new Stage(new ScreenViewport()); Gdx.input.setInputProcessor(stage); gameViewport = new StretchViewport(800, 800); ViewportWidget viewportWidget = new ViewportWidget(gameViewport); ResizeWidget resizeWidget = new ResizeWidget(viewportWidget, skin, "default"); resizeWidget.setResizingFromCenter(true); resizeWidget.setMinWidth(100); resizeWidget.setMinHeight(100); resizeWidget.setFillParent(true); stage.addActor(resizeWidget); } @Override public void render() { Gdx.gl.glClearColor(1, 1, 1, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); stage.act(); gameViewport.apply(true); spriteBatch.setProjectionMatrix(gameViewport.getCamera().combined); TextureRegion textureRegion = skin.getRegion("island"); spriteBatch.begin(); spriteBatch.draw(textureRegion, 0, 0); spriteBatch.end(); stage.getViewport().apply(); stage.draw(); } @Override public void resize(int width, int height) { stage.getViewport().update(width, height, true); } @Override public void dispose() { skin.dispose(); } public static void main(String[] args) { Lwjgl3ApplicationConfiguration config = new Lwjgl3ApplicationConfiguration(); config.setWindowedMode(800, 800); new Lwjgl3Application(new ViewportWidgetTest(), config); } }
34.173333
86
0.69723
95de9e8ad2bfd1583d9c4a74cbcbc4943e571f8b
902
package com.jimmy.service.impl; import com.jimmy.dao.UserCheckMapper; import com.jimmy.entity.UserInfo; import com.jimmy.service.UserCheck; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * <p> * User: lian zd Date:2017/9/21 ProjectName: spring_learn1 Version: 1.0 */ @Service public class UserCheckImpl implements UserCheck { @Autowired(required = false) private UserCheckMapper userCheckMapper; /** * 登录验证 * * @param userName 登录名 * @param passWord 密码 * @return 账户信息 */ @Override public UserInfo checkUser(String userName, String passWord) { UserInfo userInfo = new UserInfo(); userInfo.setUserName(userName); userInfo.setPassWord(passWord); UserInfo userInfoResult = userCheckMapper.getUserInfo(userInfo); return userInfoResult; } }
25.771429
72
0.706208
80e7bc10d6585224a81776272f935006e3f6ad0d
1,369
package br.com.location.indoor.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import br.com.location.indoor.dto.RouteDto; import br.com.location.indoor.dto.RouteFormDto; import br.com.location.indoor.model.Route; import br.com.location.indoor.repository.RouteRepository; @Service public class RouteService { @Autowired private RouteRepository routeRository; public List<RouteDto> findAll() { return null; } public RouteDto findRoute(RouteFormDto routeForm) { Optional<Route> currentRoute = getRoute(routeForm); return currentRoute.isPresent() ? new RouteDto(currentRoute.get()) : new RouteDto(); } private Optional<Route> getRoute(RouteFormDto routeForm) { Optional<Route> currentRoute = routeRository.findByInitialLocationAndFinalLocation(routeForm.getInitialLocation(), routeForm.getFinalLocation()); return currentRoute; } public RouteDto saveRoute(RouteFormDto routeForm) { Optional<Route> route = getRoute(routeForm); if (route.isPresent()) { return new RouteDto(route.get()); } Route routeToSave = new Route(routeForm); routeRository.save(routeToSave); return new RouteDto(routeToSave); } }
30.422222
153
0.724617
1e7fcaf0fcb4daabf41675c6a4c12d28f35a8806
3,596
/** * */ package csironi.ggp.course.gamers.old; import java.util.ArrayList; import java.util.List; import org.ggp.base.player.gamer.event.GamerSelectedMoveEvent; import org.ggp.base.player.gamer.statemachine.sample.SampleGamer; import org.ggp.base.util.statemachine.abstractsm.AbstractStateMachine; import org.ggp.base.util.statemachine.exceptions.GoalDefinitionException; import org.ggp.base.util.statemachine.exceptions.MoveDefinitionException; import org.ggp.base.util.statemachine.exceptions.StateMachineException; import org.ggp.base.util.statemachine.exceptions.TransitionDefinitionException; import org.ggp.base.util.statemachine.structure.MachineState; import org.ggp.base.util.statemachine.structure.Move; import org.ggp.base.util.statemachine.structure.Role; import org.ggp.base.util.statemachine.structure.explicit.ExplicitMove; /** * Implementation of a Compulsive Deliberation player for the GGP course. * * NOTE: this player only works on single-player games! Do not use it for multi-player games! * * @author C.Sironi * */ public class MyDeliberationGamer extends SampleGamer { /** * */ public MyDeliberationGamer() { // TODO Auto-generated constructor stub } /* (non-Javadoc) * @see org.ggp.base.player.gamer.statemachine.StateMachineGamer#stateMachineSelectMove(long) */ @Override public ExplicitMove stateMachineSelectMove(long timeout) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException, StateMachineException { long start = System.currentTimeMillis(); AbstractStateMachine stateMachine = getStateMachine(); MachineState state = getCurrentState(); Role role = getRole(); List<Move> moves = stateMachine.getLegalMoves(state, role); Move selection = bestmove(role, state); long stop = System.currentTimeMillis(); notifyObservers(new GamerSelectedMoveEvent(stateMachine.convertToExplicitMoves(moves), stateMachine.convertToExplicitMove(selection), stop - start)); return stateMachine.convertToExplicitMove(selection); } /** * @throws StateMachineException * * */ private Move bestmove(Role role, MachineState state) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException, StateMachineException{ AbstractStateMachine stateMachine = getStateMachine(); List<Move> moves = stateMachine.getLegalMoves(state, role); Move selection = moves.get(0); double maxScore = 0; for (Move move: moves){ ArrayList<Move> jointMoves = new ArrayList<Move>(); jointMoves.add(move); double currentScore = maxscore(role, stateMachine.getNextState(state, jointMoves)); if(currentScore == 100){ return move; } if(currentScore > maxScore){ maxScore = currentScore; selection = move; } } return selection; } /** * @throws StateMachineException * * */ private double maxscore(Role role, MachineState state) throws TransitionDefinitionException, MoveDefinitionException, GoalDefinitionException, StateMachineException{ AbstractStateMachine stateMachine = getStateMachine(); if(stateMachine.isTerminal(state)){ return stateMachine.getSafeGoalsAvgForAllRoles(state)[stateMachine.getRoleIndices().get(role)]; } List<Move> moves = stateMachine.getLegalMoves(state, role); double maxScore = 0; for (Move move: moves){ ArrayList<Move> jointMoves = new ArrayList<Move>(); jointMoves.add(move); double currentScore = maxscore(role, stateMachine.getNextState(state, jointMoves)); if(currentScore > maxScore){ maxScore = currentScore; } } return maxScore; } }
29
151
0.766963
e60601f43e8dc9b7ac087b0121bf009b170a6183
3,463
/* * Copyright 2018-2019 Karakun AG. * Copyright 2015-2018 Canoo Engineering AG. * * 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 dev.rico.internal.core.functional; import dev.rico.core.functional.CheckedBiFunction; import dev.rico.core.functional.CheckedConsumer; import dev.rico.core.functional.CheckedFunction; import dev.rico.core.functional.CheckedRunnable; import dev.rico.core.functional.Result; import dev.rico.core.functional.ResultWithInput; import dev.rico.internal.core.Assert; import java.util.function.BiConsumer; import java.util.function.Consumer; /** * Implementation of a {@link dev.rico.core.functional.Result} that is based * on a successfully executed function * * @param <T> type of the input * @param <R> type of the output */ public class Success<T, R> implements ResultWithInput<T, R> { private final T input; private final R result; public Success(final T input, final R result) { this.input = input; this.result = result; } public Success(final R result) { this.input = null; this.result = result; } @Override public boolean isSuccessful() { return true; } @Override public T getInput() { return input; } @Override public Exception getException() { return null; } @Override public R getResult() { return result; } @Override public R orElse(R value) { return result; } @Override public <U> Result<U> map(final CheckedFunction<R, U> mapper) { Assert.requireNonNull(mapper, "mapper"); try { return new Success<>(input, mapper.apply(result)); } catch (Exception e) { return new Fail<>(input, e); } } @Override public Result<R> recover(CheckedFunction<Exception, R> exceptionHandler) { Assert.requireNonNull(exceptionHandler, "exceptionHandler"); return this; } @Override public ResultWithInput<T, R> recover(CheckedBiFunction<T, Exception, R> exceptionHandler) { Assert.requireNonNull(exceptionHandler, "exceptionHandler"); return this; } @Override public Result<Void> onSuccess(CheckedConsumer<R> consumer) { Assert.requireNonNull(consumer, "consumer"); return map(v -> { consumer.accept(v); return null; }); } @Override public Result<Void> onSuccess(CheckedRunnable runnable) { Assert.requireNonNull(runnable, "runnable"); return map(v -> { runnable.run(); return null; }); } @Override public void onFailure(Consumer<Exception> consumer) { Assert.requireNonNull(consumer, "consumer"); // do nothing } @Override public void onFailure(BiConsumer<T, Exception> consumer) { Assert.requireNonNull(consumer, "consumer"); // do nothing } }
26.435115
95
0.654346
60d34b8be51d329a23a23032b8745797e11c91fe
4,646
package br.com.zup.mercadolivre.controller.request; import br.com.zup.mercadolivre.model.Category; import br.com.zup.mercadolivre.model.Product; import br.com.zup.mercadolivre.model.User; import br.com.zup.mercadolivre.repository.CategoryRepository; import br.com.zup.mercadolivre.validator.ExistsId; import br.com.zup.mercadolivre.validator.UniqueValue; import org.hibernate.validator.constraints.Length; import javax.validation.Valid; import javax.validation.constraints.*; import java.math.BigDecimal; import java.util.*; import java.util.stream.Collectors; public class ProductRequestDto { @NotBlank(message = "O nome é obrigatório.") @UniqueValue(domainClass = Product.class, fieldName = "name", message = "Produto já cadastrado.") private String name; @NotNull(message = "A quantidade é obrigatória.") @PositiveOrZero(message = "A quantidade deve ser maior ou igual a zero.") private Integer quantity; @NotBlank(message = "A descrição é obrigatória.") @Length(max = 1000, message = "A descrição deve ter no máximo 1000 caracteres.") private String description; @NotNull(message = "O preço é obrigatório.") @Positive(message = "Preço precisa ser um valor positivo.") private BigDecimal price; @NotNull(message = "Obrigatório informar a categoria.") @ExistsId(domainClass = Category.class, fieldName = "id") private Long categoryId; @Size(min = 3, message = "É preciso informar pelo menos três características do produto.") @Valid private List<CharacteristicsRequestDto> characteristics = new ArrayList<>(); @Deprecated public ProductRequestDto(){} public ProductRequestDto(@NotBlank(message = "O nome é obrigatório.") String name, @NotBlank(message = "A quantidade é obrigatória.") @NotNull(message = "A quantidade é obrigatória.") @PositiveOrZero(message = "A quantidade deve ser maior ou igual a zero.") Integer quantity, @NotBlank(message = "A descrição é obrigatória.") @Length(max = 1000, message = "A descrição deve ter no máximo 1000 caracteres.") String description, @NotNull(message = "O preço é obrigatório.") @Positive(message = "Preço precisa ser um valor positivo.") BigDecimal price, @NotNull(message = "Obrigatório informar a categoria.") Long categoryId, @Size(min = 3, message = "É preciso informar pelo menos três características do produto.") List<CharacteristicsRequestDto> characteristics) { this.name = name; this.quantity = quantity; this.description = description; this.price = price; this.categoryId = categoryId; this.characteristics.addAll(characteristics); } public String getName() { return name; } public Integer getQuantity() { return quantity; } public String getDescription() { return description; } public BigDecimal getPrice() { return price; } public Long getCategoryId() { return categoryId; } public List<CharacteristicsRequestDto> getCharacteristics() { return characteristics; } @Override public String toString() { return "ProductRequestDto{" + "Preço:'" + name + '\'' + ", Quantidade:" + quantity + ", Descrição:'" + description + '\'' + ", Preço:" + price + ", CategoriaId:" + categoryId + ", Características:" + characteristics.stream().map(item -> item.getName() + ": " + item.getDescription()).collect(Collectors.toList()) + '}'; } public Product toModel(CategoryRepository repository, User productOwner) { Category category = repository.findById(categoryId).orElseThrow(() -> new NoSuchElementException("Categoria não encontrada.")); return new Product(name, quantity, description, price, category, productOwner, characteristics); } public Set<String> findRepeatedCharacteristics() { HashSet<String> equalNames = new HashSet<>(); HashSet<String> result = new HashSet<>(); for (CharacteristicsRequestDto characteristic : characteristics) { String name = characteristic.getName(); if (!equalNames.add(name)) { result.add(name); } } return result; } }
38.081967
129
0.626991
9ce6fe455e8d389f681df23501b664e2aff5bbe9
999
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.iot.deviceupdate.models; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; /** Operation status filter. */ @Fluent public final class OperationFilter { /* * Operation status filter. */ @JsonProperty(value = "status") private OperationFilterStatus status; /** * Get the status property: Operation status filter. * * @return the status value. */ public OperationFilterStatus getStatus() { return this.status; } /** * Set the status property: Operation status filter. * * @param status the status value to set. * @return the OperationFilter object itself. */ public OperationFilter setStatus(OperationFilterStatus status) { this.status = status; return this; } }
25.615385
68
0.675676
223f74a887b20c889d5d6fa69afcc102ba9d67d0
11,214
/* * 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.river.test.spec.export.servercontext; // org.apache.river.qa import org.apache.river.qa.harness.QATestEnvironment; // org.apache.river.qa.harness import org.apache.river.qa.harness.QAConfig; // base class for QAConfig import org.apache.river.qa.harness.Test; import org.apache.river.qa.harness.TestException; // java.util import java.util.logging.Level; import java.util.ArrayList; import java.util.Collection; // davis packages import net.jini.export.ServerContext; // java.rmi // Server Context Elements import org.apache.river.test.spec.export.util.FakeType; import org.apache.river.test.spec.export.util.AnFakeType; /** * <pre> * * Purpose: * This test verifies the behavior of the * {@link net.jini.export.ServerContext#getServerContextElement(Class)} * method. * getServerContextElement() returns the first element in the current * server context collection (obtained by calling * {@link net.jini.export.ServerContext#getServerContext()}) that is an * instance of the given type. If no element in the collection is an * instance of the type, then null is returned. * Parameters: * type - the type of the element * Returns: * the first element in the server context collection that is an instance * of the type or null * * Test Cases: * TestCase 1: * getServerContextElement(FakeType.class) method is invoked when an empty * context is set for the current thread. * It's expected that null is returned. * TestCase 2: * getServerContextElement(FakeType.class) method is invoked when context is * set for the current thread; in this context collection only one element * is an instance of the type FakeType. * It's expected that this element of the type FakeType is returned. * TestCase 3: * getServerContextElement(FakeType.class) method is invoked when context is * set for the current thread; there are 2 elements that are instances of * the type FakeType in this context collection. * It's expected that the first element of the type FakeType is returned. * * Infrastructure: * - {@link GetServerContextElement} * performs actions * - {@link org.apache.river.test.spec.export.util.FakeType} * used as an element in a context * - {@link org.apache.river.test.spec.export.util.AnFakeType} * used as an element in a context * * Actions: * Test performs the following steps: * - creating context collection elements: * - 2 FakeType objects and * - 1 AnFakeType object; * - creating an empty context collection; * - creating context collection that contains only one element of the * type FakeType; * - creating context collection that contains 2 elements of the type * FakeType. * In each test case the test invokes getServerContextElement() method; * the server context is set with * {@link net.jini.export.ServerContext#doWithServerContext(Runnable,Collection)} * method. The returned result is compared with the expected one. * * </pre> */ public class GetServerContextElement extends QATestEnvironment implements Test { QAConfig config; /** * Server context element of the type * {@link org.apache.river.test.spec.export.util.FakeType} */ FakeType cnxtElement1; /** * Server context element of the type * {@link org.apache.river.test.spec.export.util.FakeType} */ FakeType cnxtElement2; /** * Server context element of the type * {@link org.apache.river.test.spec.export.util.AnFakeType} */ AnFakeType cnxtElement3; /** * Server context collection for use in TestCase #1. */ ArrayList context1; /** * Server context collection for use in TestCase #2. */ ArrayList context2; /** * Server context collection for use in TestCase #3. */ ArrayList context3; /** * String that describes a test case result. */ String testCaseResultDesc = null; /** * This method performs all preparations. */ public Test construct(QAConfig config) throws Exception { super.construct(config); this.config = (QAConfig) config; // or this.config = getConfig(); /* Create server context elements */ cnxtElement1 = new FakeType("Fake Context Element #1"); cnxtElement2 = new FakeType("Fake Context Element #2"); cnxtElement3 = new AnFakeType(1234567890); /* * Create server context collection for TestCase #1. * It's an empty server context collection without any element of * the type FakeType. */ context1 = new ArrayList(); context1.clear(); // logger.log(Level.FINE, // "context for TestCase #1:: " + context1.toString()); /* * Create server context collection for TestCase #2. * It consists of 1 element of the type FakeType and * 1 element of the type AnFakeType only. */ context2 = new ArrayList(); context2.clear(); context2.add(cnxtElement1); context2.add(cnxtElement3); // logger.log(Level.FINE, // "context for TestCase #2:: " + context2.toString()); /* * Create server context collection for TestCase #3. * It consists of 2 elements of the type FakeType and * 1 element of the type AnFakeType only. */ context3 = new ArrayList(); context3.clear(); context3.add(cnxtElement1); context3.add(cnxtElement2); context3.add(cnxtElement3); // logger.log(Level.FINE, // "context for TestCase #3:: " + context3.toString()); return this; } /** * This method performs all actions mentioned in class description. */ public void run() throws Exception { /* * TestCase 1: An empty server context collection * (no elements of the type FakeType) */ testCaseActions(1, "An empty server context collection (no elements of the type " + "FakeType)", (Collection) context1, FakeType.class, null); /* * TestCase 2: Server context collection consists of: * - 1 element of the type FakeType and * - 1 element of the type AnFakeType only */ testCaseActions(2, "Server context collection consists of 1 element of the type " + "FakeType and 1 element of the type AnFakeType only", (Collection) context2, FakeType.class, (Object) cnxtElement1); /* * TestCase 3: Server context collection consists of: * - 2 elements of the type FakeType and * - 1 element of the type AnFakeType only */ testCaseActions(3, "Server context collection consists of 2 elements of the type " + "FakeType and 1 element of the type AnFakeType only", (Collection) context3, FakeType.class, (Object) cnxtElement1); return; } /** * This method performs each test case actions. * The current server context is set with * {@link net.jini.export.ServerContext#doWithServerContext(Runnable,Collection)}. * In the run() method of the supplied {@link java.lang.Runnable} object * {@link net.jini.export.ServerContext#getServerContextElement(Class)} is * invoked. The result of getServerContextElement() is compared with the * supplied expected one. * * @param tc_num TestCase # * @param tc_desc TestCase description * @param context server context collection to set with * {@link net.jini.export.ServerContext#doWithServerContext(Runnable,Collection)} * @param type the type of element in the current server context collection * @param expCnxtElement expected element returned by * {@link net.jini.export.ServerContext#getServerContextElement(Class)} */ public void testCaseActions(int tc_num, String tc_desc, Collection context, final Class type, final Object expCnxtElement) throws Exception { logger.log(Level.FINE, "\n\n\t+++++ TestCase " + tc_num + " +++++\n"); logger.log(Level.FINE, tc_desc); logger.log(Level.FINE, "The supplied context:: " + context); ServerContext.doWithServerContext(new Runnable() { public void run() { /* * Try to get the first element in the current server * context collection that is an instance of the specified * type. */ try { Object retCnxtElement = ServerContext.getServerContextElement(type); logger.log(Level.FINE, "\texpected element:: " + expCnxtElement); logger.log(Level.FINE, "\treturned element:: " + retCnxtElement); if (expCnxtElement == retCnxtElement) { testCaseResultDesc = null; } else if (!type.isInstance(retCnxtElement)) { testCaseResultDesc = "Returned element in the current server " + "context collection isn't instance of " + type; } else if (!retCnxtElement.equals(expCnxtElement)) { testCaseResultDesc = "Returned element in the current server " + "context collection isn't equal to the " + "expected one"; } } catch (Exception e) { testCaseResultDesc = "ServerContext.getServerContextElement(" + type + ") has thrown: " + e; } } } , context); if (testCaseResultDesc != null) { logger.log(Level.FINE, "The reason of the FAIL:: " + testCaseResultDesc); throw new TestException(testCaseResultDesc); } return; } }
37.630872
86
0.616283
8e85d020f522b59375c19d8346043ffed9dbdc29
437
package com.thepencil.journel.ui; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import android.os.Bundle; import com.thepencil.journel.R; public class AuthActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); DataBindingUtil.setContentView(this, R.layout.activity_auth); } }
25.705882
69
0.782609
367d8437931d01d7664a5503c005fba8c45c9dd1
1,424
package com.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.model.User; @Repository public class UserDaoImpl implements UserDao { @Autowired private SessionFactory sessionFactory; public List<User> getAllUsers() { Session session = sessionFactory.openSession(); //List<Product> products = session.createQuery("from Product").list(); List<User> users= session.createCriteria(User.class).list(); System.out.println(users); session.close(); return users; } public void deleteUser(String userId) { Session session = sessionFactory.openSession(); User user = (User) session.get(User.class, userId); session.saveOrUpdate(user); session.flush(); session.close();// close the session } public void addUser(User user) { Session session = sessionFactory.openSession(); session.save(user); session.close(); } public User getUserById(String userId) { // Reading the records from the table Session session = sessionFactory.openSession(); // select * from Product where isbn=i // if we call get method,Record doesnot exist it will return null // if we call load, if the record doesnt exist it will throw exception User user = (User) session.get(User.class, userId); session.close(); return user; } }
26.867925
72
0.742978
c205d40f748b1f0deca0296cdf0acc8458d3b032
278
package com.knu.cse.member.dto; import lombok.Data; @Data public class LoginSuccessDto { private Long userId; private String nickname; public LoginSuccessDto(Long userId, String nickname) { this.userId = userId; this.nickname = nickname; } }
17.375
58
0.683453
9a772a2aa304a58dc972755f64e14684514158dd
140
package poussecafe.source.validation.namesmoduleduplicate; import poussecafe.domain.Module; public interface MyModule extends Module { }
17.5
58
0.835714
f7cccede56d410e539efb97a61b71d56d22ba69c
48,670
/* * 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.phoenix.coprocessor; import static org.apache.phoenix.coprocessor.GlobalIndexRegionScanner.adjustScanFilter; import static org.apache.phoenix.query.QueryConstants.AGG_TIMESTAMP; import static org.apache.phoenix.query.QueryConstants.SINGLE_COLUMN; import static org.apache.phoenix.query.QueryConstants.SINGLE_COLUMN_FAMILY; import static org.apache.phoenix.query.QueryConstants.UNGROUPED_AGG_ROW_KEY; import static org.apache.phoenix.schema.stats.StatisticsCollectionRunTracker.COMPACTION_UPDATE_STATS_ROW_COUNT; import static org.apache.phoenix.schema.stats.StatisticsCollectionRunTracker.CONCURRENT_UPDATE_STATS_ROW_COUNT; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.security.PrivilegedExceptionAction; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import javax.annotation.concurrent.GuardedBy; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CoprocessorEnvironment; import org.apache.hadoop.hbase.DoNotRetryIOException; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.NamespaceDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Mutation; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.coprocessor.ObserverContext; import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment; import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter; import org.apache.hadoop.hbase.io.ImmutableBytesWritable; import org.apache.hadoop.hbase.ipc.RpcControllerFactory; import org.apache.hadoop.hbase.ipc.controller.InterRegionServerIndexRpcControllerFactory; import org.apache.hadoop.hbase.regionserver.InternalScanner; import org.apache.hadoop.hbase.regionserver.KeyValueScanner; import org.apache.hadoop.hbase.regionserver.Region; import org.apache.hadoop.hbase.regionserver.RegionScanner; import org.apache.hadoop.hbase.regionserver.ScanInfoUtil; import org.apache.hadoop.hbase.regionserver.ScanType; import org.apache.hadoop.hbase.regionserver.Store; import org.apache.hadoop.hbase.regionserver.StoreScanner; import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Pair; import org.apache.hadoop.io.WritableUtils; import org.apache.phoenix.coprocessor.generated.PTableProtos; import org.apache.phoenix.exception.SQLExceptionCode; import org.apache.phoenix.execute.TupleProjector; import org.apache.phoenix.expression.Expression; import org.apache.phoenix.expression.ExpressionType; import org.apache.phoenix.filter.AllVersionsIndexRebuildFilter; import org.apache.phoenix.hbase.index.Indexer; import org.apache.phoenix.hbase.index.covered.update.ColumnReference; import org.apache.phoenix.hbase.index.exception.IndexWriteException; import org.apache.phoenix.index.GlobalIndexChecker; import org.apache.phoenix.index.IndexMaintainer; import org.apache.phoenix.index.PhoenixIndexCodec; import org.apache.phoenix.index.PhoenixIndexFailurePolicy; import org.apache.phoenix.index.PhoenixIndexFailurePolicy.MutateCommand; import org.apache.phoenix.index.PhoenixIndexMetaData; import org.apache.phoenix.jdbc.PhoenixConnection; import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData; import org.apache.phoenix.join.HashJoinInfo; import org.apache.phoenix.mapreduce.index.IndexTool; import org.apache.phoenix.query.QueryConstants; import org.apache.phoenix.query.QueryServices; import org.apache.phoenix.query.QueryServicesOptions; import org.apache.phoenix.schema.ColumnFamilyNotFoundException; import org.apache.phoenix.schema.PTable; import org.apache.phoenix.schema.PTableImpl; import org.apache.phoenix.schema.PTableType; import org.apache.phoenix.schema.TableNotFoundException; import org.apache.phoenix.schema.stats.NoOpStatisticsCollector; import org.apache.phoenix.schema.stats.StatisticsCollectionRunTracker; import org.apache.phoenix.schema.stats.StatisticsCollector; import org.apache.phoenix.schema.stats.StatisticsCollectorFactory; import org.apache.phoenix.schema.stats.StatsCollectionDisabledOnServerException; import org.apache.phoenix.schema.types.PDataType; import org.apache.phoenix.schema.types.PLong; import org.apache.phoenix.util.EncodedColumnsUtil; import org.apache.phoenix.util.EnvironmentEdgeManager; import org.apache.phoenix.util.IndexUtil; import org.apache.phoenix.util.KeyValueUtil; import org.apache.phoenix.util.PhoenixRuntime; import org.apache.phoenix.util.PropertiesUtil; import org.apache.phoenix.util.QueryUtil; import org.apache.phoenix.util.ReadOnlyProps; import org.apache.phoenix.util.ScanUtil; import org.apache.phoenix.util.SchemaUtil; import org.apache.phoenix.util.ServerUtil; import org.apache.phoenix.util.ServerUtil.ConnectionType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Throwables; import com.google.common.collect.Lists; /** * Region observer that aggregates ungrouped rows(i.e. SQL query with aggregation function and no GROUP BY). * * * @since 0.1 */ public class UngroupedAggregateRegionObserver extends BaseScannerRegionObserver { // TODO: move all constants into a single class public static final String UNGROUPED_AGG = "UngroupedAgg"; public static final String DELETE_AGG = "DeleteAgg"; public static final String DELETE_CQ = "DeleteCQ"; public static final String DELETE_CF = "DeleteCF"; public static final String EMPTY_CF = "EmptyCF"; /** * This lock used for synchronizing the state of * {@link UngroupedAggregateRegionObserver#scansReferenceCount}, * {@link UngroupedAggregateRegionObserver#isRegionClosingOrSplitting} variables used to avoid possible * dead lock situation in case below steps: * 1. We get read lock when we start writing local indexes, deletes etc.. * 2. when memstore reach threshold, flushes happen. Since they use read (shared) lock they * happen without any problem until someone tries to obtain write lock. * 3. at one moment we decide to split/bulkload/close and try to acquire write lock. * 4. Since that moment all attempts to get read lock will be blocked. I.e. no more * flushes will happen. But we continue to fill memstore with local index batches and * finally we get RTBE. * * The solution to this is to not allow or delay operations acquire the write lock. * 1) In case of split we just throw IOException so split won't happen but it will not cause any harm. * 2) In case of bulkload failing it by throwing the exception. * 3) In case of region close by balancer/move wait before closing the reason and fail the query which * does write after reading. * * See PHOENIX-3111 for more info. */ private final Object lock = new Object(); /** * To maintain the number of scans used for create index, delete and upsert select operations * which reads and writes to same region in coprocessors. */ @GuardedBy("lock") private int scansReferenceCount = 0; @GuardedBy("lock") private boolean isRegionClosingOrSplitting = false; private static final Logger LOGGER = LoggerFactory.getLogger(UngroupedAggregateRegionObserver.class); private Configuration upsertSelectConfig; private Configuration compactionConfig; private Configuration indexWriteConfig; private ReadOnlyProps indexWriteProps; @Override public void start(CoprocessorEnvironment e) throws IOException { super.start(e); /* * We need to create a copy of region's configuration since we don't want any side effect of * setting the RpcControllerFactory. */ upsertSelectConfig = PropertiesUtil.cloneConfig(e.getConfiguration()); /* * Till PHOENIX-3995 is fixed, we need to use the * InterRegionServerIndexRpcControllerFactory. Although this would cause remote RPCs to use * index handlers on the destination region servers, it is better than using the regular * priority handlers which could result in a deadlock. */ upsertSelectConfig.setClass(RpcControllerFactory.CUSTOM_CONTROLLER_CONF_KEY, InterRegionServerIndexRpcControllerFactory.class, RpcControllerFactory.class); compactionConfig = ServerUtil.getCompactionConfig(e.getConfiguration()); // For retries of index write failures, use the same # of retries as the rebuilder indexWriteConfig = PropertiesUtil.cloneConfig(e.getConfiguration()); indexWriteConfig.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, e.getConfiguration().getInt(QueryServices.INDEX_REBUILD_RPC_RETRIES_COUNTER, QueryServicesOptions.DEFAULT_INDEX_REBUILD_RPC_RETRIES_COUNTER)); indexWriteProps = new ReadOnlyProps(indexWriteConfig.iterator()); } Configuration getUpsertSelectConfig() { return upsertSelectConfig; } void incrementScansReferenceCount() throws IOException{ synchronized (lock) { if (isRegionClosingOrSplitting) { throw new IOException("Temporarily unable to write from scan because region is closing or splitting"); } scansReferenceCount++; lock.notifyAll(); } } void decrementScansReferenceCount() { synchronized (lock) { scansReferenceCount--; if (scansReferenceCount < 0) { LOGGER.warn( "Scan reference count went below zero. Something isn't correct. Resetting it back to zero"); scansReferenceCount = 0; } lock.notifyAll(); } } void commitBatchWithRetries(final Region region, final List<Mutation> localRegionMutations, final long blockingMemstoreSize) throws IOException { try { commitBatch(region, localRegionMutations, blockingMemstoreSize); } catch (IOException e) { handleIndexWriteException(localRegionMutations, e, new MutateCommand() { @Override public void doMutation() throws IOException { commitBatch(region, localRegionMutations, blockingMemstoreSize); } @Override public List<Mutation> getMutationList() { return localRegionMutations; } }); } } void commitBatch(Region region, List<Mutation> mutations, long blockingMemstoreSize) throws IOException { if (mutations.isEmpty()) { return; } Mutation[] mutationArray = new Mutation[mutations.size()]; // When memstore size reaches blockingMemstoreSize we are waiting 3 seconds for the // flush happen which decrease the memstore size and then writes allowed on the region. for (int i = 0; blockingMemstoreSize > 0 && region.getMemstoreSize() > blockingMemstoreSize && i < 30; i++) { try { checkForRegionClosing(); Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } // TODO: should we use the one that is all or none? LOGGER.debug("Committing batch of " + mutations.size() + " mutations for " + region.getRegionInfo().getTable().getNameAsString()); region.batchMutate(mutations.toArray(mutationArray), HConstants.NO_NONCE, HConstants.NO_NONCE); } static void setIndexAndTransactionProperties(List<Mutation> mutations, byte[] indexUUID, byte[] indexMaintainersPtr, byte[] txState, byte[] clientVersionBytes, boolean useIndexProto) { for (Mutation m : mutations) { if (indexMaintainersPtr != null) { m.setAttribute(useIndexProto ? PhoenixIndexCodec.INDEX_PROTO_MD : PhoenixIndexCodec.INDEX_MD, indexMaintainersPtr); } if (indexUUID != null) { m.setAttribute(PhoenixIndexCodec.INDEX_UUID, indexUUID); } if (txState != null) { m.setAttribute(BaseScannerRegionObserver.TX_STATE, txState); } if (clientVersionBytes != null) { m.setAttribute(BaseScannerRegionObserver.CLIENT_VERSION, clientVersionBytes); } } } private void commitBatchWithHTable(HTable table, List<Mutation> mutations) throws IOException { if (mutations.isEmpty()) { return; } LOGGER.debug("Committing batch of " + mutations.size() + " mutations for " + table); try { table.batch(mutations); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } /** * There is a chance that region might be closing while running balancer/move/merge. In this * case if the memstore size reaches blockingMemstoreSize better to fail query because there is * a high chance that flush might not proceed and memstore won't be freed up. * @throws IOException */ void checkForRegionClosing() throws IOException { synchronized (lock) { if(isRegionClosingOrSplitting) { lock.notifyAll(); throw new IOException("Region is getting closed. Not allowing to write to avoid possible deadlock."); } } } public static void serializeIntoScan(Scan scan) { scan.setAttribute(BaseScannerRegionObserver.UNGROUPED_AGG, QueryConstants.TRUE); } @Override public RegionScanner preScannerOpen(ObserverContext<RegionCoprocessorEnvironment> e, Scan scan, RegionScanner s) throws IOException { s = super.preScannerOpen(e, scan, s); if (ScanUtil.isAnalyzeTable(scan)) { // We are setting the start row and stop row such that it covers the entire region. As part // of Phonenix-1263 we are storing the guideposts against the physical table rather than // individual tenant specific tables. scan.setStartRow(HConstants.EMPTY_START_ROW); scan.setStopRow(HConstants.EMPTY_END_ROW); scan.setFilter(null); } return s; } public static class MutationList extends ArrayList<Mutation> { private long byteSize = 0l; public MutationList() { super(); } public MutationList(int size){ super(size); } @Override public boolean add(Mutation e) { boolean r = super.add(e); if (r) { this.byteSize += KeyValueUtil.calculateMutationDiskSize(e); } return r; } public long byteSize() { return byteSize; } @Override public void clear() { byteSize = 0l; super.clear(); } } static long getBlockingMemstoreSize(Region region, Configuration conf) { long flushSize = region.getTableDesc().getMemStoreFlushSize(); if (flushSize <= 0) { flushSize = conf.getLong(HConstants.HREGION_MEMSTORE_FLUSH_SIZE, HTableDescriptor.DEFAULT_MEMSTORE_FLUSH_SIZE); } return flushSize * (conf.getLong(HConstants.HREGION_MEMSTORE_BLOCK_MULTIPLIER, HConstants.DEFAULT_HREGION_MEMSTORE_BLOCK_MULTIPLIER)-1); } @Override protected RegionScanner doPostScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c, final Scan scan, final RegionScanner s) throws IOException, SQLException { final RegionCoprocessorEnvironment env = c.getEnvironment(); final Region region = env.getRegion(); long ts = scan.getTimeRange().getMax(); boolean localIndexScan = ScanUtil.isLocalIndex(scan); if (ScanUtil.isAnalyzeTable(scan)) { byte[] gp_width_bytes = scan.getAttribute(BaseScannerRegionObserver.GUIDEPOST_WIDTH_BYTES); byte[] gp_per_region_bytes = scan.getAttribute(BaseScannerRegionObserver.GUIDEPOST_PER_REGION); // Let this throw, as this scan is being done for the sole purpose of collecting stats StatisticsCollector statsCollector = StatisticsCollectorFactory.createStatisticsCollector( env, region.getRegionInfo().getTable().getNameAsString(), ts, gp_width_bytes, gp_per_region_bytes); if (statsCollector instanceof NoOpStatisticsCollector) { throw new StatsCollectionDisabledOnServerException(); } else { return collectStats(s, statsCollector, region, scan, env.getConfiguration()); } } else if (ScanUtil.isIndexRebuild(scan)) { return User.runAsLoginUser(new PrivilegedExceptionAction<RegionScanner>() { @Override public RegionScanner run() throws Exception { return rebuildIndices(s, region, scan, env); } }); } boolean useNewValueColumnQualifier = EncodedColumnsUtil.useNewValueColumnQualifier(scan); int offsetToBe = 0; if (localIndexScan) { offsetToBe = region.getRegionInfo().getStartKey().length != 0 ? region.getRegionInfo().getStartKey().length : region.getRegionInfo().getEndKey().length; } final int offset = offsetToBe; byte[] descRowKeyTableBytes = scan.getAttribute(UPGRADE_DESC_ROW_KEY); boolean isDescRowKeyOrderUpgrade = descRowKeyTableBytes != null; boolean useProto = false; byte[] localIndexBytes = scan.getAttribute(LOCAL_INDEX_BUILD_PROTO); useProto = localIndexBytes != null; if (localIndexBytes == null) { localIndexBytes = scan.getAttribute(LOCAL_INDEX_BUILD); } List<IndexMaintainer> indexMaintainers = localIndexBytes == null ? null : IndexMaintainer.deserialize(localIndexBytes, useProto); RegionScanner theScanner = s; byte[] upsertSelectTable = scan.getAttribute(BaseScannerRegionObserver.UPSERT_SELECT_TABLE); boolean isDelete = false; if (upsertSelectTable == null) { byte[] isDeleteAgg = scan.getAttribute(BaseScannerRegionObserver.DELETE_AGG); isDelete = isDeleteAgg != null && Bytes.compareTo(PDataType.TRUE_BYTES, isDeleteAgg) == 0; } TupleProjector tupleProjector = null; byte[][] viewConstants = null; ColumnReference[] dataColumns = IndexUtil.deserializeDataTableColumnsToJoin(scan); final TupleProjector p = TupleProjector.deserializeProjectorFromScan(scan); final HashJoinInfo j = HashJoinInfo.deserializeHashJoinFromScan(scan); boolean useQualifierAsIndex = EncodedColumnsUtil.useQualifierAsIndex(EncodedColumnsUtil.getMinMaxQualifiersFromScan(scan)); if ((localIndexScan && !isDelete && !isDescRowKeyOrderUpgrade) || (j == null && p != null)) { if (dataColumns != null) { tupleProjector = IndexUtil.getTupleProjector(scan, dataColumns); viewConstants = IndexUtil.deserializeViewConstantsFromScan(scan); } ImmutableBytesWritable tempPtr = new ImmutableBytesWritable(); theScanner = getWrappedScanner(c, theScanner, offset, scan, dataColumns, tupleProjector, region, indexMaintainers == null ? null : indexMaintainers.get(0), viewConstants, p, tempPtr, useQualifierAsIndex); } if (j != null) { theScanner = new HashJoinRegionScanner(theScanner, scan, p, j, ScanUtil.getTenantId(scan), env, useQualifierAsIndex, useNewValueColumnQualifier); } return new UngroupedAggregateRegionScanner(c, theScanner,region, scan, env, this); } static void checkForLocalIndexColumnFamilies(Region region, List<IndexMaintainer> indexMaintainers) throws IOException { HTableDescriptor tableDesc = region.getTableDesc(); String schemaName = tableDesc.getTableName().getNamespaceAsString() .equals(NamespaceDescriptor.DEFAULT_NAMESPACE_NAME_STR) ? SchemaUtil .getSchemaNameFromFullName(tableDesc.getTableName().getNameAsString()) : tableDesc.getTableName().getNamespaceAsString(); String tableName = SchemaUtil.getTableNameFromFullName(tableDesc.getTableName().getNameAsString()); for (IndexMaintainer indexMaintainer : indexMaintainers) { Set<ColumnReference> coveredColumns = indexMaintainer.getCoveredColumns(); if(coveredColumns.isEmpty()) { byte[] localIndexCf = indexMaintainer.getEmptyKeyValueFamily().get(); // When covered columns empty we store index data in default column family so check for it. if (tableDesc.getFamily(localIndexCf) == null) { ServerUtil.throwIOException("Column Family Not Found", new ColumnFamilyNotFoundException(schemaName, tableName, Bytes .toString(localIndexCf))); } } for (ColumnReference reference : coveredColumns) { byte[] cf = IndexUtil.getLocalIndexColumnFamily(reference.getFamily()); HColumnDescriptor family = region.getTableDesc().getFamily(cf); if (family == null) { ServerUtil.throwIOException("Column Family Not Found", new ColumnFamilyNotFoundException(schemaName, tableName, Bytes.toString(cf))); } } } } void commit(final Region region, List<Mutation> mutations, byte[] indexUUID, final long blockingMemStoreSize, byte[] indexMaintainersPtr, byte[] txState, final HTable targetHTable, boolean useIndexProto, boolean isPKChanging, byte[] clientVersionBytes) throws IOException { final List<Mutation> localRegionMutations = Lists.newArrayList(); final List<Mutation> remoteRegionMutations = Lists.newArrayList(); setIndexAndTransactionProperties(mutations, indexUUID, indexMaintainersPtr, txState, clientVersionBytes, useIndexProto); separateLocalAndRemoteMutations(targetHTable, region, mutations, localRegionMutations, remoteRegionMutations, isPKChanging); commitBatchWithRetries(region, localRegionMutations, blockingMemStoreSize); try { commitBatchWithHTable(targetHTable, remoteRegionMutations); } catch (IOException e) { handleIndexWriteException(remoteRegionMutations, e, new MutateCommand() { @Override public void doMutation() throws IOException { commitBatchWithHTable(targetHTable, remoteRegionMutations); } @Override public List<Mutation> getMutationList() { return remoteRegionMutations; } }); } localRegionMutations.clear(); remoteRegionMutations.clear(); } private void handleIndexWriteException(final List<Mutation> localRegionMutations, IOException origIOE, MutateCommand mutateCommand) throws IOException { long serverTimestamp = ServerUtil.parseTimestampFromRemoteException(origIOE); SQLException inferredE = ServerUtil.parseLocalOrRemoteServerException(origIOE); if (inferredE != null && inferredE.getErrorCode() == SQLExceptionCode.INDEX_WRITE_FAILURE.getErrorCode()) { // For an index write failure, the data table write succeeded, // so when we retry we need to set REPLAY_WRITES for (Mutation mutation : localRegionMutations) { if (PhoenixIndexMetaData.isIndexRebuild(mutation.getAttributesMap())) { mutation.setAttribute(BaseScannerRegionObserver.REPLAY_WRITES, BaseScannerRegionObserver.REPLAY_INDEX_REBUILD_WRITES); } else { mutation.setAttribute(BaseScannerRegionObserver.REPLAY_WRITES, BaseScannerRegionObserver.REPLAY_ONLY_INDEX_WRITES); } // use the server timestamp for index write retrys KeyValueUtil.setTimestamp(mutation, serverTimestamp); } IndexWriteException iwe = PhoenixIndexFailurePolicy.getIndexWriteException(inferredE); try (PhoenixConnection conn = QueryUtil.getConnectionOnServer(indexWriteConfig) .unwrap(PhoenixConnection.class)) { PhoenixIndexFailurePolicy.doBatchWithRetries(mutateCommand, iwe, conn, indexWriteProps); } catch (Exception e) { throw new DoNotRetryIOException(e); } } else { throw origIOE; } } private void separateLocalAndRemoteMutations(HTable targetHTable, Region region, List<Mutation> mutations, List<Mutation> localRegionMutations, List<Mutation> remoteRegionMutations, boolean isPKChanging){ boolean areMutationsInSameTable = areMutationsInSameTable(targetHTable, region); //if we're writing to the same table, but the PK can change, that means that some //mutations might be in our current region, and others in a different one. if (areMutationsInSameTable && isPKChanging) { HRegionInfo regionInfo = region.getRegionInfo(); for (Mutation mutation : mutations){ if (regionInfo.containsRow(mutation.getRow())){ localRegionMutations.add(mutation); } else { remoteRegionMutations.add(mutation); } } } else if (areMutationsInSameTable && !isPKChanging) { localRegionMutations.addAll(mutations); } else { remoteRegionMutations.addAll(mutations); } } private boolean areMutationsInSameTable(HTable targetHTable, Region region) { return (targetHTable == null || Bytes.compareTo(targetHTable.getTableName(), region.getTableDesc().getTableName().getName()) == 0); } @Override public InternalScanner preCompact(final ObserverContext<RegionCoprocessorEnvironment> c, final Store store, final InternalScanner scanner, final ScanType scanType) throws IOException { if (scanType.equals(ScanType.COMPACT_DROP_DELETES)) { final TableName table = c.getEnvironment().getRegion().getRegionInfo().getTable(); // Compaction and split upcalls run with the effective user context of the requesting user. // This will lead to failure of cross cluster RPC if the effective user is not // the login user. Switch to the login user context to ensure we have the expected // security context. return User.runAsLoginUser(new PrivilegedExceptionAction<InternalScanner>() { @Override public InternalScanner run() throws Exception { InternalScanner internalScanner = scanner; try { long clientTimeStamp = EnvironmentEdgeManager.currentTimeMillis(); DelegateRegionCoprocessorEnvironment compactionConfEnv = new DelegateRegionCoprocessorEnvironment(c.getEnvironment(), ConnectionType.COMPACTION_CONNECTION); StatisticsCollector statisticsCollector = StatisticsCollectorFactory.createStatisticsCollector( compactionConfEnv, table.getNameAsString(), clientTimeStamp, store.getFamily().getName()); statisticsCollector.init(); internalScanner = statisticsCollector.createCompactionScanner(compactionConfEnv, store, internalScanner); } catch (Exception e) { // If we can't reach the stats table, don't interrupt the normal // compaction operation, just log a warning. if (LOGGER.isWarnEnabled()) { LOGGER.warn("Unable to collect stats for " + table, e); } } return internalScanner; } }); } return scanner; } static PTable deserializeTable(byte[] b) { try { PTableProtos.PTable ptableProto = PTableProtos.PTable.parseFrom(b); return PTableImpl.createFromProto(ptableProto); } catch (IOException e) { throw new RuntimeException(e); } } private RegionScanner getRegionScanner(final RegionScanner innerScanner, final Region region, final Scan scan, final RegionCoprocessorEnvironment env, final boolean oldCoproc) throws IOException { if (oldCoproc) { return new IndexerRegionScanner(innerScanner, region, scan, env, this); } else { if (region.getTableDesc().hasCoprocessor(GlobalIndexChecker.class.getCanonicalName())) { return new IndexRepairRegionScanner(innerScanner, region, scan, env, this); } else { return new IndexRebuildRegionScanner(innerScanner, region, scan, env, this); } } } private RegionScanner rebuildIndices(RegionScanner innerScanner, final Region region, final Scan scan, final RegionCoprocessorEnvironment env) throws IOException { boolean oldCoproc = region.getTableDesc().hasCoprocessor(Indexer.class.getCanonicalName()); byte[] valueBytes = scan.getAttribute(BaseScannerRegionObserver.INDEX_REBUILD_VERIFY_TYPE); IndexTool.IndexVerifyType verifyType = (valueBytes != null) ? IndexTool.IndexVerifyType.fromValue(valueBytes) : IndexTool.IndexVerifyType.NONE; if (oldCoproc && verifyType == IndexTool.IndexVerifyType.ONLY) { return new IndexerRegionScanner(innerScanner, region, scan, env, this); } RegionScanner scanner; if (!scan.isRaw()) { Scan rawScan = new Scan(scan); rawScan.setRaw(true); rawScan.setMaxVersions(); rawScan.getFamilyMap().clear(); adjustScanFilter(rawScan); rawScan.setCacheBlocks(false); for (byte[] family : scan.getFamilyMap().keySet()) { rawScan.addFamily(family); } scanner = ((BaseRegionScanner)innerScanner).getNewRegionScanner(rawScan); innerScanner.close(); } else { if (adjustScanFilter(scan)) { scanner = ((BaseRegionScanner) innerScanner).getNewRegionScanner(scan); innerScanner.close(); } else { scanner = innerScanner; } } return getRegionScanner(scanner, region, scan, env, oldCoproc); } private RegionScanner collectStats(final RegionScanner innerScanner, StatisticsCollector stats, final Region region, final Scan scan, Configuration config) throws IOException { StatsCollectionCallable callable = new StatsCollectionCallable(stats, region, innerScanner, config, scan); byte[] asyncBytes = scan.getAttribute(BaseScannerRegionObserver.RUN_UPDATE_STATS_ASYNC_ATTRIB); boolean async = false; if (asyncBytes != null) { async = Bytes.toBoolean(asyncBytes); } long rowCount = 0; // in case of async, we report 0 as number of rows updated StatisticsCollectionRunTracker statsRunTracker = StatisticsCollectionRunTracker.getInstance(config); final boolean runUpdateStats = statsRunTracker.addUpdateStatsCommandRegion(region.getRegionInfo(),scan.getFamilyMap().keySet()); if (runUpdateStats) { if (!async) { rowCount = callable.call(); } else { statsRunTracker.runTask(callable); } } else { rowCount = CONCURRENT_UPDATE_STATS_ROW_COUNT; LOGGER.info("UPDATE STATISTICS didn't run because another UPDATE STATISTICS command was already running on the region " + region.getRegionInfo().getRegionNameAsString()); } byte[] rowCountBytes = PLong.INSTANCE.toBytes(Long.valueOf(rowCount)); final KeyValue aggKeyValue = KeyValueUtil.newKeyValue(UNGROUPED_AGG_ROW_KEY, SINGLE_COLUMN_FAMILY, SINGLE_COLUMN, AGG_TIMESTAMP, rowCountBytes, 0, rowCountBytes.length); RegionScanner scanner = new BaseRegionScanner(innerScanner) { @Override public HRegionInfo getRegionInfo() { return region.getRegionInfo(); } @Override public boolean isFilterDone() { return true; } @Override public void close() throws IOException { // If we ran/scheduled StatsCollectionCallable the delegate // scanner is closed there. Otherwise close it here. if (!runUpdateStats) { super.close(); } } @Override public boolean next(List<Cell> results) throws IOException { results.add(aggKeyValue); return false; } @Override public long getMaxResultSize() { return scan.getMaxResultSize(); } }; return scanner; } /** * * Callable to encapsulate the collection of stats triggered by * UPDATE STATISTICS command. * * Package private for tests. */ static class StatsCollectionCallable implements Callable<Long> { private final StatisticsCollector statsCollector; private final Region region; private final RegionScanner innerScanner; private final Configuration config; private final Scan scan; StatsCollectionCallable(StatisticsCollector s, Region r, RegionScanner rs, Configuration config, Scan scan) { this.statsCollector = s; this.region = r; this.innerScanner = rs; this.config = config; this.scan = scan; } @Override public Long call() throws IOException { return collectStatsInternal(); } private boolean areStatsBeingCollectedViaCompaction() { return StatisticsCollectionRunTracker.getInstance(config) .areStatsBeingCollectedOnCompaction(region.getRegionInfo()); } private long collectStatsInternal() throws IOException { long startTime = EnvironmentEdgeManager.currentTimeMillis(); region.startRegionOperation(); boolean hasMore = false; boolean noErrors = false; boolean compactionRunning = areStatsBeingCollectedViaCompaction(); long rowCount = 0; try { if (!compactionRunning) { statsCollector.init(); synchronized (innerScanner) { do { List<Cell> results = new ArrayList<Cell>(); hasMore = innerScanner.nextRaw(results); statsCollector.collectStatistics(results); rowCount++; compactionRunning = areStatsBeingCollectedViaCompaction(); } while (hasMore && !compactionRunning); noErrors = true; } } return compactionRunning ? COMPACTION_UPDATE_STATS_ROW_COUNT : rowCount; } catch (IOException e) { LOGGER.error("IOException in update stats: " + Throwables.getStackTraceAsString(e)); throw e; } finally { try { if (noErrors && !compactionRunning) { statsCollector.updateStatistics(region, scan); LOGGER.info("UPDATE STATISTICS finished successfully for scanner: " + innerScanner + ". Number of rows scanned: " + rowCount + ". Time: " + (EnvironmentEdgeManager.currentTimeMillis() - startTime)); } if (compactionRunning) { LOGGER.info("UPDATE STATISTICS stopped in between because major compaction was running for region " + region.getRegionInfo().getRegionNameAsString()); } } finally { try { StatisticsCollectionRunTracker.getInstance(config).removeUpdateStatsCommandRegion(region.getRegionInfo(), scan.getFamilyMap().keySet()); statsCollector.close(); } finally { try { innerScanner.close(); } finally { region.closeRegionOperation(); } } } } } } static List<Expression> deserializeExpressions(byte[] b) { ByteArrayInputStream stream = new ByteArrayInputStream(b); try { DataInputStream input = new DataInputStream(stream); int size = WritableUtils.readVInt(input); List<Expression> selectExpressions = Lists.newArrayListWithExpectedSize(size); for (int i = 0; i < size; i++) { ExpressionType type = ExpressionType.values()[WritableUtils.readVInt(input)]; Expression selectExpression = type.newInstance(); selectExpression.readFields(input); selectExpressions.add(selectExpression); } return selectExpressions; } catch (IOException e) { throw new RuntimeException(e); } finally { try { stream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } public static byte[] serialize(PTable projectedTable) { PTableProtos.PTable ptableProto = PTableImpl.toProto(projectedTable); return ptableProto.toByteArray(); } public static byte[] serialize(List<Expression> selectExpressions) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { DataOutputStream output = new DataOutputStream(stream); WritableUtils.writeVInt(output, selectExpressions.size()); for (int i = 0; i < selectExpressions.size(); i++) { Expression expression = selectExpressions.get(i); WritableUtils.writeVInt(output, ExpressionType.valueOf(expression).ordinal()); expression.write(output); } return stream.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { stream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } @Override public void preSplit(ObserverContext<RegionCoprocessorEnvironment> c, byte[] splitRow) throws IOException { waitForScansToFinish(c); } @Override public void preRollBackSplit(ObserverContext<RegionCoprocessorEnvironment> ctx) throws IOException { // We need to reset the state in case of a failed split Region region = ctx.getEnvironment().getRegion(); synchronized (lock) { if (isRegionClosingOrSplitting) { if (!region.isClosed() && !region.isClosing()) { isRegionClosingOrSplitting = false; } } } } // Don't allow splitting/closing if operations need read and write to same region are going on in the // the coprocessors to avoid dead lock scenario. See PHOENIX-3111. private void waitForScansToFinish(ObserverContext<RegionCoprocessorEnvironment> c) throws IOException { int maxWaitTime = c.getEnvironment().getConfiguration().getInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT, HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT); long start = EnvironmentEdgeManager.currentTimeMillis(); synchronized (lock) { isRegionClosingOrSplitting = true; while (scansReferenceCount > 0) { try { lock.wait(1000); if (EnvironmentEdgeManager.currentTimeMillis() - start >= maxWaitTime) { isRegionClosingOrSplitting = false; // must reset in case split is not retried throw new IOException(String.format( "Operations like local index building/delete/upsert select" + " might be going on so not allowing to split/close. scansReferenceCount=%s region=%s", scansReferenceCount, c.getEnvironment().getRegionInfo().getRegionNameAsString())); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } @Override public void preBulkLoadHFile(ObserverContext<RegionCoprocessorEnvironment> c, List<Pair<byte[], String>> familyPaths) throws IOException { // Don't allow bulkload if operations need read and write to same region are going on in the // the coprocessors to avoid dead lock scenario. See PHOENIX-3111. synchronized (lock) { if (scansReferenceCount > 0) { throw new DoNotRetryIOException("Operations like local index building/delete/upsert select" + " might be going on so not allowing to bulkload."); } } } @Override public void preClose(ObserverContext<RegionCoprocessorEnvironment> c, boolean abortRequested) throws IOException { waitForScansToFinish(c); } @Override protected boolean isRegionObserverFor(Scan scan) { return scan.getAttribute(BaseScannerRegionObserver.UNGROUPED_AGG) != null; } @Override public InternalScanner preCompactScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c, final Store store, final List<? extends KeyValueScanner> scanners, ScanType scanType, long earliestPutTs, final InternalScanner s, final CompactionRequest request) throws IOException { // Compaction and split upcalls run with the effective user context of the requesting user. // This will lead to failure of cross cluster RPC if the effective user is not // the login user. Switch to the login user context to ensure we have the expected // security context. final String fullTableName = c.getEnvironment().getRegion().getRegionInfo().getTable().getNameAsString(); // since we will make a call to syscat, do nothing if we are compacting syscat itself // also, if max lookback age is already configured, we're already taken care of elsewhere // unless the index stays disabled beyond the max lookback age, in which case you probably // want to rebuild anyway if (request.isMajor() && !ScanInfoUtil.isMaxLookbackTimeEnabled(compactionConfig) && !PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME.equals(fullTableName)) { return User.runAsLoginUser(new PrivilegedExceptionAction<InternalScanner>() { @Override public InternalScanner run() throws Exception { // If the index is disabled, keep the deleted cells so the rebuild doesn't corrupt the index try (PhoenixConnection conn = QueryUtil.getConnectionOnServer(compactionConfig).unwrap(PhoenixConnection.class)) { PTable table = PhoenixRuntime.getTableNoCache(conn, fullTableName); List<PTable> indexes = PTableType.INDEX.equals(table.getType()) ? Lists.newArrayList(table) : table.getIndexes(); // FIXME need to handle views and indexes on views as well for (PTable index : indexes) { if (index.getIndexDisableTimestamp() != 0) { LOGGER.info( "Modifying major compaction scanner to retain deleted cells for a table with disabled index: " + fullTableName); Scan scan = new Scan(); scan.setMaxVersions(); // close the passed scanner since we are returning a brand-new one try { if (s != null) { s.close(); } } catch (IOException ignore) {} return new StoreScanner(store, store.getScanInfo(), scan, scanners, ScanType.COMPACT_RETAIN_DELETES, store.getSmallestReadPoint(), HConstants.OLDEST_TIMESTAMP); } } } catch (Exception e) { if (e instanceof TableNotFoundException) { LOGGER.debug("Ignoring HBase table that is not a Phoenix table: " + fullTableName); // non-Phoenix HBase tables won't be found, do nothing } else { LOGGER.error("Unable to modify compaction scanner to retain deleted cells for a table with disabled Index; " + fullTableName, e); } } return s; } }); } return s; } /** * roll back after split failed, will isRegionClosingOrSplitting set false, * and then write region will is available * @param ctx * @throws IOException */ @Override public void postRollBackSplit(ObserverContext<RegionCoprocessorEnvironment> ctx) throws IOException { synchronized (lock) { isRegionClosingOrSplitting = false; } } }
48.379722
188
0.639901
1de5718a3eb58a41ded7f2e2bfe121fb7bcb084e
2,336
package ai.cellbots.common.data; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.Exclude; import com.google.firebase.database.IgnoreExtraProperties; import com.google.firebase.database.PropertyName; import com.google.firebase.database.ServerValue; /** * File information used by the cloud file manager. */ @IgnoreExtraProperties public class FileInfo { private static final String TIMESTAMP = "timestamp"; private static final String NAME = "name"; @Exclude private final String mId; @PropertyName(NAME) private final String mName; @PropertyName(TIMESTAMP) private final Object mTimestamp; /** * Create an empty FileInfo. */ public FileInfo() { mId = null; mName = null; mTimestamp = ServerValue.TIMESTAMP; } /** * Create a FileInfo with an ID. * @param id The ID of the file. * @param copy The FileInfo to copy from. */ private FileInfo(String id, FileInfo copy) { mId = id; mName = copy.getName(); mTimestamp = copy.getRawTimestamp(); } /** * Create a FileInfo from the firebase database. * @param dataSnapshot The dataSnapshot to read from. * @return The FileInfo. */ public static FileInfo fromFirebase(DataSnapshot dataSnapshot) { return new FileInfo(dataSnapshot.getKey(), dataSnapshot.getValue(FileInfo.class)); } /** * Get the id of the FileInfo * @return The id */ @Exclude() public String getId() { return mId; } /** * Get the name of the FileInfo * @return The filename */ @PropertyName(NAME) public String getName() { return mName; } /** * Get the raw timestamp object, to be written to firebase. * @return The raw timestamp object. */ @PropertyName(TIMESTAMP) public Object getRawTimestamp() { return mTimestamp; } /** * Get the timestamp value. * @return The timestamp value or -1 if it does not exist. */ @Exclude public long getTimestamp() { if (mTimestamp instanceof Long) { return (long) mTimestamp; } if (mTimestamp instanceof Integer) { return (long) mTimestamp; } return -1; } }
24.589474
90
0.623288
e17ee9ef213bd57b462b696261bfbbe730c4df9d
4,545
package com.habbyge.iwatch.patch; import android.text.TextUtils; import android.util.Log; import androidx.annotation.Keep; import com.habbyge.iwatch.IWatch; import com.habbyge.iwatch.util.HellUtils; import java.io.File; import java.io.IOException; import java.util.List; /** * Created by habbyge on 2021/1/5. * * 1. patch下载的url,iWatch透明,让业务app自己处理,iWatch不做处理 * 2. patch下载目录、存储目录,iWatch透明,且让业务app提供下载器,因为一般业务app都有自己的下载器(一般在下载前会做安全校验) * 这样做的目的是为了让业务app控制存储目录,满足业务app的存储管理要求,例如:微信对sdcard、/data目录都有非常严格的管理要求, * 还设计了vfs,管理文件目录、生命周期(失效、清理逻辑等)、大小等。iWatch需要服从业务app的这些要求。避免搞破坏。 */ @Keep // 对外接口需要keep住 public final class PatchManager { private static final String TAG = "iWatch.PatchManager"; private String mAppVersion = null; private Patch mPatch; private IWatch mWatch; private static PatchManager mInstance; @Keep public static PatchManager getInstance() { if (mInstance == null) { synchronized (PatchManager.class) { if (mInstance == null) { mInstance = new PatchManager(); } } } return mInstance; } private PatchManager() { } @Keep public boolean init(String version, List<String> mBaseVerList, String appVersion, String patchPath, boolean open) { if (!open) { Log.e(TAG, "__XYX__ init switcher is CLOSE !"); return false; } if (TextUtils.isEmpty(patchPath)) { Log.e(TAG, "__XYX__ init patchPath is NULL !"); return false; } File patchFile = new File(patchPath); if (!patchFile.exists() || !patchFile.isFile()) { Log.e(TAG, "__XYX__ init patchFile is legal !"); return false; } mAppVersion = appVersion; Log.i(TAG, "version=" + version + ", appVersion=" + appVersion + ", patchPath=" + patchPath); mWatch = new IWatch(); return initPatchs(patchFile, mBaseVerList); } /** * 实时加载补丁 */ @Keep public boolean loadPatch(List<String> baseVerList, String appVersion, String patchPath, boolean open) { if (!open) { Log.e(TAG, "__XYX__ addPatch switcher is CLOSE !"); resetAllPatch(); // 清理掉旧的patch,重新load新的;恢复原始方法,重新hook新的方法 return false; } File patchFile = new File(patchPath); if (!patchFile.exists()) { return false; } resetAllPatch(); // 清理掉旧的patch,重新load新的;恢复原始方法,重新hook新的方法 boolean success = addPatch(patchFile, baseVerList); if (success && mPatch != null) { return loadPatch(mPatch); } return false; } /** * remove all patchs && resotore all origin methods. * 恢复机制执行时机: * 1. iWatch开关-关闭 * 2. host版本不符 * 3. 获取的patch包信息异常 */ private void resetAllPatch() { mWatch.reset(); // 恢复原始函数,清理掉缓存 cleanPatch(); // 删除所有补丁 } private boolean initPatchs(File patchFile, List<String> baseVerList) { boolean success = addPatch(patchFile, baseVerList); if (!success) { resetAllPatch(); mPatch = null; Log.e(TAG, "initPatchs, failure: all patch files is illegal !"); return false; } return loadPatch(mPatch); } private boolean loadPatch(Patch patch) { List<String> classes = patch.getClasses(); if (classes == null || classes.isEmpty()) { resetAllPatch(); mPatch = null; return false; } return mWatch.fix(patch.getFile(), classes); } private boolean addPatch(File pathFile, List<String> baseVerList) { boolean succe = false; if (pathFile.getName().endsWith(Patch.SUFFIX)) { try { mPatch = new Patch(pathFile, baseVerList); if (!mPatch.canPatch(mAppVersion)) { resetAllPatch(); mPatch = null; succe = false; } else { succe = true; } } catch (IOException e) { Log.e(TAG, "addPatch", e); succe = false; } } return succe; } private void cleanPatch() { File file; if (mPatch != null && (file = mPatch.getFile()) != null) { if (!HellUtils.deleteFile(file)) { Log.e(TAG, file.getName() + " delete error."); } } } }
28.055556
119
0.562596
200a7dbe3fa166ece99e4935da36ca980e44f536
4,019
package game.container.impl; import java.util.Arrays; import game.container.ItemContainer; import game.container.ItemContainerNotePolicy; import game.container.ItemContainerStackPolicy; import game.content.item.ItemInteraction; import game.item.GameItem; import game.item.ItemAssistant; import game.npc.Npc; import game.player.Player; /** * Represents a bag item container which carries permitted items only * * @author 2012 * */ public class BagItemContainer extends ItemContainer implements ItemInteraction { /** * The permitted id */ private int[] permitted; /** * Represents a bag item container * * @param capacity the capacity * @param permitted the permitted items */ public BagItemContainer(int capacity, int[] permitted) { super(capacity, ItemContainerStackPolicy.UNSTACKABLE, ItemContainerNotePolicy.DENOTE); this.permitted = permitted; } /** * Inspecting the bag * * @param player the player */ public void inspect(Player player) { /* * The message */ String message = ""; /* * Checking permitted */ for (int i = 0; i < permitted.length; i++) { message += ItemAssistant.getItemName(permitted[i]) + ": " + amount(permitted[i]) + "."; } /* * The collection */ player.getPA().sendMessage("Contents in bag: " + message); } /** * Withdrawing * * @param player the player */ public void withdraw(Player player) { /* * The free slots */ int freeSlots = ItemAssistant.getFreeInventorySlots(player); /* * No free slots */ if (freeSlots == 0) { player.getPA() .sendMessage("You don't have any inventory space to withdraw anymore content."); return; } /* * Empty */ if (slotsUnavailable() == 0) { player.getPA().sendMessage("The bag is empty."); return; } /* * More slots than available */ if (freeSlots > slotsUnavailable()) { freeSlots = slotsUnavailable(); } /* * Withdraws the item */ forNonNull((index, item) -> { if (ItemAssistant.getFreeInventorySlots(player) > 0) { /* * Delete from container */ delete(item); /* * Add to inventory */ ItemAssistant.addItem(player, item.getId(), item.getAmount()); } }); player.getPA().sendMessage("You withdraw content from the bag"); } /** * Adding content to bag * * @param player the player * @param id the id */ public void addContent(Player player, int id) { /* * Only permitted content */ if (!isValid(id)) { player.getPA().sendMessage("That cannot be stored in this bag."); return; } /* * The max space */ if (slotsUnavailable() == getCapacity()) { player.getPA().sendMessage("Your bag is full and cannot carry anymore content."); return; } /* * Has item */ if (ItemAssistant.hasItemInInventory(player, id)) { ItemAssistant.deleteItemFromInventory(player, id, 1); add(new GameItem(id)); player.getPA().sendMessage("You add some content to your bag."); } } /** * Checking if valid * * @param id the id * @return valid */ public boolean isValid(int id) { return Arrays.stream(permitted).anyMatch(gem -> gem == id); } @Override public boolean canEquip(Player player, int id, int slot) { if (id == 18338 || id == 18339) { withdraw(player); return false; } return false; } @Override public void operate(Player player, int id) { } @Override public boolean sendItemAction(Player player, int id, int type) { if (id == 18338 || id == 18339) { if (type == 1) { inspect(player); } else if (type == 2) { withdraw(player); } return true; } return false; } @Override public boolean useItem(Player player, int id, int useWith) { return false; } @Override public boolean useItemOnObject(Player player, int id, int object) { return false; } @Override public boolean useItemOnNpc(Player player, int id, Npc npc) { return false; } @Override public boolean dropItem(Player player, int id) { return false; } }
20.505102
90
0.64842
a0fb19cc299748552caa0968ade4f3b95d767ed8
283
package com.example.vimeoplayer.model.vimeo; import com.google.gson.annotations.SerializedName; public class Request{ @SerializedName("files") private Files files; public void setFiles(Files files){ this.files = files; } public Files getFiles(){ return files; } }
12.863636
50
0.734982
4dcbd7d04bbb0ec0c9df28222c952351de36a6cd
1,478
package sk.ivankohut.quantifa.xmldom; import lombok.RequiredArgsConstructor; import org.cactoos.Scalar; import org.cactoos.Text; import org.cactoos.scalar.Unchecked; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.util.Iterator; @RequiredArgsConstructor public class XPathNodes implements Iterable<Node> { private static final XPathFactory FACTORY = XPathFactory.newInstance(); private final Scalar<? extends Node> node; private final XPathExpression expression; public XPathNodes(Scalar<? extends Node> node, String expression) { this(node, compileExpression(expression)); } public XPathNodes(Text xml, String expression) { this(new XmlDocument(xml), expression); } private static XPathExpression compileExpression(String expression) { try { return FACTORY.newXPath().compile(expression); } catch (XPathExpressionException e) { throw new IllegalArgumentException(e); } } @Override public Iterator<Node> iterator() { try { return new ListOfNodesIterator((NodeList) expression.evaluate(new Unchecked<>(node).value(), XPathConstants.NODESET)); } catch (XPathExpressionException e) { throw new IllegalArgumentException(e); } } }
30.163265
130
0.717185
bc5393c1dc8effd32c9c32beb4b99cfb2eee3930
543
package ru.codewars; public class GrassHopper { public static String weatherInfo(int temperature) { int celsius = (temperature - 32) * 5/9; double c = (double)celsius; if (c < 0) return (c + " is freezing temperature"); else return (c + " is above freezing temperature"); } public static void main(String[] args) { } /* public static int convertToCelsius(int temperature) { int celsius = (temperature - 32) * 5/9; return celsius; }*/ }
24.681818
59
0.569061
408c4ad91df89eae5ecc410e5975facd6d8531ac
7,528
package org.dvare.expression.datatype; import org.dvare.annotations.OperationMapping; import org.dvare.annotations.Type; import org.dvare.expression.literal.LiteralExpression; import org.dvare.expression.operation.aggregation.Maximum; import org.dvare.expression.operation.aggregation.Minimum; import org.dvare.expression.operation.arithmetic.*; import org.dvare.expression.operation.relational.*; import java.util.ArrayList; import java.util.List; /** * @author Muhammad Hammad * @since 2016-06-30 */ @Type(dataType = DataType.FloatType) public class FloatType extends DataTypeExpression { public FloatType() { super(DataType.FloatType); } @OperationMapping(operations = { Equals.class }) public boolean equal(LiteralExpression<?> left, LiteralExpression<?> right) { Float leftValue = (Float) left.getValue(); if (right.getValue() instanceof Integer) { return Math.ceil(leftValue) == (Integer) right.getValue(); } else { Float rightValue = (Float) right.getValue(); return leftValue.compareTo(rightValue) == 0; } } @OperationMapping(operations = { NotEquals.class }) public boolean notEqual(LiteralExpression<?> left, LiteralExpression<?> right) { Float leftValue = (Float) left.getValue(); if (right.getValue() instanceof Integer) { return Math.ceil(leftValue) != (Integer) right.getValue(); } else { Float rightValue = (Float) right.getValue(); return leftValue.compareTo(rightValue) != 0; } } @OperationMapping(operations = { LessThan.class }) public boolean less(LiteralExpression<?> left, LiteralExpression<?> right) { Float leftValue = (Float) left.getValue(); if (right.getValue() instanceof Integer) { return leftValue < (Integer) right.getValue(); } else { Float rightValue = (Float) right.getValue(); return leftValue < rightValue; } } @OperationMapping(operations = { LessEqual.class }) public boolean lessEqual(LiteralExpression<?> left, LiteralExpression<?> right) { Float leftValue = (Float) left.getValue(); if (right.getValue() instanceof Integer) { return leftValue < (Integer) right.getValue(); } else { Float rightValue = (Float) right.getValue(); return leftValue <= rightValue; } } @OperationMapping(operations = { GreaterThan.class }) public boolean greater(LiteralExpression<?> left, LiteralExpression<?> right) { Float leftValue = (Float) left.getValue(); if (right.getValue() instanceof Integer) { return leftValue > (Integer) right.getValue(); } else { Float rightValue = (Float) right.getValue(); return leftValue > rightValue; } } @OperationMapping(operations = { GreaterEqual.class }) public boolean greaterEqual(LiteralExpression<?> left, LiteralExpression<?> right) { Float leftValue = (Float) left.getValue(); if (right.getValue() instanceof Integer) { return leftValue >= (Integer) right.getValue(); } else { Float rightValue = (Float) right.getValue(); return leftValue >= rightValue; } } @OperationMapping(operations = { In.class }) public boolean in(LiteralExpression<?> left, LiteralExpression<?> right) { Float leftValue = (Float) left.getValue(); List<Float> rightValues = buildFloatList((List<Object>) right.getValue()); return rightValues.contains(leftValue); } @OperationMapping(operations = { NotIn.class }) public boolean notIn(LiteralExpression<?> left, LiteralExpression<?> right) { Float leftValue = (Float) left.getValue(); List<Float> rightValues = buildFloatList((List<Object>) right.getValue()); return !rightValues.contains(leftValue); } @OperationMapping(operations = { Between.class }) public boolean between(LiteralExpression<?> left, LiteralExpression<?> right) { Float leftValue = (Float) left.getValue(); List<Float> rightValues = buildFloatList((List<Object>) right.getValue()); Float lower = rightValues.get(0); Float upper = rightValues.get(1); return lower <= leftValue && leftValue <= upper; } @OperationMapping(operations = { org.dvare.expression.operation.aggregation.Sum.class, Add.class }) public Float sum(LiteralExpression<?> left, LiteralExpression<?> right) { Float leftValue = (Float) left.getValue(); Float rightValue = (Float) right.getValue(); return leftValue + rightValue; } @OperationMapping(operations = { Subtract.class }) public Float sub(LiteralExpression<?> left, LiteralExpression<?> right) { Float leftValue = (Float) left.getValue(); Float rightValue = (Float) right.getValue(); return leftValue - rightValue; } @OperationMapping(operations = { Multiply.class }) public Float mul(LiteralExpression<?> left, LiteralExpression<?> right) { Float leftValue = (Float) left.getValue(); Float rightValue = (Float) right.getValue(); return leftValue * rightValue; } @OperationMapping(operations = { Divide.class }) public Float div(LiteralExpression<?> left, LiteralExpression<?> right) { Float leftValue = (Float) left.getValue(); Float rightValue = (Float) right.getValue(); return leftValue / rightValue; } @OperationMapping(operations = { Power.class }) public Float pow(LiteralExpression<?> left, LiteralExpression<?> right) { Float leftValue = (Float) left.getValue(); if (right.getValue() instanceof Integer) { return (float) Math.pow(leftValue, (Integer) right.getValue()); } else if (right.getValue() instanceof Float) { return (float) Math.pow(leftValue, (Float) right.getValue()); } return null; } @OperationMapping(operations = { Minimum.class, Min.class }) public Float min(LiteralExpression<?> left, LiteralExpression<?> right) { Float leftValue = (Float) left.getValue(); Float rightValue = (Float) right.getValue(); return Float.min((leftValue), rightValue); } @OperationMapping(operations = { Maximum.class, Max.class }) public Float max(LiteralExpression<?> left, LiteralExpression<?> right) { Float leftValue = (Float) left.getValue(); Float rightValue = (Float) right.getValue(); return Float.max((leftValue), rightValue); } private List<Float> buildFloatList(List<Object> tempValues) { List<Float> values = new ArrayList<>(); for (Object tempValue : tempValues) { if (tempValue instanceof Float) { values.add((Float) tempValue); } else { try { values.add(Float.parseFloat(tempValue.toString())); } catch (NumberFormatException | NullPointerException e) { values.add(null); } } } return values; } }
31.366667
88
0.609989
1f7be8d984ca97df76b31315885606b8ec697d96
3,286
package model; import java.security.InvalidKeyException; import java.util.*; import stats.LanguageStats; public class Contest { final List<Problem> problems; final List<Team> teams; final Analyzer analyzer; final List<Submission> submissions; final List<Language> languages; final LanguageStats stats; double contestTime = 0; int lengthInMinutes = 300; public Contest() { this.problems = new ArrayList<Problem>(); this.teams = new ArrayList<Team>(); this.analyzer = new Analyzer(this, 0); this.languages = new ArrayList<Language>(); this.submissions = new ArrayList<Submission>(); this.stats = new LanguageStats(); analyzer.addRule(stats.submissionsPerLanguage); } public Team registerTeam(int teamNumber, String teamName) { Team newTeam = new Team(this,teamNumber, teamName); teams.add(newTeam); return newTeam; } public Team[] getTeams() { return teams.toArray(new Team[0]); } public Standings getStandings() { return getStandings(getSubmissionCount()); } public Standings getStandings(int submissionCount) { List<Score> teamScores = new ArrayList<Score>(); for (Team team : teams) { teamScores.add(team.getScore(submissionCount)); } return new Standings(this, teamScores, submissionCount); } public int getSubmissionCount() { return submissions.size(); } public void updateTime(double contestTime) { if (contestTime > this.contestTime) { this.contestTime = contestTime; } } public int getMinutesFromStart() { return (int) (contestTime / 60.0); } public int getSubmissionsAtTime(int minutes) { int count = 0; for (Submission s : submissions) { if (s.getMinutesFromStart()>minutes) { break; } count++; } return count; } public List<Submission> getSubmissions() { return submissions; } public int getLengthInMinutes() { return this.lengthInMinutes; } public Analyzer getAnalyzer() { return this.analyzer; } public void processSubmission(Submission newSubmission) { submissions.add(newSubmission); analyzer.notifySubmission(newSubmission); } public void addProblem(Problem newProblem) { problems.add(newProblem); } public void addLanguage(Language language) { languages.add(language); stats.submissionsPerLanguage.addLanguage(language.getName()); } public List<Problem> getProblems() { return problems; } public void addTeam(Team newTeam) { teams.add(newTeam); } public Team getTeam(int teamNumber) throws InvalidKeyException { for (Team candidate : teams) { if (teamNumber == candidate.getTeamNumber()) { return candidate; } } throw new InvalidKeyException(String.format("%n is not a known team", teamNumber)); } public Problem getProblem(String problemId) throws InvalidKeyException { for (Problem problem : problems) { if (problemId.equals(problem.getId())) { return problem; } } throw new InvalidKeyException(String.format("%s is not a known problem", problemId)); } public Problem getProblemByAbbreviation(String problemId) throws InvalidKeyException { for (Problem problem : problems) { if (problemId.equalsIgnoreCase(problem.getLetter())) { return problem; } } throw new InvalidKeyException(String.format("%s is not a known problem", problemId)); } }
23.471429
87
0.720024
d3b9fd0520df0bac78effe820a300b10c50ee75d
8,885
/* * 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.tools.ant.taskdefs; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Arrays; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; /** * Sets properties to the host provided, or localhost if no information is * provided. The default properties are NAME, FQDN, ADDR4, ADDR6; * * @since Ant 1.8 * @ant.task category="utility" */ public class HostInfo extends Task { private static final String DEF_REM_ADDR6 = "::"; private static final String DEF_REM_ADDR4 = "0.0.0.0"; private static final String DEF_LOCAL_ADDR6 = "::1"; private static final String DEF_LOCAL_ADDR4 = "127.0.0.1"; private static final String DEF_LOCAL_NAME = "localhost"; private static final String DEF_DOMAIN = "localdomain"; private static final String DOMAIN = "DOMAIN"; private static final String NAME = "NAME"; private static final String ADDR4 = "ADDR4"; private static final String ADDR6 = "ADDR6"; private String prefix = ""; private String host; private InetAddress nameAddr; private InetAddress best6; private InetAddress best4; private List inetAddrs; /** * Set a prefix for the properties. If the prefix does not end with a "." * one is automatically added. * * @param aPrefix * the prefix to use. * @since Ant 1.8 */ public void setPrefix(String aPrefix) { prefix = aPrefix; if (!prefix.endsWith(".")) { prefix += "."; } } /** * Set the host to be retrieved. * * @param aHost * the name or the address of the host, data for the local host * will be retrieved if ommited. * @since Ant 1.8 */ public void setHost(String aHost) { host = aHost; } /** * set the properties. * * @throws BuildException * on error. */ public void execute() throws BuildException { if (host == null || "".equals(host)) { executeLocal(); } else { executeRemote(); } } private void executeLocal() { try { Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); inetAddrs = new LinkedList(); while (interfaces.hasMoreElements()) { NetworkInterface currentif = (NetworkInterface) interfaces .nextElement(); Enumeration addrs = currentif.getInetAddresses(); while (addrs.hasMoreElements()) { inetAddrs.add(addrs.nextElement()); } } selectAddresses(); if (nameAddr != null && hasHostName(nameAddr)) { setDomainAndName(nameAddr.getCanonicalHostName()); } else { setProperty(DOMAIN, DEF_DOMAIN); setProperty(NAME, DEF_LOCAL_NAME); } if (best4 != null) { setProperty(ADDR4, best4.getHostAddress()); } else { setProperty(ADDR4, DEF_LOCAL_ADDR4); } if (best6 != null) { setProperty(ADDR6, best6.getHostAddress()); } else { setProperty(ADDR6, DEF_LOCAL_ADDR6); } } catch (Exception e) { log("Error retrieving local host information", e, Project.MSG_WARN); setProperty(DOMAIN, DEF_DOMAIN); setProperty(NAME, DEF_LOCAL_NAME); setProperty(ADDR4, DEF_LOCAL_ADDR4); setProperty(ADDR6, DEF_LOCAL_ADDR6); } } private boolean hasHostName(InetAddress addr) { return !addr.getHostAddress().equals(addr.getCanonicalHostName()); } private void selectAddresses() { Iterator i = inetAddrs.iterator(); while (i.hasNext()) { InetAddress current = (InetAddress) i.next(); if (!current.isMulticastAddress()) { if (current instanceof Inet4Address) { best4 = selectBestAddress(best4, current); } else if (current instanceof Inet6Address) { best6 = selectBestAddress(best6, current); } } } nameAddr = selectBestAddress(best4, best6); } private InetAddress selectBestAddress(InetAddress bestSoFar, InetAddress current) { InetAddress best = bestSoFar; if (best == null) { // none selected so far, so this one is better. best = current; } else { if (current == null || current.isLoopbackAddress()) { // definitely not better than the previously selected address. } else if (current.isLinkLocalAddress()) { // link local considered better than loopback if (best.isLoopbackAddress()) { best = current; } } else if (current.isSiteLocalAddress()) { // site local considered better than link local (and loopback) // address with hostname resolved considered better than // address without hostname if (best.isLoopbackAddress() || best.isLinkLocalAddress() || (best.isSiteLocalAddress() && !hasHostName(best))) { best = current; } } else { // current is a "Global address", considered better than // site local (and better than link local, loopback) // address with hostname resolved considered better than // address without hostname if (best.isLoopbackAddress() || best.isLinkLocalAddress() || best.isSiteLocalAddress() || !hasHostName(best)) { best = current; } } } return best; } private void executeRemote() { try { inetAddrs = Arrays.asList(InetAddress.getAllByName(host)); selectAddresses(); if (nameAddr != null && hasHostName(nameAddr)) { setDomainAndName(nameAddr.getCanonicalHostName()); } else { setDomainAndName(host); } if (best4 != null) { setProperty(ADDR4, best4.getHostAddress()); } else { setProperty(ADDR4, DEF_REM_ADDR4); } if (best6 != null) { setProperty(ADDR6, best6.getHostAddress()); } else { setProperty(ADDR6, DEF_REM_ADDR6); } } catch (Exception e) { log("Error retrieving remote host information for host:" + host + ".", e, Project.MSG_WARN); setDomainAndName(host); setProperty(ADDR4, DEF_REM_ADDR4); setProperty(ADDR6, DEF_REM_ADDR6); } } private void setDomainAndName(String fqdn) { int idx = fqdn.indexOf('.'); if (idx > 0) { setProperty(NAME, fqdn.substring(0, idx)); setProperty(DOMAIN, fqdn.substring(idx+1)); } else { setProperty(NAME, fqdn); setProperty(DOMAIN, DEF_DOMAIN); } } private void setProperty(String name, String value) { getProject().setNewProperty(prefix + name, value); } }
33.655303
81
0.549803
fed28f1b6434ca8d0b6a03137b5d2ebe0355581b
733
package com.denofprogramming.service; import org.springframework.stereotype.Service; @Service("basicMessageOfDay") public class BasicMessageOfTheDayImpl implements MessageOfTheDayService { private String message = "hello world"; public BasicMessageOfTheDayImpl() { System.out.println("no-arg Constructor called for " + BasicMessageOfTheDayImpl.class.getName()); } public void init() { System.out.println("init() called for " + BasicMessageOfTheDayImpl.class.getName()); } public void destroy() { System.out.println("destroy() called for " + BasicMessageOfTheDayImpl.class.getName()); } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
22.90625
98
0.75307
d359f391d8728c87f3d008f10553f716a60843db
786
package com.algorithm.dynamic; /** * http://www.geeksforgeeks.org/dynamic-programming-set-10-0-1-knapsack-problem/ */ public class Knapsack01 { public int calculate(int val[], int wt[], int W) { int K[][] = new int[val.length + 1][W + 1]; for (int i = 0; i <= val.length; i++) { for (int j = 0; j <= W; j++) { if (i == 0 || j == 0) { K[i][j] = 0; continue; } if (j - wt[i - 1] >= 0) { K[i][j] = Math.max(K[i - 1][j], K[i - 1][j - wt[i - 1]] + val[i - 1]); } else { K[i][j] = K[i - 1][j]; } } } return K[val.length][W]; } public static void main(String args[]) { Knapsack01 k = new Knapsack01(); int val[] = { 60, 20, 15, 30 }; int wt[] = { 4, 2, 3, 5 }; int r = k.calculate(val, wt, 8); System.out.print(r); } }
22.457143
80
0.493639
12eacf7b40378198144d6f8a32cbb54426570c52
1,386
package ro.dcmt.mobile; import java.io.IOException; 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.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.JsonObject; import ro.dcmt.data.beans.User; import ro.dcmt.data.controllers.UserService; public class MobileAuthEndpoint extends HttpServlet { private static final long serialVersionUID = 1L; private static Logger logger = LoggerFactory.getLogger(MobileAuthEndpoint.class); public MobileAuthEndpoint() { super(); } public void init(ServletConfig config) throws ServletException { logger.info("Mobile Authentication Endpoint initialized"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { User u = new User(); u.setEmail(request.getParameter("email")); u.setPassword(request.getParameter("password")); if (UserService.checkAuthMobile(u)) { logger.info("Mobile user logged in: " + u.getEmail()); response.getWriter().append("OK"); } else { logger.info("Mobile user failed authentication with: " + u.getEmail()); response.getWriter().append("NOK"); } } }
24.75
83
0.730159
a1479ccd2d42d41d44b62d1b21afd1f55e150010
1,850
package ccl.rt.use; /** * Created by Matthias on 05.07.2017. */ public interface InstructionBytes { String[] BYTE_TO_STRING = new String[]{ "__whiletrue","__while","__forarr", "__fornum","__whiletrue_nb","__while_nb", "__forarr_nb","__fornum_nb","__println", "__println_f","__println_c","__println_cf", "__setvar","__mkvar","__exit", "__throw","__throw_c","nnr", "nnr2","load","putI", "invoke","invoke1","__float", "store1","putS","putA", "putM","get","duplicate", "pop","ret","reserve", "__undefined", "__mkvar_u", "__java", "__invoke0", "__invoke1", "__invoke2", "__arrpush1", "__arrpush2", "newscope", "oldscope", "store" }; byte __WHILETRUE = 0; byte __WHILE = 1; byte __FORARR = 2; byte __FORNUM = 3; byte __WHILETRUE_NB = 4; byte __WHILE_NB = 5; byte __FORARR_NB = 6; byte __FORNUM_NB = 7; byte __PRINTLN = 8; byte __PRINTLN_F = 9; byte __PRINTLN_C = 10; byte __PRINTLN_CF = 11; byte __SETVAR = 12; byte __MKVAR = 13; byte __EXIT = 14; byte __THROW = 15; byte __THROW_C = 16; byte NNR = 17; byte NNR2 = 18; byte LOAD = 19; byte PUTI = 20; byte INVOKE = 21; byte INVOKE1 = 22; byte __FLOAT = 23; byte STORE1 = 24; byte PUTS = 25; byte PUTA = 26; byte PUTM = 27; byte GET = 28; byte DUPLICATE = 29; byte POP = 30; byte RET = 31; byte RESERVE = 32; byte __UNDEFINED = 33; byte __MKVAR_U = 34; byte __JAVA = 35; byte __INVOKE0 = 36; byte __INVOKE1 = 37; byte __INVOKE2 = 38; byte __ARRPUSH1 = 39; byte __ARRPUSH2 = 40; byte NEWSCOPE = 41; byte OLDSCOPE = 42; byte STORE = 43; }
25.694444
55
0.551351
0087b68c8c6bce5978fcbd5179fdefd1821a63ae
4,690
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.desarrollo.entidades; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.Size; /** * * @author mpluas */ @Entity @Table(name = "rol") public class Rol implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "idrol") private Integer idrol; @Size(max = 45) @Column(name = "rol") private String rol; @Size(max = 150) @Column(name = "observacion") private String observacion; @Column(name = "fecha_registro") @Temporal(TemporalType.DATE) private Date fechaRegistro; @Size(max = 2) @Column(name = "estado") private String estado; @OneToMany(cascade = CascadeType.ALL, mappedBy = "rol", fetch = FetchType.LAZY) private List<Menu> menuList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "rol", fetch = FetchType.LAZY) private List<Usuarios> usuariosList; public Rol() { this.menuList = new ArrayList<>(); this.usuariosList = new ArrayList<>(); } public Rol(Integer idrol) { this.idrol = idrol; this.menuList = new ArrayList<>(); this.usuariosList = new ArrayList<>(); } public Rol(String rol, String observacion, Date fechaRegistro, String estado) { this.rol = rol; this.observacion = observacion; this.fechaRegistro = fechaRegistro; this.estado = estado; this.menuList = new ArrayList<>(); this.usuariosList = new ArrayList<>(); } public Integer getIdrol() { return idrol; } public void setIdrol(Integer idrol) { this.idrol = idrol; } public String getRol() { return rol; } public void setRol(String rol) { this.rol = rol; } public String getObservacion() { return observacion; } public void setObservacion(String observacion) { this.observacion = observacion; } public Date getFechaRegistro() { return fechaRegistro; } public void setFechaRegistro(Date fechaRegistro) { this.fechaRegistro = fechaRegistro; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } public List<Menu> getMenuList() { return menuList; } public void setMenuList(List<Menu> menuList) { this.menuList = menuList; } public void addMenu(Menu menu){ this.menuList.add(menu); if(menu.getRol()!= this){ menu.setRol(this); } } public void addUsuarios(Usuarios usuarios){ this.usuariosList.add(usuarios); if(usuarios.getRol()!= this){ usuarios.setRol(this); } } public List<Usuarios> getUsuariosList() { return usuariosList; } public void setUsuariosList(List<Usuarios> usuariosList) { this.usuariosList = usuariosList; } @Override public int hashCode() { int hash = 0; hash += (idrol != null ? idrol.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Rol)) { return false; } Rol other = (Rol) object; if ((this.idrol == null && other.idrol != null) || (this.idrol != null && !this.idrol.equals(other.idrol))) { return false; } return true; } @Override public String toString() { return "com.desarrollo.entidades.Rol[ idrol=" + idrol + " ]"; } }
26.647727
118
0.610874
43236e6b8e5114d0c765c6cd1a887c8ff7b4bda6
436
package daggerok.apps.app.mappers; import daggerok.apps.app.validators.InputValidator; import javax.inject.Inject; public class InputMapper { private final InputValidator inputValidator; @Inject public InputMapper(final InputValidator inputValidator) { this.inputValidator = inputValidator; } public String trimmed(final String input) { return inputValidator.isValid(input) ? input.trim() : input; } }
20.761905
59
0.752294
f043126984005845075a99bfa80eb4ee05bb3404
11,283
package io.videofirst.basic; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Bob Marks */ public class StacktraceTest { private static final String[] STACKTRACE = {"org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)", "org.junit.jupiter.api.AssertTrue.assertTrue(AssertTrue.java:40)", "org.junit.jupiter.api.AssertTrue.assertTrue(AssertTrue.java:35)", "org.junit.jupiter.api.Assertions.assertTrue(Assertions.java:162)", "io.videofirst.basic.ErrorActions.fail(ErrorActions.java:21)", "io.videofirst.basic.$ErrorActionsDefinition$Intercepted.$$access$$fail(Unknown Source)", "io.videofirst.basic.$ErrorActionsDefinition$$exec2.invokeInternal(Unknown Source)", "io.micronaut.context.AbstractExecutableMethod.invoke(AbstractExecutableMethod.java:151)", "io.micronaut.aop.chain.MethodInterceptorChain.proceed(MethodInterceptorChain.java:87)", "io.videofirst.vfa.aop.VfaActionInterceptor.intercept(VfaActionInterceptor.java:47)", "io.micronaut.aop.chain.MethodInterceptorChain.proceed(MethodInterceptorChain.java:96)", "io.videofirst.basic.$ErrorActionsDefinition$Intercepted.fail(Unknown Source)", "io.videofirst.basic.ErrorTest.actionFail(ErrorTest.java:51)", "sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)", "sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)", "sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)", "java.lang.reflect.Method.invoke(Method.java:498)", "org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)", "org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)", "org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)", "org.junit.jupiter.api.extension.InvocationInterceptor.interceptTestMethod(InvocationInterceptor.java:117)", "org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)", "org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)", "org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)", "org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)", "org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)", "org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)", "org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)", "org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)", "org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)", "org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)", "org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)", "org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)", "org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)", "org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)", "org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)", "org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)", "org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)", "org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)", "org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)", "org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)", "org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)", "org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)", "org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)", "org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)", "org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)", "org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)", "org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)", "java.util.ArrayList.forEach(ArrayList.java:1257)", "org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)", "org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)", "org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)", "org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)", "org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)", "org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)", "org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)", "org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)", "org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)", "java.util.ArrayList.forEach(ArrayList.java:1257)", "org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)", "org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)", "org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)", "org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)", "org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)", "org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)", "org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)", "org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)", "org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)", "org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)", "org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)", "org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)", "org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)", "org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)", "org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)", "org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)", "org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)", "org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)", "org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)", "com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)", "com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)", "com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)", "com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)"}; private static final String[] STRACKTRACE_IGNORE_REGEXES = { "org\\.junit.*", "com\\.intellij.*", "sun\\.reflect.*", "java\\.lang\\.reflect.*", "java\\.util\\.ArrayList.*", "io\\.micronaut\\.(aop|context).*", "io\\.videofirst\\.vfa.*", ".*\\.\\$\\w+\\$.*" }; private static final List<Pattern> patterns = new ArrayList<>(); public static void main(String[] args) { int i = 1; for (String regex : STRACKTRACE_IGNORE_REGEXES) { patterns.add(Pattern.compile("^" + regex + "$")); } for (String line : STACKTRACE) { // 82 no filtering if (!ignoreStacktraceLine(line)) { String lineNum = (i++) + "\t"; System.out.println(lineNum + line); } } System.out.println(); for (String line : STACKTRACE) { // 82 no filtering if (!ignoreStacktraceLine(line)) { String lineNum = (i++) + "\t"; String abbreviatedLine = abbreviate(line); System.out.println(lineNum + abbreviatedLine); } } System.out.println(); System.out.println("io.videofirst.google.ErrorActions(ErrorActions.java:21)"); } private static boolean ignoreStacktraceLine(String line) { for (Pattern ignorePrefix : patterns) { Matcher matcher = ignorePrefix.matcher(line); if (matcher.find()) { return true; } } return false; } private static String abbreviate(String logLine) { int index = logLine.indexOf("("); String[] parts = logLine.substring(0, index).split("\\."); if (parts.length <= 2) { return logLine; // no change } StringBuilder sb = new StringBuilder(); String sep = ""; for (int i = 0; i < parts.length; i++) { boolean abbreviate = i < parts.length - 3; String part = abbreviate ? parts[i].substring(0, 1) : parts[i]; sb.append(sep + part); sep = "."; } sb.append(logLine.substring(index)); return sb.toString(); } }
69.648148
160
0.736063
93ccda6fc8b323f4025d4476e65af6ed13f7234f
11,290
package net.minecraft.client.gui; import com.mojang.blaze3d.platform.GlStateManager; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.BufferBuilder; import com.mojang.blaze3d.vertex.BufferUploader; import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.Tesselator; import com.mojang.blaze3d.vertex.VertexFormat; import com.mojang.math.Matrix4f; import java.util.function.BiConsumer; import net.minecraft.client.renderer.GameRenderer; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.FormattedCharSequence; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) public abstract class GuiComponent { public static final ResourceLocation BACKGROUND_LOCATION = new ResourceLocation("textures/gui/options_background.png"); public static final ResourceLocation STATS_ICON_LOCATION = new ResourceLocation("textures/gui/container/stats_icons.png"); public static final ResourceLocation GUI_ICONS_LOCATION = new ResourceLocation("textures/gui/icons.png"); private int blitOffset; protected void hLine(PoseStack p_93155_, int p_93156_, int p_93157_, int p_93158_, int p_93159_) { if (p_93157_ < p_93156_) { int i = p_93156_; p_93156_ = p_93157_; p_93157_ = i; } fill(p_93155_, p_93156_, p_93158_, p_93157_ + 1, p_93158_ + 1, p_93159_); } protected void vLine(PoseStack p_93223_, int p_93224_, int p_93225_, int p_93226_, int p_93227_) { if (p_93226_ < p_93225_) { int i = p_93225_; p_93225_ = p_93226_; p_93226_ = i; } fill(p_93223_, p_93224_, p_93225_ + 1, p_93224_ + 1, p_93226_, p_93227_); } public static void fill(PoseStack p_93173_, int p_93174_, int p_93175_, int p_93176_, int p_93177_, int p_93178_) { innerFill(p_93173_.last().pose(), p_93174_, p_93175_, p_93176_, p_93177_, p_93178_); } private static void innerFill(Matrix4f p_93106_, int p_93107_, int p_93108_, int p_93109_, int p_93110_, int p_93111_) { if (p_93107_ < p_93109_) { int i = p_93107_; p_93107_ = p_93109_; p_93109_ = i; } if (p_93108_ < p_93110_) { int j = p_93108_; p_93108_ = p_93110_; p_93110_ = j; } float f3 = (float)(p_93111_ >> 24 & 255) / 255.0F; float f = (float)(p_93111_ >> 16 & 255) / 255.0F; float f1 = (float)(p_93111_ >> 8 & 255) / 255.0F; float f2 = (float)(p_93111_ & 255) / 255.0F; BufferBuilder bufferbuilder = Tesselator.getInstance().getBuilder(); RenderSystem.enableBlend(); RenderSystem.disableTexture(); RenderSystem.defaultBlendFunc(); RenderSystem.setShader(GameRenderer::getPositionColorShader); bufferbuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); bufferbuilder.vertex(p_93106_, (float)p_93107_, (float)p_93110_, 0.0F).color(f, f1, f2, f3).endVertex(); bufferbuilder.vertex(p_93106_, (float)p_93109_, (float)p_93110_, 0.0F).color(f, f1, f2, f3).endVertex(); bufferbuilder.vertex(p_93106_, (float)p_93109_, (float)p_93108_, 0.0F).color(f, f1, f2, f3).endVertex(); bufferbuilder.vertex(p_93106_, (float)p_93107_, (float)p_93108_, 0.0F).color(f, f1, f2, f3).endVertex(); bufferbuilder.end(); BufferUploader.end(bufferbuilder); RenderSystem.enableTexture(); RenderSystem.disableBlend(); } protected void fillGradient(PoseStack p_93180_, int p_93181_, int p_93182_, int p_93183_, int p_93184_, int p_93185_, int p_93186_) { fillGradient(p_93180_, p_93181_, p_93182_, p_93183_, p_93184_, p_93185_, p_93186_, this.blitOffset); } protected static void fillGradient(PoseStack p_168741_, int p_168742_, int p_168743_, int p_168744_, int p_168745_, int p_168746_, int p_168747_, int p_168748_) { RenderSystem.disableTexture(); RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); RenderSystem.setShader(GameRenderer::getPositionColorShader); Tesselator tesselator = Tesselator.getInstance(); BufferBuilder bufferbuilder = tesselator.getBuilder(); bufferbuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); fillGradient(p_168741_.last().pose(), bufferbuilder, p_168742_, p_168743_, p_168744_, p_168745_, p_168748_, p_168746_, p_168747_); tesselator.end(); RenderSystem.disableBlend(); RenderSystem.enableTexture(); } protected static void fillGradient(Matrix4f p_93124_, BufferBuilder p_93125_, int p_93126_, int p_93127_, int p_93128_, int p_93129_, int p_93130_, int p_93131_, int p_93132_) { float f = (float)(p_93131_ >> 24 & 255) / 255.0F; float f1 = (float)(p_93131_ >> 16 & 255) / 255.0F; float f2 = (float)(p_93131_ >> 8 & 255) / 255.0F; float f3 = (float)(p_93131_ & 255) / 255.0F; float f4 = (float)(p_93132_ >> 24 & 255) / 255.0F; float f5 = (float)(p_93132_ >> 16 & 255) / 255.0F; float f6 = (float)(p_93132_ >> 8 & 255) / 255.0F; float f7 = (float)(p_93132_ & 255) / 255.0F; p_93125_.vertex(p_93124_, (float)p_93128_, (float)p_93127_, (float)p_93130_).color(f1, f2, f3, f).endVertex(); p_93125_.vertex(p_93124_, (float)p_93126_, (float)p_93127_, (float)p_93130_).color(f1, f2, f3, f).endVertex(); p_93125_.vertex(p_93124_, (float)p_93126_, (float)p_93129_, (float)p_93130_).color(f5, f6, f7, f4).endVertex(); p_93125_.vertex(p_93124_, (float)p_93128_, (float)p_93129_, (float)p_93130_).color(f5, f6, f7, f4).endVertex(); } public static void drawCenteredString(PoseStack p_93209_, Font p_93210_, String p_93211_, int p_93212_, int p_93213_, int p_93214_) { p_93210_.drawShadow(p_93209_, p_93211_, (float)(p_93212_ - p_93210_.width(p_93211_) / 2), (float)p_93213_, p_93214_); } public static void drawCenteredString(PoseStack p_93216_, Font p_93217_, Component p_93218_, int p_93219_, int p_93220_, int p_93221_) { FormattedCharSequence formattedcharsequence = p_93218_.getVisualOrderText(); p_93217_.drawShadow(p_93216_, formattedcharsequence, (float)(p_93219_ - p_93217_.width(formattedcharsequence) / 2), (float)p_93220_, p_93221_); } public static void drawCenteredString(PoseStack p_168750_, Font p_168751_, FormattedCharSequence p_168752_, int p_168753_, int p_168754_, int p_168755_) { p_168751_.drawShadow(p_168750_, p_168752_, (float)(p_168753_ - p_168751_.width(p_168752_) / 2), (float)p_168754_, p_168755_); } public static void drawString(PoseStack p_93237_, Font p_93238_, String p_93239_, int p_93240_, int p_93241_, int p_93242_) { p_93238_.drawShadow(p_93237_, p_93239_, (float)p_93240_, (float)p_93241_, p_93242_); } public static void drawString(PoseStack p_168757_, Font p_168758_, FormattedCharSequence p_168759_, int p_168760_, int p_168761_, int p_168762_) { p_168758_.drawShadow(p_168757_, p_168759_, (float)p_168760_, (float)p_168761_, p_168762_); } public static void drawString(PoseStack p_93244_, Font p_93245_, Component p_93246_, int p_93247_, int p_93248_, int p_93249_) { p_93245_.drawShadow(p_93244_, p_93246_, (float)p_93247_, (float)p_93248_, p_93249_); } public void blitOutlineBlack(int p_93102_, int p_93103_, BiConsumer<Integer, Integer> p_93104_) { RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.ZERO, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); p_93104_.accept(p_93102_ + 1, p_93103_); p_93104_.accept(p_93102_ - 1, p_93103_); p_93104_.accept(p_93102_, p_93103_ + 1); p_93104_.accept(p_93102_, p_93103_ - 1); RenderSystem.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); p_93104_.accept(p_93102_, p_93103_); } public static void blit(PoseStack p_93201_, int p_93202_, int p_93203_, int p_93204_, int p_93205_, int p_93206_, TextureAtlasSprite p_93207_) { innerBlit(p_93201_.last().pose(), p_93202_, p_93202_ + p_93205_, p_93203_, p_93203_ + p_93206_, p_93204_, p_93207_.getU0(), p_93207_.getU1(), p_93207_.getV0(), p_93207_.getV1()); } public void blit(PoseStack p_93229_, int p_93230_, int p_93231_, int p_93232_, int p_93233_, int p_93234_, int p_93235_) { blit(p_93229_, p_93230_, p_93231_, this.blitOffset, (float)p_93232_, (float)p_93233_, p_93234_, p_93235_, 256, 256); } public static void blit(PoseStack p_93144_, int p_93145_, int p_93146_, int p_93147_, float p_93148_, float p_93149_, int p_93150_, int p_93151_, int p_93152_, int p_93153_) { innerBlit(p_93144_, p_93145_, p_93145_ + p_93150_, p_93146_, p_93146_ + p_93151_, p_93147_, p_93150_, p_93151_, p_93148_, p_93149_, p_93153_, p_93152_); } public static void blit(PoseStack p_93161_, int p_93162_, int p_93163_, int p_93164_, int p_93165_, float p_93166_, float p_93167_, int p_93168_, int p_93169_, int p_93170_, int p_93171_) { innerBlit(p_93161_, p_93162_, p_93162_ + p_93164_, p_93163_, p_93163_ + p_93165_, 0, p_93168_, p_93169_, p_93166_, p_93167_, p_93170_, p_93171_); } public static void blit(PoseStack p_93134_, int p_93135_, int p_93136_, float p_93137_, float p_93138_, int p_93139_, int p_93140_, int p_93141_, int p_93142_) { blit(p_93134_, p_93135_, p_93136_, p_93139_, p_93140_, p_93137_, p_93138_, p_93139_, p_93140_, p_93141_, p_93142_); } private static void innerBlit(PoseStack p_93188_, int p_93189_, int p_93190_, int p_93191_, int p_93192_, int p_93193_, int p_93194_, int p_93195_, float p_93196_, float p_93197_, int p_93198_, int p_93199_) { innerBlit(p_93188_.last().pose(), p_93189_, p_93190_, p_93191_, p_93192_, p_93193_, (p_93196_ + 0.0F) / (float)p_93198_, (p_93196_ + (float)p_93194_) / (float)p_93198_, (p_93197_ + 0.0F) / (float)p_93199_, (p_93197_ + (float)p_93195_) / (float)p_93199_); } private static void innerBlit(Matrix4f p_93113_, int p_93114_, int p_93115_, int p_93116_, int p_93117_, int p_93118_, float p_93119_, float p_93120_, float p_93121_, float p_93122_) { RenderSystem.setShader(GameRenderer::getPositionTexShader); BufferBuilder bufferbuilder = Tesselator.getInstance().getBuilder(); bufferbuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_TEX); bufferbuilder.vertex(p_93113_, (float)p_93114_, (float)p_93117_, (float)p_93118_).uv(p_93119_, p_93122_).endVertex(); bufferbuilder.vertex(p_93113_, (float)p_93115_, (float)p_93117_, (float)p_93118_).uv(p_93120_, p_93122_).endVertex(); bufferbuilder.vertex(p_93113_, (float)p_93115_, (float)p_93116_, (float)p_93118_).uv(p_93120_, p_93121_).endVertex(); bufferbuilder.vertex(p_93113_, (float)p_93114_, (float)p_93116_, (float)p_93118_).uv(p_93119_, p_93121_).endVertex(); bufferbuilder.end(); BufferUploader.end(bufferbuilder); } public int getBlitOffset() { return this.blitOffset; } public void setBlitOffset(int p_93251_) { this.blitOffset = p_93251_; } }
57.602041
260
0.731178
3189d591445ee69be2e4dfd1cd617cbc91d79cfb
3,839
package tk.ainiyue.danyuan.application.user.userrole.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Example; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Order; import org.springframework.stereotype.Service; import tk.ainiyue.danyuan.application.user.userrole.dao.SysUserRolesDao; import tk.ainiyue.danyuan.application.user.userrole.po.SysUserRolesInfo; import tk.ainiyue.danyuan.application.user.userrole.service.SysUserRolesService; /** * 文件名 : SysUserRolesServiceImpl.java * 包 名 : tk.ainiyue.admin.userrole.service.impl * 描 述 : TODO(用一句话描述该文件做什么) * 机能名称: * 技能ID : * 作 者 : Tenghui.Wang * 时 间 : 2016年7月17日 下午3:59:07 * 版 本 : V1.0 */ @Service("sysUserRolesService") public class SysUserRolesServiceImpl implements SysUserRolesService { // @Autowired private SysUserRolesDao sysUserRolesDao; /** * 方法名 : findAll * 功 能 : TODO(这里用一句话描述这个方法的作用) * 参 数 : @return * 参 考 : @see * tk.ainiyue.admin.userrole.service.SysUserRolesService#findAll() * 作 者 : Tenghui.Wang */ @Override public List<SysUserRolesInfo> findAll() { return sysUserRolesDao.findAll(); } /** * 方法名 : findByUuid * 功 能 : TODO(这里用一句话描述这个方法的作用) * 参 数 : @param uuid * 参 数 : @return * 参 考 : @see * tk.ainiyue.danyuan.application.user.userrole.service.SysUserRolesService#findByUuid(java.lang.String) * 作 者 : Administrator */ @Override public SysUserRolesInfo findByUuid(String uuid) { return sysUserRolesDao.findOne(uuid); } /** * 方法名 : findAllBySearchText * 功 能 : TODO(这里用一句话描述这个方法的作用) * 参 数 : @param pageNumber * 参 数 : @param pageSize * 参 数 : @param info * 参 数 : @return * 参 考 : @see * tk.ainiyue.danyuan.application.user.userrole.service.SysUserRolesService#findAllBySearchText(int, * int, tk.ainiyue.danyuan.application.user.userrole.po.SysUserRolesInfo) * 作 者 : Administrator */ @Override public Page<SysUserRolesInfo> findAllBySearchText(int pageNumber, int pageSize, SysUserRolesInfo info) { Example<SysUserRolesInfo> example = Example.of(info); Sort sort = new Sort(new Order(Direction.ASC, "createTime")); PageRequest request = new PageRequest(pageNumber - 1, pageSize, sort); Page<SysUserRolesInfo> sourceCodes = sysUserRolesDao.findAll(example, request); return sourceCodes; } /** * 方法名 : save * 功 能 : TODO(这里用一句话描述这个方法的作用) * 参 数 : @param info * 参 考 : @see * tk.ainiyue.danyuan.application.user.userrole.service.SysUserRolesService#save(tk.ainiyue.danyuan.application.user.userrole.po.SysUserRolesInfo) * 作 者 : Administrator */ @Override public void save(SysUserRolesInfo info) { sysUserRolesDao.save(info); } /** * 方法名 : delete * 功 能 : TODO(这里用一句话描述这个方法的作用) * 参 数 : @param info * 参 考 : @see * tk.ainiyue.danyuan.application.user.userrole.service.SysUserRolesService#delete(tk.ainiyue.danyuan.application.user.userrole.po.SysUserRolesInfo) * 作 者 : Administrator */ @Override public void delete(SysUserRolesInfo info) { sysUserRolesDao.delete(info); } /** * 方法名 : delete * 功 能 : TODO(这里用一句话描述这个方法的作用) * 参 数 : @param list * 参 考 : @see * tk.ainiyue.danyuan.application.user.userrole.service.SysUserRolesService#delete(java.util.List) * 作 者 : Administrator */ @Override public void delete(List<SysUserRolesInfo> list) { sysUserRolesDao.delete(list); } /** * 方法名 : trunc * 功 能 : TODO(这里用一句话描述这个方法的作用) * 参 数 : * 参 考 : @see * tk.ainiyue.danyuan.application.user.userrole.service.SysUserRolesService#trunc() * 作 者 : Administrator */ @Override public void trunc() { sysUserRolesDao.deleteAll(); } }
26.846154
149
0.72571
0caed1759015f20c98f472ba2080a66dbca4c47b
10,642
package com.facebook; import android.util.Log; import com.facebook.internal.Logger; import com.facebook.internal.Utility; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; public class GraphResponse { private static final String BODY_KEY = "body"; private static final String CODE_KEY = "code"; public static final String NON_JSON_RESPONSE_PROPERTY = "FACEBOOK_NON_JSON_RESULT"; private static final String RESPONSE_LOG_TAG = "Response"; public static final String SUCCESS_KEY = "success"; private static final String TAG = GraphResponse.class.getSimpleName(); private final HttpURLConnection connection; private final FacebookRequestError error; private final JSONObject graphObject; private final JSONArray graphObjectArray; private final String rawResponse; private final GraphRequest request; public enum PagingDirection { NEXT, PREVIOUS } GraphResponse(GraphRequest request2, HttpURLConnection connection2, String rawResponse2, JSONObject graphObject2) { this(request2, connection2, rawResponse2, graphObject2, null, null); } GraphResponse(GraphRequest request2, HttpURLConnection connection2, String rawResponse2, JSONArray graphObjects) { this(request2, connection2, rawResponse2, null, graphObjects, null); } GraphResponse(GraphRequest request2, HttpURLConnection connection2, FacebookRequestError error2) { this(request2, connection2, null, null, null, error2); } GraphResponse(GraphRequest request2, HttpURLConnection connection2, String rawResponse2, JSONObject graphObject2, JSONArray graphObjects, FacebookRequestError error2) { this.request = request2; this.connection = connection2; this.rawResponse = rawResponse2; this.graphObject = graphObject2; this.graphObjectArray = graphObjects; this.error = error2; } public final FacebookRequestError getError() { return this.error; } public final JSONObject getJSONObject() { return this.graphObject; } public final JSONArray getJSONArray() { return this.graphObjectArray; } public final HttpURLConnection getConnection() { return this.connection; } public GraphRequest getRequest() { return this.request; } public String getRawResponse() { return this.rawResponse; } public GraphRequest getRequestForPagedResults(PagingDirection direction) { String link = null; if (this.graphObject != null) { JSONObject pagingInfo = this.graphObject.optJSONObject("paging"); if (pagingInfo != null) { link = direction == PagingDirection.NEXT ? pagingInfo.optString("next") : pagingInfo.optString("previous"); } } if (Utility.isNullOrEmpty(link)) { return null; } if (link != null && link.equals(this.request.getUrlForSingleRequest())) { return null; } try { return new GraphRequest(this.request.getAccessToken(), new URL(link)); } catch (MalformedURLException e) { return null; } } public String toString() { String responseCode; try { Locale locale = Locale.US; String str = "%d"; Object[] objArr = new Object[1]; objArr[0] = Integer.valueOf(this.connection != null ? this.connection.getResponseCode() : 200); responseCode = String.format(locale, str, objArr); } catch (IOException e) { responseCode = "unknown"; } return "{Response: " + " responseCode: " + responseCode + ", graphObject: " + this.graphObject + ", error: " + this.error + "}"; } static List<GraphResponse> fromHttpConnection(HttpURLConnection connection2, GraphRequestBatch requests) { List<GraphResponse> constructErrorResponses; InputStream stream; InputStream stream2 = null; try { if (connection2.getResponseCode() >= 400) { stream = connection2.getErrorStream(); } else { stream = connection2.getInputStream(); } constructErrorResponses = createResponsesFromStream(stream2, connection2, requests); } catch (FacebookException facebookException) { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", facebookException); constructErrorResponses = constructErrorResponses(requests, connection2, facebookException); } catch (Exception exception) { Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response <Error>: %s", exception); constructErrorResponses = constructErrorResponses(requests, connection2, new FacebookException((Throwable) exception)); } finally { Utility.closeQuietly(stream2); } return constructErrorResponses; } static List<GraphResponse> createResponsesFromStream(InputStream stream, HttpURLConnection connection2, GraphRequestBatch requests) throws FacebookException, JSONException, IOException { String responseString = Utility.readStreamToString(stream); Logger.log(LoggingBehavior.INCLUDE_RAW_RESPONSES, RESPONSE_LOG_TAG, "Response (raw)\n Size: %d\n Response:\n%s\n", Integer.valueOf(responseString.length()), responseString); return createResponsesFromString(responseString, connection2, requests); } static List<GraphResponse> createResponsesFromString(String responseString, HttpURLConnection connection2, GraphRequestBatch requests) throws FacebookException, JSONException, IOException { List<GraphResponse> responses = createResponsesFromObject(connection2, requests, new JSONTokener(responseString).nextValue()); Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response\n Id: %s\n Size: %d\n Responses:\n%s\n", requests.getId(), Integer.valueOf(responseString.length()), responses); return responses; } private static List<GraphResponse> createResponsesFromObject(HttpURLConnection connection2, List<GraphRequest> requests, Object object) throws FacebookException, JSONException { int numRequests = requests.size(); List<GraphResponse> responses = new ArrayList<>(numRequests); Object originalResult = object; if (numRequests == 1) { GraphRequest request2 = (GraphRequest) requests.get(0); try { JSONObject jsonObject = new JSONObject(); jsonObject.put(BODY_KEY, object); jsonObject.put(CODE_KEY, connection2 != null ? connection2.getResponseCode() : 200); JSONArray jsonArray = new JSONArray(); jsonArray.put(jsonObject); object = jsonArray; } catch (JSONException e) { responses.add(new GraphResponse(request2, connection2, new FacebookRequestError(connection2, (Exception) e))); } catch (IOException e2) { responses.add(new GraphResponse(request2, connection2, new FacebookRequestError(connection2, (Exception) e2))); } } if (!(object instanceof JSONArray) || ((JSONArray) object).length() != numRequests) { throw new FacebookException("Unexpected number of results"); } JSONArray jsonArray2 = (JSONArray) object; for (int i = 0; i < jsonArray2.length(); i++) { GraphRequest request3 = (GraphRequest) requests.get(i); try { responses.add(createResponseFromObject(request3, connection2, jsonArray2.get(i), originalResult)); } catch (JSONException e3) { responses.add(new GraphResponse(request3, connection2, new FacebookRequestError(connection2, (Exception) e3))); } catch (FacebookException e4) { responses.add(new GraphResponse(request3, connection2, new FacebookRequestError(connection2, (Exception) e4))); } } return responses; } private static GraphResponse createResponseFromObject(GraphRequest request2, HttpURLConnection connection2, Object object, Object originalResult) throws JSONException { if (object instanceof JSONObject) { JSONObject jsonObject = (JSONObject) object; FacebookRequestError error2 = FacebookRequestError.checkResponseAndCreateError(jsonObject, originalResult, connection2); if (error2 != null) { Log.e(TAG, error2.toString()); if (error2.getErrorCode() == 190 && Utility.isCurrentAccessToken(request2.getAccessToken())) { if (error2.getSubErrorCode() != 493) { AccessToken.setCurrentAccessToken(null); } else if (!AccessToken.getCurrentAccessToken().isExpired()) { AccessToken.expireCurrentAccessToken(); } } return new GraphResponse(request2, connection2, error2); } Object body = Utility.getStringPropertyAsJSON(jsonObject, BODY_KEY, NON_JSON_RESPONSE_PROPERTY); if (body instanceof JSONObject) { return new GraphResponse(request2, connection2, body.toString(), (JSONObject) body); } if (body instanceof JSONArray) { return new GraphResponse(request2, connection2, body.toString(), (JSONArray) body); } object = JSONObject.NULL; } if (object == JSONObject.NULL) { return new GraphResponse(request2, connection2, object.toString(), (JSONObject) null); } throw new FacebookException("Got unexpected object type in response, class: " + object.getClass().getSimpleName()); } static List<GraphResponse> constructErrorResponses(List<GraphRequest> requests, HttpURLConnection connection2, FacebookException error2) { int count = requests.size(); List<GraphResponse> responses = new ArrayList<>(count); for (int i = 0; i < count; i++) { responses.add(new GraphResponse((GraphRequest) requests.get(i), connection2, new FacebookRequestError(connection2, (Exception) error2))); } return responses; } }
46.675439
193
0.666416
e81eccd16f09de1cda31f46c5c768f34744b6502
490
package io.github.pflima92.plyshare.microservice.utility; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.json.JsonObject; public class NotificationServiceImpl implements NotificationService { @Override public NotificationService createNotification(Handler<AsyncResult<JsonObject>> resultHandler) { Future<JsonObject> future = Future.future(); future.complete(); resultHandler.handle(future); return this; } }
27.222222
96
0.804082
74bc0b258806561edf805a20e43c30166faee00f
439
package ro.ase.cts.design.patterns.decorator; public class ShieldDecorator extends HeroDecorator{ public ShieldDecorator(AbstractHero hero, int shieldPoints) { super(hero); this.shieldStrength = shieldPoints; } int shieldStrength; @Override public void defend(int hitPoints) { System.out.println("The kinght is using a shield"); hitPoints -= this.shieldStrength; if(hitPoints > 0) this.hero.defend(hitPoints); } }
20.904762
62
0.749431
80e04aa3e29b8796ba342b0caeee7e4342b30af3
346
/** * <p>This package contains the main API of mu-server, for example the server builders, request and response objects.</p> * <p>For more documentation, see <a href="../../overview-summary.html">the overview page.</a></p> * @see io.muserver.MuServerBuilder * @see io.muserver.MuRequest * @see io.muserver.MuResponse */ package io.muserver;
43.25
121
0.716763
2916712d5512f2ae0b47fb31e810edb037e99bf1
3,353
package jp.posl.jprophet; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Test; import jp.posl.jprophet.project.GradleProject; import jp.posl.jprophet.project.MavenProject; import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; public class ProjectBuilderTest { private File buildDir; private RepairConfiguration gradleConfig, mavenConfig; private ProjectBuilder builder; /** * テスト入力用のプロジェクトの用意 */ @Before public void setUpProject(){ this.buildDir = new File("./tmp/"); this.gradleConfig = new RepairConfiguration(buildDir.getPath(), null, new GradleProject("src/test/resources/testGradleProject01"), null); this.mavenConfig = new RepairConfiguration(buildDir.getPath(), null, new MavenProject("src/test/resources/testMavenProject01"), null); this.builder = new ProjectBuilder(); } /** * gradleプロジェクトのビルドが成功したかどうかテスト */ @Test public void testForBuildGradleProject() { boolean isSuccess = this.builder.build(gradleConfig); assertThat(isSuccess).isTrue(); try { FileUtils.deleteDirectory(this.buildDir); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } } /** * gradleプロジェクトのクラスファイルが生成されているかどうかテスト */ @Test public void testForBuildGradleProjectPath(){ this.builder.build(gradleConfig); assertThat(new File("./tmp/testGradleProject01").exists()).isTrue(); assertThat(new File("./tmp/testGradleProject01/App.class").exists()).isTrue(); assertThat(new File("./tmp/testGradleProject01/AppTest.class").exists()).isTrue(); assertThat(new File("./tmp/testGradleProject01/App2.class").exists()).isTrue(); assertThat(new File("./tmp/testGradleProject01/App2Test.class").exists()).isTrue(); try { FileUtils.deleteDirectory(this.buildDir); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } } /** * mavenプロジェクトのビルドが成功したかどうかテスト */ @Test public void testForBuildMavenProject() { boolean isSuccess = this.builder.build(mavenConfig); assertThat(isSuccess).isTrue(); try { FileUtils.deleteDirectory(this.buildDir); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } } /** * mavenプロジェクトのクラスファイルが生成されているかどうかテスト */ @Test public void testForBuildMavenProjectPath(){ this.builder.build(mavenConfig); assertThat(new File("./tmp/testMavenProject01").exists()).isTrue(); assertThat(new File("./tmp/testMavenProject01/App.class").exists()).isTrue(); assertThat(new File("./tmp/testMavenProject01/AppTest.class").exists()).isTrue(); assertThat(new File("./tmp/testMavenProject01/App2.class").exists()).isTrue(); assertThat(new File("./tmp/testMavenProject01/App2Test.class").exists()).isTrue(); try { FileUtils.deleteDirectory(this.buildDir); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } } }
34.56701
145
0.644796
4fa8dd3b67cf515519234541608fc6d7560cfb6c
4,443
package app.vedicnerd.ytwua.pojo; import android.os.Parcel; import android.os.Parcelable; public class ItemSnippet implements Parcelable { private String publishedAt; private String channelId; private String title; private String description; private SnippetThumbnail thumbnails; private String channelTitle; private String playlistId; private Integer position; private SnippetResourceId resourceId; /** * @return The publishedAt */ public String getPublishedAt() { return publishedAt; } /** * @param publishedAt The publishedAt */ public void setPublishedAt(String publishedAt) { this.publishedAt = publishedAt; } /** * @return The channelId */ public String getChannelId() { return channelId; } /** * @param channelId The channelId */ public void setChannelId(String channelId) { this.channelId = channelId; } /** * @return The title */ public String getTitle() { return title; } /** * @param title The title */ public void setTitle(String title) { this.title = title; } /** * @return The description */ public String getDescription() { return description; } /** * @param description The description */ public void setDescription(String description) { this.description = description; } /** * @return The snippetThumbnail */ public SnippetThumbnail getSnippetThumbnail() { return thumbnails; } /** * @param thumbnails The snippetThumbnail */ public void setSnippetThumbnail(SnippetThumbnail thumbnails) { this.thumbnails = thumbnails; } /** * @return The channelTitle */ public String getChannelTitle() { return channelTitle; } /** * @param channelTitle The channelTitle */ public void setChannelTitle(String channelTitle) { this.channelTitle = channelTitle; } /** * @return The playlistId */ public String getPlaylistId() { return playlistId; } /** * @param playlistId The playlistId */ public void setPlaylistId(String playlistId) { this.playlistId = playlistId; } /** * @return The position */ public Integer getPosition() { return position; } /** * @param position The position */ public void setPosition(Integer position) { this.position = position; } /** * @return The resourceId */ public SnippetResourceId getSnippetResourceId() { return resourceId; } /** * @param resourceId The resourceId */ public void setSnippetResourceId(SnippetResourceId resourceId) { this.resourceId = resourceId; } ItemSnippet(Parcel in) { publishedAt = in.readString(); channelId = in.readString(); title = in.readString(); description = in.readString(); thumbnails = (SnippetThumbnail) in.readValue(SnippetThumbnail.class.getClassLoader()); channelTitle = in.readString(); playlistId = in.readString(); position = in.readByte() == 0x00 ? null : in.readInt(); resourceId = (SnippetResourceId) in.readValue(SnippetResourceId.class.getClassLoader()); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(publishedAt); dest.writeString(channelId); dest.writeString(title); dest.writeString(description); dest.writeValue(thumbnails); dest.writeString(channelTitle); dest.writeString(playlistId); if (position == null) { dest.writeByte((byte) (0x00)); } else { dest.writeByte((byte) (0x01)); dest.writeInt(position); } dest.writeValue(resourceId); } @SuppressWarnings("unused") public static final Parcelable.Creator<ItemSnippet> CREATOR = new Parcelable.Creator<ItemSnippet>() { @Override public ItemSnippet createFromParcel(Parcel in) { return new ItemSnippet(in); } @Override public ItemSnippet[] newArray(int size) { return new ItemSnippet[size]; } }; }
23.140625
105
0.603421
40fd297815d39ee51cb0b587b478af7709f81093
2,154
/* * Copyright 2013-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.cloud.contract.spec.internal; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.nio.file.Files; /** * Represents a property that will become a File content. * * @since 2.1.0 */ public class FromFileProperty implements Serializable { private final File file; private final String charset; private final Class type; public FromFileProperty(File file, Class type) { this(file, type, Charset.defaultCharset()); } public FromFileProperty(File file, Class type, Charset charset) { this.file = file; this.type = type; this.charset = charset.toString(); } public boolean isString() { return String.class.equals(this.type); } public boolean isByte() { return byte[].class.equals(this.type) || Byte[].class.equals(this.type); } public String asString() { try { return new String(asBytes(), this.charset); } catch (UnsupportedEncodingException ex) { throw new IllegalStateException(ex); } } public String fileName() { return this.file.getName(); } public byte[] asBytes() { try { return Files.readAllBytes(this.file.toPath()); } catch (IOException ex) { throw new IllegalStateException(ex); } } @Override public String toString() { return asString(); } public final File getFile() { return file; } public final String getCharset() { return charset; } public final Class getType() { return type; } }
22.206186
75
0.716806
b5c4174ed65a3a54bf4813a421869c35a8328e9b
117
package ru.ezhov.pixel.view; import java.io.File; interface Pixeler { void toPixel(File file, int pixelSize); }
16.714286
43
0.735043
cdb67af9b4bb1bbf11d14842be9274dc5abcaace
380
package br.com.msansone.api.portfolioservice.model.rest; public class TransactionAddRequest { private String code; private Long quantity; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Long getQuantity() { return quantity; } public void setQuantity(Long quantity) { this.quantity = quantity; } }
15.833333
56
0.715789
68ab325fc454cf5a2ca8bfb8f74747020473cf2f
2,397
package storm.starter.bolt; import backtype.storm.task.TopologyContext; import backtype.storm.topology.BasicOutputCollector; import backtype.storm.topology.IBasicBolt; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import org.json.simple.JSONValue; public class RankObjects implements IBasicBolt { List<List> _rankings = new ArrayList<List>(); int _count; Long _lastTime = null; public RankObjects(int n) { _count = n; } private int _compare(List one, List two) { long valueOne = (Long) one.get(1); long valueTwo = (Long) two.get(1); long delta = valueTwo - valueOne; if(delta > 0) { return 1; } else if (delta < 0) { return -1; } else { return 0; } } //end compare private Integer _find(Object tag) { for(int i = 0; i < _rankings.size(); ++i) { Object cur = _rankings.get(i).get(0); if (cur.equals(tag)) { return i; } } return null; } public void prepare(Map stormConf, TopologyContext context) { } public void execute(Tuple tuple, BasicOutputCollector collector) { Object tag = tuple.getValue(0); Integer existingIndex = _find(tag); if (null != existingIndex) { _rankings.set(existingIndex, tuple.getValues()); } else { _rankings.add(tuple.getValues()); } Collections.sort(_rankings, new Comparator<List>() { public int compare(List o1, List o2) { return _compare(o1, o2); } }); if (_rankings.size() > _count) { _rankings.remove(_count); } long currentTime = System.currentTimeMillis(); if(_lastTime==null || currentTime >= _lastTime + 2000) { collector.emit(new Values(JSONValue.toJSONString(_rankings))); _lastTime = currentTime; } } public void cleanup() { } public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("list")); } }
22.613208
74
0.599499
61e87b0477a705eb739003197d34f39f5f320997
590
package nl.arjanfrans.mario.actions; import nl.arjanfrans.mario.actions.MarioActions.stopImmume; import nl.arjanfrans.mario.model.Mario; import nl.arjanfrans.mario.model.World; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.actions.Actions; public class ActorActions extends Actions { static public class removeActor extends Action { public removeActor(Actor actor) { this.actor = actor; } public boolean act(float delta) { World.objectsToRemove.add(actor); return true; } } }
21.851852
59
0.772881