repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
qjcjerry/j2ee-arch | web/src/main/java/com/sishuok/es/showcase/upload/web/controller/BatchAjaxUploadController.java | 1348 | /**
* Copyright (c) 2005-2012 https://github.com/zhangkaitao
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.sishuok.es.showcase.upload.web.controller;
import com.sishuok.es.common.Constants;
import com.sishuok.es.common.web.upload.FileUploadUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* ajax批量文件上传/下载
* <p>User: Zhang Kaitao
* <p>Date: 13-2-11 上午8:46
* <p>Version: 1.0
*/
@Controller
public class BatchAjaxUploadController {
//最大上传大小 字节为单位
private long maxSize = FileUploadUtils.DEFAULT_MAX_SIZE;
//允许的文件内容类型
private String[] allowedExtension = FileUploadUtils.DEFAULT_ALLOWED_EXTENSION;
//文件上传下载的父目录
private String baseDir = FileUploadUtils.getDefaultBaseDir();
@RequiresPermissions("showcase:upload:create")
@RequestMapping(value = "ajaxUpload", method = RequestMethod.GET)
public String showAjaxUploadForm(Model model) {
model.addAttribute(Constants.OP_NAME, "新增");
return "showcase/upload/ajax/uploadForm";
}
}
| apache-2.0 |
akosyakov/intellij-community | java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RemoveUnusedVariableUtil.java | 9120 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.ig.psiutils.SideEffectChecker;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class RemoveUnusedVariableUtil {
public enum RemoveMode {
MAKE_STATEMENT,
DELETE_ALL,
CANCEL
}
public static boolean checkSideEffects(PsiExpression element, PsiVariable variableToIgnore, List<PsiElement> sideEffects) {
if (sideEffects == null || element == null) return false;
List<PsiElement> writes = new ArrayList<PsiElement>();
SideEffectChecker.checkSideEffects(element, writes);
if (variableToIgnore != null) {
for (int i = writes.size() - 1; i >= 0; i--) {
PsiElement write = writes.get(i);
if (!(write instanceof PsiAssignmentExpression)) continue;
PsiExpression lExpression = ((PsiAssignmentExpression)write).getLExpression();
if (lExpression instanceof PsiReference && ((PsiReference)lExpression).resolve() == variableToIgnore) {
writes.remove(i);
}
}
}
sideEffects.addAll(writes);
return !writes.isEmpty();
}
static PsiElement replaceElementWithExpression(PsiExpression expression,
PsiElementFactory factory,
PsiElement element) throws IncorrectOperationException {
PsiElement elementToReplace = element;
PsiElement expressionToReplaceWith = expression;
if (element.getParent() instanceof PsiExpressionStatement) {
elementToReplace = element.getParent();
expressionToReplaceWith =
factory.createStatementFromText((expression == null ? "" : expression.getText()) + ";", null);
}
else if (element.getParent() instanceof PsiDeclarationStatement) {
expressionToReplaceWith =
factory.createStatementFromText((expression == null ? "" : expression.getText()) + ";", null);
}
return elementToReplace.replace(expressionToReplaceWith);
}
static PsiElement createStatementIfNeeded(PsiExpression expression,
PsiElementFactory factory,
PsiElement element) throws IncorrectOperationException {
// if element used in expression, subexpression will do
if (!(element.getParent() instanceof PsiExpressionStatement) &&
!(element.getParent() instanceof PsiDeclarationStatement)) {
return expression;
}
return factory.createStatementFromText((expression == null ? "" : expression.getText()) + ";", null);
}
static void deleteWholeStatement(PsiElement element, PsiElementFactory factory)
throws IncorrectOperationException {
// just delete it altogether
if (element.getParent() instanceof PsiExpressionStatement) {
PsiExpressionStatement parent = (PsiExpressionStatement)element.getParent();
if (parent.getParent() instanceof PsiCodeBlock) {
parent.delete();
}
else {
// replace with empty statement (to handle with 'if (..) i=0;' )
parent.replace(createStatementIfNeeded(null, factory, element));
}
}
else {
element.delete();
}
}
static void deleteReferences(PsiVariable variable, List<PsiElement> references, @NotNull RemoveMode mode) throws IncorrectOperationException {
for (PsiElement expression : references) {
processUsage(expression, variable, null, mode);
}
}
static void collectReferences(@NotNull PsiElement context, final PsiVariable variable, final List<PsiElement> references) {
context.accept(new JavaRecursiveElementWalkingVisitor() {
@Override public void visitReferenceExpression(PsiReferenceExpression expression) {
if (expression.resolve() == variable) references.add(expression);
super.visitReferenceExpression(expression);
}
});
}
/**
* @param sideEffects if null, delete usages, otherwise collect side effects
* @return true if there are at least one unrecoverable side effect found, false if no side effects,
* null if read usage found (may happen if interval between fix creation in invoke() call was long enough)
* @throws com.intellij.util.IncorrectOperationException
*/
static Boolean processUsage(PsiElement element, PsiVariable variable, List<PsiElement> sideEffects, @NotNull RemoveMode deleteMode)
throws IncorrectOperationException {
if (!element.isValid()) return null;
PsiElementFactory factory = JavaPsiFacade.getInstance(variable.getProject()).getElementFactory();
while (element != null) {
if (element instanceof PsiAssignmentExpression) {
PsiAssignmentExpression expression = (PsiAssignmentExpression)element;
PsiExpression lExpression = expression.getLExpression();
// there should not be read access to the variable, otherwise it is not unused
if (!(lExpression instanceof PsiReferenceExpression) || variable != ((PsiReferenceExpression)lExpression).resolve()) {
return null;
}
PsiExpression rExpression = expression.getRExpression();
rExpression = PsiUtil.deparenthesizeExpression(rExpression);
if (rExpression == null) return true;
// replace assignment with expression and resimplify
boolean sideEffectFound = checkSideEffects(rExpression, variable, sideEffects);
if (!(element.getParent() instanceof PsiExpressionStatement) || PsiUtil.isStatement(rExpression)) {
if (deleteMode == RemoveMode.MAKE_STATEMENT ||
deleteMode == RemoveMode.DELETE_ALL && !(element.getParent() instanceof PsiExpressionStatement)) {
element = replaceElementWithExpression(rExpression, factory, element);
while (element.getParent() instanceof PsiParenthesizedExpression) {
element = element.getParent().replace(element);
}
List<PsiElement> references = new ArrayList<PsiElement>();
collectReferences(element, variable, references);
deleteReferences(variable, references, deleteMode);
}
else if (deleteMode == RemoveMode.DELETE_ALL) {
deleteWholeStatement(element, factory);
}
return true;
}
else {
if (deleteMode != RemoveMode.CANCEL) {
deleteWholeStatement(element, factory);
}
return !sideEffectFound;
}
}
else if (element instanceof PsiExpressionStatement && deleteMode != RemoveMode.CANCEL) {
final PsiElement parent = element.getParent();
if (parent instanceof PsiIfStatement || parent instanceof PsiLoopStatement && ((PsiLoopStatement)parent).getBody() == element) {
element.replace(JavaPsiFacade.getElementFactory(element.getProject()).createStatementFromText(";", element));
} else {
element.delete();
}
break;
}
else if (element instanceof PsiVariable && element == variable) {
PsiExpression expression = variable.getInitializer();
if (expression != null) {
expression = PsiUtil.deparenthesizeExpression(expression);
}
boolean sideEffectsFound = checkSideEffects(expression, variable, sideEffects);
if (expression != null && PsiUtil.isStatement(expression) && variable instanceof PsiLocalVariable
&&
!(variable.getParent() instanceof PsiDeclarationStatement &&
((PsiDeclarationStatement)variable.getParent()).getDeclaredElements().length > 1)) {
if (deleteMode == RemoveMode.MAKE_STATEMENT) {
element = element.replace(createStatementIfNeeded(expression, factory, element));
List<PsiElement> references = new ArrayList<PsiElement>();
collectReferences(element, variable, references);
deleteReferences(variable, references, deleteMode);
}
else if (deleteMode == RemoveMode.DELETE_ALL) {
element.delete();
}
return true;
}
else {
if (deleteMode != RemoveMode.CANCEL) {
if (element instanceof PsiField) {
((PsiField)element).normalizeDeclaration();
}
element.delete();
}
return !sideEffectsFound;
}
}
element = element.getParent();
}
return true;
}
}
| apache-2.0 |
SGAXEU/ijkplayer-fork | ijkplayer-sample/src/main/java/tv/danmaku/ijk/media/sample/content/PathCursor.java | 4879 | /*
* Copyright (C) 2015 Zhang Rui <bbcallen@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tv.danmaku.ijk.media.sample.content;
import android.database.AbstractCursor;
import android.provider.BaseColumns;
import android.text.TextUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class PathCursor extends AbstractCursor {
private List<FileItem> mFileList = new ArrayList<>();
public static final String CN_ID = BaseColumns._ID;
public static final String CN_FILE_NAME = "file_name";
public static final String CN_FILE_PATH = "file_path";
public static final String CN_IS_DIRECTORY = "is_directory";
public static final String CN_IS_VIDEO = "is_video";
public static final String[] columnNames = new String[]{CN_ID, CN_FILE_NAME, CN_FILE_PATH, CN_IS_DIRECTORY, CN_IS_VIDEO};
public static final int CI_ID = 0;
public static final int CI_FILE_NAME = 1;
public static final int CI_FILE_PATH = 2;
public static final int CI_IS_DIRECTORY = 3;
public static final int CI_IS_VIDEO = 4;
PathCursor(File parentDirectory, File[] fileList) {
if (parentDirectory.getParent() != null) {
FileItem parentFile = new FileItem(new File(parentDirectory, ".."));
parentFile.isDirectory = true;
mFileList.add(parentFile);
}
if (fileList != null) {
for (File file : fileList) {
mFileList.add(new FileItem(file));
}
Collections.sort(this.mFileList, sComparator);
}
}
@Override
public int getCount() {
return mFileList.size();
}
@Override
public String[] getColumnNames() {
return columnNames;
}
@Override
public String getString(int column) {
switch (column) {
case CI_FILE_NAME:
return mFileList.get(getPosition()).file.getName().toString();
case CI_FILE_PATH:
return mFileList.get(getPosition()).file.toString();
}
return null;
}
@Override
public short getShort(int column) {
return (short) getLong(column);
}
@Override
public int getInt(int column) {
return (int) getLong(column);
}
@Override
public long getLong(int column) {
switch (column) {
case CI_ID:
return getPosition();
case CI_IS_DIRECTORY:
return mFileList.get(getPosition()).isDirectory ? 1 : 0;
case CI_IS_VIDEO:
return mFileList.get(getPosition()).isVideo ? 1 : 0;
}
return 0;
}
@Override
public float getFloat(int column) {
return 0;
}
@Override
public double getDouble(int column) {
return 0;
}
@Override
public boolean isNull(int column) {
return mFileList == null;
}
public static Comparator<FileItem> sComparator = new Comparator<FileItem>() {
@Override
public int compare(FileItem lhs, FileItem rhs) {
if (lhs.isDirectory && !rhs.isDirectory)
return -1;
else if (!lhs.isDirectory && rhs.isDirectory)
return 1;
return lhs.file.compareTo(rhs.file);
}
};
private static Set<String> sMediaExtSet = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
{
sMediaExtSet.add("flv");
sMediaExtSet.add("mp4");
}
private class FileItem {
public File file;
public boolean isDirectory;
public boolean isVideo;
public FileItem(String file) {
this(new File(file));
}
public FileItem(File file) {
this.file = file;
this.isDirectory = file.isDirectory();
String fileName = file.getName();
if (!TextUtils.isEmpty(fileName)) {
int extPos = fileName.lastIndexOf('.');
if (extPos >= 0) {
String ext = fileName.substring(extPos + 1);
if (!TextUtils.isEmpty(ext) && sMediaExtSet.contains(ext)) {
this.isVideo = true;
}
}
}
}
}
}
| gpl-2.0 |
akosyakov/intellij-community | platform/lang-impl/src/com/intellij/ide/fileTemplates/InternalTemplateBean.java | 1045 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.fileTemplates;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.util.xmlb.annotations.Attribute;
/**
* @author yole
*/
public class InternalTemplateBean {
public static ExtensionPointName<InternalTemplateBean> EP_NAME = ExtensionPointName.create("com.intellij.internalFileTemplate");
@Attribute("name")
public String name;
@Attribute("subject")
public String subject;
}
| apache-2.0 |
nidonglin/assist | common/src/test/java/com/sishuok/es/common/utils/html/HtmlUtilsTest.java | 1190 | /**
* Copyright (c) 2005-2012 https://github.com/zhangkaitao
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.sishuok.es.common.utils.html;
import org.junit.Assert;
import org.junit.Test;
/**
* <p>User: Zhang Kaitao
* <p>Date: 13-5-27 下午2:12
* <p>Version: 1.0
*/
public class HtmlUtilsTest {
@Test
public void testHtml2Text() {
String html = "<a>你好</a><a>你好</a>";
Assert.assertEquals("你好你好", HtmlUtils.text(html));
}
@Test
public void testHtml2TextWithMaxLength() {
String html = "<a>你好</a><a>你好</a>";
Assert.assertEquals("你好……", HtmlUtils.text(html, 2));
}
@Test
public void testRemoveUnSafeTag() {
String html = "<a onclick='alert(1)' onBlur='alert(1)'>你好</a><script>alert(1)</script><Script>alert(1)</SCRIPT>";
Assert.assertEquals("<a>你好</a>", HtmlUtils.removeUnSafeTag(html));
}
@Test
public void testRemoveTag() {
String html = "<a onclick='alert(1)' onBlur='alert(1)'>你好</a><A>1</a>";
Assert.assertEquals("", HtmlUtils.removeTag(html, "a"));
}
}
| apache-2.0 |
thanhpete/selenium | java/client/src/org/openqa/selenium/support/ui/ExpectedConditions.java | 27616 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.support.ui;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.NoSuchFrameException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Canned {@link ExpectedCondition}s which are generally useful within webdriver
* tests.
*/
public class ExpectedConditions {
private final static Logger log = Logger.getLogger(ExpectedConditions.class.getName());
private ExpectedConditions() {
// Utility class
}
/**
* An expectation for checking the title of a page.
*
* @param title the expected title, which must be an exact match
* @return true when the title matches, false otherwise
*/
public static ExpectedCondition<Boolean> titleIs(final String title) {
return new ExpectedCondition<Boolean>() {
private String currentTitle = "";
@Override
public Boolean apply(WebDriver driver) {
currentTitle = driver.getTitle();
return title.equals(currentTitle);
}
@Override
public String toString() {
return String.format("title to be \"%s\". Current title: \"%s\"", title, currentTitle);
}
};
}
/**
* An expectation for checking that the title contains a case-sensitive
* substring
*
* @param title the fragment of title expected
* @return true when the title matches, false otherwise
*/
public static ExpectedCondition<Boolean> titleContains(final String title) {
return new ExpectedCondition<Boolean>() {
private String currentTitle = "";
@Override
public Boolean apply(WebDriver driver) {
currentTitle = driver.getTitle();
return currentTitle != null && currentTitle.contains(title);
}
@Override
public String toString() {
return String.format("title to contain \"%s\". Current title: \"%s\"", title, currentTitle);
}
};
}
/**
* An expectation for the URL of the current page to be a specific url.
*
* @param url the url that the page should be on
* @return <code>true</code> when the URL is what it should be
*/
public static ExpectedCondition<Boolean> urlToBe(final String url) {
return new ExpectedCondition<Boolean>() {
private String currentUrl = "";
@Override
public Boolean apply(WebDriver driver) {
currentUrl = driver.getCurrentUrl();
return currentUrl != null && currentUrl.equals(url);
}
@Override
public String toString() {
return String.format("url to be \"%s\". Current url: \"%s\"", url, currentUrl);
}
};
}
/**
* An expectation for the URL of the current page to contain specific text.
*
* @param fraction the fraction of the url that the page should be on
* @return <code>true</code> when the URL contains the text
*/
public static ExpectedCondition<Boolean> urlContains(final String fraction) {
return new ExpectedCondition<Boolean>() {
private String currentUrl = "";
@Override
public Boolean apply(WebDriver driver) {
currentUrl = driver.getCurrentUrl();
return currentUrl != null && currentUrl.contains(fraction);
}
@Override
public String toString() {
return String.format("url to contain \"%s\". Current url: \"%s\"", fraction, currentUrl);
}
};
}
/**
* Expectation for the URL to match a specific regular expression
*
* @param regex the regular expression that the URL should match
* @return <code>true</code> if the URL matches the specified regular expression
*/
public static ExpectedCondition<Boolean> urlMatches(final String regex) {
return new ExpectedCondition<Boolean>() {
private String currentUrl;
private Pattern pattern;
private Matcher matcher;
@Override
public Boolean apply(WebDriver driver) {
currentUrl = driver.getCurrentUrl();
pattern = Pattern.compile(regex);
matcher = pattern.matcher(currentUrl);
return matcher.find();
}
@Override
public String toString() {
return String.format("url to match the regex \"%s\". Current url: \"%s\"", regex, currentUrl);
}
};
}
/**
* An expectation for checking that an element is present on the DOM of a
* page. This does not necessarily mean that the element is visible.
*
* @param locator used to find the element
* @return the WebElement once it is located
*/
public static ExpectedCondition<WebElement> presenceOfElementLocated(
final By locator) {
return new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
return findElement(locator, driver);
}
@Override
public String toString() {
return "presence of element located by: " + locator;
}
};
}
/**
* An expectation for checking that an element is present on the DOM of a page
* and visible. Visibility means that the element is not only displayed but
* also has a height and width that is greater than 0.
*
* @param locator used to find the element
* @return the WebElement once it is located and visible
*/
public static ExpectedCondition<WebElement> visibilityOfElementLocated(
final By locator) {
return new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
try {
return elementIfVisible(findElement(locator, driver));
} catch (StaleElementReferenceException e) {
return null;
}
}
@Override
public String toString() {
return "visibility of element located by " + locator;
}
};
}
/**
* An expectation for checking that all elements present on the web page that
* match the locator are visible. Visibility means that the elements are not
* only displayed but also have a height and width that is greater than 0.
*
* @param locator used to find the element
* @return the list of WebElements once they are located
*/
public static ExpectedCondition<List<WebElement>> visibilityOfAllElementsLocatedBy(
final By locator) {
return new ExpectedCondition<List<WebElement>>() {
@Override
public List<WebElement> apply(WebDriver driver) {
List<WebElement> elements = findElements(locator, driver);
for(WebElement element : elements){
if(!element.isDisplayed()){
return null;
}
}
return elements.size() > 0 ? elements : null;
}
@Override
public String toString() {
return "visibility of all elements located by " + locator;
}
};
}
/**
* An expectation for checking that all elements present on the web page that
* match the locator are visible. Visibility means that the elements are not
* only displayed but also have a height and width that is greater than 0.
*
* @param elements list of WebElements
* @return the list of WebElements once they are located
*/
public static ExpectedCondition<List<WebElement>> visibilityOfAllElements(
final List<WebElement> elements) {
return new ExpectedCondition<List<WebElement>>() {
@Override
public List<WebElement> apply(WebDriver driver) {
for(WebElement element : elements){
if(!element.isDisplayed()){
return null;
}
}
return elements.size() > 0 ? elements : null;
}
@Override
public String toString() {
return "visibility of all " + elements;
}
};
}
/**
* An expectation for checking that an element, known to be present on the DOM
* of a page, is visible. Visibility means that the element is not only
* displayed but also has a height and width that is greater than 0.
*
* @param element the WebElement
* @return the (same) WebElement once it is visible
*/
public static ExpectedCondition<WebElement> visibilityOf(
final WebElement element) {
return new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
return elementIfVisible(element);
}
@Override
public String toString() {
return "visibility of " + element;
}
};
}
/**
* @return the given element if it is visible and has non-zero size, otherwise null.
*/
private static WebElement elementIfVisible(WebElement element) {
return element.isDisplayed() ? element : null;
}
/**
* An expectation for checking that there is at least one element present on a
* web page.
*
* @param locator used to find the element
* @return the list of WebElements once they are located
*/
public static ExpectedCondition<List<WebElement>> presenceOfAllElementsLocatedBy(
final By locator) {
return new ExpectedCondition<List<WebElement>>() {
@Override
public List<WebElement> apply(WebDriver driver) {
List<WebElement> elements = findElements(locator, driver);
return elements.size() > 0 ? elements : null;
}
@Override
public String toString() {
return "presence of any elements located by " + locator;
}
};
}
/**
* An expectation for checking if the given text is present in the specified element.
*
* @param element the WebElement
* @param text to be present in the element
* @return true once the element contains the given text
*/
public static ExpectedCondition<Boolean> textToBePresentInElement(
final WebElement element, final String text) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
String elementText = element.getText();
return elementText.contains(text);
} catch (StaleElementReferenceException e) {
return null;
}
}
@Override
public String toString() {
return String.format("text ('%s') to be present in element %s", text, element);
}
};
}
/**
* An expectation for checking if the given text is present in the element that matches
* the given locator.
*
* @param locator used to find the element
* @param text to be present in the element found by the locator
* @return the WebElement once it is located and visible
*
* @deprecated Use {@link #textToBePresentInElementLocated(By, String)} instead
*/
@Deprecated
public static ExpectedCondition<Boolean> textToBePresentInElement(
final By locator, final String text) {
return textToBePresentInElementLocated(locator, text);
}
/**
* An expectation for checking if the given text is present in the element that matches
* the given locator.
*
* @param locator used to find the element
* @param text to be present in the element found by the locator
* @return true once the first element located by locator contains the given text
*/
public static ExpectedCondition<Boolean> textToBePresentInElementLocated(
final By locator, final String text) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
String elementText = findElement(locator, driver).getText();
return elementText.contains(text);
} catch (StaleElementReferenceException e) {
return null;
}
}
@Override
public String toString() {
return String.format("text ('%s') to be present in element found by %s",
text, locator);
}
};
}
/**
* An expectation for checking if the given text is present in the specified
* elements value attribute.
*
* @param element the WebElement
* @param text to be present in the element's value attribute
* @return true once the element's value attribute contains the given text
*/
public static ExpectedCondition<Boolean> textToBePresentInElementValue(
final WebElement element, final String text) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
String elementText = element.getAttribute("value");
if (elementText != null) {
return elementText.contains(text);
} else {
return false;
}
} catch (StaleElementReferenceException e) {
return null;
}
}
@Override
public String toString() {
return String.format("text ('%s') to be the value of element %s", text, element);
}
};
}
/**
* An expectation for checking if the given text is present in the specified
* elements value attribute.
*
* @param locator used to find the element
* @param text to be present in the value attribute of the element found by the locator
* @return true once the value attribute of the first element located by locator contains
* the given text
*/
public static ExpectedCondition<Boolean> textToBePresentInElementValue(
final By locator, final String text) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
String elementText = findElement(locator, driver).getAttribute("value");
if (elementText != null) {
return elementText.contains(text);
} else {
return false;
}
} catch (StaleElementReferenceException e) {
return null;
}
}
@Override
public String toString() {
return String.format("text ('%s') to be the value of element located by %s",
text, locator);
}
};
}
/**
* An expectation for checking whether the given frame is available to switch
* to. <p> If the frame is available it switches the given driver to the
* specified frame.
*
* @param frameLocator used to find the frame (id or name)
*/
public static ExpectedCondition<WebDriver> frameToBeAvailableAndSwitchToIt(
final String frameLocator) {
return new ExpectedCondition<WebDriver>() {
@Override
public WebDriver apply(WebDriver driver) {
try {
return driver.switchTo().frame(frameLocator);
} catch (NoSuchFrameException e) {
return null;
}
}
@Override
public String toString() {
return "frame to be available: " + frameLocator;
}
};
}
/**
* An expectation for checking whether the given frame is available to switch
* to. <p> If the frame is available it switches the given driver to the
* specified frame.
*
* @param locator used to find the frame
*/
public static ExpectedCondition<WebDriver> frameToBeAvailableAndSwitchToIt(
final By locator) {
return new ExpectedCondition<WebDriver>() {
@Override
public WebDriver apply(WebDriver driver) {
try {
return driver.switchTo().frame(findElement(locator, driver));
} catch (NoSuchFrameException e) {
return null;
}
}
@Override
public String toString() {
return "frame to be available: " + locator;
}
};
}
/**
* An expectation for checking whether the given frame is available to switch
* to. <p> If the frame is available it switches the given driver to the
* specified frameIndex.
*
* @param frameLocator used to find the frame (index)
*/
public static ExpectedCondition<WebDriver> frameToBeAvailableAndSwitchToIt(
final int frameLocator) {
return new ExpectedCondition<WebDriver>() {
@Override
public WebDriver apply(WebDriver driver) {
try {
return driver.switchTo().frame(frameLocator);
} catch (NoSuchFrameException e) {
return null;
}
}
@Override
public String toString() {
return "frame to be available: " + frameLocator;
}
};
}
/**
* An expectation for checking whether the given frame is available to switch
* to. <p> If the frame is available it switches the given driver to the
* specified webelement.
*
* @param frameLocator used to find the frame (webelement)
*/
public static ExpectedCondition<WebDriver> frameToBeAvailableAndSwitchToIt(
final WebElement frameLocator) {
return new ExpectedCondition<WebDriver>() {
@Override
public WebDriver apply(WebDriver driver) {
try {
return driver.switchTo().frame(frameLocator);
} catch (NoSuchFrameException e) {
return null;
}
}
@Override
public String toString() {
return "frame to be available: " + frameLocator;
}
};
}
/**
* An expectation for checking that an element is either invisible or not
* present on the DOM.
*
* @param locator used to find the element
*/
public static ExpectedCondition<Boolean> invisibilityOfElementLocated(
final By locator) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
return !(findElement(locator, driver).isDisplayed());
} catch (NoSuchElementException e) {
// Returns true because the element is not present in DOM. The
// try block checks if the element is present but is invisible.
return true;
} catch (StaleElementReferenceException e) {
// Returns true because stale element reference implies that element
// is no longer visible.
return true;
}
}
@Override
public String toString() {
return "element to no longer be visible: " + locator;
}
};
}
/**
* An expectation for checking that an element with text is either invisible
* or not present on the DOM.
*
* @param locator used to find the element
* @param text of the element
*/
public static ExpectedCondition<Boolean> invisibilityOfElementWithText(
final By locator, final String text) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
return !findElement(locator, driver).getText().equals(text);
} catch (NoSuchElementException e) {
// Returns true because the element with text is not present in DOM. The
// try block checks if the element is present but is invisible.
return true;
} catch (StaleElementReferenceException e) {
// Returns true because stale element reference implies that element
// is no longer visible.
return true;
}
}
@Override
public String toString() {
return String.format("element containing '%s' to no longer be visible: %s",
text, locator);
}
};
}
/**
* An expectation for checking an element is visible and enabled such that you
* can click it.
*
* @param locator used to find the element
* @return the WebElement once it is located and clickable (visible and enabled)
*/
public static ExpectedCondition<WebElement> elementToBeClickable(
final By locator) {
return new ExpectedCondition<WebElement>() {
public ExpectedCondition<WebElement> visibilityOfElementLocated =
ExpectedConditions.visibilityOfElementLocated(locator);
@Override
public WebElement apply(WebDriver driver) {
WebElement element = visibilityOfElementLocated.apply(driver);
try {
if (element != null && element.isEnabled()) {
return element;
} else {
return null;
}
} catch (StaleElementReferenceException e) {
return null;
}
}
@Override
public String toString() {
return "element to be clickable: " + locator;
}
};
}
/**
* An expectation for checking an element is visible and enabled such that you
* can click it.
*
* @param element the WebElement
* @return the (same) WebElement once it is clickable (visible and enabled)
*/
public static ExpectedCondition<WebElement> elementToBeClickable(
final WebElement element) {
return new ExpectedCondition<WebElement>() {
public ExpectedCondition<WebElement> visibilityOfElement =
ExpectedConditions.visibilityOf(element);
@Override
public WebElement apply(WebDriver driver) {
WebElement element = visibilityOfElement.apply(driver);
try {
if (element != null && element.isEnabled()) {
return element;
} else {
return null;
}
} catch (StaleElementReferenceException e) {
return null;
}
}
@Override
public String toString() {
return "element to be clickable: " + element;
}
};
}
/**
* Wait until an element is no longer attached to the DOM.
*
* @param element The element to wait for.
* @return false is the element is still attached to the DOM, true
* otherwise.
*/
public static ExpectedCondition<Boolean> stalenessOf(
final WebElement element) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver ignored) {
try {
// Calling any method forces a staleness check
element.isEnabled();
return false;
} catch (StaleElementReferenceException expected) {
return true;
}
}
@Override
public String toString() {
return String.format("element (%s) to become stale", element);
}
};
}
/**
* Wrapper for a condition, which allows for elements to update by redrawing.
*
* This works around the problem of conditions which have two parts: find an
* element and then check for some condition on it. For these conditions it is
* possible that an element is located and then subsequently it is redrawn on
* the client. When this happens a {@link StaleElementReferenceException} is
* thrown when the second part of the condition is checked.
*/
public static <T> ExpectedCondition<T> refreshed(
final ExpectedCondition<T> condition) {
return new ExpectedCondition<T>() {
@Override
public T apply(WebDriver driver) {
try {
return condition.apply(driver);
} catch (StaleElementReferenceException e) {
return null;
}
}
@Override
public String toString() {
return String.format("condition (%s) to be refreshed", condition);
}
};
}
/**
* An expectation for checking if the given element is selected.
*/
public static ExpectedCondition<Boolean> elementToBeSelected(final WebElement element) {
return elementSelectionStateToBe(element, true);
}
/**
* An expectation for checking if the given element is selected.
*/
public static ExpectedCondition<Boolean> elementSelectionStateToBe(final WebElement element,
final boolean selected) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
return element.isSelected() == selected;
}
@Override
public String toString() {
return String.format("element (%s) to %sbe selected", element, (selected ? "" : "not "));
}
};
}
public static ExpectedCondition<Boolean> elementToBeSelected(final By locator) {
return elementSelectionStateToBe(locator, true);
}
public static ExpectedCondition<Boolean> elementSelectionStateToBe(final By locator,
final boolean selected) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
WebElement element = driver.findElement(locator);
return element.isSelected() == selected;
} catch (StaleElementReferenceException e) {
return null;
}
}
@Override
public String toString() {
return String.format("element found by %s to %sbe selected",
locator, (selected ? "" : "not "));
}
};
}
public static ExpectedCondition<Alert> alertIsPresent() {
return new ExpectedCondition<Alert>() {
@Override
public Alert apply(WebDriver driver) {
try {
return driver.switchTo().alert();
} catch (NoAlertPresentException e) {
return null;
}
}
@Override
public String toString() {
return "alert to be present";
}
};
}
/**
* An expectation with the logical opposite condition of the given condition.
*
* Note that if the Condition your are inverting throws an exception that is
* caught by the Ignored Exceptions, the inversion will not take place and lead
* to confusing results.
*/
public static ExpectedCondition<Boolean> not(final ExpectedCondition<?> condition) {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
Object result = condition.apply(driver);
return result == null || result == Boolean.FALSE;
}
@Override
public String toString() {
return "condition to not be valid: " + condition;
}
};
}
/**
* Looks up an element. Logs and re-throws WebDriverException if thrown. <p/>
* Method exists to gather data for http://code.google.com/p/selenium/issues/detail?id=1800
*/
private static WebElement findElement(By by, WebDriver driver) {
try {
return driver.findElement(by);
} catch (NoSuchElementException e) {
throw e;
} catch (WebDriverException e) {
log.log(Level.WARNING,
String.format("WebDriverException thrown by findElement(%s)", by), e);
throw e;
}
}
/**
* @see #findElement(By, WebDriver)
*/
private static List<WebElement> findElements(By by, WebDriver driver) {
try {
return driver.findElements(by);
} catch (WebDriverException e) {
log.log(Level.WARNING,
String.format("WebDriverException thrown by findElement(%s)", by), e);
throw e;
}
}
}
| apache-2.0 |
squidsolutions/drill | exec/java-exec/src/main/java/org/apache/drill/exec/store/mock/MockStorePOP.java | 2242 | /**
* 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.drill.exec.store.mock;
import java.util.Collections;
import java.util.List;
import org.apache.drill.exec.physical.EndpointAffinity;
import org.apache.drill.exec.physical.base.AbstractStore;
import org.apache.drill.exec.physical.base.PhysicalOperator;
import org.apache.drill.exec.physical.base.Store;
import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
@JsonTypeName("mock-store")
public class MockStorePOP extends AbstractStore {
static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MockStorePOP.class);
@JsonCreator
public MockStorePOP(@JsonProperty("child") PhysicalOperator child) {
super(child);
}
public int getMaxWidth() {
return 1;
}
@Override
public List<EndpointAffinity> getOperatorAffinity() {
return Collections.emptyList();
}
@Override
public void applyAssignments(List<DrillbitEndpoint> endpoints) {
}
@Override
public Store getSpecificStore(PhysicalOperator child, int minorFragmentId) {
return new MockStorePOP(child);
}
@Override
protected PhysicalOperator getNewWithChild(PhysicalOperator child) {
return new MockStorePOP(child);
}
@Override
public int getOperatorType() {
throw new UnsupportedOperationException();
}
}
| apache-2.0 |
agoncharuk/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheLocalTxStoreExceptionSelfTest.java | 1263 | /*
* 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.ignite.internal.processors.cache;
import org.apache.ignite.cache.CacheMode;
import static org.apache.ignite.cache.CacheMode.LOCAL;
/**
*
*/
public class GridCacheLocalTxStoreExceptionSelfTest extends IgniteTxStoreExceptionAbstractSelfTest {
/** {@inheritDoc} */
@Override protected int gridCount() {
return 1;
}
/** {@inheritDoc} */
@Override protected CacheMode cacheMode() {
return LOCAL;
}
} | apache-2.0 |
masconsult/android-recipes-app | vendors/android-support-v7-appcompat/libs-src/android-support-v4/android/support/v4/content/pm/ActivityInfoCompat.java | 1171 | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.support.v4.content.pm;
/**
* Helper for accessing features in {@link android.content.pm.ActivityInfo}
* introduced after API level 4 in a backwards compatible fashion.
*/
public class ActivityInfoCompat {
private ActivityInfoCompat() {
/* Hide constructor */
}
/**
* Bit in ActivityInfo#configChanges that indicates that the
* activity can itself handle the ui mode. Set from the
* {@link android.R.attr#configChanges} attribute.
*/
public static final int CONFIG_UI_MODE = 0x0200;
}
| apache-2.0 |
pulasthi7/carbon-identity | components/user-store/org.wso2.carbon.ldap.server/src/test/java/org/wso2/carbon/apacheds/impl/MyUser.java | 12902 | /*
*
* Copyright (c) 2005, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apacheds.impl;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import java.util.Hashtable;
public class MyUser implements DirContext {
Attributes myAttrs;
public MyUser(String userId, String surName, String commonName) {
myAttrs = new BasicAttributes(true); // Case ignore
Attribute oc = new BasicAttribute("objectclass");
oc.add("inetOrgPerson");
oc.add("organizationalPerson");
oc.add("person");
oc.add("top");
Attribute sn = new BasicAttribute("sn");
sn.add(surName);
Attribute cn = new BasicAttribute("cn");
cn.add(commonName);
Attribute uid = new BasicAttribute("uid");
uid.add(userId);
myAttrs.put(sn);
myAttrs.put(cn);
myAttrs.put(uid);
myAttrs.put(oc);
}
public Attributes getAttributes(Name name)
throws NamingException {
return (Attributes)myAttrs.clone();
}
public Attributes getAttributes(String name)
throws NamingException {
return (Attributes)myAttrs.clone();
}
public Attributes getAttributes(Name name, String[] attrIds)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Attributes getAttributes(String name, String[] attrIds)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public void modifyAttributes(Name name, int mod_op, Attributes attrs)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void modifyAttributes(String name, int mod_op, Attributes attrs)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void modifyAttributes(Name name, ModificationItem[] mods)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void modifyAttributes(String name, ModificationItem[] mods)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void bind(Name name, Object obj, Attributes attrs)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void bind(String name, Object obj, Attributes attrs)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void rebind(Name name, Object obj, Attributes attrs)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void rebind(String name, Object obj, Attributes attrs)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public DirContext createSubcontext(Name name, Attributes attrs)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public DirContext createSubcontext(String name, Attributes attrs)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public DirContext getSchema(Name name)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public DirContext getSchema(String name)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public DirContext getSchemaClassDefinition(Name name)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public DirContext getSchemaClassDefinition(String name)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes, String[] attributesToReturn)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes,
String[] attributesToReturn)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NamingEnumeration<SearchResult> search(Name name, Attributes matchingAttributes)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NamingEnumeration<SearchResult> search(String name, Attributes matchingAttributes)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NamingEnumeration<SearchResult> search(Name name, String filter, SearchControls cons)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NamingEnumeration<SearchResult> search(Name name, String filterExpr, Object[] filterArgs,
SearchControls cons)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NamingEnumeration<SearchResult> search(String name, String filterExpr, Object[] filterArgs,
SearchControls cons)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Object lookup(Name name)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Object lookup(String name)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public void bind(Name name, Object obj)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void bind(String name, Object obj)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void rebind(Name name, Object obj)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void rebind(String name, Object obj)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void unbind(Name name)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void unbind(String name)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void rename(Name oldName, Name newName)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void rename(String oldName, String newName)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public NamingEnumeration<NameClassPair> list(Name name)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NamingEnumeration<NameClassPair> list(String name)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NamingEnumeration<Binding> listBindings(Name name)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NamingEnumeration<Binding> listBindings(String name)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public void destroySubcontext(Name name)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public void destroySubcontext(String name)
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public Context createSubcontext(Name name)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Context createSubcontext(String name)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Object lookupLink(Name name)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Object lookupLink(String name)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NameParser getNameParser(Name name)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public NameParser getNameParser(String name)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Name composeName(Name name, Name prefix)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public String composeName(String name, String prefix)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Object addToEnvironment(String propName, Object propVal)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Object removeFromEnvironment(String propName)
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public Hashtable<?, ?> getEnvironment()
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public void close()
throws NamingException {
//To change body of implemented methods use File | Settings | File Templates.
}
public String getNameInNamespace()
throws NamingException {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
} | apache-2.0 |
marsorp/blog | presto166/presto-ml/src/main/java/com/facebook/presto/ml/type/ClassifierType.java | 1798 | /*
* 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.facebook.presto.ml.type;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spi.type.TypeSignature;
import com.facebook.presto.spi.type.TypeSignatureParameter;
import com.google.common.collect.ImmutableList;
import java.util.List;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.spi.type.VarcharType.VARCHAR;
import static com.google.common.base.Preconditions.checkArgument;
// Layout is <size>:<model>, where
// size: is an int describing the length of the model bytes
// model: is the serialized model
public class ClassifierType
extends ModelType
{
public static final ClassifierType BIGINT_CLASSIFIER = new ClassifierType(BIGINT);
public static final ClassifierType VARCHAR_CLASSIFIER = new ClassifierType(VARCHAR);
private final Type labelType;
public ClassifierType(Type type)
{
super(new TypeSignature(ClassifierParametricType.NAME, TypeSignatureParameter.of(type.getTypeSignature())));
checkArgument(type.isComparable(), "type must be comparable");
labelType = type;
}
@Override
public List<Type> getTypeParameters()
{
return ImmutableList.of(labelType);
}
}
| apache-2.0 |
gunaangs/Feedonymous | node_modules/react-native/ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactIntegrationTestCase.java | 6664 | /**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.react.testing;
import javax.annotation.Nullable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import android.app.Application;
import android.support.test.InstrumentationRegistry;
import android.test.AndroidTestCase;
import android.view.View;
import android.view.ViewGroup;
import com.facebook.infer.annotation.Assertions;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.CatalystInstance;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.SoftAssertions;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.common.futures.SimpleSettableFuture;
import com.facebook.react.devsupport.interfaces.DevSupportManager;
import com.facebook.react.modules.core.Timing;
import com.facebook.react.testing.idledetection.ReactBridgeIdleSignaler;
import com.facebook.react.testing.idledetection.ReactIdleDetectionUtil;
import com.facebook.soloader.SoLoader;
import static org.mockito.Mockito.mock;
/**
* Use this class for writing integration tests of catalyst. This class will run all JNI call
* within separate android looper, thus you don't need to care about starting your own looper.
*
* Keep in mind that all JS remote method calls and script load calls are asynchronous and you
* should not expect them to return results immediately.
*
* In order to write catalyst integration:
* 1) Make {@link ReactIntegrationTestCase} a base class of your test case
* 2) Use {@link ReactTestHelper#catalystInstanceBuilder()}
* instead of {@link com.facebook.react.bridge.CatalystInstanceImpl.Builder} to build catalyst
* instance for testing purposes
*
*/
public abstract class ReactIntegrationTestCase extends AndroidTestCase {
// we need a bigger timeout for CI builds because they run on a slow emulator
private static final long IDLE_TIMEOUT_MS = 60000;
private @Nullable CatalystInstance mInstance;
private @Nullable ReactBridgeIdleSignaler mBridgeIdleSignaler;
private @Nullable ReactApplicationContext mReactContext;
@Override
public ReactApplicationContext getContext() {
if (mReactContext == null) {
mReactContext = new ReactApplicationContext(super.getContext());
Assertions.assertNotNull(mReactContext);
}
return mReactContext;
}
public void shutDownContext() {
if (mInstance != null) {
final ReactContext contextToDestroy = mReactContext;
mReactContext = null;
mInstance = null;
final SimpleSettableFuture<Void> semaphore = new SimpleSettableFuture<>();
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
if (contextToDestroy != null) {
contextToDestroy.destroy();
}
semaphore.set(null);
}
});
semaphore.getOrThrow();
}
}
/**
* This method isn't safe since it doesn't factor in layout-only view removal. Use
* {@link #getViewByTestId} instead.
*/
@Deprecated
public <T extends View> T getViewAtPath(ViewGroup rootView, int... path) {
return ReactTestHelper.getViewAtPath(rootView, path);
}
public <T extends View> T getViewByTestId(ViewGroup rootView, String testID) {
return (T) ReactTestHelper.getViewWithReactTestId(rootView, testID);
}
public static class Event {
private final CountDownLatch mLatch;
public Event() {
this(1);
}
public Event(int counter) {
mLatch = new CountDownLatch(counter);
}
public void occur() {
mLatch.countDown();
}
public boolean didOccur() {
return mLatch.getCount() == 0;
}
public boolean await(long millis) {
try {
return mLatch.await(millis, TimeUnit.MILLISECONDS);
} catch (InterruptedException ignore) {
return false;
}
}
}
/**
* Timing module needs to be created on the main thread so that it gets the correct Choreographer.
*/
protected Timing createTimingModule() {
final SimpleSettableFuture<Timing> simpleSettableFuture = new SimpleSettableFuture<Timing>();
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
public void run() {
Timing timing = new Timing(getContext(), mock(DevSupportManager.class));
simpleSettableFuture.set(timing);
}
});
try {
return simpleSettableFuture.get(5000, TimeUnit.MILLISECONDS);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void initializeWithInstance(CatalystInstance instance) {
mInstance = instance;
mBridgeIdleSignaler = new ReactBridgeIdleSignaler();
mInstance.addBridgeIdleDebugListener(mBridgeIdleSignaler);
getContext().initializeWithInstance(mInstance);
}
public boolean waitForBridgeIdle(long millis) {
return Assertions.assertNotNull(mBridgeIdleSignaler).waitForIdle(millis);
}
public void waitForIdleSync() {
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
}
public void waitForBridgeAndUIIdle() {
ReactIdleDetectionUtil.waitForBridgeAndUIIdle(
Assertions.assertNotNull(mBridgeIdleSignaler),
getContext(),
IDLE_TIMEOUT_MS);
}
@Override
protected void setUp() throws Exception {
super.setUp();
SoLoader.init(getContext(), /* native exopackage */ false);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
shutDownContext();
}
protected static void initializeJavaModule(final BaseJavaModule javaModule) {
final Semaphore semaphore = new Semaphore(0);
UiThreadUtil.runOnUiThread(
new Runnable() {
@Override
public void run() {
javaModule.initialize();
if (javaModule instanceof LifecycleEventListener) {
((LifecycleEventListener) javaModule).onHostResume();
}
semaphore.release();
}
});
try {
SoftAssertions.assertCondition(
semaphore.tryAcquire(5000, TimeUnit.MILLISECONDS),
"Timed out initializing timing module");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
| mit |
skhalifa/QDrill | drill1.2/contrib/storage-hive/core/src/main/java/org/apache/drill/exec/expr/fn/impl/hive/AbstractDrillPrimitiveObjectInspector.java | 1401 | /**
* 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.drill.exec.expr.fn.impl.hive;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.AbstractPrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
public abstract class AbstractDrillPrimitiveObjectInspector extends AbstractPrimitiveObjectInspector {
public AbstractDrillPrimitiveObjectInspector(PrimitiveTypeInfo typeEntry) {
super(typeEntry);
}
@Override
public Object copyObject(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean preferWritable() {
return false;
}
}
| apache-2.0 |
zsavvas/MPTCP-aware-SDN | src/main/java/net/floodlightcontroller/virtualnetwork/VirtualNetwork.java | 2956 | /**
* Copyright 2013, Big Switch Networks, 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 net.floodlightcontroller.virtualnetwork;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import org.projectfloodlight.openflow.types.MacAddress;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
/**
* Data structure for storing and outputing information of a virtual network created
* by VirtualNetworkFilter
*
* @author KC Wang
*/
@JsonSerialize(using=VirtualNetworkSerializer.class)
public class VirtualNetwork{
protected String name; // network name
protected String guid; // network id
protected String gateway; // network gateway
protected Map<String, MacAddress> portToMac; //port's logical namd and the host's mac address connected
/**
* Constructor requires network name and id
* @param name: network name
* @param guid: network id
*/
public VirtualNetwork(String name, String guid) {
this.name = name;
this.guid = guid;
this.gateway = null;
this.portToMac = new ConcurrentHashMap<String,MacAddress>();
return;
}
/**
* Sets network name
* @param gateway: IP address as String
*/
public void setName(String name){
this.name = name;
return;
}
/**
* Sets network gateway IP address
* @param gateway: IP address as String
*/
public void setGateway(String gateway){
this.gateway = gateway;
return;
}
/**
* Adds a host to this network record
* @param host: MAC address as MACAddress
*/
public void addHost(String port, MacAddress host){
this.portToMac.put(port, host); // ignore old mapping
return;
}
/**
* Removes a host from this network record
* @param host: MAC address as MACAddress
* @return boolean: true: removed, false: host not found
*/
public boolean removeHost(MacAddress host){
for (Entry<String, MacAddress> entry : this.portToMac.entrySet()) {
if (entry.getValue().equals(host)){
this.portToMac.remove(entry.getKey());
return true;
}
}
return false;
}
/**
* Removes all hosts from this network record
*/
public void clearHosts(){
this.portToMac.clear();
}
}
| apache-2.0 |
zillachan/actor-platform | actor-apps/core/src/main/java/im/actor/model/entity/Notification.java | 637 | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
package im.actor.model.entity;
public class Notification {
private Peer peer;
private int sender;
private ContentDescription contentDescription;
public Notification(Peer peer, int sender, ContentDescription contentDescription) {
this.peer = peer;
this.sender = sender;
this.contentDescription = contentDescription;
}
public Peer getPeer() {
return peer;
}
public int getSender() {
return sender;
}
public ContentDescription getContentDescription() {
return contentDescription;
}
} | mit |
akosyakov/intellij-community | plugins/git4idea/src/git4idea/history/wholeTree/GitCreateNewTag.java | 2401 | /*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.history.wholeTree;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.text.StringUtil;
import git4idea.branch.GitBrancher;
import git4idea.repo.GitRepository;
import java.util.Collections;
/**
* Created by IntelliJ IDEA.
* User: Irina.Chernushina
* Date: 10/26/11
* Time: 3:07 PM
*/
public class GitCreateNewTag {
private final Project myProject;
private final GitRepository myRepository;
private final String myReference;
private final Runnable myCallInAwtAfterExecution;
public GitCreateNewTag(Project project, GitRepository repository, String reference, Runnable callInAwtAfterExecution) {
myProject = project;
myRepository = repository;
myReference = reference;
myCallInAwtAfterExecution = callInAwtAfterExecution;
}
public void execute() {
final String name = Messages.showInputDialog(myProject, "Enter the name of new tag", "Create New Tag On " + myReference,
Messages.getQuestionIcon(), "", new InputValidator() {
@Override
public boolean checkInput(String inputString) {
return ! StringUtil.isEmpty(inputString) && ! StringUtil.containsWhitespaces(inputString);
}
@Override
public boolean canClose(String inputString) {
return ! StringUtil.isEmpty(inputString) && ! StringUtil.containsWhitespaces(inputString);
}
});
if (name != null) {
GitBrancher brancher = ServiceManager.getService(myProject, GitBrancher.class);
brancher.createNewTag(name, myReference, Collections.singletonList(myRepository), myCallInAwtAfterExecution);
}
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/src/solaris/classes/sun/awt/motif/X11KSC5601.java | 5192 | /*
* Copyright (c) 1996, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.awt.motif;
import java.nio.CharBuffer;
import java.nio.ByteBuffer;
import java.nio.charset.*;
import sun.nio.cs.ext.*;
import static sun.nio.cs.CharsetMapping.*;
public class X11KSC5601 extends Charset {
public X11KSC5601 () {
super("X11KSC5601", null);
}
public CharsetEncoder newEncoder() {
return new Encoder(this);
}
public CharsetDecoder newDecoder() {
return new Decoder(this);
}
public boolean contains(Charset cs) {
return cs instanceof X11KSC5601;
}
private class Encoder extends CharsetEncoder {
private DoubleByte.Encoder enc = (DoubleByte.Encoder)new EUC_KR().newEncoder();
public Encoder(Charset cs) {
super(cs, 2.0f, 2.0f);
}
public boolean canEncode(char c) {
if (c <= 0x7F) {
return false;
}
return enc.canEncode(c);
}
protected int encodeDouble(char c) {
return enc.encodeChar(c);
}
protected CoderResult encodeLoop(CharBuffer src, ByteBuffer dst) {
char[] sa = src.array();
int sp = src.arrayOffset() + src.position();
int sl = src.arrayOffset() + src.limit();
byte[] da = dst.array();
int dp = dst.arrayOffset() + dst.position();
int dl = dst.arrayOffset() + dst.limit();
try {
while (sp < sl) {
char c = sa[sp];
if (c <= '\u007f')
return CoderResult.unmappableForLength(1);
int ncode = encodeDouble(c);
if (ncode != 0 && c != '\u0000' ) {
da[dp++] = (byte) ((ncode >> 8) & 0x7f);
da[dp++] = (byte) (ncode & 0x7f);
sp++;
continue;
}
return CoderResult.unmappableForLength(1);
}
return CoderResult.UNDERFLOW;
} finally {
src.position(sp - src.arrayOffset());
dst.position(dp - dst.arrayOffset());
}
}
public boolean isLegalReplacement(byte[] repl) {
return true;
}
}
private class Decoder extends CharsetDecoder {
private DoubleByte.Decoder dec = (DoubleByte.Decoder)new EUC_KR().newDecoder();
public Decoder(Charset cs) {
super(cs, 0.5f, 1.0f);
}
protected char decodeDouble(int b1, int b2) {
return dec.decodeDouble(b1, b2);
}
protected CoderResult decodeLoop(ByteBuffer src, CharBuffer dst) {
byte[] sa = src.array();
int sp = src.arrayOffset() + src.position();
int sl = src.arrayOffset() + src.limit();
assert (sp <= sl);
sp = (sp <= sl ? sp : sl);
char[] da = dst.array();
int dp = dst.arrayOffset() + dst.position();
int dl = dst.arrayOffset() + dst.limit();
assert (dp <= dl);
dp = (dp <= dl ? dp : dl);
try {
while (sp < sl) {
if ( sl - sp < 2) {
return CoderResult.UNDERFLOW;
}
int b1 = sa[sp] & 0xFF | 0x80;
int b2 = sa[sp + 1] & 0xFF | 0x80;
char c = decodeDouble(b1, b2);
if (c == UNMAPPABLE_DECODING) {
return CoderResult.unmappableForLength(2);
}
if (dl - dp < 1)
return CoderResult.OVERFLOW;
da[dp++] = c;
sp +=2;
}
return CoderResult.UNDERFLOW;
} finally {
src.position(sp - src.arrayOffset());
dst.position(dp - dst.arrayOffset());
}
}
}
}
| mit |
rokn/Count_Words_2015 | testing/openjdk2/jdk/test/com/sun/jdi/LocationTest.java | 6545 | /*
* Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4419453
* @summary Test that Method.location() returns the right values
*
* @author Robert Field
*
* @run build TestScaffold VMConnection TargetListener TargetAdapter
* @run compile -g LocationTest.java
* @run main LocationTest
*/
import com.sun.jdi.*;
import com.sun.jdi.event.*;
import com.sun.jdi.request.*;
import java.util.*;
/********** target program **********/
abstract class AbstractLocationTarg {
abstract void foo();
}
class LocationTarg extends AbstractLocationTarg {
public static void main(String[] args){
System.out.println("Howdy!"); // don't change the following 3 lines
}
void foo() {
System.out.println("Never here!"); // must be 3 lines after "Howdy!"
}
}
/********** test program **********/
public class LocationTest extends TestScaffold {
ReferenceType targetClass;
ThreadReference mainThread;
LocationTest (String args[]) {
super(args);
}
public static void main(String[] args) throws Exception {
new LocationTest(args).startTests();
}
/********** test assist **********/
Location getLocation(String refName, String methodName) {
List refs = vm().classesByName(refName);
if (refs.size() != 1) {
failure("Test failure: " + refs.size() +
" ReferenceTypes named: " + refName);
return null;
}
ReferenceType refType = (ReferenceType)refs.get(0);
List meths = refType.methodsByName(methodName);
if (meths.size() != 1) {
failure("Test failure: " + meths.size() +
" methods named: " + methodName);
return null;
}
Method meth = (Method)meths.get(0);
return meth.location();
}
/********** test core **********/
protected void runTests() throws Exception {
Location loc;
/*
* Get to the top of main() to get everything loaded
*/
startToMain("LocationTarg");
/*
* Test the values of location()
*/
loc = getLocation("AbstractLocationTarg", "foo");
if (loc != null) {
failure("location of AbstractLocationTarg.foo() should have " +
"been null, but was: " + loc);
}
loc = getLocation("java.util.List", "clear");
if (loc != null) {
failure("location of java.util.List.clear() " +
"should have been null, but was: " + loc);
}
loc = getLocation("java.lang.Object", "getClass");
if (loc == null) {
failure("location of Object.getClass() " +
"should have been non-null, but was: " + loc);
} else {
if (!loc.declaringType().name().equals("java.lang.Object")) {
failure("location.declaringType() of Object.getClass() " +
"should have been java.lang.Object, but was: " +
loc.declaringType());
}
if (!loc.method().name().equals("getClass")) {
failure("location.method() of Object.getClass() " +
"should have been getClass, but was: " +
loc.method());
}
if (loc.codeIndex() != -1) {
failure("location.codeIndex() of Object.getClass() " +
"should have been -1, but was: " +
loc.codeIndex());
}
if (loc.lineNumber() != -1) {
failure("location.lineNumber() of Object.getClass() " +
"should have been -1, but was: " +
loc.lineNumber());
}
}
Location mainLoc = getLocation("LocationTarg", "main");
loc = getLocation("LocationTarg", "foo");
if (loc == null) {
failure("location of LocationTarg.foo() " +
"should have been non-null, but was: " + loc);
} else {
if (!loc.declaringType().name().equals("LocationTarg")) {
failure("location.declaringType() of LocationTarg.foo() " +
"should have been LocationTarg, but was: " +
loc.declaringType());
}
if (!loc.method().name().equals("foo")) {
failure("location.method() of LocationTarg.foo() " +
"should have been foo, but was: " +
loc.method());
}
if (loc.codeIndex() != 0) { // implementation dependent!!!
failure("location.codeIndex() of LocationTarg.foo() " +
"should have been 0, but was: " +
loc.codeIndex());
}
if (loc.lineNumber() != (mainLoc.lineNumber() + 3)) {
failure("location.lineNumber() of LocationTarg.foo() " +
"should have been " + (mainLoc.lineNumber() + 3) +
", but was: " + loc.lineNumber());
}
}
/*
* resume until the end
*/
listenUntilVMDisconnect();
/*
* deal with results of test
* if anything has called failure("foo") testFailed will be true
*/
if (!testFailed) {
println("LocationTest: passed");
} else {
throw new Exception("LocationTest: failed");
}
}
}
| mit |
winstonewert/elasticsearch | modules/lang-expression/src/main/java/org/elasticsearch/script/expression/CountMethodValueSource.java | 2875 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.script.expression;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.DoubleDocValues;
import org.elasticsearch.index.fielddata.AtomicNumericFieldData;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.fielddata.SortedNumericDoubleValues;
/**
* A ValueSource to create FunctionValues to get the count of the number of values in a field for a document.
*/
final class CountMethodValueSource extends ValueSource {
IndexFieldData<?> fieldData;
CountMethodValueSource(IndexFieldData<?> fieldData) {
Objects.requireNonNull(fieldData);
this.fieldData = fieldData;
}
@Override
@SuppressWarnings("rawtypes") // ValueSource uses a rawtype
public FunctionValues getValues(Map context, LeafReaderContext leaf) throws IOException {
AtomicNumericFieldData leafData = (AtomicNumericFieldData) fieldData.load(leaf);
final SortedNumericDoubleValues values = leafData.getDoubleValues();
return new DoubleDocValues(this) {
@Override
public double doubleVal(int doc) throws IOException {
if (values.advanceExact(doc)) {
return values.docValueCount();
} else {
return 0;
}
}
};
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FieldDataValueSource that = (FieldDataValueSource) o;
return fieldData.equals(that.fieldData);
}
@Override
public int hashCode() {
return 31 * getClass().hashCode() + fieldData.hashCode();
}
@Override
public String description() {
return "count: field(" + fieldData.getFieldName() + ")";
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/jdk/test/java/beans/PropertyEditor/TestShortClassJava.java | 1335 | /*
* Copyright (c) 2006, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4506596
* @summary Tests PropertyEditor for value of type Short
* @author Sergey Malenkov
*/
public class TestShortClassJava {
public static void main(String[] args) {
new TestEditor(Short.class).testJava(Short.valueOf((short) 12));
}
}
| mit |
rokn/Count_Words_2015 | testing/openjdk2/langtools/test/tools/javac/generics/diamond/neg/Neg03.java | 1700 | /*
* @test /nodynamiccopyright/
* @bug 6939620 7020044
*
* @summary Check that diamond fails when inference violates declared bounds
* (test with inner class, qualified/simple type expressions)
* @author mcimadamore
* @compile/fail/ref=Neg03.out Neg03.java -XDrawDiagnostics
*
*/
class Neg03<U> {
class Foo<V extends Number> {
Foo(V x) {}
<Z> Foo(V x, Z z) {}
}
void testSimple() {
Foo<String> f1 = new Foo<>("");
Foo<? extends String> f2 = new Foo<>("");
Foo<?> f3 = new Foo<>("");
Foo<? super String> f4 = new Foo<>("");
Foo<String> f5 = new Foo<>("", "");
Foo<? extends String> f6 = new Foo<>("", "");
Foo<?> f7 = new Foo<>("", "");
Foo<? super String> f8 = new Foo<>("", "");
}
void testQualified_1() {
Foo<String> f1 = new Neg03<U>.Foo<>("");
Foo<? extends String> f2 = new Neg03<U>.Foo<>("");
Foo<?> f3 = new Neg03<U>.Foo<>("");
Foo<? super String> f4 = new Neg03<U>.Foo<>("");
Foo<String> f5 = new Neg03<U>.Foo<>("", "");
Foo<? extends String> f6 = new Neg03<U>.Foo<>("", "");
Foo<?> f7 = new Neg03<U>.Foo<>("", "");
Foo<? super String> f8 = new Neg03<U>.Foo<>("", "");
}
void testQualified_2(Neg03<U> n) {
Foo<String> f1 = n.new Foo<>("");
Foo<? extends String> f2 = n.new Foo<>("");
Foo<?> f3 = n.new Foo<>("");
Foo<? super String> f4 = n.new Foo<>("");
Foo<String> f5 = n.new Foo<>("", "");
Foo<? extends String> f6 = n.new Foo<>("", "");
Foo<?> f7 = n.new Foo<>("", "");
Foo<? super String> f8 = n.new Foo<>("", "");
}
}
| mit |
sofvindex/BAI_ItemsKeeper | www/lib/cordova-android/test/app/src/main/java/org/apache/cordova/unittests/TestActivity.java | 2310 | /*
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.cordova.unittests;
import android.os.Bundle;
import org.apache.cordova.CordovaActivity;
import org.apache.cordova.CordovaWebView;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RunnableFuture;
/**
* The purpose of this activity is to allow the test framework to manipulate the start url, which
* is normally locked down by CordovaActivity to standard users who aren't editing their Java code.
*/
public class TestActivity extends CordovaActivity {
public final ArrayBlockingQueue<String> onPageFinishedUrl = new ArrayBlockingQueue<String>(500);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// enable Cordova apps to be started in the background
Bundle extras = getIntent().getExtras();
if (extras != null) {
if (extras.getBoolean("cdvStartInBackground", false)) {
moveTaskToBack(true);
}
launchUrl = extras.getString("startUrl", "index.html");
}
// Set by <content src="index.html" /> in config.xml
loadUrl(launchUrl);
}
@Override
public Object onMessage(String id, Object data) {
if ("onPageFinished".equals(id)) {
onPageFinishedUrl.add((String) data);
}
return super.onMessage(id, data);
}
public CordovaWebView getWebInterface() { return this.appView; }
}
| mit |
paran0ids0ul/binnavi | src/main/java/com/google/security/zynamics/reil/translators/arm/ARMSwpTranslator.java | 4614 | /*
Copyright 2015 Google Inc. 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.google.security.zynamics.reil.translators.arm;
import com.google.security.zynamics.reil.OperandSize;
import com.google.security.zynamics.reil.ReilHelpers;
import com.google.security.zynamics.reil.ReilInstruction;
import com.google.security.zynamics.reil.translators.ITranslationEnvironment;
import com.google.security.zynamics.reil.translators.InternalTranslationException;
import com.google.security.zynamics.reil.translators.TranslationHelpers;
import com.google.security.zynamics.zylib.disassembly.IInstruction;
import com.google.security.zynamics.zylib.disassembly.IOperandTreeNode;
import java.util.List;
public class ARMSwpTranslator extends ARMBaseTranslator {
@Override
protected void translateCore(final ITranslationEnvironment environment,
final IInstruction instruction, final List<ReilInstruction> instructions) {
final IOperandTreeNode registerOperand1 =
instruction.getOperands().get(0).getRootNode().getChildren().get(0);
final IOperandTreeNode registerOperand2 =
instruction.getOperands().get(1).getRootNode().getChildren().get(0);
final IOperandTreeNode registerOperand3 =
instruction.getOperands().get(2).getRootNode().getChildren().get(0).getChildren().get(0);
final String targetRegister = (registerOperand1.getValue());
final String sourceRegister1 = (registerOperand2.getValue());
final String memoryRegister2 = (registerOperand3.getValue());
final OperandSize dw = OperandSize.DWORD;
long baseOffset = (instruction.getAddress().toLong() * 0x100) + instructions.size();
final String negRotVal2 = environment.getNextVariableString();
final String rotVal1 = environment.getNextVariableString();
final String rotVal2 = environment.getNextVariableString();
final String tmpResult = environment.getNextVariableString();
final String tmpRotate1 = environment.getNextVariableString();
final String tmpRotate2 = environment.getNextVariableString();
final String tmpVal1 = environment.getNextVariableString();
// load
instructions.add(ReilHelpers.createLdm(baseOffset++, dw, memoryRegister2, dw, tmpVal1));
// rotate
instructions.add(ReilHelpers.createAnd(baseOffset++, dw, memoryRegister2, dw,
String.valueOf(0x3), dw, rotVal1));
instructions.add(ReilHelpers.createMul(baseOffset++, dw, rotVal1, dw, String.valueOf(8), dw,
rotVal2));
instructions.add(ReilHelpers.createSub(baseOffset++, dw, String.valueOf(0), dw, rotVal2, dw,
negRotVal2));
instructions.add(ReilHelpers.createBsh(baseOffset++, dw, tmpVal1, dw, negRotVal2, dw,
tmpRotate1));
instructions.add(ReilHelpers.createBsh(baseOffset++, dw, tmpVal1, dw, rotVal2, dw, tmpRotate2));
instructions.add(ReilHelpers.createOr(baseOffset++, dw, tmpRotate1, dw, tmpRotate2, dw,
tmpResult));
instructions.add(ReilHelpers.createAnd(baseOffset++, dw, tmpResult, dw,
String.valueOf(0xFFFFFFFFL), dw, targetRegister));
// store
instructions.add(ReilHelpers.createStm(baseOffset++, dw, sourceRegister1, dw, memoryRegister2));
}
/**
* SWP{<cond>} <Rd>, <Rm>, [<Rn>]
*
* Operation:
*
* MemoryAccess(B-bit, E-bit) processor_id = ExecutingProcessor() if ConditionPassed(cond) then if
* (CP15_reg1_Ubit == 0) then temp = Memory[address,4] Rotate_Right (8 * address[1:0])
* Memory[address,4] = Rm Rd = temp else // CP15_reg1_Ubit ==1 temp = Memory[address,4]
* Memory[address,4] = Rm Rd = temp if Shared(address) then // ARMv6 physical_address =
* TLB(address) ClearExclusiveByAddress(physical_address,processor_id,4) // See Summary of
* operation on page A2-49
*/
@Override
public void translate(final ITranslationEnvironment environment, final IInstruction instruction,
final List<ReilInstruction> instructions) throws InternalTranslationException {
TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, "SWP");
translateAll(environment, instruction, "SWP", instructions);
}
}
| apache-2.0 |
guiquanz/binnavi | src/main/java/com/google/security/zynamics/binnavi/Tutorials/CTutorialStep.java | 3277 | /*
Copyright 2015 Google Inc. 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.google.security.zynamics.binnavi.Tutorials;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Preconditions;
/**
* Represents a single tutorial step.
*/
public final class CTutorialStep {
/**
* Description of the step.
*/
private final String m_description;
/**
* Action identifiers that finish this tutorial step.
*/
private final List<Long> m_mandatory;
/**
* Action identifiers that are allowed but do not finish the tutorial step.
*/
private final List<Long> m_allowed;
/**
* Flag that determines whether the Next button is available for this step.
*/
private final boolean m_next;
/**
* Creates a new tutorial step object.
*
* @param description Description of the step.
* @param mandatory Action identifiers that finish this tutorial step.
* @param allowed Action identifiers that are allowed but do not finish the tutorial step.
* @param next Flag that determines whether the Next button is available for this step.
*/
public CTutorialStep(final String description, final List<Long> mandatory,
final List<Long> allowed, final boolean next) {
Preconditions.checkNotNull(description, "IE01003: Description argument can not be null");
Preconditions.checkNotNull(mandatory, "IE01004: Mandatory argument can not be null");
Preconditions.checkNotNull(allowed, "IE01005: Allowed argument can not be null");
m_description = description;
m_mandatory = new ArrayList<Long>(mandatory);
m_allowed = new ArrayList<Long>(allowed);
m_next = next;
}
/**
* Returns whether the Next button is available for this tutorial step.
*
* @return A flag that indicates whether the Next button is available.
*/
public boolean canNext() {
return m_next;
}
/**
* Returns the description of the step.
*
* @return The description of the step.
*/
public String getDescription() {
return m_description;
}
/**
* Decides whether a given action can be executed while this tutorial step is active.
*
* @param identifier An action identifier.
*
* @return True, if the given action is allowed for this tutorial step. False, if it is not.
*/
public boolean handles(final long identifier) {
return m_mandatory.contains(identifier) || m_allowed.contains(identifier);
}
/**
* Decides whether a given action finishes this tutorial step.
*
* @param identifier An action identifier.
*
* @return True, if the given action finishes this tutorial step. False, if it does not.
*/
public boolean mandates(final long identifier) {
return m_mandatory.contains(identifier);
}
}
| apache-2.0 |
crowell/binnavi | src/main/java/com/google/security/zynamics/binnavi/Gui/Debug/EventLists/Implementations/CTraceNodeFinder.java | 3969 | /*
Copyright 2015 Google Inc. 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.google.security.zynamics.binnavi.Gui.Debug.EventLists.Implementations;
import com.google.security.zynamics.binnavi.Exceptions.MaybeNullException;
import com.google.security.zynamics.binnavi.debug.models.breakpoints.BreakpointAddress;
import com.google.security.zynamics.binnavi.debug.models.trace.TraceList;
import com.google.security.zynamics.binnavi.debug.models.trace.interfaces.ITraceEvent;
import com.google.security.zynamics.binnavi.disassembly.CCodeNodeHelpers;
import com.google.security.zynamics.binnavi.disassembly.INaviCodeNode;
import com.google.security.zynamics.binnavi.disassembly.INaviFunctionNode;
import com.google.security.zynamics.binnavi.yfileswrap.zygraph.NaviNode;
import com.google.security.zynamics.binnavi.yfileswrap.zygraph.ZyGraph;
import com.google.security.zynamics.zylib.gui.zygraph.helpers.GraphHelpers;
import com.google.security.zynamics.zylib.types.common.ICollectionFilter;
import java.util.List;
/**
* Contains code for finding the nodes of a graph that were hit by a trace.
*/
public final class CTraceNodeFinder {
/**
* You are not supposed to instantiate this class.
*/
private CTraceNodeFinder() {
}
/**
* Checks whether a code node was hit by a trace.
*
* @param node The node to check.
* @param eventList Provides the events of the trace.
*
* @return True, if the node was hit by the trace. False, otherwise.
*/
private static boolean isEventNode(final INaviCodeNode node, final TraceList eventList) {
for (final ITraceEvent traceEvent : eventList) {
final BreakpointAddress eventAddress = traceEvent.getOffset();
try {
if (node.getParentFunction().getModule() == eventAddress.getModule()
&& CCodeNodeHelpers.containsAddress(node, eventAddress.getAddress().getAddress())) {
return true;
}
} catch (final MaybeNullException e) {
}
}
return false;
}
/**
* Checks whether a function node was hit by a trace.
*
* @param node The node to check.
* @param eventList Provides the events of the trace.
*
* @return True, if the node was hit by the trace. False, otherwise.
*/
private static boolean isEventNode(final INaviFunctionNode node, final TraceList eventList) {
for (final ITraceEvent traceEvent : eventList) {
if (traceEvent.getOffset().getModule() == node.getFunction().getModule() && node.getFunction()
.getAddress().equals(traceEvent.getOffset().getAddress().getAddress())) {
return true;
}
}
return false;
}
/**
* Returns the nodes of a graph that were hit by the events in a given trace list.
*
* @param graph The graph whose nodes are returned.
* @param eventList Provides the events to search for.
*
* @return The nodes of the graph that were hit by the events in the list.
*/
public static List<NaviNode> getTraceNodes(final ZyGraph graph, final TraceList eventList) {
return GraphHelpers.filter(graph, new ICollectionFilter<NaviNode>() {
@Override
public boolean qualifies(final NaviNode item) {
return item.getRawNode() instanceof INaviCodeNode && isEventNode(
(INaviCodeNode) item.getRawNode(), eventList)
|| item.getRawNode() instanceof INaviFunctionNode
&& isEventNode((INaviFunctionNode) item.getRawNode(), eventList);
}
});
}
}
| apache-2.0 |
clumsy/intellij-community | plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/dateOrRevision/SimpleRevision.java | 1757 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.cvsSupport2.cvsoperations.dateOrRevision;
import com.intellij.cvsSupport2.history.CvsRevisionNumber;
import com.intellij.openapi.util.text.StringUtil;
import org.netbeans.lib.cvsclient.command.Command;
/**
* author: lesya
*/
public class SimpleRevision implements RevisionOrDate {
private final String myRevision;
public SimpleRevision(String revision) {
myRevision = prepareRevision(revision);
}
private static String prepareRevision(String revision) {
if (revision == null) {
return null;
}
else if (StringUtil.startsWithChar(revision, '-')) {
return revision.substring(1);
}
else {
return revision;
}
}
public String getRevision() {
return myRevision;
}
public void setForCommand(Command command) {
command.setUpdateByRevisionOrDate(myRevision, null);
}
public CvsRevisionNumber getCvsRevisionNumber() {
if (myRevision == null) return null;
try {
return new CvsRevisionNumber(myRevision);
}
catch (NumberFormatException ex) {
return null;
}
}
@Override
public String toString() {
return myRevision;
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/langtools/src/share/classes/com/sun/tools/classfile/CompilationID_attribute.java | 2479 | /*
* Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.classfile;
import java.io.IOException;
/**
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class CompilationID_attribute extends Attribute {
CompilationID_attribute(ClassReader cr, int name_index, int length) throws IOException {
super(name_index, length);
compilationID_index = cr.readUnsignedShort();
}
public CompilationID_attribute(ConstantPool constant_pool, int compilationID_index)
throws ConstantPoolException {
this(constant_pool.getUTF8Index(Attribute.CompilationID), compilationID_index);
}
public CompilationID_attribute(int name_index, int compilationID_index) {
super(name_index, 2);
this.compilationID_index = compilationID_index;
}
String getCompilationID(ConstantPool constant_pool)
throws ConstantPoolException {
return constant_pool.getUTF8Value(compilationID_index);
}
public <R, D> R accept(Visitor<R, D> visitor, D data) {
return visitor.visitCompilationID(this, data);
}
public final int compilationID_index;
}
| mit |
dgrif/binnavi | src/test/java/com/google/security/zynamics/reil/translators/ppc/AddmeTranslatorTest.java | 9554 | /*
Copyright 2014 Google Inc. 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.google.security.zynamics.reil.translators.ppc;
import static org.junit.Assert.assertEquals;
import com.google.common.collect.Lists;
import com.google.security.zynamics.reil.OperandSize;
import com.google.security.zynamics.reil.ReilInstruction;
import com.google.security.zynamics.reil.TestHelpers;
import com.google.security.zynamics.reil.interpreter.CpuPolicyPPC;
import com.google.security.zynamics.reil.interpreter.EmptyInterpreterPolicy;
import com.google.security.zynamics.reil.interpreter.Endianness;
import com.google.security.zynamics.reil.interpreter.InterpreterException;
import com.google.security.zynamics.reil.interpreter.ReilInterpreter;
import com.google.security.zynamics.reil.interpreter.ReilRegisterStatus;
import com.google.security.zynamics.reil.translators.InternalTranslationException;
import com.google.security.zynamics.reil.translators.StandardEnvironment;
import com.google.security.zynamics.reil.translators.ppc.AddmeTranslator;
import com.google.security.zynamics.zylib.disassembly.ExpressionType;
import com.google.security.zynamics.zylib.disassembly.IInstruction;
import com.google.security.zynamics.zylib.disassembly.MockInstruction;
import com.google.security.zynamics.zylib.disassembly.MockOperandTree;
import com.google.security.zynamics.zylib.disassembly.MockOperandTreeNode;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
@RunWith(JUnit4.class)
public class AddmeTranslatorTest {
private final ReilInterpreter interpreter = new ReilInterpreter(Endianness.BIG_ENDIAN,
new CpuPolicyPPC(), new EmptyInterpreterPolicy());
private final StandardEnvironment environment = new StandardEnvironment();
private final AddmeTranslator translator = new AddmeTranslator();
private final ArrayList<ReilInstruction> instructions = new ArrayList<ReilInstruction>();
@Before
public void setUp() {
interpreter.setRegister("XEROV", BigInteger.ZERO, OperandSize.WORD, ReilRegisterStatus.DEFINED);
interpreter.setRegister("XERSO", BigInteger.ZERO, OperandSize.WORD, ReilRegisterStatus.DEFINED);
interpreter.setRegister("CR0EQ", BigInteger.ZERO, OperandSize.WORD, ReilRegisterStatus.DEFINED);
interpreter.setRegister("CR0LT", BigInteger.ZERO, OperandSize.WORD, ReilRegisterStatus.DEFINED);
interpreter.setRegister("CR0SO", BigInteger.ZERO, OperandSize.WORD, ReilRegisterStatus.DEFINED);
interpreter.setRegister("CR0GT", BigInteger.ZERO, OperandSize.WORD, ReilRegisterStatus.DEFINED);
}
@Test
public void testCarryCleared() throws InternalTranslationException, InterpreterException {
interpreter.setRegister("%r0", BigInteger.ZERO, OperandSize.BYTE, ReilRegisterStatus.DEFINED);
interpreter.setRegister("%r1", BigInteger.valueOf(0x4000), OperandSize.DWORD,
ReilRegisterStatus.DEFINED);
interpreter.setRegister("XERCA", BigInteger.ZERO, OperandSize.WORD, ReilRegisterStatus.DEFINED);
final MockOperandTree operandTree1 = new MockOperandTree();
operandTree1.root = new MockOperandTreeNode(ExpressionType.SIZE_PREFIX, "dword");
operandTree1.root.m_children.add(new MockOperandTreeNode(ExpressionType.REGISTER, "%r0"));
final MockOperandTree operandTree2 = new MockOperandTree();
operandTree2.root = new MockOperandTreeNode(ExpressionType.SIZE_PREFIX, "dword");
operandTree2.root.m_children.add(new MockOperandTreeNode(ExpressionType.REGISTER, "%r1"));
final List<MockOperandTree> operands = Lists.newArrayList(operandTree1, operandTree2);
final IInstruction instruction = new MockInstruction("addme", operands);
translator.translate(environment, instruction, instructions);
interpreter.interpret(TestHelpers.createMapping(instructions), BigInteger.valueOf(0x100));
assertEquals(BigInteger.valueOf(0x3FFF), interpreter.getVariableValue("%r0"));
assertEquals(BigInteger.valueOf(0x4000), interpreter.getVariableValue("%r1"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("XEROV"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("XERSO"));
assertEquals(BigInteger.ONE, interpreter.getVariableValue("XERCA"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("CR0EQ"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("CR0LT"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("CR0SO"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("CR0GT"));
assertEquals(BigInteger.ZERO, BigInteger.valueOf(interpreter.getMemorySize()));
assertEquals(10, TestHelpers.filterNativeRegisters(interpreter.getDefinedRegisters()).size());
}
@Test
public void testCarrySet() throws InternalTranslationException, InterpreterException {
interpreter.setRegister("%r0", BigInteger.ZERO, OperandSize.BYTE, ReilRegisterStatus.DEFINED);
interpreter.setRegister("%r1", BigInteger.valueOf(0x4000), OperandSize.DWORD,
ReilRegisterStatus.DEFINED);
interpreter.setRegister("XERCA", BigInteger.ZERO, OperandSize.WORD, ReilRegisterStatus.DEFINED);
final MockOperandTree operandTree1 = new MockOperandTree();
operandTree1.root = new MockOperandTreeNode(ExpressionType.SIZE_PREFIX, "dword");
operandTree1.root.m_children.add(new MockOperandTreeNode(ExpressionType.REGISTER, "%r0"));
final MockOperandTree operandTree2 = new MockOperandTree();
operandTree2.root = new MockOperandTreeNode(ExpressionType.SIZE_PREFIX, "dword");
operandTree2.root.m_children.add(new MockOperandTreeNode(ExpressionType.REGISTER, "%r1"));
final List<MockOperandTree> operands = Lists.newArrayList(operandTree1, operandTree2);
final IInstruction instruction = new MockInstruction("addme", operands);
translator.translate(environment, instruction, instructions);
interpreter.interpret(TestHelpers.createMapping(instructions), BigInteger.valueOf(0x100));
assertEquals(BigInteger.valueOf(0x3FFF), interpreter.getVariableValue("%r0"));
assertEquals(BigInteger.valueOf(0x4000), interpreter.getVariableValue("%r1"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("XEROV"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("XERSO"));
assertEquals(BigInteger.ONE, interpreter.getVariableValue("XERCA"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("CR0EQ"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("CR0LT"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("CR0SO"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("CR0GT"));
assertEquals(BigInteger.ZERO, BigInteger.valueOf(interpreter.getMemorySize()));
assertEquals(10, TestHelpers.filterNativeRegisters(interpreter.getDefinedRegisters()).size());
}
@Test
public void testUnderflow() throws InternalTranslationException, InterpreterException {
interpreter.setRegister("%r0", BigInteger.ZERO, OperandSize.BYTE, ReilRegisterStatus.DEFINED);
interpreter.setRegister("%r1", BigInteger.valueOf(0x80000000L), OperandSize.DWORD,
ReilRegisterStatus.DEFINED);
interpreter.setRegister("XERCA", BigInteger.ZERO, OperandSize.WORD, ReilRegisterStatus.DEFINED);
final MockOperandTree operandTree1 = new MockOperandTree();
operandTree1.root = new MockOperandTreeNode(ExpressionType.SIZE_PREFIX, "dword");
operandTree1.root.m_children.add(new MockOperandTreeNode(ExpressionType.REGISTER, "%r0"));
final MockOperandTree operandTree2 = new MockOperandTree();
operandTree2.root = new MockOperandTreeNode(ExpressionType.SIZE_PREFIX, "dword");
operandTree2.root.m_children.add(new MockOperandTreeNode(ExpressionType.REGISTER, "%r1"));
final List<MockOperandTree> operands = Lists.newArrayList(operandTree1, operandTree2);
final IInstruction instruction = new MockInstruction("addme", operands);
translator.translate(environment, instruction, instructions);
interpreter.interpret(TestHelpers.createMapping(instructions), BigInteger.valueOf(0x100));
assertEquals(BigInteger.valueOf(0x7FFFFFFF), interpreter.getVariableValue("%r0"));
assertEquals(BigInteger.valueOf(0x80000000L), interpreter.getVariableValue("%r1"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("XEROV"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("XERSO"));
assertEquals(BigInteger.ONE, interpreter.getVariableValue("XERCA"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("CR0EQ"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("CR0LT"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("CR0SO"));
assertEquals(BigInteger.ZERO, interpreter.getVariableValue("CR0GT"));
assertEquals(BigInteger.ZERO, BigInteger.valueOf(interpreter.getMemorySize()));
assertEquals(10, TestHelpers.filterNativeRegisters(interpreter.getDefinedRegisters()).size());
}
}
| apache-2.0 |
Flipkart/elasticsearch | src/main/java/org/elasticsearch/index/query/DisMaxQueryParser.java | 4322 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index.query;
import org.apache.lucene.search.DisjunctionMaxQuery;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
/**
*
*/
public class DisMaxQueryParser implements QueryParser {
public static final String NAME = "dis_max";
@Inject
public DisMaxQueryParser() {
}
@Override
public String[] names() {
return new String[]{NAME, Strings.toCamelCase(NAME)};
}
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
XContentParser parser = parseContext.parser();
float boost = 1.0f;
float tieBreaker = 0.0f;
List<Query> queries = newArrayList();
boolean queriesFound = false;
String queryName = null;
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if ("queries".equals(currentFieldName)) {
queriesFound = true;
Query query = parseContext.parseInnerQuery();
if (query != null) {
queries.add(query);
}
} else {
throw new QueryParsingException(parseContext, "[dis_max] query does not support [" + currentFieldName + "]");
}
} else if (token == XContentParser.Token.START_ARRAY) {
if ("queries".equals(currentFieldName)) {
queriesFound = true;
while (token != XContentParser.Token.END_ARRAY) {
Query query = parseContext.parseInnerQuery();
if (query != null) {
queries.add(query);
}
token = parser.nextToken();
}
} else {
throw new QueryParsingException(parseContext, "[dis_max] query does not support [" + currentFieldName + "]");
}
} else {
if ("boost".equals(currentFieldName)) {
boost = parser.floatValue();
} else if ("tie_breaker".equals(currentFieldName) || "tieBreaker".equals(currentFieldName)) {
tieBreaker = parser.floatValue();
} else if ("_name".equals(currentFieldName)) {
queryName = parser.text();
} else {
throw new QueryParsingException(parseContext, "[dis_max] query does not support [" + currentFieldName + "]");
}
}
}
if (!queriesFound) {
throw new QueryParsingException(parseContext, "[dis_max] requires 'queries' field");
}
if (queries.isEmpty()) {
return null;
}
DisjunctionMaxQuery query = new DisjunctionMaxQuery(queries, tieBreaker);
query.setBoost(boost);
if (queryName != null) {
parseContext.addNamedQuery(queryName, query);
}
return query;
}
} | apache-2.0 |
Greblys/openhab | bundles/binding/org.openhab.binding.pulseaudio/src/main/java/org/openhab/binding/pulseaudio/internal/items/SourceOutput.java | 830 | /**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.pulseaudio.internal.items;
/**
* A SourceOutput is the audio stream which is produced by a (@link Source}
*
* @author Tobias Bräutigam
* @since 1.2.0
*/
public class SourceOutput extends AbstractAudioDeviceConfig {
private Source source;
public SourceOutput(int id, String name, Module module) {
super(id, name, module);
}
public Source getSource() {
return source;
}
public void setSource(Source source) {
this.source = source;
}
}
| epl-1.0 |
caot/intellij-community | java/java-tests/testData/codeInsight/generateSuperMethodCall/beforeOverride.java | 124 | class s implements Runnable {
public void run() {
}
}
class Over extends s {
public void run() {<caret>
}
} | apache-2.0 |
kayelau/spring-boot | spring-boot-devtools/src/test/java/org/springframework/boot/devtools/RemoteUrlPropertyExtractorTests.java | 2821 | /*
* Copyright 2012-2015 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.boot.devtools;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import ch.qos.logback.classic.Logger;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
/**
* Tests for {@link RemoteUrlPropertyExtractor}.
*
* @author Phillip Webb
*/
public class RemoteUrlPropertyExtractorTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@After
public void preventRunFailuresFromPollutingLoggerContext() {
((Logger) LoggerFactory.getLogger(RemoteUrlPropertyExtractorTests.class))
.getLoggerContext().getTurboFilterList().clear();
}
@Test
public void missingUrl() throws Exception {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("No remote URL specified");
doTest();
}
@Test
public void malformedUrl() throws Exception {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Malformed URL '::://wibble'");
doTest("::://wibble");
}
@Test
public void multipleUrls() throws Exception {
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Multiple URLs specified");
doTest("http://localhost:8080", "http://localhost:9090");
}
@Test
public void validUrl() throws Exception {
ApplicationContext context = doTest("http://localhost:8080");
assertThat(context.getEnvironment().getProperty("remoteUrl"),
equalTo("http://localhost:8080"));
assertThat(context.getEnvironment().getProperty("spring.thymeleaf.cache"),
is(nullValue()));
}
private ApplicationContext doTest(String... args) {
SpringApplication application = new SpringApplication(Config.class);
application.setWebEnvironment(false);
application.addListeners(new RemoteUrlPropertyExtractor());
return application.run(args);
}
@Configuration
static class Config {
}
}
| apache-2.0 |
rhoybeen/floodlightLB | lib/gen-java/org/sdnplatform/sync/thrift/ClockEntry.java | 14858 | /**
* Autogenerated by Thrift Compiler (0.9.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.sdnplatform.sync.thrift;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("all") public class ClockEntry implements org.apache.thrift.TBase<ClockEntry, ClockEntry._Fields>, java.io.Serializable, Cloneable {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ClockEntry");
private static final org.apache.thrift.protocol.TField NODE_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("nodeId", org.apache.thrift.protocol.TType.I16, (short)1);
private static final org.apache.thrift.protocol.TField VERSION_FIELD_DESC = new org.apache.thrift.protocol.TField("version", org.apache.thrift.protocol.TType.I64, (short)2);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new ClockEntryStandardSchemeFactory());
schemes.put(TupleScheme.class, new ClockEntryTupleSchemeFactory());
}
public short nodeId; // required
public long version; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
NODE_ID((short)1, "nodeId"),
VERSION((short)2, "version");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // NODE_ID
return NODE_ID;
case 2: // VERSION
return VERSION;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __NODEID_ISSET_ID = 0;
private static final int __VERSION_ISSET_ID = 1;
private byte __isset_bitfield = 0;
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.NODE_ID, new org.apache.thrift.meta_data.FieldMetaData("nodeId", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16)));
tmpMap.put(_Fields.VERSION, new org.apache.thrift.meta_data.FieldMetaData("version", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ClockEntry.class, metaDataMap);
}
public ClockEntry() {
}
public ClockEntry(
short nodeId,
long version)
{
this();
this.nodeId = nodeId;
setNodeIdIsSet(true);
this.version = version;
setVersionIsSet(true);
}
/**
* Performs a deep copy on <i>other</i>.
*/
public ClockEntry(ClockEntry other) {
__isset_bitfield = other.__isset_bitfield;
this.nodeId = other.nodeId;
this.version = other.version;
}
public ClockEntry deepCopy() {
return new ClockEntry(this);
}
@Override
public void clear() {
setNodeIdIsSet(false);
this.nodeId = 0;
setVersionIsSet(false);
this.version = 0;
}
public short getNodeId() {
return this.nodeId;
}
public ClockEntry setNodeId(short nodeId) {
this.nodeId = nodeId;
setNodeIdIsSet(true);
return this;
}
public void unsetNodeId() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __NODEID_ISSET_ID);
}
/** Returns true if field nodeId is set (has been assigned a value) and false otherwise */
public boolean isSetNodeId() {
return EncodingUtils.testBit(__isset_bitfield, __NODEID_ISSET_ID);
}
public void setNodeIdIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __NODEID_ISSET_ID, value);
}
public long getVersion() {
return this.version;
}
public ClockEntry setVersion(long version) {
this.version = version;
setVersionIsSet(true);
return this;
}
public void unsetVersion() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __VERSION_ISSET_ID);
}
/** Returns true if field version is set (has been assigned a value) and false otherwise */
public boolean isSetVersion() {
return EncodingUtils.testBit(__isset_bitfield, __VERSION_ISSET_ID);
}
public void setVersionIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __VERSION_ISSET_ID, value);
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case NODE_ID:
if (value == null) {
unsetNodeId();
} else {
setNodeId((Short)value);
}
break;
case VERSION:
if (value == null) {
unsetVersion();
} else {
setVersion((Long)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case NODE_ID:
return Short.valueOf(getNodeId());
case VERSION:
return Long.valueOf(getVersion());
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case NODE_ID:
return isSetNodeId();
case VERSION:
return isSetVersion();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof ClockEntry)
return this.equals((ClockEntry)that);
return false;
}
public boolean equals(ClockEntry that) {
if (that == null)
return false;
boolean this_present_nodeId = true;
boolean that_present_nodeId = true;
if (this_present_nodeId || that_present_nodeId) {
if (!(this_present_nodeId && that_present_nodeId))
return false;
if (this.nodeId != that.nodeId)
return false;
}
boolean this_present_version = true;
boolean that_present_version = true;
if (this_present_version || that_present_version) {
if (!(this_present_version && that_present_version))
return false;
if (this.version != that.version)
return false;
}
return true;
}
@Override
public int hashCode() {
return 0;
}
public int compareTo(ClockEntry other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
ClockEntry typedOther = (ClockEntry)other;
lastComparison = Boolean.valueOf(isSetNodeId()).compareTo(typedOther.isSetNodeId());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetNodeId()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.nodeId, typedOther.nodeId);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetVersion()).compareTo(typedOther.isSetVersion());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetVersion()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.version, typedOther.version);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("ClockEntry(");
boolean first = true;
sb.append("nodeId:");
sb.append(this.nodeId);
first = false;
if (!first) sb.append(", ");
sb.append("version:");
sb.append(this.version);
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// alas, we cannot check 'nodeId' because it's a primitive and you chose the non-beans generator.
// alas, we cannot check 'version' because it's a primitive and you chose the non-beans generator.
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class ClockEntryStandardSchemeFactory implements SchemeFactory {
public ClockEntryStandardScheme getScheme() {
return new ClockEntryStandardScheme();
}
}
private static class ClockEntryStandardScheme extends StandardScheme<ClockEntry> {
public void read(org.apache.thrift.protocol.TProtocol iprot, ClockEntry struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // NODE_ID
if (schemeField.type == org.apache.thrift.protocol.TType.I16) {
struct.nodeId = iprot.readI16();
struct.setNodeIdIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // VERSION
if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
struct.version = iprot.readI64();
struct.setVersionIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
if (!struct.isSetNodeId()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'nodeId' was not found in serialized data! Struct: " + toString());
}
if (!struct.isSetVersion()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'version' was not found in serialized data! Struct: " + toString());
}
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, ClockEntry struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldBegin(NODE_ID_FIELD_DESC);
oprot.writeI16(struct.nodeId);
oprot.writeFieldEnd();
oprot.writeFieldBegin(VERSION_FIELD_DESC);
oprot.writeI64(struct.version);
oprot.writeFieldEnd();
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class ClockEntryTupleSchemeFactory implements SchemeFactory {
public ClockEntryTupleScheme getScheme() {
return new ClockEntryTupleScheme();
}
}
private static class ClockEntryTupleScheme extends TupleScheme<ClockEntry> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, ClockEntry struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
oprot.writeI16(struct.nodeId);
oprot.writeI64(struct.version);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, ClockEntry struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
struct.nodeId = iprot.readI16();
struct.setNodeIdIsSet(true);
struct.version = iprot.readI64();
struct.setVersionIsSet(true);
}
}
}
| apache-2.0 |
YMartsynkevych/camel | components/camel-spring/src/test/java/org/apache/camel/spring/management/SpringJmxRecipientListRegisterAlwaysTest.java | 3365 | /**
* 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.camel.spring.management;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.spring.SpringTestSupport;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @version
*/
public class SpringJmxRecipientListRegisterAlwaysTest extends SpringTestSupport {
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/spring/management/SpringJmxRecipientListTestRegisterAlways.xml");
}
protected MBeanServer getMBeanServer() {
return context.getManagementStrategy().getManagementAgent().getMBeanServer();
}
public void testJmxEndpointsAddedDynamicallyAlwaysRegister() throws Exception {
MockEndpoint x = getMockEndpoint("mock:x");
MockEndpoint y = getMockEndpoint("mock:y");
MockEndpoint z = getMockEndpoint("mock:z");
x.expectedBodiesReceived("answer");
y.expectedBodiesReceived("answer");
z.expectedBodiesReceived("answer");
template.sendBodyAndHeader("direct:a", "answer", "recipientListHeader", "mock:x,mock:y,mock:z");
assertMockEndpointsSatisfied();
MBeanServer mbeanServer = getMBeanServer();
// this endpoint is part of the route and should be registered
ObjectName name = ObjectName.getInstance("org.apache.camel:context=camel-1,type=endpoints,name=\"direct://a\"");
assertTrue("Should be registered", mbeanServer.isRegistered(name));
// endpoints added after routes has been started is now also registered
name = ObjectName.getInstance("org.apache.camel:context=camel-1,type=endpoints,name=\"mock://x\"");
assertTrue("Should be registered", mbeanServer.isRegistered(name));
name = ObjectName.getInstance("org.apache.camel:context=camel-1,type=endpoints,name=\"mock://y\"");
assertTrue("Should be registered", mbeanServer.isRegistered(name));
name = ObjectName.getInstance("org.apache.camel:context=camel-1,type=endpoints,name=\"mock://z\"");
assertTrue("Should be registered", mbeanServer.isRegistered(name));
// however components is always registered
name = ObjectName.getInstance("org.apache.camel:context=camel-1,type=components,name=\"mock\"");
assertTrue("Should be registered", mbeanServer.isRegistered(name));
}
}
| apache-2.0 |
rokn/Count_Words_2015 | testing/openjdk2/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/proc/SharedObject.java | 1670 | /*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
package sun.jvm.hotspot.debugger.proc;
import sun.jvm.hotspot.debugger.*;
import sun.jvm.hotspot.debugger.cdbg.*;
import sun.jvm.hotspot.debugger.posix.*;
/** A Object can represent either a .so or an a.out file. */
class SharedObject extends DSO {
SharedObject(ProcDebugger dbg, String filename, long size, Address relocation) {
super(filename, size, relocation);
this.dbg = dbg;
}
protected Address newAddress(long address) {
return dbg.newAddress(address);
}
protected long getAddressValue(Address addr) {
return dbg.getAddressValue(addr);
}
private ProcDebugger dbg;
}
| mit |
liuyangning/WX_web | xampp/tomcat/webapps/examples/WEB-INF/classes/jsp2/examples/FooBean.java | 1053 | /*
* 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 jsp2.examples;
public class FooBean {
private String bar;
public FooBean() {
bar = "Initial value";
}
public String getBar() {
return this.bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
| mit |
Beabel2/jeesite | src/main/java/com/thinkgem/jeesite/modules/sys/web/AreaController.java | 4525 | /**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.sys.web;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.Area;
import com.thinkgem.jeesite.modules.sys.service.AreaService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
/**
* 区域Controller
* @author ThinkGem
* @version 2013-5-15
*/
@Controller
@RequestMapping(value = "${adminPath}/sys/area")
public class AreaController extends BaseController {
@Autowired
private AreaService areaService;
@ModelAttribute("area")
public Area get(@RequestParam(required=false) String id) {
if (StringUtils.isNotBlank(id)){
return areaService.get(id);
}else{
return new Area();
}
}
@RequiresPermissions("sys:area:view")
@RequestMapping(value = {"list", ""})
public String list(Area area, Model model) {
model.addAttribute("list", areaService.findAll());
return "modules/sys/areaList";
}
@RequiresPermissions("sys:area:view")
@RequestMapping(value = "form")
public String form(Area area, Model model) {
if (area.getParent()==null||area.getParent().getId()==null){
area.setParent(UserUtils.getUser().getOffice().getArea());
}
area.setParent(areaService.get(area.getParent().getId()));
// // 自动获取排序号
// if (StringUtils.isBlank(area.getId())){
// int size = 0;
// List<Area> list = areaService.findAll();
// for (int i=0; i<list.size(); i++){
// Area e = list.get(i);
// if (e.getParent()!=null && e.getParent().getId()!=null
// && e.getParent().getId().equals(area.getParent().getId())){
// size++;
// }
// }
// area.setCode(area.getParent().getCode() + StringUtils.leftPad(String.valueOf(size > 0 ? size : 1), 4, "0"));
// }
model.addAttribute("area", area);
return "modules/sys/areaForm";
}
@RequiresPermissions("sys:area:edit")
@RequestMapping(value = "save")
public String save(Area area, Model model, RedirectAttributes redirectAttributes) {
if(Global.isDemoMode()){
addMessage(redirectAttributes, "演示模式,不允许操作!");
return "redirect:" + adminPath + "/sys/area";
}
if (!beanValidator(model, area)){
return form(area, model);
}
areaService.save(area);
addMessage(redirectAttributes, "保存区域'" + area.getName() + "'成功");
return "redirect:" + adminPath + "/sys/area/";
}
@RequiresPermissions("sys:area:edit")
@RequestMapping(value = "delete")
public String delete(Area area, RedirectAttributes redirectAttributes) {
if(Global.isDemoMode()){
addMessage(redirectAttributes, "演示模式,不允许操作!");
return "redirect:" + adminPath + "/sys/area";
}
// if (Area.isRoot(id)){
// addMessage(redirectAttributes, "删除区域失败, 不允许删除顶级区域或编号为空");
// }else{
areaService.delete(area);
addMessage(redirectAttributes, "删除区域成功");
// }
return "redirect:" + adminPath + "/sys/area/";
}
@RequiresPermissions("user")
@ResponseBody
@RequestMapping(value = "treeData")
public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, HttpServletResponse response) {
List<Map<String, Object>> mapList = Lists.newArrayList();
List<Area> list = areaService.findAll();
for (int i=0; i<list.size(); i++){
Area e = list.get(i);
if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
Map<String, Object> map = Maps.newHashMap();
map.put("id", e.getId());
map.put("pId", e.getParentId());
map.put("name", e.getName());
mapList.add(map);
}
}
return mapList;
}
}
| apache-2.0 |
joakibj/camel | camel-core/src/test/java/org/apache/camel/management/AddEventNotifierTest.java | 3253 | /**
* 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.camel.management;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.spi.EventNotifier;
import org.apache.camel.support.EventNotifierSupport;
/**
* @version
*/
public class AddEventNotifierTest extends ContextTestSupport {
private static List<EventObject> events = new ArrayList<EventObject>();
private EventNotifier notifier;
@Override
public void setUp() throws Exception {
events.clear();
super.setUp();
}
public void testAddAndRemove() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
assertEquals(0, events.size());
// we should be able to add after CamelContext has been started
notifier = new EventNotifierSupport() {
public void notify(EventObject event) throws Exception {
events.add(event);
}
public boolean isEnabled(EventObject event) {
return true;
}
@Override
protected void doStart() throws Exception {
}
@Override
protected void doStop() throws Exception {
}
};
// must add notifier as a service so its started
context.addService(notifier);
context.getManagementStrategy().addEventNotifier(notifier);
resetMocks();
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:start", "Bye World");
assertMockEndpointsSatisfied();
assertEquals(8, events.size());
// remove and we should not get new events
context.getManagementStrategy().removeEventNotifier(notifier);
resetMocks();
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:start", "Hi World");
assertMockEndpointsSatisfied();
assertEquals(8, events.size());
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start").to("log:foo").to("mock:result");
}
};
}
}
| apache-2.0 |
RohanHart/camel | components/camel-jetty9/src/test/java/org/apache/camel/component/jetty/jettyproducer/JettyHttpProducerSynchronousTest.java | 2723 | /**
* 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.camel.component.jetty.jettyproducer;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jetty.BaseJettyTest;
import org.junit.Test;
/**
* @version
*/
public class JettyHttpProducerSynchronousTest extends BaseJettyTest {
private static String beforeThreadName;
private static String afterThreadName;
private String url = "jetty://http://127.0.0.1:" + getPort() + "/sync?synchronous=true";
@Test
public void testSynchronous() throws Exception {
// give Jetty time to startup properly
Thread.sleep(1000);
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:start", null);
assertMockEndpointsSatisfied();
assertTrue("Should use same threads", beforeThreadName.equalsIgnoreCase(afterThreadName));
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.to("log:before")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
beforeThreadName = Thread.currentThread().getName();
}
})
.to(url)
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
afterThreadName = Thread.currentThread().getName();
}
})
.to("log:after")
.to("mock:result");
from(url).transform(constant("Bye World"));
}
};
}
} | apache-2.0 |
RainPlanter/spring-boot | spring-boot/src/main/java/org/springframework/boot/jta/atomikos/AtomikosXAConnectionFactoryWrapper.java | 1328 | /*
* Copyright 2012-2014 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.boot.jta.atomikos;
import javax.jms.ConnectionFactory;
import javax.jms.XAConnectionFactory;
import org.springframework.boot.jta.XAConnectionFactoryWrapper;
/**
* {@link XAConnectionFactoryWrapper} that uses an {@link AtomikosConnectionFactoryBean}
* to wrap a {@link XAConnectionFactory}.
*
* @author Phillip Webb
* @since 1.2.0
*/
public class AtomikosXAConnectionFactoryWrapper implements XAConnectionFactoryWrapper {
@Override
public ConnectionFactory wrapConnectionFactory(XAConnectionFactory connectionFactory) {
AtomikosConnectionFactoryBean bean = new AtomikosConnectionFactoryBean();
bean.setXaConnectionFactory(connectionFactory);
return bean;
}
}
| apache-2.0 |
wuqiangxjtu/dubbo-practise | dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboInvoker.java | 5984 | /*
* Copyright 1999-2011 Alibaba Group.
*
* 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.alibaba.dubbo.rpc.protocol.dubbo;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.utils.AtomicPositiveInteger;
import com.alibaba.dubbo.remoting.RemotingException;
import com.alibaba.dubbo.remoting.TimeoutException;
import com.alibaba.dubbo.remoting.exchange.ExchangeClient;
import com.alibaba.dubbo.remoting.exchange.ResponseFuture;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.RpcInvocation;
import com.alibaba.dubbo.rpc.RpcResult;
import com.alibaba.dubbo.rpc.protocol.AbstractInvoker;
import com.alibaba.dubbo.rpc.support.RpcUtils;
/**
* DubboInvoker
*
* @author william.liangf
* @author chao.liuc
*/
public class DubboInvoker<T> extends AbstractInvoker<T> {
private final ExchangeClient[] clients;
private final AtomicPositiveInteger index = new AtomicPositiveInteger();
private final String version;
private final ReentrantLock destroyLock = new ReentrantLock();
private final Set<Invoker<?>> invokers;
public DubboInvoker(Class<T> serviceType, URL url, ExchangeClient[] clients){
this(serviceType, url, clients, null);
}
public DubboInvoker(Class<T> serviceType, URL url, ExchangeClient[] clients, Set<Invoker<?>> invokers){
super(serviceType, url, new String[] {Constants.INTERFACE_KEY, Constants.GROUP_KEY, Constants.TOKEN_KEY, Constants.TIMEOUT_KEY});
this.clients = clients;
// get version.
this.version = url.getParameter(Constants.VERSION_KEY, "0.0.0");
this.invokers = invokers;
}
@Override
protected Result doInvoke(final Invocation invocation) throws Throwable {
RpcInvocation inv = (RpcInvocation) invocation;
final String methodName = RpcUtils.getMethodName(invocation);
inv.setAttachment(Constants.PATH_KEY, getUrl().getPath());
inv.setAttachment(Constants.VERSION_KEY, version);
ExchangeClient currentClient;
if (clients.length == 1) {
currentClient = clients[0];
} else {
currentClient = clients[index.getAndIncrement() % clients.length];
}
try {
boolean isAsync = RpcUtils.isAsync(getUrl(), invocation);
boolean isOneway = RpcUtils.isOneway(getUrl(), invocation);
int timeout = getUrl().getMethodParameter(methodName, Constants.TIMEOUT_KEY,Constants.DEFAULT_TIMEOUT);
if (isOneway) {
boolean isSent = getUrl().getMethodParameter(methodName, Constants.SENT_KEY, false);
currentClient.send(inv, isSent);
RpcContext.getContext().setFuture(null);
return new RpcResult();
} else if (isAsync) {
ResponseFuture future = currentClient.request(inv, timeout) ;
RpcContext.getContext().setFuture(new FutureAdapter<Object>(future));
return new RpcResult();
} else {
RpcContext.getContext().setFuture(null);
return (Result) currentClient.request(inv, timeout).get();
}
} catch (TimeoutException e) {
throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e);
} catch (RemotingException e) {
throw new RpcException(RpcException.NETWORK_EXCEPTION, "Failed to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e);
}
}
@Override
public boolean isAvailable() {
if (!super.isAvailable())
return false;
for (ExchangeClient client : clients){
if (client.isConnected() && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)){
//cannot write == not Available ?
return true ;
}
}
return false;
}
public void destroy() {
//防止client被关闭多次.在connect per jvm的情况下,client.close方法会调用计数器-1,当计数器小于等于0的情况下,才真正关闭
if (super.isDestroyed()){
return ;
} else {
//dubbo check ,避免多次关闭
destroyLock.lock();
try{
if (super.isDestroyed()){
return ;
}
super.destroy();
if (invokers != null){
invokers.remove(this);
}
for (ExchangeClient client : clients) {
try {
client.close();
} catch (Throwable t) {
logger.warn(t.getMessage(), t);
}
}
}finally {
destroyLock.unlock();
}
}
}
} | apache-2.0 |
tseen/Federated-HDFS | tseenliu/FedHDFS-hadoop-src/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/aggregate/StringValueMax.java | 2330 | /**
* 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.hadoop.mapreduce.lib.aggregate;
import java.util.ArrayList;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
/**
* This class implements a value aggregator that maintain the biggest of
* a sequence of strings.
*
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public class StringValueMax implements ValueAggregator<String> {
String maxVal = null;
/**
* the default constructor
*
*/
public StringValueMax() {
reset();
}
/**
* add a value to the aggregator
*
* @param val
* a string.
*
*/
public void addNextValue(Object val) {
String newVal = val.toString();
if (this.maxVal == null || this.maxVal.compareTo(newVal) < 0) {
this.maxVal = newVal;
}
}
/**
* @return the aggregated value
*/
public String getVal() {
return this.maxVal;
}
/**
* @return the string representation of the aggregated value
*/
public String getReport() {
return maxVal;
}
/**
* reset the aggregator
*/
public void reset() {
maxVal = null;
}
/**
* @return return an array of one element. The element is a string
* representation of the aggregated value. The return value is
* expected to be used by the a combiner.
*/
public ArrayList<String> getCombinerOutput() {
ArrayList<String> retv = new ArrayList<String>(1);
retv.add(maxVal);
return retv;
}
}
| apache-2.0 |
nwillc/opa | src/main/java/com/github/nwillc/opa/impl/CachingDao.java | 2226 | /*
* Copyright 2018 nwillc@gmail.com
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with or without
* fee is hereby granted, provided that the above copyright notice and this permission notice appear
* in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
* OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.github.nwillc.opa.impl;
import com.github.nwillc.opa.Dao;
import com.github.nwillc.opa.HasKey;
import com.github.nwillc.opa.query.Query;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;
/**
* A simple cache in front on another dao.
*
* @param <K> cache's key type
* @param <T> cache's stored type
* @since 0.2.0
*/
public class CachingDao<K, T extends HasKey<K>> implements Dao<K, T> {
private final Dao<K, T> dao;
private final Map<K, T> map = new ConcurrentHashMap<>();
public CachingDao(final Dao<K, T> dao) {
this.dao = dao;
}
@Override
public Optional<T> findOne(final K key) {
if (map.containsKey(key)) {
return Optional.of(map.get(key));
} else {
final Optional<T> one = dao.findOne(key);
one.ifPresent(t -> map.put(key, t));
return one;
}
}
@Override
public Stream<T> findAll() {
return dao.findAll().peek(t -> map.put(t.getKey(), t));
}
@Override
public Stream<T> find(final Query<T> query) {
return dao.find(query).peek(t -> map.put(t.getKey(), t));
}
@Override
public void save(final T entity) {
map.put(entity.getKey(), entity);
dao.save(entity);
}
@Override
public void delete(final K key) {
dao.delete(key);
map.remove(key);
}
}
| isc |
mkotb/Reddigram | src/main/java/xyz/mkotb/reddigram/data/SavedLiveThread.java | 793 | package xyz.mkotb.reddigram.data;
import xyz.mkotb.reddigram.ReddigramBot;
import xyz.mkotb.reddigram.live.LiveFollower;
import java.util.Set;
public class SavedLiveThread {
private String id;
private Set<String> subscribedChats;
public SavedLiveThread(String id, Set<String> subscribedChats) {
this.id = id;
this.subscribedChats = subscribedChats;
}
public SavedLiveThread() {
}
public String id() {
return id;
}
public Set<String> subscribedChats() {
return subscribedChats;
}
public LiveFollower toActiveFollower(ReddigramBot bot) {
LiveFollower follower = new LiveFollower(bot, id);
subscribedChats.forEach(follower::subscribe);
follower.start();
return follower;
}
}
| isc |
Killianoc/FYP | src/net/scapeemulator/game/model/player/consumable/Food.java | 1143 | package net.scapeemulator.game.model.player.consumable;
/**
* Normal food that only heals health, no extra effects.
*
* @author David Insley
*/
public enum Food {
CRAYFISH(1, 13433),
ANCHOVIES(1, 0),
SHRIMP(3, 0),
CHICKEN(3, 0),
MEAT(3, 0),
CAKE(4, 1891, 1893, 1895),
BREAD(5, 0),
HERRING(5, 0),
MACKEREL(6, 0),
PLAIN_PIZZA(7, 2289, 2291),
TROUT(7, 0),
PIKE(8, 0),
LOBSTER(12, 0);
private final int heal;
private final int[] bites;
private Food(int heal, int... bites) {
this.heal = heal;
this.bites = bites;
}
public static Food forId(int biteId) {
for (Food food : values()) {
for (int bite : food.bites) {
if (bite == biteId) {
return food;
}
}
}
return null;
}
public int getNextBite(int bite) {
for (int i = 0; i < bites.length - 1; i++) {
if (bites[i] == bite) {
return bites[i + 1];
}
}
return -1;
}
public int getHeal() {
return heal;
}
}
| isc |
io7m/r2 | com.io7m.r2.transforms/src/main/java/com/io7m/r2/transforms/R2TransformOTReadableType.java | 1104 | /*
* Copyright © 2016 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.r2.transforms;
/**
* A readable transform that exposes an orientation, followed by a translation.
*/
public interface R2TransformOTReadableType
extends R2TransformOrthogonalReadableType,
R2TransformOrientationReadableType,
R2TransformTranslationReadableType
{
// No extra methods
}
| isc |
io7m/r2 | com.io7m.r2.tests/src/test/java/com/io7m/r2/tests/rendering/geometry/api/R2GeometryRendererContract.java | 10644 | /*
* Copyright © 2016 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.r2.tests.rendering.geometry.api;
import com.io7m.jcanephora.core.api.JCGLContextType;
import com.io7m.jcanephora.core.api.JCGLFramebuffersType;
import com.io7m.jcanephora.core.api.JCGLInterfaceGL33Type;
import com.io7m.jcanephora.profiler.JCGLProfiling;
import com.io7m.jcanephora.profiler.JCGLProfilingContextType;
import com.io7m.jcanephora.profiler.JCGLProfilingFrameType;
import com.io7m.jcanephora.profiler.JCGLProfilingType;
import com.io7m.jcanephora.texture.unit_allocator.JCGLTextureUnitAllocator;
import com.io7m.jcanephora.texture.unit_allocator.JCGLTextureUnitAllocatorType;
import com.io7m.jcanephora.texture.unit_allocator.JCGLTextureUnitContextParentType;
import com.io7m.jregions.core.unparameterized.sizes.AreaSizeL;
import com.io7m.jregions.core.unparameterized.sizes.AreaSizesL;
import com.io7m.jtensors.core.parameterized.matrices.PMatrices3x3D;
import com.io7m.jtensors.core.parameterized.matrices.PMatrices4x4D;
import com.io7m.r2.core.api.ids.R2IDPool;
import com.io7m.r2.core.api.ids.R2IDPoolType;
import com.io7m.r2.instances.R2InstanceSingle;
import com.io7m.r2.instances.R2InstanceSingleType;
import com.io7m.r2.matrices.R2Matrices;
import com.io7m.r2.matrices.R2MatricesType;
import com.io7m.r2.meshes.defaults.R2UnitQuad;
import com.io7m.r2.projections.R2ProjectionOrthographic;
import com.io7m.r2.rendering.geometry.R2GeometryBuffer;
import com.io7m.r2.rendering.geometry.R2SceneOpaques;
import com.io7m.r2.rendering.geometry.api.R2GeometryBufferComponents;
import com.io7m.r2.rendering.geometry.api.R2GeometryBufferDescription;
import com.io7m.r2.rendering.geometry.api.R2GeometryBufferType;
import com.io7m.r2.rendering.geometry.api.R2GeometryRendererType;
import com.io7m.r2.rendering.geometry.api.R2MaterialOpaqueSingle;
import com.io7m.r2.rendering.geometry.api.R2MaterialOpaqueSingleType;
import com.io7m.r2.rendering.geometry.api.R2SceneOpaquesReadableType;
import com.io7m.r2.rendering.geometry.api.R2SceneOpaquesType;
import com.io7m.r2.shaders.api.R2ShaderPreprocessingEnvironmentType;
import com.io7m.r2.shaders.geometry.R2GeometryShaderBasicParameters;
import com.io7m.r2.shaders.geometry.R2GeometryShaderBasicSingle;
import com.io7m.r2.shaders.geometry.api.R2ShaderGeometrySingleType;
import com.io7m.r2.tests.R2JCGLContract;
import com.io7m.r2.tests.ShaderPreprocessing;
import com.io7m.r2.textures.R2TextureDefaults;
import com.io7m.r2.textures.R2TextureDefaultsType;
import com.io7m.r2.transforms.R2TransformIdentity;
import com.io7m.r2.unit_quads.R2UnitQuadType;
import org.junit.Assert;
import org.junit.Test;
import java.util.Optional;
import static com.io7m.jfunctional.Unit.unit;
import static java.util.Optional.empty;
public abstract class R2GeometryRendererContract extends R2JCGLContract
{
private static R2SceneOpaquesReadableType newScene(
final JCGLInterfaceGL33Type g,
final R2TextureDefaultsType td,
final R2UnitQuadType quad,
final R2IDPoolType id_pool)
{
final R2ShaderPreprocessingEnvironmentType sources =
ShaderPreprocessing.preprocessor();
final R2InstanceSingleType i =
R2InstanceSingle.of(
id_pool.freshID(),
quad.arrayObject(),
R2TransformIdentity.get(),
PMatrices3x3D.identity());
final R2ShaderGeometrySingleType<R2GeometryShaderBasicParameters> ds =
R2GeometryShaderBasicSingle.create(g.shaders(), sources, id_pool);
final R2GeometryShaderBasicParameters ds_param =
R2GeometryShaderBasicParameters.builder().setTextureDefaults(td).build();
final R2MaterialOpaqueSingleType<R2GeometryShaderBasicParameters> mat =
R2MaterialOpaqueSingle.of(id_pool.freshID(), ds, ds_param);
final R2SceneOpaquesType s = R2SceneOpaques.create();
s.opaquesAddSingleInstance(i, mat);
return s;
}
protected abstract R2GeometryRendererType getRenderer(
final JCGLInterfaceGL33Type g);
@Test
public final void testIdentities()
{
final JCGLContextType c =
this.newGL33Context("main", 24, 8);
final JCGLInterfaceGL33Type g =
c.contextGetGL33();
final R2GeometryRendererType r = this.getRenderer(g);
Assert.assertFalse(r.isDeleted());
r.delete(g);
Assert.assertTrue(r.isDeleted());
}
@Test
public final void testFramebufferBindingDefaultNotProvided()
{
final JCGLContextType c =
this.newGL33Context("main", 24, 8);
final JCGLInterfaceGL33Type g =
c.contextGetGL33();
final R2GeometryRendererType r =
this.getRenderer(g);
final JCGLFramebuffersType g_fb =
g.framebuffers();
final AreaSizeL area = AreaSizeL.of(640L, 480L);
final JCGLTextureUnitAllocatorType ta =
JCGLTextureUnitAllocator.newAllocatorWithStack(
8, g.textures().textureGetUnits());
final JCGLTextureUnitContextParentType tc =
ta.rootContext();
final R2TextureDefaultsType td =
R2TextureDefaults.create(g.textures(), tc);
final R2UnitQuadType quad =
R2UnitQuad.newUnitQuad(g);
final R2IDPoolType id_pool =
R2IDPool.newPool();
final JCGLProfilingType pro =
JCGLProfiling.newProfiling(g.timers());
final JCGLProfilingFrameType pro_frame =
pro.startFrame();
final JCGLProfilingContextType pro_root =
pro_frame.childContext("main");
final R2SceneOpaquesReadableType s =
newScene(g, td, quad, id_pool);
final R2ProjectionOrthographic proj =
R2ProjectionOrthographic.create();
g_fb.framebufferReadUnbind();
g_fb.framebufferDrawUnbind();
final R2MatricesType m = R2Matrices.create();
m.withObserver(
PMatrices4x4D.identity(),
proj,
unit(),
(x, y) -> {
r.renderGeometry(AreaSizesL.area(area), empty(), pro_root, tc, x, s);
return unit();
});
Assert.assertFalse(g_fb.framebufferReadAnyIsBound());
Assert.assertFalse(g_fb.framebufferDrawAnyIsBound());
}
@Test
public final void testFramebufferBindingNonDefaultNotProvided()
{
final JCGLContextType c =
this.newGL33Context("main", 24, 8);
final JCGLInterfaceGL33Type g =
c.contextGetGL33();
final R2GeometryRendererType r =
this.getRenderer(g);
final JCGLFramebuffersType g_fb =
g.framebuffers();
final AreaSizeL area = AreaSizeL.of(640L, 480L);
final JCGLTextureUnitAllocatorType ta =
JCGLTextureUnitAllocator.newAllocatorWithStack(
8, g.textures().textureGetUnits());
final JCGLTextureUnitContextParentType tc =
ta.rootContext();
final R2TextureDefaultsType td =
R2TextureDefaults.create(g.textures(), tc);
final R2UnitQuadType quad =
R2UnitQuad.newUnitQuad(g);
final R2IDPoolType id_pool =
R2IDPool.newPool();
final JCGLProfilingType pro =
JCGLProfiling.newProfiling(g.timers());
final JCGLProfilingFrameType pro_frame =
pro.startFrame();
final JCGLProfilingContextType pro_root =
pro_frame.childContext("main");
final R2SceneOpaquesReadableType s =
newScene(g, td, quad, id_pool);
final R2ProjectionOrthographic proj =
R2ProjectionOrthographic.create();
final R2GeometryBufferType gbuffer = R2GeometryBuffer.create(
g_fb,
g.textures(),
tc,
R2GeometryBufferDescription.of(
area, R2GeometryBufferComponents.R2_GEOMETRY_BUFFER_FULL));
g_fb.framebufferReadUnbind();
g_fb.framebufferDrawUnbind();
g_fb.framebufferDrawBind(gbuffer.primaryFramebuffer());
final R2MatricesType m = R2Matrices.create();
m.withObserver(
PMatrices4x4D.identity(),
proj,
unit(),
(x, y) -> {
r.renderGeometry(AreaSizesL.area(area), empty(), pro_root, tc, x, s);
return unit();
});
Assert.assertFalse(g_fb.framebufferReadAnyIsBound());
Assert.assertTrue(
g_fb.framebufferDrawIsBound(gbuffer.primaryFramebuffer()));
}
@Test
public final void testFramebufferBindingDefaultProvided()
{
final JCGLContextType c =
this.newGL33Context("main", 24, 8);
final JCGLInterfaceGL33Type g =
c.contextGetGL33();
final R2GeometryRendererType r =
this.getRenderer(g);
final JCGLFramebuffersType g_fb =
g.framebuffers();
final AreaSizeL area = AreaSizeL.of(640L, 480L);
final JCGLTextureUnitAllocatorType ta =
JCGLTextureUnitAllocator.newAllocatorWithStack(
8, g.textures().textureGetUnits());
final JCGLTextureUnitContextParentType tc =
ta.rootContext();
final R2TextureDefaultsType td =
R2TextureDefaults.create(g.textures(), tc);
final R2UnitQuadType quad =
R2UnitQuad.newUnitQuad(g);
final R2IDPoolType id_pool =
R2IDPool.newPool();
final JCGLProfilingType pro =
JCGLProfiling.newProfiling(g.timers());
final JCGLProfilingFrameType pro_frame =
pro.startFrame();
final JCGLProfilingContextType pro_root =
pro_frame.childContext("main");
final R2SceneOpaquesReadableType s =
newScene(g, td, quad, id_pool);
final R2ProjectionOrthographic proj =
R2ProjectionOrthographic.create();
final R2GeometryBufferType gbuffer = R2GeometryBuffer.create(
g_fb,
g.textures(),
tc,
R2GeometryBufferDescription.of(
area,
R2GeometryBufferComponents.R2_GEOMETRY_BUFFER_FULL));
g_fb.framebufferReadUnbind();
g_fb.framebufferDrawUnbind();
final R2MatricesType m = R2Matrices.create();
m.withObserver(
PMatrices4x4D.identity(),
proj,
unit(),
(x, y) -> {
r.renderGeometry(
AreaSizesL.area(area),
Optional.of(gbuffer),
pro_root,
tc,
x,
s);
return unit();
});
Assert.assertFalse(g_fb.framebufferReadAnyIsBound());
Assert.assertTrue(
g_fb.framebufferDrawIsBound(gbuffer.primaryFramebuffer()));
}
}
| isc |
Juriy/masterhack | server/src/main/java/mastercard/mcwallet/sdk/xml/commontypes/ExtensionPoint.java | 2694 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.08.21 at 12:20:47 PM CDT
//
package mastercard.mcwallet.sdk.xml.commontypes;
import javax.xml.bind.annotation.*;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>Java class for ExtensionPoint complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ExtensionPoint">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <any maxOccurs="unbounded"/>
* </sequence>
* <anyAttribute/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ExtensionPoint", propOrder = {
"any"
})
public class ExtensionPoint {
@XmlAnyElement(lax = true)
protected List<Object> any;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
/**
* Gets the value of the any property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the any property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAny().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Object }
*
*
*/
public List<Object> getAny() {
if (any == null) {
any = new ArrayList<Object>();
}
return this.any;
}
/**
* Gets a map that contains attributes that aren't bound to any typed property on this class.
*
* <p>
* the map is keyed by the name of the attribute and
* the value is the string value of the attribute.
*
* the map returned by this method is live, and you can add new attribute
* by updating the map directly. Because of this design, there's no setter.
*
*
* @return
* always non-null
*/
public Map<QName, String> getOtherAttributes() {
return otherAttributes;
}
}
| isc |
AWildridge/ProtoScape | src/org/apollo/game/event/impl/FirstItemOptionEvent.java | 483 | package org.apollo.game.event.impl;
/**
* The first {@link ItemOptionEvent}, used for eating food or identifying herbs (amongst others).
* @author Chris Fletcher
*/
public final class FirstItemOptionEvent extends ItemOptionEvent {
/**
* Creates the first item option event.
* @param interfaceId The interface id.
* @param id The id.
* @param slot The slot.
*/
public FirstItemOptionEvent(int interfaceId, int id, int slot) {
super(1, interfaceId, id, slot);
}
}
| isc |
Nick-Mazuk/Music-App | Playing Single Note/PlayingaNote/app/src/androidTest/java/io/github/nick_mazuk/playinganote/ApplicationTest.java | 364 | package io.github.nick_mazuk.playinganote;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | mit |
PrograAvanzadaPick60/jrpg | dominio/src/main/java/dominio/Peleable.java | 318 | package dominio;
public interface Peleable {
public int serAtacado(int daño);
public int getSalud();
public void despuesDeTurno();
public int atacar(Peleable atacado);
public int otorgarExp();
public int getAtaque();
public void setAtaque(int ataque);
public boolean estaVivo();
public String getNombre();
}
| mit |
korrio/VMChat-Fix | app/src/main/java/co/aquario/chatapp/event/request/ConversationEvent.java | 296 | package co.aquario.chatapp.event.request;
/**
* Created by Mac on 3/2/15.
*/
public class ConversationEvent {
public int userId;
public int partnerId;
public ConversationEvent(int userId, int partnerId) {
this.userId = userId;
this.partnerId = partnerId;
}
}
| mit |
CS2103AUG2016-T11-C3/main | src/main/java/seedu/stask/logic/LogicManager.java | 1397 | package seedu.stask.logic;
import javafx.collections.ObservableList;
import seedu.stask.commons.core.ComponentManager;
import seedu.stask.commons.core.LogsCenter;
import seedu.stask.logic.commands.Command;
import seedu.stask.logic.commands.CommandResult;
import seedu.stask.logic.parser.Parser;
import seedu.stask.model.Model;
import seedu.stask.model.task.ReadOnlyTask;
import seedu.stask.storage.Storage;
import java.util.logging.Logger;
/**
* The main LogicManager of the app.
*/
public class LogicManager extends ComponentManager implements Logic {
private final Logger logger = LogsCenter.getLogger(LogicManager.class);
private final Model model;
private final Parser parser;
public LogicManager(Model model, Storage storage) {
this.model = model;
this.parser = new Parser();
}
@Override
public CommandResult execute(String commandText) {
logger.info("----------------[USER COMMAND][" + commandText + "]");
Command command = parser.parseCommand(commandText);
command.setData(model);
return command.execute();
}
@Override
public ObservableList<ReadOnlyTask> getFilteredDatedTaskList() {
return model.getFilteredDatedTaskList();
}
@Override
public ObservableList<ReadOnlyTask> getFilteredUndatedTaskList() {
return model.getFilteredUndatedTaskList();
}
}
| mit |
r3kdotio/gamify9dotcom | src/main/java/io/r3k/gamify9dotcom/services/challenge2/CompileMyGameService.java | 1557 | package io.r3k.gamify9dotcom.services.challenge2;
import io.r3k.gamify9dotcom.domain.ChallengeReponse;
import io.r3k.gamify9dotcom.services.challenge.AbstractChallenge;
import javax.validation.constraints.NotNull;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path = "/api/challenge2", produces = {MediaType.APPLICATION_JSON_VALUE})
public class CompileMyGameService extends AbstractChallenge {
public CompileMyGameService() {
super("challenge2.compilemygameservice");
}
@PostMapping(path = "/compilemygame/compilewithoutmoduledir")
public ResponseEntity<ChallengeReponse> compileWithoutModuleDir(@RequestBody @NotNull String givenString) {
if (givenString.contains("error: module not found: com.gamify9.gameengine")) {
return success();
} else {
return failure("Compile does not contain expected error");
}
}
@PostMapping(path = "/compilemygame/compilewithmoduledir")
public ResponseEntity<ChallengeReponse> compileWithModuleDir(@RequestBody @NotNull String givenString) {
if (givenString.contains("mods/com.gamify9.mygame")) {
return success();
} else {
return failure("Compile does not contain expected output of compile to mods/com.gamify9.mygame");
}
}
}
| mit |
intuit/karate | karate-core/src/test/java/com/intuit/karate/http/HttpUtilsTest.java | 3735 | package com.intuit.karate.http;
import static com.intuit.karate.TestUtils.*;
import com.intuit.karate.StringUtils;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
/**
*
* @author pthomas3
*/
class HttpUtilsTest {
@Test
void testParseContentTypeCharset() {
assertEquals(StandardCharsets.UTF_8, HttpUtils.parseContentTypeCharset("application/json; charset=UTF-8"));
assertEquals(StandardCharsets.UTF_8, HttpUtils.parseContentTypeCharset("application/json; charset = UTF-8 "));
assertEquals(StandardCharsets.UTF_8, HttpUtils.parseContentTypeCharset("application/json; charset=UTF-8; version=1.2.3"));
assertEquals(StandardCharsets.UTF_8, HttpUtils.parseContentTypeCharset("application/json; charset = UTF-8 ; version=1.2.3"));
}
@Test
void testParseContentTypeParams() {
Map<String, String> map = HttpUtils.parseContentTypeParams("application/json");
assertNull(map);
map = HttpUtils.parseContentTypeParams("application/json; charset=UTF-8");
match(map, "{ charset: 'UTF-8' }");
map = HttpUtils.parseContentTypeParams("application/json; charset = UTF-8 ");
match(map, "{ charset: 'UTF-8' }");
map = HttpUtils.parseContentTypeParams("application/json; charset=UTF-8; version=1.2.3");
match(map, "{ charset: 'UTF-8', version: '1.2.3' }");
map = HttpUtils.parseContentTypeParams("application/json; charset = UTF-8 ; version=1.2.3");
match(map, "{ charset: 'UTF-8', version: '1.2.3' }");
map = HttpUtils.parseContentTypeParams("application/vnd.app.test+json;ton-version=1");
match(map, "{ 'ton-version': '1' }");
}
@Test
void testParseUriPathPatterns() {
Map<String, String> map = HttpUtils.parseUriPattern("/cats/{id}", "/cats/1");
match(map, "{ id: '1' }");
map = HttpUtils.parseUriPattern("/cats/{id}/", "/cats/1"); // trailing slash
match(map, "{ id: '1' }");
map = HttpUtils.parseUriPattern("/cats/{id}", "/cats/1/"); // trailing slash
match(map, "{ id: '1' }");
map = HttpUtils.parseUriPattern("/cats/{id}", "/foo/bar");
match(map, null);
map = HttpUtils.parseUriPattern("/cats", "/cats/1"); // exact match
match(map, null);
map = HttpUtils.parseUriPattern("/{path}/{id}", "/cats/1");
match(map, "{ path: 'cats', id: '1' }");
map = HttpUtils.parseUriPattern("/cats/{id}/foo", "/cats/1/foo");
match(map, "{ id: '1' }");
map = HttpUtils.parseUriPattern("/api/{img}", "/api/billie.jpg");
match(map, "{ img: 'billie.jpg' }");
map = HttpUtils.parseUriPattern("/hello/{raw}", "/hello/�Ill~Formed@RequiredString!");
match(map, "{ raw: '�Ill~Formed@RequiredString!' }");
}
static void splitUrl(String raw, String left, String right) {
StringUtils.Pair pair = HttpUtils.parseUriIntoUrlBaseAndPath(raw);
assertEquals(left, pair.left);
assertEquals(right, pair.right);
}
@Test
void testUriParsing() {
splitUrl("http://foo/bar", "http://foo", "/bar");
splitUrl("/bar", null, "/bar");
splitUrl("/bar?baz=ban", null, "/bar?baz=ban");
splitUrl("http://foo/bar?baz=ban", "http://foo", "/bar?baz=ban");
splitUrl("localhost:50856", null, "");
splitUrl("127.0.0.1:50856", null, "");
splitUrl("http://foo:8080/bar", "http://foo:8080", "/bar");
splitUrl("http://foo.com:8080/bar", "http://foo.com:8080", "/bar");
splitUrl("https://api.randomuser.me/?nat=us", "https://api.randomuser.me", "/?nat=us");
}
}
| mit |
fmarchioni/mastertheboss | quarkus/infinispan-demo/src/main/java/com/sample/infinispan/client/AnotherEndpoint.java | 840 | package com.sample.infinispan.client;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonObjectBuilder;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.jboss.logging.Logger;
import org.jboss.resteasy.annotations.jaxrs.PathParam;
@Path("/test")
@ApplicationScoped
public class AnotherEndpoint {
@GET
@Path("/{id}")
public void getCustomer(@PathParam Integer id) {
System.out.println("id " +id);
}
}
| mit |
jmthompson2015/vizzini | ai/src/test/java/org/vizzini/ai/geneticalgorithm/geneticprogramming/problem/artificialant/SimulatorTest.java | 1365 | package org.vizzini.ai.geneticalgorithm.geneticprogramming.problem.artificialant;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.Converter;
import org.vizzini.ai.geneticalgorithm.geneticprogramming.TreeNode;
/**
* Provides tests for the <code>Simulator</code> class.
*/
public final class SimulatorTest
{
/** Converter. */
private final Converter<Integer> converter = new Converter<Integer>(Integer.class);
/**
* Test the <code>run()</code> method.
*/
@Test
public void runMove()
{
// Setup.
final TreeNode<Integer> function = new MoveTerminal(converter);
final Simulator simulator = new Simulator();
// Run.
final int result = simulator.run(function);
// Verify.
assertThat(result, is(3));
}
/**
* Test the <code>run()</code> method.
*/
@Test
public void runSolution()
{
// Setup.
final ArtificialAntProblem problem = new ArtificialAntProblem();
final TreeNode<Integer> solution = problem.getSolution();
final Simulator simulator = new Simulator();
// Run.
final int result = simulator.run(solution);
// Verify.
assertThat(result, is(89));
}
}
| mit |
dcchivian/kb_util_dylan | lib/src/us/kbase/kbutildylan/FractionateOptions.java | 2566 |
package us.kbase.kbutildylan;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
/**
* <p>Original spec-file type: Fractionate_Options</p>
* <pre>
* KButil_Random_Subsample_Reads()
* **
* ** Method for random subsampling of reads library
* </pre>
*
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("com.googlecode.jsonschema2pojo")
@JsonPropertyOrder({
"split_num",
"reads_num",
"reads_perc"
})
public class FractionateOptions {
@JsonProperty("split_num")
private Long splitNum;
@JsonProperty("reads_num")
private Long readsNum;
@JsonProperty("reads_perc")
private Double readsPerc;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("split_num")
public Long getSplitNum() {
return splitNum;
}
@JsonProperty("split_num")
public void setSplitNum(Long splitNum) {
this.splitNum = splitNum;
}
public FractionateOptions withSplitNum(Long splitNum) {
this.splitNum = splitNum;
return this;
}
@JsonProperty("reads_num")
public Long getReadsNum() {
return readsNum;
}
@JsonProperty("reads_num")
public void setReadsNum(Long readsNum) {
this.readsNum = readsNum;
}
public FractionateOptions withReadsNum(Long readsNum) {
this.readsNum = readsNum;
return this;
}
@JsonProperty("reads_perc")
public Double getReadsPerc() {
return readsPerc;
}
@JsonProperty("reads_perc")
public void setReadsPerc(Double readsPerc) {
this.readsPerc = readsPerc;
}
public FractionateOptions withReadsPerc(Double readsPerc) {
this.readsPerc = readsPerc;
return this;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperties(String name, Object value) {
this.additionalProperties.put(name, value);
}
@Override
public String toString() {
return ((((((((("FractionateOptions"+" [splitNum=")+ splitNum)+", readsNum=")+ readsNum)+", readsPerc=")+ readsPerc)+", additionalProperties=")+ additionalProperties)+"]");
}
}
| mit |
rinaldo-santana/ponto-inteligente-api | src/main/java/com/everest/pontointeligente/api/security/services/JwtUserDetailsServiceImpl.java | 1105 | package com.everest.pontointeligente.api.security.services;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.everest.pontointeligente.api.entities.Funcionario;
import com.everest.pontointeligente.api.security.JwtUserFactory;
import com.everest.pontointeligente.api.services.FuncionarioService;
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService{
@Autowired
private FuncionarioService funcionarioService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<Funcionario> funcionario = funcionarioService.buscarPorEmail(username);
if (funcionario.isPresent()) {
return JwtUserFactory.create(funcionario.get());
}
throw new UsernameNotFoundException("Email não encontrado.");
}
}
| mit |
jwiesel/sfdcCommander | sfdcCommander/src/main/java/com/sforce/soap/_2006/_04/metadata/ContentAssetAccess.java | 3011 | /**
* ContentAssetAccess.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.sforce.soap._2006._04.metadata;
public class ContentAssetAccess implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected ContentAssetAccess(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _VIEWER = "VIEWER";
public static final java.lang.String _COLLABORATOR = "COLLABORATOR";
public static final java.lang.String _INFERRED = "INFERRED";
public static final ContentAssetAccess VIEWER = new ContentAssetAccess(_VIEWER);
public static final ContentAssetAccess COLLABORATOR = new ContentAssetAccess(_COLLABORATOR);
public static final ContentAssetAccess INFERRED = new ContentAssetAccess(_INFERRED);
public java.lang.String getValue() { return _value_;}
public static ContentAssetAccess fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
ContentAssetAccess enumeration = (ContentAssetAccess)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static ContentAssetAccess fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(ContentAssetAccess.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "ContentAssetAccess"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
| mit |
Ben880/GNGH-2 | src/world/event/TrainEvent.java | 1047 | package world.event;
import gui.winow.Slider;
import java.util.Random;
/*
BenjaminWilcox
Dec 16, 2016
GNGH_2
*/
public class TrainEvent extends Event
{
Random rand = new Random();
int people = 0;
int troops = 0;
public void create()
{
Slider slider = new Slider();
int desired = slider.getNumber("train", "troops") / 10;
if (desired != 0)
{
troops = desired - rand.nextInt(desired / 2);
people = desired - troops;
// resources.people().subtrat(desired);
setCompleet(rand.nextInt(10) + day.getDay() + 5);
setMessage(troops + " trainees have compeeted their training. " + (people) + " have failed their training.");
console.append(desired + " people have been set to train");
} else
{
dispatch.cancelEvent();
}
}
public void end()
{
console.append(message);
// resources.troops().add(troops);
// resources.people().add(people);
}
}
| mit |
ConcordiaUniProgrammers/inse6260-real-estate | REAgency/src/infrastructure/restful/filemanager/MultiPartFieldInjectedResource.java | 800 | package infrastructure.restful.filemanager;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
@Path("/form-field-injected")
public class MultiPartFieldInjectedResource {
@FormDataParam("string")
private String s;
@FormDataParam("string")
private FormDataContentDisposition sd;
@FormDataParam("bean")
private Bean b;
@FormDataParam("bean")
private FormDataContentDisposition bd;
@POST
@Path("xml-jaxb-part")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public String post() {
return s + ":" + sd.getFileName() + "," + b.value + ":"
+ bd.getFileName();
}
}
| mit |
dancarpenter21/lol-api-rxjava | src/main/java/org/dc/riot/lol/rx/service/interfaces/ApiFactory.java | 17126 | package org.dc.riot.lol.rx.service.interfaces;
import java.lang.reflect.Type;
import java.net.Proxy;
import org.dc.riot.lol.rx.model.common.Mastery;
import org.dc.riot.lol.rx.model.common.Rune;
import org.dc.riot.lol.rx.model.staticdata.RangeDto;
import org.dc.riot.lol.rx.service.ApiKey;
import org.dc.riot.lol.rx.service.Region;
import org.dc.riot.lol.rx.service.RiotApi;
import org.dc.riot.lol.rx.service.RiotApi.RateType;
import org.dc.riot.lol.rx.service.error.InvalidVersionException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
/**
* Use this class to generate instances of {@link RiotApi} interfaces. Use the associated {@link Builder}
* to call into specific versions if needed. {@link ApiFactory#newDefaultFactory(ApiKey)} is the easiest
* way to get {@link ApiFactory} and {@link RiotApi} instances.
*
* @author Dc
* @since 1.0.0
*/
public final class ApiFactory {
private static Gson GSON = null;
static {
GsonBuilder builder = new GsonBuilder();
/*
* Deserialize weirdness with ranges
*/
builder.registerTypeAdapter(RangeDto.class, new JsonDeserializer<RangeDto>() {
@Override
public RangeDto deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String rString = json.toString().replace("\"", ""); // sometimes the JsonElement has superfluous quotes in it
int[] ranges = null;
if (!"self".equalsIgnoreCase(rString)) {
JsonArray jRanges = json.getAsJsonArray();
int index = 0;
ranges = new int[jRanges.size()];
for (JsonElement o : jRanges) {
ranges[index] = o.getAsInt();
index++;
}
}
return new RangeDto(ranges);
}
});
/*
* Deserialize inconsistencies with Mastery objects returned from the LoL API
*/
builder.registerTypeAdapter(Mastery.class, new JsonDeserializer<Mastery>() {
@Override
public Mastery deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
Mastery dto = new Mastery();
JsonObject jsonObject = json.getAsJsonObject();
int rank = jsonObject.get("rank").getAsInt();
dto.setRank(rank);
long id = (jsonObject.get("id") != null) ? jsonObject.get("id").getAsLong() : jsonObject.get("masteryId").getAsLong();
dto.setMasteryId(id);
return dto;
}
});
/*
* Deserialize inconsistencies with Rune objects returned from the LoL API
*/
builder.registerTypeAdapter(Rune.class, new JsonDeserializer<Rune>() {
@Override
public Rune deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
Rune dto = new Rune();
JsonObject jsonObject = json.getAsJsonObject();
long runeId = jsonObject.get("runeId").getAsLong();
dto.setRuneId(runeId);
int rank = (jsonObject.get("count") != null) ? jsonObject.get("count").getAsInt() : jsonObject.get("rank").getAsInt();
dto.setCount(rank);
return dto;
}
});
/*
* Deserialize Regions.
*/
builder.registerTypeAdapter(Region.class, new JsonDeserializer<Region>() {
@Override
public Region deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
String regionCode = json.getAsString();
return Region.from(regionCode);
}
});
GSON = builder.create();
}
/**
* @return the {@link Gson} to be used for all deserializations. This is a custom built
* {@link Gson} instance, new instances of {@link Gson} may not properly deserialize
* responses.
*/
public static Gson getGson() {
return GSON;
}
/**
* Basic entry point to fetching Riot's LoL API data. This method creates a factory that
* will return interface calls for all recent versions of the LoL API.
*
* @param apiKey API key that this factory will use to create interface connections
* @return a {@link ApiFactory} for the given API key to access all newest
* LoL API versions
*/
public static ApiFactory newDefaultFactory(ApiKey apiKey) {
return new Builder(apiKey).build();
}
/*
* API versions
*/
private float champVersion;
private float championMasteryVersion;
private float currentGameVersion;
private float featuredGamesVersion;
private float recentGamesVersion;
private float leagueVersion;
private float staticDataVersion;
private float statsVersion;
private float statusVersion;
private float matchVersion;
private float matchlistVersion;
private float summonerVersion;
private float teamVersion;
/*
* Operating behind HTTP proxies
*/
private Proxy proxy;
private boolean autoRetry;
private int retryCount;
private final ApiKey apiKey;
private ApiFactory(ApiKey apiKey) {
this.apiKey = apiKey;
}
public RiotApi.Champion newChampionInterface(Region region, boolean autoRateControl) {
RiotApi.Champion api = null;
if (champVersion >= 1.2) {
api = new Champion_v1_2(apiKey, region);
} else {
throw new InvalidVersionException("Lowest supported Champion version is 1.2");
}
completeBuild(RiotApi.Champion.getSupportedRegions(api.getVersion()), region, api, autoRateControl);
return api;
}
public RiotApi.ChampionMastery newChampionMasteryInterface(Region region, boolean autoRateControl) {
RiotApi.ChampionMastery api = null;
if (championMasteryVersion >= 1.0) {
api = new ChampionMastery_v1_0(apiKey, region);
} else {
throw new InvalidVersionException("Lowest supported ChampionMastery version is 1.0");
}
completeBuild(RiotApi.ChampionMastery.getSupportedRegions(api.getVersion()), region, api, autoRateControl);
return api;
}
public RiotApi.CurrentGame newCurrentGameInterface(Region region, boolean autoRateControl) {
RiotApi.CurrentGame api = null;
if (currentGameVersion >= 1.0f) {
api = new CurrentGame_v1_0(apiKey, region);
} else {
throw new InvalidVersionException("Lowest supported CurrentGame version is 1.0");
}
completeBuild(RiotApi.CurrentGame.getSupportedRegions(api.getVersion()), region, api, autoRateControl);
return api;
}
public RiotApi.FeaturedGames newFeaturedGamesInterface(Region region, boolean autoRateControl) {
RiotApi.FeaturedGames api = null;
if (featuredGamesVersion >= 1.0f) {
api = new FeaturedGames_v1_0(apiKey, region);
} else {
throw new InvalidVersionException("Lowest supported FeaturedGames version is 1.0");
}
completeBuild(RiotApi.FeaturedGames.getSupportedRegions(api.getVersion()), region, api, autoRateControl);
return api;
}
public RiotApi.RecentGames newRecentGamesInterface(Region region, boolean autoRateControl) {
RiotApi.RecentGames api = null;
if (recentGamesVersion >= 1.3f) {
api = new RecentGames_v1_3(apiKey, region);
} else {
throw new InvalidVersionException("Lowest supported RecentGames version is 1.3");
}
completeBuild(RiotApi.RecentGames.getSupportedRegions(api.getVersion()), region, api, autoRateControl);
return api;
}
public RiotApi.League newLeagueInterface(Region region, boolean autoRateControl) {
RiotApi.League api = null;
if (leagueVersion >= 2.5) {
api = new League_v2_5(apiKey, region);
} else {
throw new InvalidVersionException("Lowest supported League version is 2.5");
}
completeBuild(RiotApi.League.getSupportedRegions(api.getVersion()), region, api, autoRateControl);
return api;
}
public RiotApi.StaticData newStaticDataInterface(Region region, boolean autoRateControl) {
RiotApi.StaticData api = null;
if (staticDataVersion >= 1.2) {
api = new StaticData_v1_2(apiKey, region);
} else {
throw new InvalidVersionException("Lowest supported StaticData version is 1.2");
}
completeBuild(RiotApi.StaticData.getSupportedRegions(api.getVersion()), region, api, autoRateControl);
return api;
}
public RiotApi.Stats newStatsInterface(Region region, boolean autoRateControl) {
RiotApi.Stats api = null;
if (statsVersion >= 1.3f) {
api = new Stats_v1_3(apiKey, region);
} else {
throw new InvalidVersionException("Lowest supported StaticData version is 1.3");
}
completeBuild(RiotApi.Stats.getSupportedRegions(api.getVersion()), region, api, autoRateControl);
return api;
}
public RiotApi.LolStatus newStatusInterface(Region region, boolean autoRateControl) {
RiotApi.LolStatus api = null;
if (statusVersion >= 1.0f) {
api = new LolStatus_v1_0(apiKey, region);
} else {
throw new InvalidVersionException("Lowest supported LolStatus version is 1.0");
}
completeBuild(RiotApi.LolStatus.getSupportedRegions(api.getVersion()), region, api, autoRateControl);
return api;
}
public RiotApi.Match newMatchInterface(Region region, boolean autoRateControl) {
RiotApi.Match api = null;
if (matchVersion >= 2.2f) {
api = new Match_v2_2(apiKey, region);
} else {
throw new InvalidVersionException("Lowest supported Match version is 2.2");
}
completeBuild(RiotApi.Match.getSupportedRegions(api.getVersion()), region, api, autoRateControl);
return api;
}
public RiotApi.MatchList newMatchListInterface(Region region, boolean autoRateControl) {
RiotApi.MatchList api = null;
if (matchlistVersion >= 2.2) {
api = new MatchList_v2_2(apiKey, region);
} else {
throw new InvalidVersionException("Lowest supported MatchListDto version is 2.2");
}
completeBuild(RiotApi.MatchList.getSupportedRegions(api.getVersion()), region, api, autoRateControl);
return api;
}
public RiotApi.Summoner newSummonerInterface(Region region, boolean autoRateControl) {
RiotApi.Summoner api = null;
if (summonerVersion >= 1.4f) {
api = new Summoner_v1_4(apiKey, region);
} else {
throw new InvalidVersionException("Lowest supported Summoner version is 1.4");
}
completeBuild(RiotApi.Summoner.getSupportedRegions(api.getVersion()), region, api, autoRateControl);
return api;
}
public RiotApi.Team newTeamInterface(Region region, boolean autoRateControl) {
RiotApi.Team api = null;
if (teamVersion >= 2.4f) {
api = new Team_v2_4(apiKey, region);
} else {
throw new InvalidVersionException("Lowest supported Team version is 2.4");
}
completeBuild(RiotApi.Team.getSupportedRegions(api.getVersion()), region, api, autoRateControl);
return api;
}
private void completeBuild(Region[] supportedRegions, Region region, RiotApi api, boolean autoRateControl) {
boolean supported = false;
for (Region r : supportedRegions) {
if (r == region) {
supported = true;
break;
}
}
if (!supported) {
throw new IllegalArgumentException("The API " + api.getClass().getSimpleName() + " is not supported for region " + region);
}
if (autoRateControl && api.getRateType() == RateType.PERSONAL) {
api.setRateControl(true);
}
api.setAutoRetry(autoRetry);
api.setRetryCount(retryCount);
api.setProxy(proxy);
}
/**
* Used to create {@link ApiFactory} instances pointed at specific versions.
*/
public static class Builder {
private float champVersion = 1.2f; // baseline Champion version
private float championMasteryVersion = 1.0f; // baseline ChampionMastery version
private float currentGameVersion = 1.0f; // baseline CurrentGame version
private float featuredGamesVersion = 1.0f; // baseline FeaturedGame version
private float recentGamesVersion = 1.3f; // baseline FeaturedGame version
private float leagueVersion = 2.5f; // baseline League version
private float statsVersion = 1.3f; // baseline Stats version
private float staticDataVersion = 1.2f; // baseline StaticData version
private float statusVersion = 1.0f; // baseline LolStatus version
private float matchVersion = 2.2f; // baseline Match version
private float matchlistVersion = 2.2f; // baseline MatchListDto version
private float summonerVersion = 1.4f; // baseline Summoner version
private float teamVersion = 2.4f; // baseline Team version
private boolean autoRetry = true;
private int retryCount = 5;
private Proxy proxy = null;
private final ApiKey apiKey;
public Builder(ApiKey apiKey) {
this.apiKey = apiKey;
}
public Builder setChampionVersion(float champVersion) {
this.champVersion = champVersion;
return this;
}
public Builder setChampionMasteryVersion(float championMasteryVersion) {
this.championMasteryVersion = championMasteryVersion;
return this;
}
public Builder setCurrentGameVersion(float currentGameVersion) {
this.currentGameVersion = currentGameVersion;
return this;
}
public Builder setFeaturedGamesVersion(float featuredGamesVersion) {
this.featuredGamesVersion = featuredGamesVersion;
return this;
}
public Builder setRecentGamesVersion(float recentGamesVersion) {
this.recentGamesVersion = recentGamesVersion;
return this;
}
public Builder setLeagueVersion(float leagueVersion) {
this.leagueVersion = leagueVersion;
return this;
}
public Builder setStaticDataVersion(float staticDataVersion) {
this.staticDataVersion = staticDataVersion;
return this;
}
public Builder setStatsVersion(float statsVersion) {
this.statsVersion = statsVersion;
return this;
}
public Builder setStatusVersion(float statusVersion) {
this.statusVersion = statusVersion;
return this;
}
public Builder setMatchVersion(float matchVersion) {
this.matchVersion = matchVersion;
return this;
}
public Builder setMatchListVersion(float matchlistVersion) {
this.matchlistVersion = matchlistVersion;
return this;
}
public Builder setSummonerVersion(float summonerVersion) {
this.summonerVersion = summonerVersion;
return this;
}
public Builder setTeamVersion(float teamVersion) {
this.teamVersion = teamVersion;
return this;
}
public Builder setProxy(Proxy proxy) {
this.proxy = proxy;
return this;
}
public Builder setAutoRetry(boolean autoRetry) {
this.autoRetry = autoRetry;
return this;
}
public Builder setRetyCount(int retryCount) {
this.retryCount = retryCount;
return this;
}
public ApiFactory build() {
ApiFactory factory = new ApiFactory(apiKey);
factory.champVersion = champVersion;
factory.championMasteryVersion = championMasteryVersion;
factory.currentGameVersion = currentGameVersion;
factory.featuredGamesVersion = featuredGamesVersion;
factory.recentGamesVersion = recentGamesVersion;
factory.leagueVersion = leagueVersion;
factory.staticDataVersion = staticDataVersion;
factory.statsVersion = statsVersion;
factory.statusVersion = statusVersion;
factory.matchVersion = matchVersion;
factory.matchlistVersion = matchlistVersion;
factory.summonerVersion = summonerVersion;
factory.teamVersion = teamVersion;
factory.proxy = proxy;
factory.autoRetry = autoRetry;
factory.retryCount = retryCount;
return factory;
}
}
}
| mit |
avedensky/JavaRushTasks | 2.JavaCore/src/com/javarush/task/task12/task1211/Solution.java | 355 | package com.javarush.task.task12.task1211;
/*
Абстрактный класс Pet
Сделать класс Pet абстрактным.
*/
public class Solution {
public static void main(String[] args) {
}
public abstract static class Pet {
public String getName() {
return "Я - котенок";
}
}
}
| mit |
alexsomai/external-workspace-manager-plugin | src/main/java/org/jenkinsci/plugins/ewm/facets/WorkspaceBrowserFacet.java | 878 | package org.jenkinsci.plugins.ewm.facets;
import hudson.model.Fingerprint;
import jenkins.model.FingerprintFacet;
import org.jenkinsci.plugins.ewm.model.ExternalWorkspace;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import javax.annotation.Nonnull;
/**
* {@link FingerprintFacet} implementation that holds the {@link ExternalWorkspace} metadata.
*
* @author Alexandru Somai
*/
public class WorkspaceBrowserFacet extends FingerprintFacet {
private final ExternalWorkspace workspace;
public WorkspaceBrowserFacet(@Nonnull Fingerprint fingerprint, long timestamp, @Nonnull ExternalWorkspace workspace) {
super(fingerprint, timestamp);
this.workspace = workspace;
}
@Restricted(NoExternalUse.class)
@Nonnull
public ExternalWorkspace getWorkspace() {
return workspace;
}
}
| mit |
scr/memory-mapped-hashmap | src/main/java/com/github/scr/hashmap/collections/ByteBufferCollection.java | 4924 | /*
The MIT License (MIT)
Copyright (c) 2015 Sheridan C Rawlins
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.github.scr.hashmap.collections;
import com.github.scr.hashmap.function.PrimitiveByteIterator;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.DataOutput;
import java.io.IOException;
import java.lang.reflect.Array;
import java.nio.ByteBuffer;
import java.util.Collection;
import static com.github.scr.hashmap.Constants.MAGIC;
import static com.github.scr.hashmap.Constants.VERSION;
/**
* Created by scr on 7/2/15.
*/
public class ByteBufferCollection implements IndexedCollection<Byte> {
@Nonnull
private final ByteBuffer BUFFER;
@Nullable
@Override
public Byte get(int index) {
return BUFFER.get(index);
}
@Override
public void writeOutput(DataOutput dataOutput) throws IOException {
dataOutput.writeInt(MAGIC);
dataOutput.writeInt(VERSION);
int size = BUFFER.remaining();
dataOutput.writeInt(size);
for (int i = 0; i < size; ++i) {
dataOutput.writeByte(BUFFER.get(i));
}
}
public static class BufferIterator implements PrimitiveByteIterator {
@Nonnull
private final ByteBuffer BUFFER;
public BufferIterator(ByteBuffer buffer) {
BUFFER = buffer.duplicate();
}
@Override
public boolean hasNext() {
return BUFFER.hasRemaining();
}
@Override
public byte nextByte() {
return BUFFER.get();
}
}
public ByteBufferCollection(ByteBuffer ints) {
BUFFER = ints;
}
@Override
public int size() {
return BUFFER.capacity();
}
@Override
public boolean isEmpty() {
return BUFFER.capacity() > 0;
}
@Override
public boolean contains(Object o) {
if (!(o instanceof Byte)) {
return false;
}
Byte oByte = (Byte) o;
return Iterators.contains(iterator(), oByte);
}
@Nonnull
@Override
public PrimitiveByteIterator iterator() {
return new BufferIterator(BUFFER);
}
@Nonnull
public byte[] toByteArray() {
int size = size();
byte[] ret = new byte[size];
for (int i = 0; i < size; i++) {
ret[i] = BUFFER.get(i);
}
return ret;
}
@Nonnull
@Override
public Object[] toArray() {
return Iterables.toArray(this, Byte.class);
}
@Nonnull
@Override
public <T> T[] toArray(T[] a) {
int size = size();
//noinspection unchecked
a = a.length >= size ? a : (T[]) Array.newInstance(a.getClass().getComponentType(), size);
for (int i = 0; i < size; ++i) {
Array.setByte(a, i, BUFFER.get(i));
}
return a;
}
@Override
public boolean add(Byte aByte) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> c) {
for (Object o : c) {
if (!contains(o)) {
return false;
}
}
return true;
}
@Override
public boolean addAll(Collection<? extends Byte> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public byte getByte(int index) {
return BUFFER.get(index);
}
}
| mit |
jsquared21/Intro-to-Java-Programming | Exercise_05/Exercise_05_38/Exercise_05_38.java | 732 | /*
(Decimal to octal) Write a program that prompts the user to enter a decimal
integer and displays its corresponding octal value. Don’t use Java’s Integer
.toOctalString(int) in this program.
*/
import java.util.Scanner;
public class Exercise_05_38 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // Create a Scanner
// Prompt the user to enter a decimal integer
System.out.print("Enter a decimal integer: ");
int decimal = input.nextInt();
// Convet decimal to octal
String octal = ""; // Hold octal value
for (int i = decimal; i > 0; i /= 8) {
octal = i % 8 + octal;
}
// Display results
System.out.println("The octal of " + decimal + " is " + octal);
}
} | mit |
SpongePowered/Sponge | src/main/java/org/spongepowered/common/world/volume/buffer/archetype/AbstractReferentArchetypeVolume.java | 14784 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.world.volume.buffer.archetype;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.block.entity.BlockEntityArchetype;
import org.spongepowered.api.entity.EntityArchetype;
import org.spongepowered.api.fluid.FluidState;
import org.spongepowered.api.util.Axis;
import org.spongepowered.api.util.mirror.Mirror;
import org.spongepowered.api.util.mirror.Mirrors;
import org.spongepowered.api.util.rotation.Rotation;
import org.spongepowered.api.util.transformation.Transformation;
import org.spongepowered.api.world.biome.Biome;
import org.spongepowered.api.world.volume.Volume;
import org.spongepowered.api.world.volume.archetype.ArchetypeVolume;
import org.spongepowered.api.world.volume.archetype.block.entity.BlockEntityArchetypeVolume;
import org.spongepowered.api.world.volume.archetype.entity.EntityArchetypeEntry;
import org.spongepowered.api.world.volume.archetype.entity.EntityArchetypeVolume;
import org.spongepowered.api.world.volume.biome.BiomeVolume;
import org.spongepowered.api.world.volume.block.BlockVolume;
import org.spongepowered.api.world.volume.stream.StreamOptions;
import org.spongepowered.api.world.volume.stream.VolumeElement;
import org.spongepowered.api.world.volume.stream.VolumePositionTranslators;
import org.spongepowered.api.world.volume.stream.VolumeStream;
import org.spongepowered.common.util.MemoizedSupplier;
import org.spongepowered.common.world.volume.VolumeStreamUtils;
import org.spongepowered.math.vector.Vector3d;
import org.spongepowered.math.vector.Vector3i;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class AbstractReferentArchetypeVolume<A extends ArchetypeVolume> implements ArchetypeVolume {
protected final Supplier<A> reference;
protected final Transformation transformation;
protected AbstractReferentArchetypeVolume(final Supplier<A> reference, final Transformation transformation) {
this.reference = MemoizedSupplier.memoize(reference);
this.transformation = transformation;
}
public final Transformation transformation() {
return this.transformation;
}
protected <T> T applyReference(final Function<A, T> function) {
final @Nullable A archetypeVolume = this.reference.get();
Objects.requireNonNull(archetypeVolume, "ArchetypeVolume reference lost");
return function.apply(archetypeVolume);
}
protected void consumeReference(final Consumer<A> function) {
final @Nullable A archetypeVolume = this.reference.get();
Objects.requireNonNull(archetypeVolume, "ArchetypeVolume reference lost");
function.accept(archetypeVolume);
}
public Vector3i inverseTransform(final double x, final double y, final double z) {
return this.transformation.inverse()
.transformPosition(new Vector3d(x, y, z))
.toInt();
}
protected Vector3i transformBlockSizes(final Vector3i min, final Vector3i max, final BiFunction<Vector3i, Vector3i, Vector3i> minmax) {
final Vector3d rawBlockMin = min.toDouble().add(VolumePositionTranslators.BLOCK_OFFSET);
final Vector3i transformedMin = this.transformation.transformPosition(rawBlockMin)
.sub(VolumePositionTranslators.BLOCK_OFFSET)
.toInt();
final Vector3d rawBlockMax = max.toDouble().add(VolumePositionTranslators.BLOCK_OFFSET);
final Vector3i transformedMax = this.transformation.transformPosition(rawBlockMax)
.sub(VolumePositionTranslators.BLOCK_OFFSET)
.toInt();
return minmax.apply(transformedMin, transformedMax);
}
protected Vector3i transformBlockSize(final BiFunction<Vector3i, Vector3i, Vector3i> minmax) {
return this.applyReference(a -> this.transformBlockSizes(a.min(), a.max(), minmax));
}
protected Vector3d transformStreamBlockPosition(final Vector3d blockPosition) {
// we assume that the position is already center adjusted, but since
// we're not going to want to "flatten" the positions, we need to correctly
// round and then re-add the offset post transformation
return this.transformation.transformPosition(blockPosition);
}
@Override
public Vector3i min() {
return this.transformBlockSize(Vector3i::min);
}
@Override
public Vector3i max() {
return this.transformBlockSize(Vector3i::max);
}
@Override
public Vector3i size() {
return this.applyReference(ArchetypeVolume::size);
}
@Override
public boolean contains(final int x, final int y, final int z) {
final Vector3i transformed = this.inverseTransform(x, y, z);
return this.applyReference(a -> a.contains(transformed.x(), transformed.y(), transformed.z()));
}
@Override
public boolean isAreaAvailable(final int x, final int y, final int z) {
final Vector3i transformed = this.inverseTransform(x, y, z);
return this.applyReference(a -> a.isAreaAvailable(transformed.x(), transformed.y(), transformed.z()));
}
@Override
public ArchetypeVolume transform(final Transformation transformation) {
return new ReferentArchetypeVolume(
this, Objects.requireNonNull(transformation, "Transformation cannot be null"));
}
@Override
public Optional<BlockEntityArchetype> blockEntityArchetype(
final int x, final int y, final int z
) {
final Vector3i transformed = this.inverseTransform(x, y, z);
return this.applyReference(a -> a.blockEntityArchetype(transformed.x(), transformed.y(), transformed.z()));
}
@Override
public Map<Vector3i, BlockEntityArchetype> blockEntityArchetypes() {
return this.applyReference(a -> a.blockEntityArchetypes().entrySet().stream()
.collect(
Collectors.toMap(
e -> this.transformation.transformPosition(e.getKey().toDouble()).toInt(),
Map.Entry::getValue
)));
}
@Override
public VolumeStream<ArchetypeVolume, BlockEntityArchetype> blockEntityArchetypeStream(
final Vector3i min, final Vector3i max, final StreamOptions options
) {
return this.applyTransformationsToStream(
min,
max,
options,
BlockEntityArchetypeVolume.Streamable::blockEntityArchetypeStream,
(e, rotation, mirror) -> e.type()
);
}
@Override
public void addBlockEntity(final int x, final int y, final int z, final BlockEntityArchetype archetype) {
final Vector3i transformed = this.inverseTransform(x, y, z);
this.consumeReference(a -> a.addBlockEntity(transformed.x(), transformed.y(), transformed.z(), archetype));
}
@Override
public void removeBlockEntity(final int x, final int y, final int z) {
final Vector3i transformed = this.inverseTransform(x, y, z);
this.consumeReference(a -> a.removeBlockEntity(transformed.x(), transformed.y(), transformed.z()));
}
@Override
public Collection<EntityArchetype> entityArchetypes() {
return this.applyReference(EntityArchetypeVolume::entityArchetypes);
}
@Override
public Collection<EntityArchetypeEntry> entityArchetypesByPosition() {
return this.applyReference(a -> a.entityArchetypesByPosition()
.stream()
.map(e -> EntityArchetypeEntry.of(e.archetype(), this.transformation.transformPosition(e.position())))
.collect(Collectors.toList())
);
}
@Override
public Collection<EntityArchetype> entityArchetypes(
final Predicate<EntityArchetype> filter
) {
return this.applyReference(e -> e.entityArchetypes(filter));
}
@Override
public VolumeStream<ArchetypeVolume, EntityArchetype> entityArchetypeStream(
final Vector3i min, final Vector3i max, final StreamOptions options
) {
return this.applyTransformationsToStream(
min,
max,
options,
EntityArchetypeVolume.Streamable::entityArchetypeStream,
(e, rotation, mirror) -> e.type()
);
}
@Override
public Stream<EntityArchetypeEntry> entitiesByPosition() {
return this.applyReference(a -> a.entityArchetypesByPosition()
.stream()
.map(e -> EntityArchetypeEntry.of(e.archetype(), this.transformation.transformPosition(e.position())))
);
}
@Override
public void addEntity(final EntityArchetypeEntry entry) {
final Vector3d position = entry.position();
final Vector3i transformed = this.inverseTransform(position.x(), position.y(), position.z());
this.consumeReference(a -> a.addEntity(entry.archetype(), transformed.toDouble()));
}
@Override
public Biome biome(final int x, final int y, final int z) {
final Vector3i transformed = this.inverseTransform(x, y, z);
return this.applyReference(a -> a.biome(transformed.x(), transformed.y(), transformed.z()));
}
@Override
public VolumeStream<ArchetypeVolume, Biome> biomeStream(
final Vector3i min, final Vector3i max, final StreamOptions options
) {
return this.applyTransformationsToStream(
min,
max,
options,
BiomeVolume.Streamable::biomeStream,
(e, rotation, mirror) -> e.type()
);
}
@Override
public boolean setBiome(final int x, final int y, final int z, final Biome biome) {
final Vector3i transformed = this.inverseTransform(x, y, z);
return this.applyReference(a -> a.setBiome(transformed.x(), transformed.y(), transformed.z(), biome));
}
@Override
public BlockState block(final int x, final int y, final int z) {
final Vector3i transformed = this.inverseTransform(x, y, z);
return this.applyReference(a -> a.block(transformed.x(), transformed.y(), transformed.z()));
}
@Override
public FluidState fluid(final int x, final int y, final int z) {
final Vector3i transformed = this.inverseTransform(x, y, z);
return this.applyReference(a -> a.fluid(transformed.x(), transformed.y(), transformed.z()));
}
@Override
public int highestYAt(final int x, final int z) {
final Vector3i transformed = this.inverseTransform(x, 0, z);
return this.applyReference(a -> a.highestYAt(transformed.x(), transformed.z()));
}
@Override
public VolumeStream<ArchetypeVolume, BlockState> blockStateStream(
final Vector3i min, final Vector3i max, final StreamOptions options
) {
return this.applyTransformationsToStream(
min,
max,
options,
BlockVolume.Streamable::blockStateStream,
(e, rotation, mirror) -> e.type()
.mirror(mirror)
.rotate(rotation)
);
}
@Override
public boolean setBlock(final int x, final int y, final int z, final BlockState block) {
final Vector3i transformed = this.inverseTransform(x, y, z);
return this.applyReference(a -> a.setBlock(transformed.x(), transformed.y(), transformed.z(), block));
}
@Override
public boolean removeBlock(final int x, final int y, final int z) {
final Vector3i transformed = this.inverseTransform(x, y, z);
return this.applyReference(a -> a.removeBlock(transformed.x(), transformed.y(), transformed.z()));
}
protected interface StreamCreator<TA extends Volume, SE> {
VolumeStream<ArchetypeVolume, SE> createStream(
TA targetVolume,
Vector3i min,
Vector3i max,
StreamOptions options
);
}
private <T> VolumeStream<ArchetypeVolume, T> applyTransformationsToStream(
final Vector3i min,
final Vector3i max,
final StreamOptions options,
final StreamCreator<A, T> streamCreator,
final VolumeStreamUtils.TriFunction<VolumeElement<ArchetypeVolume, T>, Supplier<Rotation>, Supplier<Mirror>, T> elementTransform
) {
final Vector3i transformedMin = this.min();
final Vector3i transformedMax = this.max();
VolumeStreamUtils.validateStreamArgs(min, max, transformedMin, transformedMax, options);
final Vector3i minDiff = min.sub(transformedMin);
final Vector3i maxDiff = transformedMax.sub(max);
final boolean xMirror = this.transformation.mirror(Axis.X);
final boolean zMirror = this.transformation.mirror(Axis.Z);
final Supplier<Mirror> mirror = xMirror
? Mirrors.FRONT_BACK
: zMirror ? Mirrors.LEFT_RIGHT : Mirrors.NONE;
return this.applyReference(a -> streamCreator.createStream(a, a.min().add(minDiff), a.max().sub(maxDiff), options))
.transform(e -> VolumeElement.of(
this,
elementTransform.apply(e, this.transformation::rotation, mirror),
this.transformStreamBlockPosition(e.position().add(VolumePositionTranslators.BLOCK_OFFSET)).sub(VolumePositionTranslators.BLOCK_OFFSET)
));
}
}
| mit |
calle2010/testJpa | testJpa/src/test/java/testJpa/spring/table/dao/SpringTableTest.java | 6094 | package testJpa.spring.table.dao;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.ExpectedDatabase;
import com.github.springtestdbunit.assertion.DatabaseAssertionMode;
import testJpa.TestJpaTestConfiguration;
import testJpa.spring.table.domain.SpringTable;
/**
* Test CRUD functionality of a simple table without relationships.
* <p>
* This class uses DBUnit for database setup and verification of results. All
* changes are rolled back at the end of a test method.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestJpaTestConfiguration.class)
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
TransactionDbUnitTestExecutionListener.class })
@Transactional
public class SpringTableTest {
@Autowired
SpringTableDao dao;
@PersistenceContext
EntityManager em;
private static final Logger LOGGER = LoggerFactory.getLogger(SpringTableTest.class);
@Test
@DatabaseSetup("setup_SpringTable.xml")
public void testCount() {
assertEquals(3, dao.count());
}
@Test
@DatabaseSetup("setup_SpringTable.xml")
@ExpectedDatabase(value = "expect_SpringTable_created.xml", assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED)
public void testCreate() {
final SpringTable st = new SpringTable();
st.setData("new entry");
final SpringTable stPersisted = dao.save(st);
assertNotEquals(0, stPersisted.getId().longValue());
assertEquals(4, dao.count());
}
@Test
@DatabaseSetup("setup_SpringTable.xml")
public void testExists() {
assertTrue(dao.exists(10001000l));
}
@Test
@DatabaseSetup("setup_SpringTable.xml")
public void testExistsFailing() {
assertFalse(dao.exists(999l));
}
@Test
@DatabaseSetup("setup_SpringTable.xml")
public void testFindAll() {
final Iterable<SpringTable> allEntries = dao.findAll();
final List<SpringTable> list = new ArrayList<>();
for (final SpringTable st : allEntries) {
list.add(st);
}
assertEquals(3, list.size());
}
@Test
@DatabaseSetup("setup_SpringTable.xml")
public void testFindByData() {
final List<SpringTable> list = dao.findByData("one thousand");
assertEquals(1, list.size());
assertEquals(10001000, list.get(0).getId().longValue());
}
@Test
@DatabaseSetup("setup_SpringTable.xml")
public void testFindByDataFailing() {
final Iterable<SpringTable> entities = dao.findByData("does not exist");
final Iterator<SpringTable> ei = entities.iterator();
assertFalse(ei.hasNext());
}
@Test
@DatabaseSetup("setup_SpringTable.xml")
public void testFindById() {
final SpringTable entity = dao.findOne(10001000l);
assertEquals(10001000, entity.getId().longValue());
assertEquals("one thousand", entity.getData());
}
@Test
@DatabaseSetup("setup_SpringTable.xml")
public void testFindByIdFailing() {
assertNull(dao.findOne(999l));
}
@Test
@DatabaseSetup("setup_SpringTable_empty.xml")
public void testIsEmpty() {
assertTrue(dao.isEmpty());
}
@Test
@DatabaseSetup("setup_SpringTable.xml")
public void testisNotEmpty() {
assertFalse(dao.isEmpty());
}
@Test
@DatabaseSetup("setup_SpringTable.xml")
@ExpectedDatabase(value = "expect_SpringTable_deleted.xml", assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED)
public void testRemoveManaged() {
final SpringTable st = dao.findOne(10001000l);
assertNotNull("entity to delete must not be null", st);
dao.delete(st);
assertNull("most not find deleted entity", dao.findOne(10001000l));
assertEquals("must be one entry less", 2, dao.count());
em.flush();
}
@Test
@DatabaseSetup("setup_SpringTable.xml")
@ExpectedDatabase(value = "expect_SpringTable_updated.xml", assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED)
public void testUpdateManaged() {
LOGGER.info("start test update managed");
final SpringTable st = dao.findOne(10001000l);
st.setData("updated");
em.flush();
LOGGER.info("end test update managed");
}
@Test
@DatabaseSetup("setup_SpringTable.xml")
@ExpectedDatabase(value = "expect_SpringTable_updated.xml", assertionMode = DatabaseAssertionMode.NON_STRICT_UNORDERED)
public void testUpdateUnmanaged() {
LOGGER.info("start test update unmanaged");
final SpringTable st = new SpringTable();
st.setId(10001000l);
st.setData("updated");
dao.save(st);
em.flush();
LOGGER.info("end test update unmanaged");
}
}
| mit |
rafaelph/work-mode-android | app/src/test/java/com/rafaelkarlo/workmode/mainscreen/service/alarm/WorkModeAlarmOnBootSchedulerTest.java | 3887 | package com.rafaelkarlo.workmode.mainscreen.service.alarm;
import android.content.Context;
import com.rafaelkarlo.workmode.MainApplication;
import com.rafaelkarlo.workmode.mainscreen.config.MainActivityComponent;
import com.rafaelkarlo.workmode.mainscreen.service.WorkModeService;
import com.rafaelkarlo.workmode.mainscreen.service.time.WorkTimeServiceImpl;
import org.joda.time.LocalTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class WorkModeAlarmOnBootSchedulerTest {
@Mock
private WorkTimeServiceImpl workTimeService;
@Mock
private WorkModeAlarmImpl workModeAlarm;
@Mock
private WorkModeService workModeService;
@Mock
private Context context;
@Mock
private MainApplication mainApplication;
@Mock
private MainActivityComponent mainActivityComponent;
private WorkModeAlarmOnBootScheduler workModeAlarmOnBootScheduler;
@Before
public void setup() {
workModeAlarmOnBootScheduler = new WorkModeAlarmOnBootScheduler();
workModeAlarmOnBootScheduler.setWorkTimeService(workTimeService);
workModeAlarmOnBootScheduler.setAlarmService(workModeAlarm);
workModeAlarmOnBootScheduler.setWorkModeService(workModeService);
setupDaggerMocks();
}
@After
public void verifyDependenciesHaveBeenInjected() {
verify(mainApplication).getMainActivityComponent();
verify(mainActivityComponent).inject(workModeAlarmOnBootScheduler);
}
@Test
public void shouldSetTheAlarmsForWorkModeOnBootWhenActivated() {
LocalTime startWorkTime = new LocalTime(9, 0, 0);
LocalTime endWorkTime = new LocalTime(17, 0, 0);
when(workTimeService.getStartWorkTime()).thenReturn(startWorkTime);
when(workTimeService.getEndWorkTime()).thenReturn(endWorkTime);
when(workModeService.isActivated()).thenReturn(true);
workModeAlarmOnBootScheduler.onReceive(context, null);
verify(workModeAlarm).startAlarm(startWorkTime, endWorkTime);
}
@Test
public void shouldNotSetTheAlarmsWhenDeactivated() {
LocalTime startWorkTime = new LocalTime(9, 0, 0);
LocalTime endWorkTime = new LocalTime(17, 0, 0);
when(workTimeService.getStartWorkTime()).thenReturn(startWorkTime);
when(workTimeService.getEndWorkTime()).thenReturn(endWorkTime);
when(workModeService.isActivated()).thenReturn(false);
workModeAlarmOnBootScheduler.onReceive(context, null);
verifyZeroInteractions(workModeAlarm);
}
@Test
public void shouldNotSetAlarmWhenStartWorkTimeIsNull() {
LocalTime endWorkTime = new LocalTime(17, 0, 0);
when(workTimeService.getStartWorkTime()).thenReturn(null);
when(workTimeService.getEndWorkTime()).thenReturn(endWorkTime);
workModeAlarmOnBootScheduler.onReceive(context, null);
verifyNoMoreInteractions(workModeAlarm);
}
@Test
public void shouldNotSetAlarmWhenEndWorkTimeIsNull() {
LocalTime startWorkTime = new LocalTime(9, 0, 0);
when(workTimeService.getEndWorkTime()).thenReturn(null);
when(workTimeService.getStartWorkTime()).thenReturn(startWorkTime);
workModeAlarmOnBootScheduler.onReceive(context, null);
verifyNoMoreInteractions(workModeAlarm);
}
private void setupDaggerMocks() {
when(context.getApplicationContext()).thenReturn(mainApplication);
when(mainApplication.getMainActivityComponent()).thenReturn(mainActivityComponent);
}
} | mit |
janzoner/DBFlow | dbflow-tests/src/test/java/com/raizlabs/android/dbflow/test/sql/PropertyFactoryTest.java | 4304 | package com.raizlabs.android.dbflow.test.sql;
import com.raizlabs.android.dbflow.sql.QueryBuilder;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.raizlabs.android.dbflow.sql.language.Where;
import com.raizlabs.android.dbflow.sql.language.property.ByteProperty;
import com.raizlabs.android.dbflow.sql.language.property.CharProperty;
import com.raizlabs.android.dbflow.sql.language.property.DoubleProperty;
import com.raizlabs.android.dbflow.sql.language.property.FloatProperty;
import com.raizlabs.android.dbflow.sql.language.property.IntProperty;
import com.raizlabs.android.dbflow.sql.language.property.Property;
import com.raizlabs.android.dbflow.sql.language.property.PropertyFactory;
import com.raizlabs.android.dbflow.test.FlowTestCase;
import com.raizlabs.android.dbflow.test.structure.TestModel1;
import com.raizlabs.android.dbflow.test.structure.TestModel1_Table;
import com.raizlabs.android.dbflow.test.structure.TestModel2;
import com.raizlabs.android.dbflow.test.structure.TestModel2_Table;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Description:
*/
public class PropertyFactoryTest extends FlowTestCase {
@Test
public void testPropertyFactory() {
long time = System.currentTimeMillis();
Where<TestModel2> delete = SQLite.delete(TestModel2.class)
.where(TestModel2_Table.model_order.plus(PropertyFactory.from(5)).lessThan((int) time));
assertEquals("DELETE FROM `TestModel2` WHERE `model_order` + 5<" + (int) time, delete.getQuery().trim());
CharProperty charProperty = PropertyFactory.from('c');
assertEquals("'c'", charProperty.getQuery());
QueryBuilder queryBuilder = new QueryBuilder();
charProperty.between('d').and('e').appendConditionToQuery(queryBuilder);
assertEquals("'c' BETWEEN 'd' AND 'e'", queryBuilder.getQuery().trim());
Property<String> stringProperty = PropertyFactory.from("MyGirl");
assertEquals("'MyGirl'", stringProperty.getQuery());
queryBuilder = new QueryBuilder();
stringProperty.concatenate("Talkin' About").appendConditionToQuery(queryBuilder);
assertEquals("'MyGirl'='MyGirl' || 'Talkin'' About'", queryBuilder.getQuery().trim());
ByteProperty byteProperty = PropertyFactory.from((byte) 5);
assertEquals("5", byteProperty.getQuery());
queryBuilder = new QueryBuilder();
byteProperty.in((byte) 6, (byte) 7, (byte) 8, (byte) 9).appendConditionToQuery(queryBuilder);
assertEquals("5 IN (6,7,8,9)", queryBuilder.getQuery().trim());
IntProperty intProperty = PropertyFactory.from(5);
assertEquals("5", intProperty.getQuery());
queryBuilder = new QueryBuilder();
intProperty.greaterThan(TestModel2_Table.model_order).appendConditionToQuery(queryBuilder);
assertEquals("5>`model_order`", queryBuilder.getQuery().trim());
DoubleProperty doubleProperty = PropertyFactory.from(10d);
assertEquals("10.0", doubleProperty.getQuery());
queryBuilder = new QueryBuilder();
doubleProperty.plus(ConditionModel_Table.fraction).lessThan(ConditionModel_Table.fraction).appendConditionToQuery(queryBuilder);
assertEquals("10.0 + `fraction`<`fraction`", queryBuilder.getQuery().trim());
FloatProperty floatProperty = PropertyFactory.from(20f);
assertEquals("20.0", floatProperty.getQuery());
queryBuilder = new QueryBuilder();
floatProperty.minus(ConditionModel_Table.floatie).minus(ConditionModel_Table.floatie).eq(5f).appendConditionToQuery(queryBuilder);
Property<TestModel1> model1Property = PropertyFactory.from(
SQLite.select().from(TestModel1.class).where(TestModel1_Table.name.eq("Test"))).as("Cool");
assertEquals("(SELECT * FROM `TestModel1` WHERE `name`='Test' ) AS `Cool`", model1Property.getDefinition());
queryBuilder = new QueryBuilder();
model1Property.minus(ConditionModel_Table.fraction).plus(TestModel1_Table.name.withTable()).like("%somethingnotvalid%").appendConditionToQuery(queryBuilder);
assertEquals("(SELECT * FROM `TestModel1` WHERE `name`='Test' ) - `fraction` + `TestModel1`.`name` LIKE '%somethingnotvalid%'", queryBuilder.getQuery().trim());
}
}
| mit |
shaunmahony/seqcode | src/edu/psu/compbio/seqcode/gse/datasets/function/TextFunctionLoader.java | 7272 | /*
* Created on Nov 19, 2007
*
* TODO
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package edu.psu.compbio.seqcode.gse.datasets.function;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.io.*;
import edu.psu.compbio.seqcode.gse.datasets.function.parsing.*;
public class TextFunctionLoader implements FunctionLoader {
public static void main(String[] args) {
try {
File obo = new File(args[0]);
TextFunctionLoader loader = new TextFunctionLoader(obo);
FunctionVersion version = loader.getVersion(obo.getName());
loader.addGOAFile(new File(args[1]));
System.out.print(">"); System.out.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while((line = br.readLine()) != null) {
line = line.trim();
Category c = loader.getCategory(line);
Collection<Assignment> assigns = loader.getAssignments(c);
for(Assignment a : assigns) {
System.out.println(String.format("\t%s --> %s (%s)",
a.getObject(), a.getCategory().getName(),
a.getCategory().getDescription()));
}
System.out.println(String.format("# Assigns: %d", assigns.size()));
System.out.print(">"); System.out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private FunctionVersion version;
private Set<Category> categories;
private Set<Assignment> assignments;
private Map<String,Category> categoryMap;
private Map<Category,Set<Category>> categoryChildren;
private Map<Category,Set<Assignment>> categoryAssignments;
private Map<String,Set<Assignment>> objectAssignments;
public TextFunctionLoader(File oboFile) throws IOException {
version = new FunctionVersion(oboFile.getName());
categories = new LinkedHashSet<Category>();
assignments = new LinkedHashSet<Assignment>();
categoryChildren = new HashMap<Category,Set<Category>>();
categoryAssignments = new HashMap<Category,Set<Assignment>>();
objectAssignments = new HashMap<String,Set<Assignment>>();
categoryMap = new HashMap<String,Category>();
loadOBOFile(oboFile);
}
public Category getCategory(String cname) { return categoryMap.get(cname); }
public Category getCategory(FunctionVersion fv, String cname) { return categoryMap.get(cname); }
private void loadOBOFile(File f) throws IOException {
OBOParser parser = new OBOParser(f);
ProvisionalGOTerm[] terms = parser.createGOTerms();
for(int i = 0; i < terms.length; i++) {
ProvisionalGOTerm term = terms[i];
Category c = new Category(version, term.getID(), term.getName());
categories.add(c);
categoryMap.put(term.getID(), c);
}
for(int i = 0; i < terms.length; i++) {
ProvisionalGOTerm term = terms[i];
Category c = categoryMap.get(term.getID());
for(ProvisionalGOTerm pterm : term.getParents()) {
Category pc = categoryMap.get(pterm.getID());
c.addParent(pc);
if(!categoryChildren.containsKey(pc)) {
categoryChildren.put(pc, new HashSet<Category>());
}
categoryChildren.get(pc).add(c);
}
}
}
public void addGOAFile(File goa) throws IOException {
GOAIterator itr = new GOAIterator(goa);
while(itr.hasNext()) {
GOALine line = itr.next();
Category c = categoryMap.get(line.getGOID());
if(c != null) {
addAssignment(new Assignment(line.getObjectID(),c));
addAssignment(new Assignment(line.getObjectSymbol(),c));
} else {
System.err.println(String.format("Couldn't find category \"%s\"",
line.getGOID()));
}
}
}
public void addAssignment(Assignment a) {
Category c = a.getCategory();
if(!categoryAssignments.containsKey(c)) {
categoryAssignments.put(c, new HashSet<Assignment>());
}
categoryAssignments.get(c).add(a);
String obj = a.getObject();
if(!objectAssignments.containsKey(obj)) {
objectAssignments.put(obj, new HashSet<Assignment>());
}
objectAssignments.get(obj).add(a);
assignments.add(a);
}
public void close() {
// do nothing.
}
public Collection<Assignment> getAllAssignments(Category c) {
HashSet<Assignment> assigns = new HashSet<Assignment>();
HashSet<Category> seen = new HashSet<Category>();
collectAllAssignments(c, assigns, seen);
return assigns;
}
/*
* A helper method, for getAllAssignments().
*/
private void collectAllAssignments(Category c,
HashSet<Assignment> assigns,
HashSet<Category> catsSeen) {
if(!catsSeen.contains(c)) {
catsSeen.add(c);
assigns.addAll(getAssignments(c));
Collection<Category> children = getChildCategories(c);
for(Category child : children) {
collectAllAssignments(child, assigns, catsSeen);
}
}
}
public Collection<Category> getChildCategories(Category c) {
return categoryChildren.containsKey(c) ?
categoryChildren.get(c) : new LinkedList<Category>();
}
public Collection<Assignment> getAssignments(Category c) {
return categoryAssignments.containsKey(c) ?
categoryAssignments.get(c) :
new LinkedList<Assignment>();
}
public Collection<FunctionVersion> getAllVersions() {
LinkedList<FunctionVersion> vs = new LinkedList<FunctionVersion>();
vs.add(version);
return vs;
}
public Collection<Assignment> getAssignments(FunctionVersion version) {
return assignments;
}
public Collection<Assignment> getAssignments(String obj, FunctionVersion fv) {
if(fv.equals(version)) {
return objectAssignments.containsKey(obj) ?
objectAssignments.get(obj) :
new HashSet<Assignment>();
} else {
return new LinkedList<Assignment>();
}
}
public Collection<Category> getCategories(FunctionVersion fv) {
return fv.equals(version) ?
categories : new HashSet<Category>();
}
public FunctionVersion getVersion(String versionName) {
return versionName.equals(version.getName()) ?
version : null;
}
}
| mit |
tomaszpiotro/Measurement | ArduinoMeasurement/ArduinoMeasurement/arduinoMeasurement/model/Probe.java | 808 | package arduinoMeasurement.model;
import java.util.Date;
import arduinoMeasurement.mockup.SingleProbeMockup;
/**
* pojedynczy pomiar
*
* @author ferene
*/
public class Probe implements Comparable<Probe>
{
final float value;
final Date date;
public Probe(final float value)
{
this.value = value;
this.date = new Date();
}
public Probe(final float value, final Date date)
{
this.value = value;
this.date = date;
}
@Override
public int compareTo(Probe another)
{
if(this.date.before(another.date) )
{
return -1;
}
else if(this.date.after(another.date))
{
return 1;
}
return 0;
}
public float getValue()
{
return value;
}
public Date getDate()
{
return date;
}
Probe newInstance(final Probe another)
{
return new Probe(value, date);
}
}
| mit |
conveyal/analysis-backend | src/test/java/com/conveyal/analysis/TestUtils.java | 4516 | package com.conveyal.analysis;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.restassured.response.Response;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
public class TestUtils {
private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
/**
* Parse a json string into an unmapped JsonNode object
*/
public static JsonNode parseJson(String jsonString) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.readTree(jsonString);
}
/**
* Helper to return the relative path to a test resource file
*
* @param fileName
* @return
*/
public static String getResourceFileName(String fileName) {
return String.format("./src/test/resources/%s", fileName);
}
/**
* Recursively removes all specified keys. This is used to make reliable snapshots.
*/
public static void removeKeysAndValues (JsonNode json, String[] keysToRemove) {
// remove key/value pairs that are likely to have different values each test run
for (String key : keysToRemove) {
if (json.has(key)) {
((ObjectNode) json).remove(key);
}
}
// iterate through either the keys or array elements of this JsonObject/JsonArray
if (json.isArray() || json.isObject()) {
for (JsonNode nextNode : json) {
removeKeysAndValues(nextNode, keysToRemove);
}
}
}
/**
* Recursively removes all dynamically generated keys in order to perform reliable snapshots
*/
public static void removeDynamicValues(JsonNode json) {
removeKeysAndValues(json, new String[]{"_id", "createdAt", "nonce", "updatedAt"});
}
/**
* Helper method to do the parsing and checking of whether an object with a given ObjectId is present or not in a
* response that contains a list of objects
*/
public static boolean objectIdInResponse(Response response, String objectId) {
ObjectWithId[] objects = response.then()
.extract()
.as(ObjectWithId[].class);
boolean foundObject = false;
for (ObjectWithId object : objects) {
if (object._id.equals(objectId)) foundObject = true;
}
return foundObject;
}
/**
* Zip files in a folder into a temporary zip file
*/
public static String zipFolderFiles(String folderName) throws IOException {
// create temporary zip file
File tempFile = File.createTempFile("temp-gtfs-zip-", ".zip");
tempFile.deleteOnExit();
String tempFilePath = tempFile.getAbsolutePath();
// create a zip output stream for adding files to
ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(tempFilePath));
// recursively add files from a folder to the zip file
String fullFolderPath = getResourceFileName(folderName);
compressDirectoryToZipfile(fullFolderPath, fullFolderPath, zipFile);
IOUtils.closeQuietly(zipFile);
return tempFilePath;
}
private static void compressDirectoryToZipfile(
String rootDir,
String sourceDir,
ZipOutputStream out
) throws IOException {
for (File file : new File(sourceDir).listFiles()) {
if (file.isDirectory()) {
compressDirectoryToZipfile(rootDir, sourceDir + File.separator + file.getName(), out);
} else {
ZipEntry entry = new ZipEntry(sourceDir.replace(rootDir, "") + file.getName());
out.putNextEntry(entry);
FileInputStream in = new FileInputStream(file.getAbsolutePath());
IOUtils.copy(in, out);
IOUtils.closeQuietly(in);
}
}
}
/**
* Helper class for parsing json objects with the _id key.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public static class ObjectWithId {
public String _id;
public ObjectWithId() {}
}
}
| mit |
zmaster587/AdvancedRocketry | src/main/java/zmaster587/advancedRocketry/atmosphere/AtmosphereHighPressure.java | 2413 | package zmaster587.advancedRocketry.atmosphere;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import zmaster587.advancedRocketry.api.EntityRocketBase;
import zmaster587.advancedRocketry.api.capability.CapabilitySpaceArmor;
import zmaster587.advancedRocketry.entity.EntityElevatorCapsule;
import zmaster587.advancedRocketry.util.ItemAirUtils;
public class AtmosphereHighPressure extends AtmosphereType{
public AtmosphereHighPressure(boolean canTick, boolean isBreathable,
String name) {
super(canTick, isBreathable, name);
}
@Override
public String getDisplayMessage() {
return "Warning: Pressure too high!";
}
@Override
public void onTick(EntityLivingBase player) {
if(player.world.getTotalWorldTime() % 20 == 0 && !isImmune(player)) {
if(!isImmune(player)) {
player.addPotionEffect(new PotionEffect(Potion.getPotionById(2), 40, 3));
player.addPotionEffect(new PotionEffect(Potion.getPotionById(4), 40, 3));
}
}
}
@Override
public boolean isImmune(EntityLivingBase player) {
//Checks if player is wearing spacesuit or anything that extends ItemSpaceArmor
ItemStack feet = player.getItemStackFromSlot(EntityEquipmentSlot.FEET);
ItemStack leg = player.getItemStackFromSlot(EntityEquipmentSlot.LEGS /*so hot you can fry an egg*/ );
ItemStack chest = player.getItemStackFromSlot(EntityEquipmentSlot.CHEST);
ItemStack helm = player.getItemStackFromSlot(EntityEquipmentSlot.HEAD);
return (player instanceof EntityPlayer && ((((EntityPlayer)player).capabilities.isCreativeMode) || ((EntityPlayer)player).isSpectator()))
|| player.getRidingEntity() instanceof EntityRocketBase || player.getRidingEntity() instanceof EntityElevatorCapsule ||
protectsFrom(helm) && protectsFrom(leg) && protectsFrom(feet) && protectsFrom(chest);
}
public boolean protectsFrom(ItemStack stack) {
return (ItemAirUtils.INSTANCE.isStackValidAirContainer(stack) && new ItemAirUtils.ItemAirWrapper(stack).protectsFromSubstance(this, stack, true) ) || (stack != null && stack.hasCapability(CapabilitySpaceArmor.PROTECTIVEARMOR, null) &&
stack.getCapability(CapabilitySpaceArmor.PROTECTIVEARMOR, null).protectsFromSubstance(this, stack, true));
}
}
| mit |
rekbun/leetcode | src/leetcode/FindSumOfPath.java | 479 | package leetcode;
/*
http://oj.leetcode.com/problems/sum-root-to-leaf-numbers/
*/
public class FindSumOfPath {
public int sumNumbers(TreeNode root) {
if(root==null) {
return 0;
}
return sumNumbersUtil(root,0);
}
public int sumNumbersUtil(TreeNode root,int num) {
if(root==null) {
return 0;
}
num=num*10+root.val;
if(root.left==null && root.right==null) {
return num;
}
return sumNumbersUtil(root.left,num)+sumNumbersUtil(root.right,num);
}
}
| mit |
jgaltidor/VarJ | analyzed_libs/jdk1.6.0_06_src/java/lang/reflect/TypeVariable.java | 2908 | /*
* @(#)TypeVariable.java 1.5 05/11/30
*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.lang.reflect;
/**
* TypeVariable is the common superinterface for type variables of kinds.
* A type variable is created the first time it is needed by a reflective
* method, as specified in this package. If a type variable t is referenced
* by a type (i.e, class, interface or annotation type) T, and T is declared
* by the nth enclosing class of T (see JLS 8.1.2), then the creation of t
* requires the resolution (see JVMS 5) of the ith enclosing class of T,
* for i = 0 to n, inclusive. Creating a type variable must not cause the
* creation of its bounds. Repeated creation of a type variable has no effect.
*
* <p>Multiple objects may be instantiated at run-time to
* represent a given type variable. Even though a type variable is
* created only once, this does not imply any requirement to cache
* instances representing the type variable. However, all instances
* representing a type variable must be equal() to each other.
* As a consequence, users of type variables must not rely on the identity
* of instances of classes implementing this interface.
*
* @param <D> the type of generic declaration that declared the
* underlying type variable.
*
* @since 1.5
*/
public interface TypeVariable<D extends GenericDeclaration> extends Type {
/**
* Returns an array of <tt>Type</tt> objects representing the
* upper bound(s) of this type variable. Note that if no upper bound is
* explicitly declared, the upper bound is <tt>Object</tt>.
*
* <p>For each upper bound B: <ul> <li>if B is a parameterized
* type or a type variable, it is created, (see {@link
* java.lang.reflect.ParameterizedType ParameterizedType} for the
* details of the creation process for parameterized types).
* <li>Otherwise, B is resolved. </ul>
*
* @throws TypeNotPresentException if any of the
* bounds refers to a non-existent type declaration
* @throws MalformedParameterizedTypeException if any of the
* bounds refer to a parameterized type that cannot be instantiated
* for any reason
* @return an array of <tt>Type</tt>s representing the upper
* bound(s) of this type variable
*/
Type[] getBounds();
/**
* Returns the <tt>GenericDeclaration</tt> object representing the
* generic declaration declared this type variable.
*
* @return the generic declaration declared for this type variable.
*
* @since 1.5
*/
D getGenericDeclaration();
/**
* Returns the name of this type variable, as it occurs in the source code.
*
* @return the name of this type variable, as it appears in the source code
*/
String getName();
}
| mit |
oxygenxml/webapp-webdav-integration | src/main/java/com/oxygenxml/examples/webdav/TranslationTags.java | 1468 | package com.oxygenxml.examples.webdav;
public interface TranslationTags {
/**
* Label for input. Used in WebDAV plugin configuration.
*
* en: Lock resources on open
*/
String LOCK_RESOURCES_ON_OPEN = "Lock_resources_on_open";
/**
* Label for input. Used in WebDAV plugin configuration.
*
* en: Autosave interval
*/
String AUTOSAVE_INTERVAL = "Autosave_interval";
/**
* Complements the 'Autosave interval' input. Used in WebDAV plugin configuration.
*
* en: seconds
*/
String SECONDS = "Seconds";
/**
* Placeholder for input. Used in WebDAV plugin configuration.
*
* en: Server URL
*/
String SERVER_URL = "Server_URL";
/**
* Label for input. Used in WebDAV plugin configuration.
*
* en: Enforced server
*/
String ENFORCED_SERVER = "Enforced_server";
/**
* Warning for the 'Enforce server' setting. Used in WebDAV plugin configuration.
*
* en: Note: Once a server is enforced, the user will only be able to browse this enforced server.
* However, it is possible for other plugins to add more enforced servers for the user to choose from.
*/
String ENFORCED_SERVER_NOTE = "Enforced_server_note";
/**
* Title of login dialog.
*
* en: Authentication required
*/
String AUTHENTICATION_REQUIRED = "Authentication_required";
/**
* Default author name for comments.
*
* en: Anonymous
*/
String ANONYMOUS = "Anonymous";
}
| mit |
jedgren/java-web-server | src/main/java/se/enelefant/handler/StatusHandler.java | 662 | package se.enelefant.handler;
import com.sun.net.httpserver.HttpExchange;
import se.enelefant.core.annotation.HandlerEndpoint;
import se.enelefant.core.annotation.ResponseStatus;
import se.enelefant.core.enums.HttpStatus;
import se.enelefant.core.enums.RequestMethod;
import se.enelefant.core.handler.WebServerHandler;
import java.io.IOException;
public class StatusHandler extends WebServerHandler {
@Override
@HandlerEndpoint(value = "/status", method = RequestMethod.GET)
public void handleRequest(HttpExchange httpExchange) throws IOException {
String response = "Server is up";
writeResponse(response, httpExchange);
}
}
| mit |
siarhei-luskanau/siarhei.luskanau.places | data/src/main/java/siarhei/luskanau/places/data/entity/PlaceEntity.java | 5498 | /**
* Copyright (C) 2015 Fernando Cejas Open Source Project
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package siarhei.luskanau.places.data.entity;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Place Entity used in the data layer.
*/
public class PlaceEntity {
@SerializedName("address_components")
private Object addressComponents;
@SerializedName(value = "formattedAddress", alternate = "formatted_address")
private String formattedAddress;
@SerializedName("formatted_phone_number")
private String formattedPhoneNumber;
@SerializedName("geometry")
private Geometry geometry;
@SerializedName("icon")
private Object icon;
@SerializedName("international_phone_number")
private String internationalPhoneNumber;
@SerializedName("name")
private String name;
@SerializedName("opening_hours")
private Object openingHours;
@SerializedName("photos")
private List<Photo> photos;
@SerializedName("place_id")
private String placeId;
@SerializedName("scope")
private Object scope;
@SerializedName("price_level")
private Object priceLevel;
@SerializedName("rating")
private Object rating;
@SerializedName("reference")
private Object reference;
@SerializedName("reviews")
private List<Object> reviews;
@SerializedName("types")
private List<Object> types;
@SerializedName("url")
private String url;
@SerializedName("utc_offset")
private long utcOffset;
@SerializedName("vicinity")
private String vicinity;
@SerializedName("website")
private String website;
public PlaceEntity() {
//empty
}
public Object getAddressComponents() {
return addressComponents;
}
public void setAddressComponents(Object addressComponents) {
this.addressComponents = addressComponents;
}
public String getFormattedAddress() {
return formattedAddress;
}
public void setFormattedAddress(String formattedAddress) {
this.formattedAddress = formattedAddress;
}
public String getFormattedPhoneNumber() {
return formattedPhoneNumber;
}
public void setFormattedPhoneNumber(String formattedPhoneNumber) {
this.formattedPhoneNumber = formattedPhoneNumber;
}
public Geometry getGeometry() {
return geometry;
}
public void setGeometry(Geometry geometry) {
this.geometry = geometry;
}
public Object getIcon() {
return icon;
}
public void setIcon(Object icon) {
this.icon = icon;
}
public String getInternationalPhoneNumber() {
return internationalPhoneNumber;
}
public void setInternationalPhoneNumber(String internationalPhoneNumber) {
this.internationalPhoneNumber = internationalPhoneNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getOpeningHours() {
return openingHours;
}
public void setOpeningHours(Object openingHours) {
this.openingHours = openingHours;
}
public List<Photo> getPhotos() {
return photos;
}
public void setPhotos(List<Photo> photos) {
this.photos = photos;
}
public String getPlaceId() {
return placeId;
}
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
public Object getScope() {
return scope;
}
public void setScope(Object scope) {
this.scope = scope;
}
public Object getPriceLevel() {
return priceLevel;
}
public void setPriceLevel(Object priceLevel) {
this.priceLevel = priceLevel;
}
public Object getRating() {
return rating;
}
public void setRating(Object rating) {
this.rating = rating;
}
public Object getReference() {
return reference;
}
public void setReference(Object reference) {
this.reference = reference;
}
public List<Object> getReviews() {
return reviews;
}
public void setReviews(List<Object> reviews) {
this.reviews = reviews;
}
public List<Object> getTypes() {
return types;
}
public void setTypes(List<Object> types) {
this.types = types;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public long getUtcOffset() {
return utcOffset;
}
public void setUtcOffset(long utcOffset) {
this.utcOffset = utcOffset;
}
public String getVicinity() {
return vicinity;
}
public void setVicinity(String vicinity) {
this.vicinity = vicinity;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
} | mit |
InfinityRaider/Elemancy | src/main/java/com/InfinityRaider/elemancy/magic/spell/melee/SpellDecapitate.java | 1079 | package com.InfinityRaider.elemancy.magic.spell.melee;
import com.InfinityRaider.elemancy.magic.DuplicateSpellException;
import com.InfinityRaider.elemancy.magic.Element;
import com.InfinityRaider.elemancy.magic.spell.SpellMelee;
import com.InfinityRaider.elemancy.reference.Names;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
public final class SpellDecapitate extends SpellMelee {
public SpellDecapitate() throws DuplicateSpellException {
super(Element.EARTH, Element.DEATH, Names.Spells.DECAPITATE);
}
@Override
public boolean isChanneled() {
return false;
}
@Override
public void castSpell(World world, int x, int y, int z, EntityPlayer player, int lvl1, int lvl2, int channelTicks) {
}
@Override
public void onStopChannel(World world, int x, int y, int z, EntityPlayer player, int lvl1, int lvl2, int channelTicks) {
}
@Override
public void spellParticles(World world, int x, int y, int z, EntityPlayer player, int lvl1, int lvl2, int channelTicks) {
}
}
| mit |
normalian/ApplicationInsights-Java | core/src/test/java/com/microsoft/applicationinsights/extensibility/initializer/docker/internal/DockerContextPollerTests.java | 3113 | /*
* ApplicationInsights-Java
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the ""Software""), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package com.microsoft.applicationinsights.extensibility.initializer.docker.internal;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.io.File;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
/**
* Created by yonisha on 7/29/2015.
*/
public class DockerContextPollerTests {
private static File contextFileMock = mock(File.class);
private static DockerContextFactory dockerContextFactoryMock = mock(DockerContextFactory.class);
private static DockerContextPoller contextPollerUnderTest;
private static DockerContext dockerContextMock = mock(DockerContext.class);
@Before
public void testInit() throws Exception {
when(dockerContextFactoryMock.createDockerContext(any(File.class))).thenReturn(dockerContextMock);
contextPollerUnderTest = new DockerContextPoller(contextFileMock, dockerContextFactoryMock);
contextPollerUnderTest.THREAD_POLLING_INTERVAL_MS = 0;
}
@Test
public void testDockerContextInitializedIfFileExists() {
when(contextFileMock.exists()).thenReturn(true);
contextPollerUnderTest.run();
DockerContext dockerContext = contextPollerUnderTest.getDockerContext();
Assert.assertEquals(dockerContextMock, dockerContext);
}
@Test
public void testIfContextFileNotExistThenPollerTryAgain() {
final int numberOfRetries = 10;
final int[] count = {0};
Mockito.doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return ++count[0] == numberOfRetries ;
}
}).when(contextFileMock).exists();
contextPollerUnderTest.run();
verify(contextFileMock, times(numberOfRetries)).exists();
}
}
| mit |
chenyiming/learn | dubbo-app/dubbo-app-service/src/main/java/com/wangsong/system/service/impl/UserServiceImpl.java | 2500 | package com.wangsong.system.service.impl;
import java.util.List;
import java.util.UUID;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wangsong.common.service.impl.BaseServiceImpl;
import com.wangsong.system.dao.UserMapper;
import com.wangsong.system.dao.UserRoleMapper;
import com.wangsong.system.model.User;
import com.wangsong.system.model.UserRole;
import com.wangsong.system.service.UserService;
@Service("userService")
@Transactional
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService{
@Autowired
private UserMapper userMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@Override
public List<UserRole> findUserRoleByUser(User user) {
UserRole userRole=new UserRole();
userRole.setUserId(user.getId());
return userRoleMapper.findTByT(userRole);
}
@Override
public int insert(User user,String[] roleId) {
String id = UUID.randomUUID().toString();
user.setId(id);
user.setPassword(DigestUtils.md5Hex(user.getPassword()));
if(roleId!=null){
for(int i=0;i<roleId.length;i++){
UserRole userRole=new UserRole();
userRole.setId(UUID.randomUUID().toString());
userRole.setUserId(id);
userRole.setRoleId(roleId[i]);
userRoleMapper.insert(userRole);
}
}
return userMapper.insert(user);
}
@Override
public int update(User user,String[] roleId) {
if(!"".equals(user.getPassword())){
user.setPassword(DigestUtils.md5Hex(user.getPassword()));
}
UserRole userRole2=new UserRole();
userRole2.setUserId(user.getId());
userRoleMapper.deleteByT(new UserRole[]{userRole2});
if(roleId!=null){
for(int i=0;i<roleId.length;i++){
UserRole userRole=new UserRole();
userRole.setId(UUID.randomUUID().toString());
userRole.setUserId(user.getId());
userRole.setRoleId(roleId[i]);
userRoleMapper.insert(userRole);
}
}
return userMapper.updateByPrimaryKey(user);
}
@Override
public int delete(String[] id) {
UserRole[] u=new UserRole[id.length];
for(int i=0;i<id.length;i++){
UserRole user=new UserRole();
user.setUserId(id[i]);
u[i]=user;
}
userRoleMapper.deleteByT(u);
userMapper.deleteByPrimaryKey(id);
return 0;
}
@Override
public User selectByKey(String id){
User u=userMapper.selectByPrimaryKey(id);
u.setPassword("");
return u;
}
}
| mit |
dat2/jvm_backend | jvm_backend/src/main/java/com/dujay/jvm/constants/enums/ConstantTag.java | 408 | package com.dujay.jvm.constants.enums;
public enum ConstantTag {
Class(7),
Fieldref(9),
Methodref(10),
InterfaceMethodref(11),
String(8),
Integer(3),
Float(4),
Long(5),
Double(6),
NameAndType(12),
Utf8(1),
MethodHandle(15),
MethodType(16),
InvokeDynamic(18);
private int tag;
ConstantTag(int flag) {
this.tag = flag;
}
public int tag() {
return tag;
}
}
| mit |
juniormesquitadandao/report4all | lib/src/net/sf/jasperreports/util/SecretsProviderFactory.java | 1368 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JasperReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Contributors:
* Gaganis Giorgos - gaganis@users.sourceforge.net
*/
package net.sf.jasperreports.util;
/**
* @author Teodor Danciu (teodord@users.sourceforge.net)
* @version $Id: SecretsProviderFactory.java 7199 2014-08-27 13:58:10Z teodord $
*/
public interface SecretsProviderFactory
{
/**
*
*/
public SecretsProvider getSecretsProvider(String category);
}
| mit |
lolkedijkstra/xml2j-gen | samples/discogs/releases/src/main/java/com/xml2j/discogs/releases/CompanyType.java | 5378 | package com.xml2j.discogs.releases;
/******************************************************************************
-----------------------------------------------------------------------------
XML2J XSD to Java code generator
-----------------------------------------------------------------------------
This code was generated using XML2J code generator.
Version: 2.4.2
Project home: XML2J https://sourceforge.net/projects/xml2j/
Module: RELEASES
Generation date: Sun Apr 15 13:02:55 CEST 2018
Author: XML2J-Generator
******************************************************************************/
import com.xml2j.util.Compare;
import com.xml2j.xml.core.ComplexDataType;
import com.xml2j.xml.core.TypeAllocator;
/**
* CompanyType data class.
*
* This class provides getters and setters for embedded attributes and elements.
* Any complex data structure can be navigated by using the element getter methods.
*
*/
public class CompanyType extends ComplexDataType {
/**
* serial version UID
*/
private static final long serialVersionUID = 1L;
/**
* Constructor for CompanyType.
*
* @param elementName the name of the originating XML tag
* @param parent the parent data
*/
public CompanyType(String elementName, ComplexDataType parent) {
super(elementName, parent);
}
/**
* Allocator class.
*
* This class implements the generic allocator interface that is used by the framework.
* The allocator is used by the framework to instantiate type CompanyType.
*/
static class Allocator implements TypeAllocator<CompanyType> {
/**
* method for getting a new instance of type CompanyType.
*
* @param elementName the name of the originating XML tag
* @param parent the parent data
* @return new instance
*/
public CompanyType newInstance(String elementName, ComplexDataType parent) {
return new CompanyType(elementName, parent);
}
}
/** instance of allocator class for this data class. */
private static Allocator allocator = new Allocator();
/**
* Get Allocator for this data class.
* This method is used by the handler class.
*
* @return instance of Allocator
*/
static public Allocator getAllocator() {
return allocator;
}
/** element item for id element.
* @serial
*/
private String m_id = null;
/** element item for name element.
* @serial
*/
private String m_name = null;
/** element item for catno element.
* @serial
*/
private String m_catno = null;
/** element item for entity_type element.
* @serial
*/
private String m_entity_type = null;
/** element item for entity_type_name element.
* @serial
*/
private String m_entity_type_name = null;
/** element item for resource_url element.
* @serial
*/
private String m_resource_url = null;
/**
* Get the embedded Id element.
* @return the item.
*/
public String getId() {
return m_id;
}
/**
* This method sets (overwrites) the element Id.
* @param data the item that needs to be added.
*/
void setId(String data) {
m_id = data;
}
/**
* Get the embedded Name element.
* @return the item.
*/
public String getName() {
return m_name;
}
/**
* This method sets (overwrites) the element Name.
* @param data the item that needs to be added.
*/
void setName(String data) {
m_name = data;
}
/**
* Get the embedded Catno element.
* @return the item.
*/
public String getCatno() {
return m_catno;
}
/**
* This method sets (overwrites) the element Catno.
* @param data the item that needs to be added.
*/
void setCatno(String data) {
m_catno = data;
}
/**
* Get the embedded Entity_type element.
* @return the item.
*/
public String getEntity_type() {
return m_entity_type;
}
/**
* This method sets (overwrites) the element Entity_type.
* @param data the item that needs to be added.
*/
void setEntity_type(String data) {
m_entity_type = data;
}
/**
* Get the embedded Entity_type_name element.
* @return the item.
*/
public String getEntity_type_name() {
return m_entity_type_name;
}
/**
* This method sets (overwrites) the element Entity_type_name.
* @param data the item that needs to be added.
*/
void setEntity_type_name(String data) {
m_entity_type_name = data;
}
/**
* Get the embedded Resource_url element.
* @return the item.
*/
public String getResource_url() {
return m_resource_url;
}
/**
* This method sets (overwrites) the element Resource_url.
* @param data the item that needs to be added.
*/
void setResource_url(String data) {
m_resource_url = data;
}
/**
* This method compares this and that.
* @return true if this and that are the same, false otherwise.
*/
public boolean equals(Object that) {
if (!super.equals(that))
return false;
CompanyType t = (CompanyType)that;
if (!Compare.equals(m_id, t.m_id))
return false;
if (!Compare.equals(m_name, t.m_name))
return false;
if (!Compare.equals(m_catno, t.m_catno))
return false;
if (!Compare.equals(m_entity_type, t.m_entity_type))
return false;
if (!Compare.equals(m_entity_type_name, t.m_entity_type_name))
return false;
if (!Compare.equals(m_resource_url, t.m_resource_url))
return false;
return true;
}
}
| mit |
KoljaTM/Yarrn | Yarrn/src/main/java/de/vanmar/android/yarrn/ravelry/dts/Favorite.java | 590 | package de.vanmar.android.yarrn.ravelry.dts;
import com.google.gson.annotations.SerializedName;
/**
* This is a mix of several classes, since all types of favorites are returned under the same field
* <p/>
* http://www.ravelry.com/api#Project_small_result
* http://www.ravelry.com/api#Pattern_list_result
*/
public class Favorite {
public int id;
public String name;
@SerializedName("pattern_name")
public String patternName;
public int progress;
@SerializedName("first_photo")
public Photo firstPhoto;
@SerializedName("user")
public User user;
}
| mit |
devshawn/vertex-coloring | library/src/main/java/com/devshawn/coloring/library/GraphGenerator.java | 2637 | package com.devshawn.coloring.library;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GraphGenerator {
// simple graph with a given number of vertices
// an edge between any two vertices with given probability
// this is referred to as the Erdos-Renyi model
public static int[][] simple(int vertices, double probability) {
if(probability < 0 || probability > 1) {
throw new ColoringException(ColoringException.INVALID_PROBABILITY);
}
int[][] graph = new int[vertices][vertices];
for(int i = 0; i < vertices; i++) {
for(int j = 0; j < i; j++) {
int number = (Math.random() < probability) ? 1 : 0;
graph[i][j] = number;
graph[j][i] = number;
}
}
return graph;
}
public static boolean isSymmetric(int[][] graph) {
for(int i = 0; i < graph.length; i++) {
for(int j = 0; j < i; j++) {
if(graph[i][j] != graph[j][i]) {
return false;
}
}
}
return true;
}
public static int[][] matrixStringToGraph(String str) {
Scanner sc = new Scanner(str);
// Find number of vertices
Matcher m = Pattern.compile("\r\n|\r|\n").matcher(str);
int vertices = 1;
while (m.find())
{
vertices++;
}
int[][] graph = new int[vertices][];
for(int i = 0; i < vertices; i++) {
String[] line = sc.nextLine().split("");
int[] numbers = new int[vertices];
for(int j = 0; j < line.length; j++) {
numbers[j] = Integer.parseInt(line[j]);
}
graph[i] = numbers;
}
return graph;
}
public static int[][] generateAdjacencyMatrix(int vertices, List<Tuple> edges) {
int[][] graph = new int[vertices][vertices];
for(Tuple edge : edges) {
graph[edge.to][edge.from] = 1;
graph[edge.from][edge.to] = 1;
}
return graph;
}
public static String adjacencyMatrixToString(int[][] graph) {
String str = "";
for(int i = 0; i < graph.length; i++) {
for(int j = 0; j < graph.length; j++) {
str += graph[i][j];
}
str += "\n";
}
return str;
}
}
class Tuple {
public final int from;
public final int to;
public Tuple(int from, int to) {
this.from = from;
this.to = to;
}
}
| mit |
fvasquezjatar/fermat-unused | PIP/plugin/actor/fermat-pip-plugin-actor-developer-bitdubai/src/main/java/com/bitdubai/fermat_pip_plugin/layer/actor/developer/developer/bitdubai/version_1/structure/DeveloperActorLogTool.java | 9386 | package com.bitdubai.fermat_pip_plugin.layer.actor.developer.developer.bitdubai.version_1.structure;
import com.bitdubai.fermat_api.Addon;
import com.bitdubai.fermat_api.Plugin;
import com.bitdubai.fermat_api.layer.osa_android.logger_system.LogLevel;
import com.bitdubai.fermat_api.layer.all_definition.developer.LogManagerForDevelopers;
import com.bitdubai.fermat_api.layer.all_definition.enums.Addons;
import com.bitdubai.fermat_api.layer.all_definition.enums.Plugins;
import com.bitdubai.fermat_pip_api.layer.pip_actor.developer.ClassHierarchyLevels;
import com.bitdubai.fermat_pip_api.layer.pip_actor.developer.LogTool;
import com.bitdubai.fermat_pip_api.layer.pip_actor.exception.CantGetClasessHierarchyAddons;
import com.bitdubai.fermat_pip_api.layer.pip_actor.exception.CantGetClasessHierarchyPlugins;
import com.bitdubai.fermat_pip_api.layer.pip_actor.exception.CantGetDataBaseTool;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Created by ciencias on 6/25/15.
*/
public class DeveloperActorLogTool implements LogTool {
private Map<Plugins,Plugin> LoggingLstPlugins;
private Map<Addons,Addon> LoggingLstAddons;
public DeveloperActorLogTool(Map<Plugins, Plugin> LoggingLstPlugins, Map<Addons, Addon> LoggingLstAddons) {
this.LoggingLstPlugins = LoggingLstPlugins;
this.LoggingLstAddons = LoggingLstAddons;
}
@Override
public List<Plugins> getAvailablePluginList() {
List<Plugins> lstPlugins=new ArrayList<Plugins>();
for(Map.Entry<Plugins, Plugin> entry : LoggingLstPlugins.entrySet()) {
Plugins key = entry.getKey();
lstPlugins.add(key);
}
return lstPlugins;
}
@Override
public List<Addons> getAvailableAddonList() {
List<Addons> lstAddons=new ArrayList<Addons>();
for(Map.Entry<Addons, Addon> entry : LoggingLstAddons.entrySet()) {
Addons key = entry.getKey();
lstAddons.add(key);
}
return lstAddons;
}
/**
* I get from the plugin the list of classes with their full paths.
* I transform that into a class to be passed to the android App.
* @param plugin
* @return
*/
@Override
public List<ClassHierarchyLevels> getClassesHierarchyPlugins(Plugins plugin) throws CantGetClasessHierarchyPlugins{
try
{
/**
* I get the class full patch from the plug in.
*/
List<String> classes = ((LogManagerForDevelopers)this.LoggingLstPlugins.get(plugin)).getClassesFullPath();
//List<Class<?>> javaClasses = ClassFinder.find(((LogManagerForDevelopers) this.LoggingLstPlugins.get(plugin)).getClass().getPackage().getName());
/**
* I need to know the minimun number of packages on the plug in.
* If there are more than three, then I will create only three levels *
*/
int minPackages=100, cantPackages = 0;
for (String myClass : classes){
String[] packages = myClass.split(Pattern.quote("."));
cantPackages = packages.length;
if (minPackages > cantPackages)
minPackages = cantPackages;
}
/**
* minPackages holds the minimun number of packages available on the plug in.
*/
/**
* I instantiate the class that will hold the levels of the packages.
* Level 1: root (which may contain a lot of packages)
* Level 2: the last package
* Level 3: the class name.
*/
List<ClassHierarchyLevels> returnedClasses = new ArrayList<ClassHierarchyLevels>();
for (String myClass : classes) {
String[] packages = myClass.split(Pattern.quote("."));
ClassHierarchyLevels classesAndPackages = new ClassHierarchyLevels();
classesAndPackages.setLevel0(plugin.getKey());
classesAndPackages.setFullPath(myClass);
if (packages.length == minPackages) {
/**
* if this is the root, then I will add it to level2 and nothing else.
*/
classesAndPackages.setLevel1(packages[packages.length - 1]);
} else {
/**
* si no es el root, I will add the other levels.
*/
StringBuilder splitedPackages = new StringBuilder();
for (int i = 0; i < packages.length - 1; i++) {
splitedPackages.append(packages[i]);
splitedPackages.append(".");
}
/**
* I remove the last dot of the package.
*/
splitedPackages.substring(0, splitedPackages.length() - 1);
classesAndPackages.setLevel1(splitedPackages.toString());
classesAndPackages.setLevel2(packages[packages.length-1]);
}
returnedClasses.add(classesAndPackages);
}
/**
* I return the object
*/
return returnedClasses;
}
catch(Exception e)
{
throw new CantGetClasessHierarchyPlugins(CantGetClasessHierarchyPlugins.DEFAULT_MESSAGE,e,"Error to get from the plugin the list of classes with their full paths","");
}
}
/*
Created by matias, used in fragment to get loglevels
*/
@Override
public List<ClassHierarchyLevels> getClassesHierarchyAddons(Addons addon) throws CantGetClasessHierarchyAddons {
try
{
/**
* I get the class full patch from the plug in.
*/
List<String> classes = ((LogManagerForDevelopers)this.LoggingLstAddons.get(addon)).getClassesFullPath();
//List<Class<?>> javaClasses = ClassFinder.find(((LogManagerForDevelopers) this.LoggingLstPlugins.get(plugin)).getClass().getPackage().getName());
/**
* I need to know the minimun number of packages on the plug in.
* If there are more than three, then I will create only three levels *
*/
int minPackages=100, cantPackages = 0;
for (String myClass : classes){
String[] packages = myClass.split(Pattern.quote("."));
cantPackages = packages.length;
if (minPackages > cantPackages)
minPackages = cantPackages;
}
/**
* minPackages holds the minimun number of packages available on the plug in.
*/
/**
* I instantiate the class that will hold the levels of the packages.
* Level 1: root (which may contain a lot of packages)
* Level 2: the last package
* Level 3: the class name.
*/
List<ClassHierarchyLevels> returnedClasses = new ArrayList<ClassHierarchyLevels>();
for (String myClass : classes) {
String[] packages = myClass.split(Pattern.quote("."));
ClassHierarchyLevels classesAndPackages = new ClassHierarchyLevels();
classesAndPackages.setLevel0(addon.getCode());
classesAndPackages.setFullPath(myClass);
if (packages.length == minPackages) {
/**
* if this is the root, then I will add it to level2 and nothing else.
*/
classesAndPackages.setLevel1(packages[packages.length - 1]);
} else {
/**
* si no es el root, I will add the other levels.
*/
StringBuilder splitedPackages = new StringBuilder();
for (int i = 0; i < packages.length - 1; i++) {
splitedPackages.append(packages[i]);
splitedPackages.append(".");
}
/**
* I remove the last dot of the package.
*/
splitedPackages.substring(0, splitedPackages.length() - 1);
classesAndPackages.setLevel1(splitedPackages.toString());
classesAndPackages.setLevel2(packages[packages.length-1]);
}
returnedClasses.add(classesAndPackages);
}
/**
* I return the object
*/
return returnedClasses;
}
catch(Exception e)
{
throw new CantGetClasessHierarchyAddons(CantGetClasessHierarchyPlugins.DEFAULT_MESSAGE,e,"Error to get from the plugin the list of classes with their full paths","");
}
}
/**
* This sets the new level in the plug in.
* @param plugin
* @param newLogLevelInClass
*/
@Override
public void setNewLogLevelInClass(Plugins plugin, HashMap<String, LogLevel> newLogLevelInClass) {
((LogManagerForDevelopers) this.LoggingLstPlugins.get(plugin)).setLoggingLevelPerClass(newLogLevelInClass);
}
}
| mit |
sliitIFS/TaxiReservation | TaxiDriver/app/src/androidTest/java/com/example/nu/taxidriver/ApplicationTest.java | 356 | package com.example.nu.taxidriver;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | mit |
vpmalley/tpblogr | app/src/main/java/blogr/vpm/fr/blogr/activity/BlogActivity.java | 1709 | package blogr.vpm.fr.blogr.activity;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import blogr.vpm.fr.blogr.R;
import blogr.vpm.fr.blogr.bean.Blog;
import blogr.vpm.fr.blogr.bean.EmailBlog;
import blogr.vpm.fr.blogr.bean.GithubBlog;
import blogr.vpm.fr.blogr.bean.TPBlog;
/**
* Created by vince on 17/10/14.
*/
public class BlogActivity extends Activity {
public static final String BLOG_KEY = "blog";
private Fragment blogEditionFragment;
private Blog blog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blog);
//blogEditionFragment = getFragmentManager().findFragmentById(R.id.blogEditionFragment);
setTitle("Blog");
getActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
if (i.hasExtra(BLOG_KEY)) {
blog = i.getParcelableExtra(BLOG_KEY);
}
if (blog != null) {
if (blog instanceof TPBlog) {
blogEditionFragment = new EmailBlogEditionFragment();
setTitle(getString(R.string.tp_blog));
} else if (blog instanceof EmailBlog) {
blogEditionFragment = new EmailBlogEditionFragment();
setTitle(getString(R.string.email_blog));
} else if (blog instanceof GithubBlog) {
blogEditionFragment = new GithubBlogEditionFragment();
setTitle(getString(R.string.github_blog));
}
Bundle args = new Bundle();
args.putParcelable(BLOG_KEY, blog);
blogEditionFragment.setArguments(args);
getFragmentManager().beginTransaction().add(R.id.blog_activity, blogEditionFragment).commit();
}
}
}
| mit |
Abarosen/id2210-vt17-master | src/main/java/se/kth/app/AppComp.java | 7815 | /*
* 2016 Royal Institute of Technology (KTH)
*
* LSelector is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package se.kth.app;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.kth.app.broadcast.CB;
import se.kth.app.broadcast.CBPort;
import se.kth.app.sets.CRDTPort;
import se.kth.app.sets.ExternalEvents;
import se.kth.app.sets.graph.GraphOperations;
import se.sics.kompics.*;
import se.sics.kompics.network.Network;
import se.sics.kompics.network.Transport;
import se.sics.kompics.timer.Timer;
import se.sics.ktoolbox.croupier.CroupierPort;
import se.sics.ktoolbox.croupier.event.CroupierSample;
import se.sics.ktoolbox.util.identifiable.Identifier;
import se.sics.ktoolbox.util.network.KAddress;
import se.sics.ktoolbox.util.network.KContentMsg;
import se.sics.ktoolbox.util.network.KHeader;
import se.sics.ktoolbox.util.network.basic.BasicContentMsg;
import se.sics.ktoolbox.util.network.basic.BasicHeader;
/**
* @author Alex Ormenisan <aaor@kth.se>
*/
public class AppComp extends ComponentDefinition {
private static final Logger LOG = LoggerFactory.getLogger(AppComp.class);
private String logPrefix = " ";
//*******************************CONNECTIONS********************************
Positive<Timer> timerPort = requires(Timer.class);
Positive<Network> networkPort = requires(Network.class);
Positive<CroupierPort> croupierPort = requires(CroupierPort.class);
Positive<CBPort> cb = requires(CBPort.class);
Positive<CRDTPort> setPort = requires(CRDTPort.class);
//**************************************************************************
private KAddress selfAdr;
private int counter = 0;
public AppComp(Init init) {
selfAdr = init.selfAdr;
logPrefix = "<nid:" + selfAdr.getId() + ">";
LOG.info("{}initiating...", logPrefix);
subscribe(handleStart, control);
subscribe(handleCroupierSample, croupierPort);
//Set handlers
subscribe(handleResponse, setPort);
subscribe(handleAdd, networkPort);
subscribe(handleRemove, networkPort);
subscribe(handleLookup, networkPort);
//Graph
subscribe(handleGResponse, setPort);
subscribe(handleAddE, networkPort);
subscribe(handleAddV, networkPort);
subscribe(handleRemoveV, networkPort);
subscribe(handleRemoveE, networkPort);
}
Handler handleStart = new Handler<Start>() {
@Override
public void handle(Start event) {
LOG.info("{}starting...", logPrefix);
}
};
Handler handleCroupierSample = new Handler<CroupierSample>() {
@Override
public void handle(CroupierSample croupierSample) {
if (croupierSample.publicSample.isEmpty()) {
return;
}
//List<KAddress> sample = CroupierHelper.getSample(croupierSample);
if(selfAdr.getId().toString().equals("1")){
//LOG.info("{} TESTING! counter:{}", logPrefix, counter);
//trigger(new CB.CB_Broadcast(new TestEvent("hello: " + counter)), cb);
//counter++;
}
/*for (KAddress peer : sample) {
KHeader header = new BasicHeader(selfAdr, peer, Transport.UDP);
KContentMsg msg = new BasicContentMsg(header, new Ping());
trigger(msg, networkPort);
}*/
}
};
class TestEvent implements KompicsEvent{
String message;
TestEvent(String message){
this.message = message;
}
}
//Handle Set
ClassMatchedHandler handleLookup
= new ClassMatchedHandler<ExternalEvents.Lookup, KContentMsg<?, ?, ExternalEvents.Lookup>>() {
@Override
public void handle(ExternalEvents.Lookup content, KContentMsg<?, ?, ExternalEvents.Lookup> container) {
LOG.info("{}received Lookup from:{}", logPrefix, container.getHeader().getSource());
trigger(new ExternalEvents.Lookup(container.getHeader().getSource(), content.key), setPort);
}
};
Handler handleResponse = new Handler<ExternalEvents.Response>() {
@Override
public void handle(ExternalEvents.Response event) {
KHeader header = new BasicHeader(selfAdr, event.ret, Transport.UDP);
KContentMsg msg = new BasicContentMsg(header, event);
trigger(msg, networkPort);
}
};
ClassMatchedHandler handleRemove
= new ClassMatchedHandler<ExternalEvents.Remove, KContentMsg<?, ?, ExternalEvents.Remove>>() {
@Override
public void handle(ExternalEvents.Remove content, KContentMsg<?, ?, ExternalEvents.Remove> container) {
LOG.trace("{}received Remove from {}", logPrefix, container.getHeader().getSource());
trigger(content, setPort);
}
};
ClassMatchedHandler handleAdd
= new ClassMatchedHandler<ExternalEvents.Add, KContentMsg<?, ?, ExternalEvents.Add>>() {
@Override
public void handle(ExternalEvents.Add content, KContentMsg<?, ?, ExternalEvents.Add> container) {
LOG.trace("{}received Add from {}", logPrefix, container.getHeader().getSource());
trigger(content, setPort);
}
};
//Graph
Handler handleGResponse = new Handler<GraphOperations.Response>() {
@Override
public void handle(GraphOperations.Response event) {
KHeader header = new BasicHeader(selfAdr, event.ret, Transport.UDP);
KContentMsg msg = new BasicContentMsg(header, event);
trigger(msg, networkPort);
}
};
ClassMatchedHandler handleRemoveE
= new ClassMatchedHandler<GraphOperations.RemoveE, KContentMsg<?, ?, GraphOperations.RemoveE>>() {
@Override
public void handle(GraphOperations.RemoveE content, KContentMsg<?, ?, GraphOperations.RemoveE> container) {
LOG.trace("{}received RemoveEdge from {}", logPrefix, container.getHeader().getSource());
trigger(content, setPort);
}
};
ClassMatchedHandler handleRemoveV
= new ClassMatchedHandler<GraphOperations.RemoveV, KContentMsg<?, ?, GraphOperations.RemoveV>>() {
@Override
public void handle(GraphOperations.RemoveV content, KContentMsg<?, ?, GraphOperations.RemoveV> container) {
LOG.trace("{}received RemoveVertex from {}", logPrefix, container.getHeader().getSource());
trigger(content, setPort);
}
};
ClassMatchedHandler handleAddE
= new ClassMatchedHandler<GraphOperations.AddE, KContentMsg<?, ?, GraphOperations.AddE>>() {
@Override
public void handle(GraphOperations.AddE content, KContentMsg<?, ?, GraphOperations.AddE> container) {
LOG.trace("{}received AddEdse from {}", logPrefix, container.getHeader().getSource());
trigger(content, setPort);
}
};
ClassMatchedHandler handleAddV
= new ClassMatchedHandler<GraphOperations.AddV, KContentMsg<?, ?, GraphOperations.AddV>>() {
@Override
public void handle(GraphOperations.AddV content, KContentMsg<?, ?, GraphOperations.AddV> container) {
LOG.trace("{}received AddV from {}", logPrefix, container.getHeader().getSource());
trigger(content, setPort);
}
};
public static class Init extends se.sics.kompics.Init<AppComp> {
public final KAddress selfAdr;
public final Identifier gradientOId;
public Init(KAddress selfAdr, Identifier gradientOId) {
this.selfAdr = selfAdr;
this.gradientOId = gradientOId;
}
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/cdn/mgmt-v2020_04_15/src/main/java/com/microsoft/azure/management/cdn/v2020_04_15/CacheExpirationActionParameters.java | 3915 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.cdn.v2020_04_15;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Defines the parameters for the cache expiration action.
*/
public class CacheExpirationActionParameters {
/**
* The odatatype property.
*/
@JsonProperty(value = "@odata\\.type", required = true)
private String odatatype;
/**
* Caching behavior for the requests. Possible values include:
* 'BypassCache', 'Override', 'SetIfMissing'.
*/
@JsonProperty(value = "cacheBehavior", required = true)
private CacheBehavior cacheBehavior;
/**
* The level at which the content needs to be cached.
*/
@JsonProperty(value = "cacheType", required = true)
private String cacheType;
/**
* The duration for which the content needs to be cached. Allowed format is
* [d.]hh:mm:ss.
*/
@JsonProperty(value = "cacheDuration")
private String cacheDuration;
/**
* Creates an instance of CacheExpirationActionParameters class.
* @param cacheBehavior caching behavior for the requests. Possible values include: 'BypassCache', 'Override', 'SetIfMissing'.
*/
public CacheExpirationActionParameters() {
odatatype = "#Microsoft.Azure.Cdn.Models.DeliveryRuleCacheExpirationActionParameters";
cacheType = "All";
}
/**
* Get the odatatype value.
*
* @return the odatatype value
*/
public String odatatype() {
return this.odatatype;
}
/**
* Set the odatatype value.
*
* @param odatatype the odatatype value to set
* @return the CacheExpirationActionParameters object itself.
*/
public CacheExpirationActionParameters withOdatatype(String odatatype) {
this.odatatype = odatatype;
return this;
}
/**
* Get caching behavior for the requests. Possible values include: 'BypassCache', 'Override', 'SetIfMissing'.
*
* @return the cacheBehavior value
*/
public CacheBehavior cacheBehavior() {
return this.cacheBehavior;
}
/**
* Set caching behavior for the requests. Possible values include: 'BypassCache', 'Override', 'SetIfMissing'.
*
* @param cacheBehavior the cacheBehavior value to set
* @return the CacheExpirationActionParameters object itself.
*/
public CacheExpirationActionParameters withCacheBehavior(CacheBehavior cacheBehavior) {
this.cacheBehavior = cacheBehavior;
return this;
}
/**
* Get the level at which the content needs to be cached.
*
* @return the cacheType value
*/
public String cacheType() {
return this.cacheType;
}
/**
* Set the level at which the content needs to be cached.
*
* @param cacheType the cacheType value to set
* @return the CacheExpirationActionParameters object itself.
*/
public CacheExpirationActionParameters withCacheType(String cacheType) {
this.cacheType = cacheType;
return this;
}
/**
* Get the duration for which the content needs to be cached. Allowed format is [d.]hh:mm:ss.
*
* @return the cacheDuration value
*/
public String cacheDuration() {
return this.cacheDuration;
}
/**
* Set the duration for which the content needs to be cached. Allowed format is [d.]hh:mm:ss.
*
* @param cacheDuration the cacheDuration value to set
* @return the CacheExpirationActionParameters object itself.
*/
public CacheExpirationActionParameters withCacheDuration(String cacheDuration) {
this.cacheDuration = cacheDuration;
return this;
}
}
| mit |
alexander-dembinsky/catuml | presentation/src/main/java/catuml/presentation/viewmodel/StartupViewModel.java | 995 | package catuml.presentation.viewmodel;
import catuml.presentation.WindowService;
import catuml.presentation.command.Command;
import catuml.presentation.document.Document;
import catuml.presentation.document.DocumentManager;
/**
* View model for startup window.
*/
public class StartupViewModel {
private final Command newDocumentCommand = Command.delegate(this::createNewDocument);
private final DocumentManager documentManager;
private final WindowService windowService;
public StartupViewModel(DocumentManager documentManager, WindowService windowService) {
this.documentManager = documentManager;
this.windowService = windowService;
}
private void createNewDocument() {
Document document = documentManager.newDocument();
DocumentViewModel viewModel = new DocumentViewModel(document);
windowService.openDocumentWindow(viewModel);
}
public Command newDocumentCommand() {
return newDocumentCommand;
}
}
| mit |
Spronghi/software-engineering | anrc/ANRC Terminal/src/com/anrc/integration/dao/DetectorDAO.java | 2914 | package com.anrc.integration.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.anrc.integration.database.ConnectorFactory;
import com.anrc.integration.util.Replacer;
import com.anrc.model.Detector;
class DetectorDAO implements DAO<Detector> {
private DetectorTypeDAO typeDAO;
private RoomDAO roomDAO;
private static final String SELECT = "SELECT `id`,`name`,`type_id`,`room_id` FROM detector";
private static final String SELECT_FROM_ID = "SELECT `id`,`name`,`type_id`,`room_id` FROM detector WHERE ID=?";
private static final String INSERT = "INSERT INTO detector(name,type_id,room_id) VALUES ('?',?,?)";
private static final String DELETE = "DELETE FROM detector WHERE id=?";
private static final String UPDATE = "UPDATE detector SET name='?',type_id=?,room_id=? WHERE id=?";
public DetectorDAO() {
typeDAO = new DetectorTypeDAO();
roomDAO = new RoomDAO();
}
private Detector setDetector(ResultSet rs) throws SQLException{
Detector detector = new Detector();
detector.setId(rs.getInt(1));
detector.setName(rs.getString(2));
detector.setType(typeDAO.get(rs.getInt(3)));
detector.setRoom(roomDAO.get(rs.getInt(4)));
return detector;
}
@Override
public List<Detector> getAll() {
List<Detector> detectors = new ArrayList<>();
ResultSet rs = ConnectorFactory.getConnection().executeQuery(SELECT);
try {
while(rs.next()) {
detectors.add(setDetector(rs));
}
} catch (SQLException e) {
e.printStackTrace();
}
return detectors;
}
@Override
public Detector get(int id) {
String query = SELECT_FROM_ID;
query = Replacer.replaceFirst(query, id);
ResultSet rs = ConnectorFactory.getConnection().executeQuery(query);
try {
if(rs.next()) {
return setDetector(rs);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public void create(Detector model) {
String query = INSERT;
query = Replacer.replaceFirst(query, model.getName());
query = Replacer.replaceFirst(query, model.getType().getId());
query = Replacer.replaceFirst(query, model.getRoom().getId());
model.setId(ConnectorFactory.getConnection().executeUpdate(query));
}
@Override
public void update(Detector model) {
String query = UPDATE;
query = Replacer.replaceFirst(query, model.getName());
query = Replacer.replaceFirst(query, model.getType().getId());
query = Replacer.replaceFirst(query, model.getRoom().getId());
ConnectorFactory.getConnection().executeUpdate(query);
}
@Override
public void delete(Detector model) {
String query = DELETE;
query = Replacer.replaceFirst(query, model.getId());
ConnectorFactory.getConnection().executeUpdate(query);
}
}
| mit |
VladimirRadojcic/Master | GraphEdit/src/graphedit/command/LinkElementsCommand.java | 2519 | package graphedit.command;
import graphedit.model.components.Link;
import graphedit.model.components.LinkableElement;
import graphedit.model.components.shortcuts.Shortcut;
import graphedit.model.diagram.GraphEditModel;
import graphedit.model.elements.GraphEditElement;
import graphedit.view.GraphEditView;
import graphedit.view.LinkPainter;
public class LinkElementsCommand extends Command {
private GraphEditModel model;
private Link link;
private LinkPainter linkPainter;
private LinkableElement sourceElement,destinationElement;
private GraphEditElement sourceGraphEditElement, destinationGraphEditElement;
public LinkElementsCommand(GraphEditView view, Link link, LinkPainter linkPainter,LinkableElement sourceElement, LinkableElement destinationElement) {
this.model = view.getModel();
this.view = view;
this.link=link;
this.linkPainter = linkPainter;
this.sourceElement=sourceElement;
this.destinationElement=destinationElement;
if (sourceElement instanceof Shortcut)
sourceGraphEditElement = ((Shortcut)sourceElement).shortcutTo().getRepresentedElement();
else
sourceGraphEditElement = sourceElement.getRepresentedElement();
if (destinationElement instanceof Shortcut)
destinationGraphEditElement = ((Shortcut)destinationElement).shortcutTo().getRepresentedElement();
else
destinationGraphEditElement = destinationElement.getRepresentedElement();
link.getSourceConnector().setRepresentedElement(sourceGraphEditElement);
link.getDestinationConnector().setRepresentedElement(destinationGraphEditElement);
}
public void execute() {
sourceElement.addConnectors(link.getSourceConnector());
destinationElement.addConnectors(link.getDestinationConnector());
model.insertIntoElementByConnectorStructure(link.getSourceConnector(), sourceElement);
model.insertIntoElementByConnectorStructure(link.getDestinationConnector(), destinationElement);
view.addLinkPainter(linkPainter);
destinationGraphEditElement.link(link, false);
sourceGraphEditElement.link(link, true);
model.addLink(link);
}
public void undo() {
sourceGraphEditElement.unlink(link, true);
destinationGraphEditElement.unlink(link, false);
model.removeFromElementByConnectorStructure(link);
model.removeLink(link);
view.removeLinkPainters(linkPainter);
view.getSelectionModel().removeSelecredLink(link);
}
public GraphEditModel getModel() {
return model;
}
public void setModel(GraphEditModel newGraphEditModel) {
this.model = newGraphEditModel;
}
} | mit |
caricsvk/sb-utils | src/main/java/milo/utils/cache/CollectionCreator.java | 140 | package milo.utils.cache;
import java.util.Collection;
public interface CollectionCreator<T> extends Creator {
Collection<T> create();
}
| mit |
mpv-android/mpv-android | app/src/main/java/is/xyz/filepicker/FileItemAdapter.java | 2536 | /*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package is.xyz.filepicker;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.SortedList;
import androidx.recyclerview.widget.RecyclerView;
import android.view.ViewGroup;
/**
* A simple adapter which also inserts a header item ".." to handle going up to the parent folder.
* @param <T> the type which is used, for example a normal java File object.
*/
public class FileItemAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
protected final LogicHandler<T> mLogic;
protected SortedList<T> mList = null;
public FileItemAdapter(@NonNull LogicHandler<T> logic) {
this.mLogic = logic;
}
public void setList(@Nullable SortedList<T> list) {
mList = list;
notifyDataSetChanged();
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return mLogic.onCreateViewHolder(parent, viewType);
}
@Override
@SuppressWarnings("unchecked")
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int headerPosition) {
if (headerPosition == 0) {
mLogic.onBindHeaderViewHolder((AbstractFilePickerFragment<T>.HeaderViewHolder) viewHolder);
} else {
int pos = headerPosition - 1;
mLogic.onBindViewHolder((AbstractFilePickerFragment<T>.DirViewHolder) viewHolder, pos, mList.get(pos));
}
}
@Override
public int getItemViewType(int headerPosition) {
if (0 == headerPosition) {
return LogicHandler.VIEWTYPE_HEADER;
} else {
int pos = headerPosition - 1;
return mLogic.getItemViewType(pos, mList.get(pos));
}
}
@Override
public int getItemCount() {
if (mList == null) {
return 0;
}
// header + count
return 1 + mList.size();
}
/**
* Get the item at the designated position in the adapter.
*
* @param position of item in adapter
* @return null if position is zero (that means it's the ".." header), the item otherwise.
*/
protected @Nullable T getItem(int position) {
if (position == 0) {
return null;
}
return mList.get(position - 1);
}
}
| mit |
liufeiit/itmarry | 2048/zhz/gen/com/itjiehun/zhz/R.java | 14797 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.itjiehun.zhz;
public final class R {
public static final class anim {
public static final int umeng_fb_slide_in_from_left=0x7f040000;
public static final int umeng_fb_slide_in_from_right=0x7f040001;
public static final int umeng_fb_slide_out_from_left=0x7f040002;
public static final int umeng_fb_slide_out_from_right=0x7f040003;
}
public static final class attr {
}
public static final class color {
public static final int background=0x7f060003;
public static final int text_black=0x7f060001;
public static final int text_brown=0x7f060002;
public static final int text_white=0x7f060000;
public static final int umeng_fb_color_btn_normal=0x7f060005;
public static final int umeng_fb_color_btn_pressed=0x7f060004;
}
public static final class dimen {
/**
Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
*/
public static final int activity_horizontal_margin=0x7f070000;
public static final int activity_vertical_margin=0x7f070001;
}
public static final class drawable {
public static final int background_rectangle=0x7f020000;
public static final int cell_rectangle=0x7f020001;
public static final int cell_rectangle_1024=0x7f020002;
public static final int cell_rectangle_128=0x7f020003;
public static final int cell_rectangle_16=0x7f020004;
public static final int cell_rectangle_2=0x7f020005;
public static final int cell_rectangle_2048=0x7f020006;
public static final int cell_rectangle_256=0x7f020007;
public static final int cell_rectangle_32=0x7f020008;
public static final int cell_rectangle_4=0x7f020009;
public static final int cell_rectangle_4096=0x7f02000a;
public static final int cell_rectangle_512=0x7f02000b;
public static final int cell_rectangle_64=0x7f02000c;
public static final int cell_rectangle_8=0x7f02000d;
public static final int cell_rectangle_8192=0x7f02000e;
public static final int fade_rectangle=0x7f02000f;
public static final int ic_action_cheat=0x7f020010;
public static final int ic_action_refresh=0x7f020011;
public static final int ic_action_settings=0x7f020012;
public static final int ic_action_undo=0x7f020013;
public static final int ic_launcher=0x7f020014;
public static final int light_up_rectangle=0x7f020015;
public static final int umeng_common_gradient_green=0x7f020016;
public static final int umeng_common_gradient_orange=0x7f020017;
public static final int umeng_common_gradient_red=0x7f020018;
public static final int umeng_fb_arrow_right=0x7f020019;
public static final int umeng_fb_back_normal=0x7f02001a;
public static final int umeng_fb_back_selected=0x7f02001b;
public static final int umeng_fb_back_selector=0x7f02001c;
public static final int umeng_fb_bar_bg=0x7f02001d;
public static final int umeng_fb_btn_bg_selector=0x7f02001e;
public static final int umeng_fb_conversation_bg=0x7f02001f;
public static final int umeng_fb_gradient_green=0x7f020020;
public static final int umeng_fb_gradient_orange=0x7f020021;
public static final int umeng_fb_gray_frame=0x7f020022;
public static final int umeng_fb_list_item=0x7f020023;
public static final int umeng_fb_list_item_pressed=0x7f020024;
public static final int umeng_fb_list_item_selector=0x7f020025;
public static final int umeng_fb_logo=0x7f020026;
public static final int umeng_fb_point_new=0x7f020027;
public static final int umeng_fb_point_normal=0x7f020028;
public static final int umeng_fb_reply_left_bg=0x7f020029;
public static final int umeng_fb_reply_right_bg=0x7f02002a;
public static final int umeng_fb_see_list_normal=0x7f02002b;
public static final int umeng_fb_see_list_pressed=0x7f02002c;
public static final int umeng_fb_see_list_selector=0x7f02002d;
public static final int umeng_fb_statusbar_icon=0x7f02002e;
public static final int umeng_fb_submit_selector=0x7f02002f;
public static final int umeng_fb_tick_normal=0x7f020030;
public static final int umeng_fb_tick_selected=0x7f020031;
public static final int umeng_fb_tick_selector=0x7f020032;
public static final int umeng_fb_top_banner=0x7f020033;
public static final int umeng_fb_user_bubble=0x7f020034;
public static final int umeng_fb_write_normal=0x7f020035;
public static final int umeng_fb_write_pressed=0x7f020036;
public static final int umeng_fb_write_selector=0x7f020037;
public static final int umeng_update_btn_check_off_focused_holo_light=0x7f020038;
public static final int umeng_update_btn_check_off_holo_light=0x7f020039;
public static final int umeng_update_btn_check_off_pressed_holo_light=0x7f02003a;
public static final int umeng_update_btn_check_on_focused_holo_light=0x7f02003b;
public static final int umeng_update_btn_check_on_holo_light=0x7f02003c;
public static final int umeng_update_btn_check_on_pressed_holo_light=0x7f02003d;
public static final int umeng_update_button_cancel_bg_focused=0x7f02003e;
public static final int umeng_update_button_cancel_bg_normal=0x7f02003f;
public static final int umeng_update_button_cancel_bg_selector=0x7f020040;
public static final int umeng_update_button_cancel_bg_tap=0x7f020041;
public static final int umeng_update_button_check_selector=0x7f020042;
public static final int umeng_update_button_close_bg_selector=0x7f020043;
public static final int umeng_update_button_ok_bg_focused=0x7f020044;
public static final int umeng_update_button_ok_bg_normal=0x7f020045;
public static final int umeng_update_button_ok_bg_selector=0x7f020046;
public static final int umeng_update_button_ok_bg_tap=0x7f020047;
public static final int umeng_update_close_bg_normal=0x7f020048;
public static final int umeng_update_close_bg_tap=0x7f020049;
public static final int umeng_update_dialog_bg=0x7f02004a;
public static final int umeng_update_title_bg=0x7f02004b;
public static final int umeng_update_wifi_disable=0x7f02004c;
public static final int zh_1=0x7f02004d;
public static final int zh_10=0x7f02004e;
public static final int zh_11=0x7f02004f;
public static final int zh_12=0x7f020050;
public static final int zh_13=0x7f020051;
public static final int zh_2=0x7f020052;
public static final int zh_3=0x7f020053;
public static final int zh_4=0x7f020054;
public static final int zh_5=0x7f020055;
public static final int zh_6=0x7f020056;
public static final int zh_7=0x7f020057;
public static final int zh_8=0x7f020058;
public static final int zh_9=0x7f020059;
}
public static final class id {
public static final int action_settings=0x7f0b001e;
public static final int umeng_common_icon_view=0x7f0b0000;
public static final int umeng_common_notification=0x7f0b0004;
public static final int umeng_common_notification_controller=0x7f0b0001;
public static final int umeng_common_progress_bar=0x7f0b0007;
public static final int umeng_common_progress_text=0x7f0b0006;
public static final int umeng_common_rich_notification_cancel=0x7f0b0003;
public static final int umeng_common_rich_notification_continue=0x7f0b0002;
public static final int umeng_common_title=0x7f0b0005;
public static final int umeng_fb_back=0x7f0b0009;
public static final int umeng_fb_contact_header=0x7f0b0008;
public static final int umeng_fb_contact_info=0x7f0b000b;
public static final int umeng_fb_contact_update_at=0x7f0b000c;
public static final int umeng_fb_conversation_contact_entry=0x7f0b000e;
public static final int umeng_fb_conversation_header=0x7f0b000d;
public static final int umeng_fb_conversation_list_wrapper=0x7f0b000f;
public static final int umeng_fb_conversation_umeng_logo=0x7f0b0014;
public static final int umeng_fb_list_reply_header=0x7f0b0015;
public static final int umeng_fb_reply_content=0x7f0b0013;
public static final int umeng_fb_reply_content_wrapper=0x7f0b0011;
public static final int umeng_fb_reply_date=0x7f0b0016;
public static final int umeng_fb_reply_list=0x7f0b0010;
public static final int umeng_fb_save=0x7f0b000a;
public static final int umeng_fb_send=0x7f0b0012;
public static final int umeng_update_content=0x7f0b0019;
public static final int umeng_update_id_cancel=0x7f0b001c;
public static final int umeng_update_id_check=0x7f0b001a;
public static final int umeng_update_id_close=0x7f0b0018;
public static final int umeng_update_id_ignore=0x7f0b001d;
public static final int umeng_update_id_ok=0x7f0b001b;
public static final int umeng_update_wifi_indicator=0x7f0b0017;
}
public static final class layout {
public static final int activity_main=0x7f030000;
public static final int umeng_common_download_notification=0x7f030001;
public static final int umeng_fb_activity_contact=0x7f030002;
public static final int umeng_fb_activity_conversation=0x7f030003;
public static final int umeng_fb_list_header=0x7f030004;
public static final int umeng_fb_list_item=0x7f030005;
public static final int umeng_fb_new_reply_alert_dialog=0x7f030006;
public static final int umeng_update_dialog=0x7f030007;
}
public static final class menu {
public static final int main=0x7f0a0000;
}
public static final class raw {
public static final int die=0x7f050000;
public static final int sfx_point=0x7f050001;
public static final int sfx_swooshing=0x7f050002;
public static final int sfx_wing=0x7f050003;
public static final int win=0x7f050004;
}
public static final class string {
public static final int UMAppUpdate=0x7f080031;
public static final int UMBreak_Network=0x7f080029;
public static final int UMDialog_InstallAPK=0x7f080035;
public static final int UMGprsCondition=0x7f08002f;
public static final int UMIgnore=0x7f080033;
public static final int UMNewVersion=0x7f08002b;
public static final int UMNotNow=0x7f080032;
public static final int UMTargetSize=0x7f08002e;
public static final int UMToast_IsUpdating=0x7f080034;
public static final int UMUpdateCheck=0x7f080036;
public static final int UMUpdateContent=0x7f08002c;
public static final int UMUpdateNow=0x7f080030;
public static final int UMUpdateSize=0x7f08002d;
public static final int UMUpdateTitle=0x7f08002a;
public static final int action_settings=0x7f080002;
public static final int app_name=0x7f080000;
public static final int endless=0x7f08000b;
public static final int for_now=0x7f08000a;
public static final int game_over=0x7f080008;
public static final int go_on=0x7f080009;
public static final int header=0x7f080001;
public static final int high_score=0x7f080004;
public static final int instructions=0x7f080006;
public static final int new_game=0x7f080003;
public static final int score=0x7f080005;
public static final int umeng_common_action_cancel=0x7f080010;
public static final int umeng_common_action_continue=0x7f08000f;
public static final int umeng_common_action_info_exist=0x7f08000c;
public static final int umeng_common_action_pause=0x7f08000e;
public static final int umeng_common_download_failed=0x7f080016;
public static final int umeng_common_download_finish=0x7f080017;
public static final int umeng_common_download_notification_prefix=0x7f080011;
public static final int umeng_common_icon=0x7f08001a;
public static final int umeng_common_info_interrupt=0x7f08000d;
public static final int umeng_common_network_break_alert=0x7f080015;
public static final int umeng_common_patch_finish=0x7f080018;
public static final int umeng_common_pause_notification_prefix=0x7f080012;
public static final int umeng_common_silent_download_finish=0x7f080019;
public static final int umeng_common_start_download_notification=0x7f080013;
public static final int umeng_common_start_patch_notification=0x7f080014;
public static final int umeng_fb_back=0x7f08001d;
public static final int umeng_fb_contact_info=0x7f080020;
public static final int umeng_fb_contact_info_hint=0x7f08001b;
public static final int umeng_fb_contact_title=0x7f08001f;
public static final int umeng_fb_contact_update_at=0x7f08001c;
public static final int umeng_fb_notification_content_formatter_multiple_msg=0x7f080028;
public static final int umeng_fb_notification_content_formatter_single_msg=0x7f080027;
public static final int umeng_fb_notification_ticker_text=0x7f080026;
public static final int umeng_fb_powered_by=0x7f080025;
public static final int umeng_fb_reply_content_default=0x7f080023;
public static final int umeng_fb_reply_content_hint=0x7f080021;
public static final int umeng_fb_reply_date_default=0x7f080024;
public static final int umeng_fb_send=0x7f080022;
public static final int umeng_fb_title=0x7f08001e;
public static final int you_win=0x7f080007;
}
public static final class style {
/**
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f090000;
public static final int AppTheme=0x7f090001;
}
}
| mit |
PaleoCrafter/Allomancy | src/main/java/de/mineformers/investiture/block/properties/package-info.java | 213 | @ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
package de.mineformers.investiture.block.properties;
import mcp.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault; | mit |