code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
package org.knowm.xchange.examples.bter.marketdata; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; import org.knowm.xchange.Exchange; import org.knowm.xchange.ExchangeFactory; import org.knowm.xchange.bter.BTERExchange; import org.knowm.xchange.bter.dto.marketdata.BTERDepth; import org.knowm.xchange.bter.dto.marketdata.BTERMarketInfoWrapper.BTERMarketInfo; import org.knowm.xchange.bter.dto.marketdata.BTERTicker; import org.knowm.xchange.bter.dto.marketdata.BTERTradeHistory; import org.knowm.xchange.bter.dto.marketdata.BTERTradeHistory.BTERPublicTrade; import org.knowm.xchange.bter.service.polling.BTERPollingMarketDataServiceRaw; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.marketdata.OrderBook; import org.knowm.xchange.dto.marketdata.Ticker; import org.knowm.xchange.dto.marketdata.Trade; import org.knowm.xchange.dto.marketdata.Trades; import org.knowm.xchange.service.polling.marketdata.PollingMarketDataService; public class BTERMarketDataDemo { public static void main(String[] args) throws IOException { Exchange exchange = ExchangeFactory.INSTANCE.createExchange(BTERExchange.class.getName()); PollingMarketDataService marketDataService = exchange.getPollingMarketDataService(); generic(marketDataService); raw((BTERPollingMarketDataServiceRaw) marketDataService); } private static void generic(PollingMarketDataService marketDataService) throws IOException { Ticker ticker = marketDataService.getTicker(CurrencyPair.PPC_BTC); System.out.println(ticker); OrderBook oderBook = marketDataService.getOrderBook(CurrencyPair.BTC_CNY); System.out.println(oderBook); Trades tradeHistory = marketDataService.getTrades(CurrencyPair.BTC_CNY); System.out.println(tradeHistory); List<Trade> trades = tradeHistory.getTrades(); if (trades.size() > 1) { Trade trade = trades.get(trades.size() - 2); tradeHistory = marketDataService.getTrades(CurrencyPair.BTC_CNY, Long.valueOf(trade.getId())); System.out.println(tradeHistory); } } private static void raw(BTERPollingMarketDataServiceRaw marketDataService) throws IOException { Map<CurrencyPair, BTERMarketInfo> marketInfoMap = marketDataService.getBTERMarketInfo(); System.out.println(marketInfoMap); Collection<CurrencyPair> pairs = marketDataService.getExchangeSymbols(); System.out.println(pairs); Map<CurrencyPair, BTERTicker> tickers = marketDataService.getBTERTickers(); System.out.println(tickers); BTERTicker ticker = marketDataService.getBTERTicker("PPC", "BTC"); System.out.println(ticker); BTERDepth depth = marketDataService.getBTEROrderBook("BTC", "CNY"); System.out.println(depth); BTERTradeHistory tradeHistory = marketDataService.getBTERTradeHistory("BTC", "CNY"); System.out.println(tradeHistory); List<BTERPublicTrade> trades = tradeHistory.getTrades(); if (trades.size() > 1) { BTERPublicTrade trade = trades.get(trades.size() - 2); tradeHistory = marketDataService.getBTERTradeHistorySince("BTC", "CNY", trade.getTradeId()); System.out.println(tradeHistory); } } }
mmithril/XChange
xchange-examples/src/main/java/org/knowm/xchange/examples/bter/marketdata/BTERMarketDataDemo.java
Java
mit
3,203
package hr.fer.oop.lab3.topic1.shell.commands; import hr.fer.oop.lab3.topic1.shell.*; public abstract class AbstractCommand implements ShellCommand{ private String commandName; private String commandDescription; public AbstractCommand(String name, String description) { this.commandName = name; this.commandDescription = description; } public String getCommandName() { return commandName; } public String getCommandDescription() { return commandDescription; } public String toString() { return commandName + "::" + commandDescription; } }
DominikDitoIvosevic/Uni
OOP/SimpleHashtableImplementation/src/hr/fer/oop/lab3/topic1/shell/commands/AbstractCommand.java
Java
mit
570
package it.uspread.android.activity.stats; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.List; import it.uspread.android.R; import it.uspread.android.data.UserRanking; /** * Gestion de l'affichage des éléments de la liste des utilisateurs. * * @author Lone Décosterd, */ public class UsersAdapter extends ArrayAdapter<UserRanking> { /** * Constructeur. * * @param context * Contexte * @param listUser * Les utilisateurs à afficher */ public UsersAdapter(Context context, List<UserRanking> listUser) { super(context, R.layout.score_user_rank, listUser); } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder; // Optimisation : création d'une nouvelle vue que si nécessaire if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.score_user_rank, parent, false); holder = new ViewHolder(); // On place les widgets de notre layout dans le holder holder.textRanking = (TextView) convertView.findViewById(R.id.text_username); holder.textUserName = (TextView) convertView.findViewById(R.id.text_ranking); // On insère le holder en tant que tag dans le layout convertView.setTag(holder); } else { // Si on recycle la vue, on récupère son holder en tag holder = (ViewHolder) convertView.getTag(); } final UserRanking user = getItem(position); holder.textRanking.setText(user.getUsername()); holder.textUserName.setText(((Integer) user.getRanking()).toString()); return convertView; } /** * Pour l'optimisation de l'affichage de la vue. Les widget du layout doivent être ajouté dans cette classe interne.<br> * (Raison lors du scroll d'une liste les layout et widget des éléments qui disparaissent sont systématiquement recyclé pour l'affichage des nouveaux éléments apparaissant) */ private static class ViewHolder { public TextView textRanking; public TextView textUserName; } }
uSpreadIt/uSpreadIt-Android
uSpreadIt/src/main/java/it/uspread/android/activity/stats/UsersAdapter.java
Java
mit
2,362
package com.faforever.client.preferences; import lombok.AllArgsConstructor; import lombok.Getter; @AllArgsConstructor @Getter public enum LanguageChannel { FRENCH("#french"), GERMAN("#german"), RUSSIAN("#russian"); private final String channelName; }
FAForever/downlords-faf-client
src/main/java/com/faforever/client/preferences/LanguageChannel.java
Java
mit
262
package com.bugsnag; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import com.fasterxml.jackson.databind.JsonNode; import org.junit.Before; import org.junit.Test; import java.util.Collections; public class NotifierTest { private Report report; private Configuration config; private SessionPayload sessionPayload; /** * Initialises the objectmapper + report for conversion to json * * @throws Throwable the throwable */ @Before public void setUp() throws Throwable { config = new Configuration("api-key"); report = new Report(config, new RuntimeException()); sessionPayload = new SessionPayload(Collections.<SessionCount>emptyList(), config); } @Test public void testNotificationSerialisation() throws Throwable { JsonNode payload = BugsnagTestUtils.mapReportToJson(config, this.report); JsonNode notifier = payload.get("notifier"); assertEquals("Bugsnag Java", notifier.get("name").asText()); assertEquals("https://github.com/bugsnag/bugsnag-java", notifier.get("url").asText()); assertFalse(notifier.get("version").asText().isEmpty()); } @Test public void testSessionSerialisation() throws Throwable { JsonNode payload = BugsnagTestUtils.mapSessionPayloadToJson(sessionPayload); JsonNode notifier = payload.get("notifier"); assertEquals("Bugsnag Java", notifier.get("name").asText()); assertEquals("https://github.com/bugsnag/bugsnag-java", notifier.get("url").asText()); assertFalse(notifier.get("version").asText().isEmpty()); } }
bugsnag/bugsnag-java
bugsnag/src/test/java/com/bugsnag/NotifierTest.java
Java
mit
1,663
/* Copyright 2017 Halvor Bjørn 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.mrbjoern.blog.api.domain.user; import com.fasterxml.jackson.annotation.JsonIgnore; import com.mrbjoern.blog.api.domain.file.UploadedFile; import com.mrbjoern.blog.api.domain.post.Post; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.Date; import java.util.List; import java.util.Set; @Entity public class BlogUser { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private long id; @Column(nullable = false, unique = true) private String username; @Column(nullable = false, unique = true) private String email; @JsonIgnore @NotNull private String hashedPassword; @JsonIgnore @OneToMany(mappedBy = "author", cascade = CascadeType.ALL) private Set<Post> posts; @JsonIgnore @OneToMany(mappedBy = "author", cascade = CascadeType.ALL) private Set<UploadedFile> files; @JsonIgnore @ElementCollection(targetClass = UserClaim.class) @CollectionTable(name = "user_claims") @Enumerated(EnumType.STRING) private List<UserClaim> claims; @NotNull private Date createdDate; public BlogUser() { } public BlogUser(final String username, final String email, final String hashedPassword) { this.username = username; this.email = email; this.hashedPassword = hashedPassword; this.createdDate = new Date(); } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getHashedPassword() { return hashedPassword; } public void setHashedPassword(String hashedPassword) { this.hashedPassword = hashedPassword; } public Set<Post> getPosts() { return posts; } public void setPosts(Set<Post> posts) { this.posts = posts; } public List<UserClaim> getClaims() { return claims; } public void setClaims(List<UserClaim> claims) { this.claims = claims; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } @Override public String toString() { return "BlogUser{" + "id=" + id + ", username='" + username + '\'' + ", email='" + email + '\'' + ", hashedPassword='" + hashedPassword + '\'' + ", createdDate=" + createdDate + '}'; } }
mrbjoern/blog-api
src/main/java/com/mrbjoern/blog/api/domain/user/BlogUser.java
Java
mit
3,868
package ro.riscutiatudor; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Service; import lombok.NonNull; import lombok.RequiredArgsConstructor; import ro.riscutiatudor.core.PersonRepository; import ro.riscutiatudor.core.model.Person; /** * Application initializer * * @author Tudor Riscutia * @version 1.0 */ @Service @RequiredArgsConstructor public class ApplicationInitializer { private static final String MOCKDATA_PATH = "persons.json"; private final @NonNull PersonRepository repository; @EventListener public void init(ApplicationReadyEvent event) throws IOException { File file = new File(getClass().getClassLoader().getResource(MOCKDATA_PATH).getFile()); List<Person> persons = Arrays.asList(new ObjectMapper().readValue(file, Person[].class)); repository.save(persons); } }
riscutiatudor/address-book
src/main/java/ro/riscutiatudor/ApplicationInitializer.java
Java
mit
1,129
package au.com.mineauz.minigames.mechanics; import au.com.mineauz.minigames.MinigameMessageType; import au.com.mineauz.minigames.objects.MinigamePlayer; import au.com.mineauz.minigames.Minigames; import au.com.mineauz.minigames.events.StartMinigameEvent; import au.com.mineauz.minigames.gametypes.MinigameType; import au.com.mineauz.minigames.minigame.Minigame; import au.com.mineauz.minigames.minigame.modules.MinigameModule; import org.bukkit.event.EventHandler; import org.bukkit.event.entity.PlayerDeathEvent; import java.util.EnumSet; import java.util.List; public class LivesMechanic extends GameMechanicBase { @Override public String getMechanic() { return "lives"; } @Override public EnumSet<MinigameType> validTypes() { return EnumSet.of(MinigameType.MULTIPLAYER); } @Override public boolean checkCanStart(Minigame minigame, MinigamePlayer caller) { if (minigame.getLives() > 0) { return true; } caller.sendMessage("The Minigame must have more than 0 lives to use this type", MinigameMessageType.ERROR); return false; } @Override public MinigameModule displaySettings(Minigame minigame) { return null; } @Override public void startMinigame(Minigame minigame, MinigamePlayer caller) { } @Override public void stopMinigame(Minigame minigame, MinigamePlayer caller) { } @Override public void onJoinMinigame(Minigame minigame, MinigamePlayer player) { } @Override public void quitMinigame(Minigame minigame, MinigamePlayer player, boolean forced) { } @Override public void endMinigame(Minigame minigame, List<MinigamePlayer> winners, List<MinigamePlayer> losers) { } @EventHandler private void minigameStart(StartMinigameEvent event) { if (event.getMinigame().getMechanicName().equals(getMechanic())) { final List<MinigamePlayer> players = event.getPlayers(); final Minigame minigame = event.getMinigame(); for (MinigamePlayer player : players) { if (!Float.isFinite(minigame.getLives())) { player.setScore(Integer.MAX_VALUE); minigame.setScore(player, Integer.MAX_VALUE); } else { int lives = Float.floatToIntBits(minigame.getLives()); player.setScore(lives); minigame.setScore(player, lives); } } } } @EventHandler private void playerDeath(PlayerDeathEvent event) { MinigamePlayer ply = Minigames.getPlugin().getPlayerManager().getMinigamePlayer(event.getEntity()); if (ply == null) return; if (ply.isInMinigame() && ply.getMinigame().getMechanicName().equals(getMechanic())) { ply.addScore(-1); ply.getMinigame().setScore(ply, ply.getScore()); } } }
AddstarMC/Minigames
Minigames/src/main/java/au/com/mineauz/minigames/mechanics/LivesMechanic.java
Java
mit
2,998
package alec_wam.CrystalMod.entities.minecarts.chests; import alec_wam.CrystalMod.tiles.chest.CrystalChestType; import net.minecraft.world.World; public class EntityCrystalChestMinecartRed extends EntityCrystalChestMinecartBase { public EntityCrystalChestMinecartRed(World worldIn) { super(worldIn); } public EntityCrystalChestMinecartRed(World worldIn, double x, double y, double z) { super(worldIn, x, y, z); } @Override public CrystalChestType getChestType() { return CrystalChestType.RED; } }
Alec-WAM/CrystalMod
src/main/java/alec_wam/CrystalMod/entities/minecarts/chests/EntityCrystalChestMinecartRed.java
Java
mit
555
package ch.eawag.chemeql; import java.io.FileWriter; import java.io.IOException; import java.text.Format; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; class MyTable extends JTable { TableCellRenderer stringRenderer; TableCellRenderer rightAlignRenderer; MyTable(TableModel model, boolean resizingAllowed) { super(model); setFont(getFont().deriveFont(12)); setShowGrid(false); setOpaque(false); setAutoResizeMode(AUTO_RESIZE_OFF); setColumnSelectionAllowed(false); setRowSelectionAllowed(false); JTableHeader th = getTableHeader(); th.setReorderingAllowed(false); th.setResizingAllowed(resizingAllowed); stringRenderer = new CustomRenderer(); rightAlignRenderer = new CustomRenderer(getFont(), SwingConstants.RIGHT); } void appendTableData(FileWriter out, Format numFormat) throws IOException { TableModel tm = getModel(); int columns = tm.getColumnCount(); int rows = tm.getRowCount(); // store column titles for (int c = 0; c < columns; c++) { out.write(tm.getColumnName(c)); out.write(Tokenizer.TAB); } out.write(Tokenizer.CR); out.write(Tokenizer.CR); for (int r = 0; r < rows; r++) { for (int c = 0; c < columns; c++) { Object v = tm.getValueAt(r, c); if (v instanceof Double || v instanceof Float) { out.write(numFormat.format(v)); } else { out.write(v.toString()); } out.write(Tokenizer.TAB); } out.write(Tokenizer.CR); } } }
eawag-surface-waters-research/ChemEQL
ChemEQL4_NB/src/ch/eawag/chemeql/MyTable.java
Java
mit
1,576
package com.ztory.lib.sleek.base.scroller; import android.view.MotionEvent; import com.ztory.lib.sleek.SleekCanvas; import com.ztory.lib.sleek.SleekCanvasInfo; import com.ztory.lib.sleek.SleekCanvasScroller; /** * Empty implementation of SleekCanvasScroller. * Created by jonruna on 09/10/14. */ public class SleekScrollerBase implements SleekCanvasScroller { private boolean mIsAutoLoading = false; public SleekScrollerBase(boolean theIsAutoLoading) { mIsAutoLoading = theIsAutoLoading; } @Override public void setSleekCanvas(SleekCanvas parentSleekCanvas) { } @Override public void setPosLeft(float posLeft) { } @Override public void setPosTop(float posTop) { } @Override public float getPosLeft() { return 0; } @Override public float getPosTop() { return 0; } @Override public void checkScrollBounds() { } @Override public void onSleekCanvasSizeChanged(SleekCanvasInfo info) { } @Override public boolean isAutoLoading() { return mIsAutoLoading; } @Override public boolean onSleekTouchEvent( MotionEvent event, SleekCanvasInfo info ) { return false; } @Override public void setBottomScrollEdge(float bottomScrollEdge) { } @Override public void setRightScrollEdge(float rightScrollEdge) { } @Override public void setPaddingTop(int topPadding) { } @Override public void setPaddingBottom(int bottomPadding) { } @Override public void setPaddingLeft(int leftPadding) { } @Override public void setPaddingRight(int rightPadding) { } @Override public int getPaddingTop() { return 0; } @Override public int getPaddingBottom() { return 0; } @Override public int getPaddingLeft() { return 0; } @Override public int getPaddingRight() { return 0; } @Override public void setMarginTop(int topMargin) { } @Override public void setMarginBottom(int bottomMargin) { } @Override public void setMarginLeft(int leftMargin) { } @Override public void setMarginRight(int rightMargin) { } @Override public int getMarginTop() { return 0; } @Override public int getMarginBottom() { return 0; } @Override public int getMarginLeft() { return 0; } @Override public int getMarginRight() { return 0; } @Override public boolean isScaled() { return false; } @Override public float getScaleX() { return 0; } @Override public float getScaleY() { return 0; } @Override public float getScalePivotX() { return 0; } @Override public float getScalePivotY() { return 0; } }
ztory/sleek
sleek_module/src/main/java/com/ztory/lib/sleek/base/scroller/SleekScrollerBase.java
Java
mit
2,945
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package automaticclickutility; /** * * @author Barbarrosa */ public class Scroll extends ClickAction{ private int x,delay; private boolean up; public Scroll(int xin, boolean upin){ myType=type.scroll; x = xin; up = upin; } public Scroll(int xin, boolean upin, int del){ myType=type.scroll; x = xin; up = upin; delay = del; } public Scroll(int xin, boolean upin, int del, int ta){ myType=type.scroll; x = xin; up = upin; delay = del; timeAfter = ta; } public void execute(){ if(up) robot.mouseWheel(-x); else robot.mouseWheel(x); } @Override public String toString(){ return "Scroll: "+x+" notches "+" - Delay:" + timeAfter/100; } }
Barbarrosa/2009-java-click-utility
source/Scroll.java
Java
mit
930
package eu.bcvsolutions.idm.core.model.service.impl; import com.google.common.collect.ImmutableMap; import eu.bcvsolutions.idm.core.api.domain.CoreResultCode; import eu.bcvsolutions.idm.core.api.dto.BaseDto; import eu.bcvsolutions.idm.core.api.dto.DelegationTypeDto; import eu.bcvsolutions.idm.core.api.dto.IdmDelegationDefinitionDto; import eu.bcvsolutions.idm.core.api.dto.IdmDelegationDto; import eu.bcvsolutions.idm.core.api.dto.filter.IdmDelegationFilter; import eu.bcvsolutions.idm.core.api.exception.ResultCodeException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import eu.bcvsolutions.idm.core.api.service.DelegationManager; import eu.bcvsolutions.idm.core.api.service.IdmDelegationService; import eu.bcvsolutions.idm.core.api.utils.DtoUtils; import eu.bcvsolutions.idm.core.eav.api.service.DelegationType; import eu.bcvsolutions.idm.core.model.delegation.type.DefaultDelegationType; import eu.bcvsolutions.idm.core.security.api.domain.BasePermission; import eu.bcvsolutions.idm.core.security.api.service.EnabledEvaluator; import eu.bcvsolutions.idm.core.workflow.service.WorkflowProcessDefinitionService; import java.util.Comparator; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import org.activiti.bpmn.model.ValuedDataObject; import org.apache.commons.collections.CollectionUtils; import org.modelmapper.internal.util.Assert; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Lazy; /** * Delegation manager * * @author Vít Švanda * @since 10.4.0 * */ @Service("delegationManager") public class DefaultDelegationManager implements DelegationManager { private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(DefaultDelegationManager.class); @Autowired private ApplicationContext context; @Lazy @Autowired private EnabledEvaluator enabledEvaluator; @Lazy @Autowired private WorkflowProcessDefinitionService processDefinitionService; @Lazy @Autowired private IdmDelegationService delegationService; @Override public List<IdmDelegationDefinitionDto> findDelegation(String type, UUID delegatorId, UUID delegatorContractId, BaseDto owner) { Assert.notNull(type, "Delegation type cannot be null!"); Assert.notNull(delegatorId, "Delegator cannot be null!"); DelegationType delegateType = this.getDelegateType(type); if (delegateType == null) { // Delegation type was not found (bad code or implementation // of delegatio type for this code missing ) -> throw exception. throw new ResultCodeException(CoreResultCode.DELEGATION_UNSUPPORTED_TYPE, ImmutableMap.of("type", type)); } List<IdmDelegationDefinitionDto> definitions = delegateType.findDelegation(delegatorId, delegatorContractId, owner); if (CollectionUtils.isEmpty(definitions)) { if (DefaultDelegationType.NAME.equals(type)) { return null; } // Try to default delegation. DelegationType defaultDelegateType = this.getDelegateType(DefaultDelegationType.NAME); definitions = defaultDelegateType.findDelegation(delegatorId, delegatorContractId, owner); if (CollectionUtils.isEmpty(definitions)) { return null; } } definitions.forEach(definition -> { LOG.debug("Delegation definition found [{}] for type [{}] and delegator [{}]", definition.getId(), type, delegatorId); }); return definitions; } @Override public IdmDelegationDto delegate(BaseDto owner, IdmDelegationDefinitionDto definition) { Assert.notNull(owner, "Delegation goal/owner cannot be null!"); Assert.notNull(definition, "Delegation definition cannot be null!"); DelegationType delegateType = this.getDelegateType(definition.getType()); if (delegateType == null) { // Delegation type was not found (bad code or implementation // of delegation type for this code missing ) -> throw exception. throw new ResultCodeException(CoreResultCode.DELEGATION_UNSUPPORTED_TYPE, ImmutableMap.of("type", definition.getType())); } return delegateType.delegate(owner, definition); } @Override public List<DelegationType> getSupportedTypes() { return context .getBeansOfType(DelegationType.class) .values() .stream() .filter(enabledEvaluator::isEnabled) .sorted(Comparator.comparing(DelegationType::getOrder)) .collect(Collectors.toList()); } @Override public DelegationTypeDto convertDelegationTypeToDto(DelegationType delegationType) { DelegationTypeDto delegationTypeDto = new DelegationTypeDto(); delegationTypeDto.setId(delegationType.getId()); delegationTypeDto.setName(delegationType.getId()); if (delegationType.getOwnerType() != null) { delegationTypeDto.setOwnerType(delegationType.getOwnerType().getCanonicalName()); } delegationTypeDto.setModule(delegationType.getModule()); delegationTypeDto.setSupportsDelegatorContract(delegationType.isSupportsDelegatorContract()); delegationTypeDto.setCanBeCreatedManually(delegationType.canBeCreatedManually()); delegationTypeDto.setSendNotifications(delegationType.sendNotifications()); // return delegationTypeDto; } @Override public DelegationType getDelegateType(String id) { return this.getSupportedTypes().stream() .filter(type -> type.getId().equals(id)) .findFirst() .orElse(null); } @Override public String getProcessDelegationType(String definitionId) { Assert.notNull(definitionId, "Workflow definition ID cannot be null!"); List<ValuedDataObject> dataObjects = processDefinitionService.getDataObjects(definitionId); if (dataObjects != null) { ValuedDataObject supportVariable = dataObjects.stream() .filter(dataObject -> WORKFLOW_DELEGATION_TYPE_KEY.equals(dataObject.getName())) .findFirst() .orElse(null); if (supportVariable != null) { Object value = supportVariable.getValue(); if (value instanceof String) { return (String) value; } } } return null; } @Override public List<IdmDelegationDto> findDelegationForOwner(BaseDto owner, BasePermission... permission) { Assert.notNull(owner, "Owner cannot be null!"); IdmDelegationFilter delegationFilter = new IdmDelegationFilter(); delegationFilter.setOwnerId(DtoUtils.toUuid(owner.getId())); delegationFilter.setOwnerType(owner.getClass().getCanonicalName()); return delegationService.find(delegationFilter, null, permission).getContent(); } }
bcvsolutions/CzechIdMng
Realization/backend/core/core-impl/src/main/java/eu/bcvsolutions/idm/core/model/service/impl/DefaultDelegationManager.java
Java
mit
6,418
package com.hyuki.dp.Flyweight; public class Main { public static void main(String[] args) { if (args.length == 0) { System.out.println("Usage: java Main digits"); System.out.println("Example: java Main 1212123"); System.exit(0); } BigString bs; bs = new BigString(args[0], false); // 共有しない bs.print(); bs = new BigString(args[0], true); // 共有する bs.print(); } }
r-jimano/ectype
src/main/java/com/hyuki/dp/Flyweight/Main.java
Java
mit
406
/* * Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * 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.tencent.mig.tmq.weak; import com.tencent.mig.tmq.abs.AbstractTMQ; import com.tencent.mig.tmq.model.IExclusiveFlag; import com.tencent.mig.tmq.simple.ControllerEnum; import com.tencent.mig.tmq.simple.FilterEnum; import com.tencent.mig.tmq.simple.ModeEnum; import com.tencent.mig.tmq.simple.SimpleTmqMsg; public class WeakTMQ extends AbstractTMQ<Object> { public WeakTMQ() { super(ControllerEnum.WEAK, FilterEnum.TYPE, ModeEnum.STRICT); } /** * 有效的消息序列初始化 * * @param tmqMsgList * 有效的消息序列 */ @Override public void iCareWhatMsg(Object... tmqMsgList) { /* * FIXME weak消息中继续借用SimpleTmqMsg.NULL做排他逻辑 * 增加设置null值为预期不应该收到任何消息的逻辑 */ if (tmqMsgList == null || tmqMsgList.length == 0 || tmqMsgList[0].equals(SimpleTmqMsg.NULL)) { controller.reset(0); controller.willCare(null); return; } boolean hasExclusiveMsg = false; int indexBeforeExclusiveFlag = 0; for (; indexBeforeExclusiveFlag < tmqMsgList.length; indexBeforeExclusiveFlag++) { Object msg = tmqMsgList[indexBeforeExclusiveFlag]; if (msg == null || msg instanceof IExclusiveFlag) { hasExclusiveMsg = true; break; } } controller.reset(indexBeforeExclusiveFlag); for (Object msg : tmqMsgList) // 这个地方加倒是可以都加上 { // 单条msg有可能是null,此时语义代表为在null后不应该收到其他通过过滤器的任何消息 controller.willCare(msg); } } }
r551/TMQ
tmqsdk/src/main/java/com/tencent/mig/tmq/weak/WeakTMQ.java
Java
mit
2,157
package thereisnospon.com.blogreader.test_mvp_test.view; import java.util.List; import thereisnospon.com.blogreader.data.database.ArticleItemCache; /** * Created by yzr on 16-3-3. */ public interface IArticleCacheView { public void showArticleCaches(List<ArticleItemCache >list); public void showMessage(String msg); }
Thereisnospon/BlogReader
BlogReader/app/src/main/java/thereisnospon/com/blogreader/test_mvp_test/view/IArticleCacheView.java
Java
mit
334
/* * Titan Robotics Framework Library * Copyright (c) 2015 Titan Robotics Club (http://www.titanrobotics.net) * * 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 hallib; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.tables.TableKeyNotDefinedException; import trclib.TrcDbgTrace; /** * This class is a wrapper for the Telemetry class. In addition to providing * a way to send named data to the Driver Station to be displayed, it also * simulates an LCD display similar to the NXT Mindstorms. The Mindstorms * has only 8 lines but this dashboard can support as many lines as the * Driver Station can support. By default, we set the number of lines to 16. * By changing a constant here, you can have as many lines as you want. This * dashboard display is very useful for displaying debug information. In * particular, the TrcMenu class uses the dashboard to display a choice menu * and interact with the user for choosing autonomous strategies and options. */ public class HalDashboard extends SmartDashboard { private static final String moduleName = "HalDashboard"; private static final boolean debugEnabled = false; private TrcDbgTrace dbgTrace = null; public static final int MAX_NUM_TEXTLINES = 16; private static final String displayKeyFormat = "%02d"; private static HalDashboard instance = null; private static String[] display = new String[MAX_NUM_TEXTLINES]; /** * Constructor: Creates an instance of the object. * There should only be one global instance of this object. * Typically, only the FtcOpMode object should construct an * instance of this object via getInstance(telemetry) and * nobody else. */ public HalDashboard() { if (debugEnabled) { dbgTrace = new TrcDbgTrace( moduleName, false, TrcDbgTrace.TraceLevel.API, TrcDbgTrace.MsgLevel.INFO); } instance = this; clearDisplay(); } //HalDashboard /** * This static method allows any class to get an instance of * the dashboard so that it can display information on its * display. * * @return global instance of the dashboard object. */ public static HalDashboard getInstance() { return instance; } //getInstance /** * This method displays a formatted message to the display on the Driver Station. * * @param lineNum specifies the line number on the display. * @param format specifies the format string. * @param args specifies variable number of substitution arguments. */ public void displayPrintf(int lineNum, String format, Object... args) { if (lineNum >= 0 && lineNum < display.length) { display[lineNum] = String.format(format, args); SmartDashboard.putString( String.format(displayKeyFormat, lineNum), display[lineNum]); } } //displayPrintf /** * This method clears all the display lines. */ public void clearDisplay() { final String funcName = "clearDisplay"; if (debugEnabled) { dbgTrace.traceEnter(funcName, TrcDbgTrace.TraceLevel.API); dbgTrace.traceExit(funcName, TrcDbgTrace.TraceLevel.API); } for (int i = 0; i < display.length; i++) { display[i] = ""; } refreshDisplay(); } //clearDisplay /** * This method refresh the display lines to the Driver Station. */ public void refreshDisplay() { final String funcName = "refreshDisplay"; if (debugEnabled) { dbgTrace.traceEnter(funcName, TrcDbgTrace.TraceLevel.API); dbgTrace.traceExit(funcName, TrcDbgTrace.TraceLevel.API); } for (int i = 0; i < display.length; i++) { SmartDashboard.putString( String.format(displayKeyFormat, i), display[i]); } } //refreshDisplay public static boolean getBoolean(String key, boolean defaultValue) { boolean value; try { value = getBoolean(key); } catch (TableKeyNotDefinedException e) { putBoolean(key, defaultValue); value = defaultValue; } return value; } //getBoolean public static double getNumber(String key, double defaultValue) { double value; try { value = getNumber(key); } catch (TableKeyNotDefinedException e) { putNumber(key, defaultValue); value = defaultValue; } return value; } //getNumber public static String getString(String key, String defaultValue) { String value; try { value = getString(key); } catch (TableKeyNotDefinedException e) { putString(key, defaultValue); value = defaultValue; } return value; } //getString } //class HalDashboard
trc492/Frc2016FirstStronghold
FirstStronghold/src/hallib/HalDashboard.java
Java
mit
6,229
package eu.bcvsolutions.idm.core.monitoring.event.processor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Description; import org.springframework.stereotype.Component; import eu.bcvsolutions.idm.core.api.event.CoreEvent; import eu.bcvsolutions.idm.core.api.event.CoreEventProcessor; import eu.bcvsolutions.idm.core.api.event.DefaultEventResult; import eu.bcvsolutions.idm.core.api.event.EntityEvent; import eu.bcvsolutions.idm.core.api.event.EventResult; import eu.bcvsolutions.idm.core.api.service.IdmCacheManager; import eu.bcvsolutions.idm.core.monitoring.api.dto.IdmMonitoringResultDto; import eu.bcvsolutions.idm.core.monitoring.api.event.MonitoringResultEvent.MonitoringResultEventType; import eu.bcvsolutions.idm.core.monitoring.api.event.processor.MonitoringResultProcessor; import eu.bcvsolutions.idm.core.monitoring.api.service.MonitoringManager; /** * Clear last result cache, when monitoring result is deleted. * * @author Radek Tomiška * @since 11.1.0 */ @Component(MonitoringResultEvictCacheProcessor.PROCESSOR_NAME) @Description("Clear last result cache, when monitoring result is deleted..") public class MonitoringResultEvictCacheProcessor extends CoreEventProcessor<IdmMonitoringResultDto> implements MonitoringResultProcessor { public static final String PROCESSOR_NAME = "core-monitoring-result-evict-cache-processor"; // @Autowired private IdmCacheManager cacheManager; public MonitoringResultEvictCacheProcessor() { super(MonitoringResultEventType.DELETE); } @Override public String getName() { return PROCESSOR_NAME; } @Override public EventResult<IdmMonitoringResultDto> process(EntityEvent<IdmMonitoringResultDto> event) { cacheManager.evictCache(MonitoringManager.LAST_RESULT_CACHE_NAME); // return new DefaultEventResult<>(event, this); } @Override public int getOrder() { return CoreEvent.DEFAULT_ORDER + 10; } }
bcvsolutions/CzechIdMng
Realization/backend/core/core-impl/src/main/java/eu/bcvsolutions/idm/core/monitoring/event/processor/MonitoringResultEvictCacheProcessor.java
Java
mit
1,953
package com.arthur.webnovel.dao; import org.hibernate.Criteria; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import com.arthur.webnovel.entity.Chapter; import com.arthur.webnovel.entity.Story; @Repository public class ChapterDao extends DaoBase{ public Integer insert(Chapter chapter) { return (Integer) session().save(chapter); } public Chapter get(Story story, int chapterId){ Criteria q = session().createCriteria(Chapter.class); q.add(Restrictions.eq("id", chapterId)) .add(Restrictions.eq("story", story)); return (Chapter) q.uniqueResult(); } public void update(Chapter chapter) { session().update(chapter); } }
remagine/webNovel
src/main/java/com/arthur/webnovel/dao/ChapterDao.java
Java
mit
747
package org.fredy.learningandroid; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; public class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener { private SharedPreferences prefs; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); } @Override public void onStart() { super.onStart(); prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); prefs.registerOnSharedPreferenceChangeListener(this); // TODO Auto-generated method stub } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { } }
fredyw/learning-android
LearningAndroid/src/org/fredy/learningandroid/SettingsFragment.java
Java
mit
970
package org.jzp.code.tree.rules; import org.jzp.code.tree.rules.element.Element; import org.jzp.code.tree.rules.element.ElementManager; import org.jzp.code.tree.rules.element.support.ElementManagerKeys; import org.jzp.code.tree.rules.element.support.PrintElementManager; import org.jzp.code.tree.rules.element.support.RoutedElementManager; import org.jzp.code.tree.rules.element.support.SystemElementManager; import org.jzp.code.tree.rules.executor.DefaultProcessExecutor; import org.jzp.code.tree.rules.parser.ScriptParser; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 脚本解析器测试类 * * @author jiazhipeng * @version 1.0 * @date 2016-11-08 */ public class ScriptParserTest { public static void main(String[] args) { RoutedElementManager rem = new RoutedElementManager(); Map<String, ElementManager> hash = new HashMap<String, ElementManager>(); hash.put("test", new TestElementManager()); hash.put(ElementManagerKeys.KEY_SYSTEM, new SystemElementManager()); hash.put(ElementManagerKeys.KEY_PRINT, new PrintElementManager()); rem.setManagerMap(hash); String json = "[{\"key\":\"1\",\"root\":{\"type\":0,\"element\":{\"op\":\"WHEN\"},\"left\":{\"type\":0,\"element\":{\"op\":\"AND\"},\"left\":{\"type\":0,\"element\":{\"op\":\"OR\"},\"left\":{\"type\":1,\"element\":{\"type\":\"condition\",\"metaId\":\"sys:true\"}},\"right\":{\"type\":1,\"element\":{\"type\":\"condition\",\"metaId\":\"sys:false\"}}},\"right\":{\"type\":1,\"element\":{\"type\":\"condition\",\"metaId\":\"sys:true\"}}},\"right\":{\"type\":1,\"element\":{\"type\":\"action\",\"metaId\":\"print:hahahahahahahahaha\"}}}}]"; //String json = "[{\"key\":\"1\",\"root\":{\"type\":0,\"element\":{\"op\":\"WHEN\"},\"left\":{\"type\":1,\"element\":{\"type\":\"condition\",\"metaId\":\"sys:true\"}},\"right\":{\"type\":1,\"element\":{\"type\":\"action\",\"metaId\":\"print:fuck!\"}}}},{\"key\":\"2\",\"root\":{\"type\":0,\"element\":{\"op\":\"WHEN\"},\"left\":{\"type\":1,\"element\":{\"type\":\"condition\",\"metaId\":\"12345\"}},\"right\":{\"type\":1,\"element\":{\"type\":\"action\",\"metaId\":\"123456\"}}}},{\"key\":\"3\",\"root\":{\"type\":0,\"element\":{\"op\":\"WHEN\"},\"left\":{\"type\":1,\"element\":{\"type\":\"condition\",\"metaId\":\"12345\"}},\"right\":{\"type\":1,\"element\":{\"type\":\"action\",\"metaId\":\"123456\"}}}}]"; ScriptParser parser = new ScriptParser(); parser.setElementManager(rem); Map<String, List<Element>> processMap = parser.parse(json); System.out.println(processMap); List<Element> elements = processMap.get("1"); DefaultProcessExecutor executor = new DefaultProcessExecutor(); executor.execute(elements, null); } }
jzpyoung/tree-rules
src/test/java/org/jzp/code/tree/rules/ScriptParserTest.java
Java
mit
2,793
package com.yaozongyou.broadcastbestpractice; import android.app.Activity; import android.os.Bundle; import android.widget.Button; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; public class MainActivity extends BaseActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button forceOffline = (Button)findViewById(R.id.force_offline); forceOffline.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("com.yaozongyou.broadcastbestpractice.FORCE_OFFLINE"); sendBroadcast(intent); } }); } }
yaozongyou/android-first-code
BroadcastBestPractice/src/main/java/com/yaozongyou/broadcastbestpractice/MainActivity.java
Java
mit
862
package uk.joshiejack.penguinlib.item.interfaces; public interface IPenguinItem { void registerModels(); }
joshiejack/Harvest-Festival
src/main/java/uk/joshiejack/penguinlib/item/interfaces/IPenguinItem.java
Java
mit
112
package net.afterlifelochie.fontbox.document; import net.afterlifelochie.fontbox.api.data.FormattedString; import net.afterlifelochie.fontbox.api.exception.LayoutException; import net.afterlifelochie.fontbox.api.formatting.layout.AlignmentMode; import net.afterlifelochie.fontbox.api.layout.IIndexed; import net.afterlifelochie.fontbox.api.layout.IPage; import net.afterlifelochie.fontbox.api.layout.IPageWriter; import net.afterlifelochie.fontbox.api.tracer.ITracer; import net.minecraft.client.gui.GuiScreen; import java.io.IOException; import java.util.List; public class Link extends Element { /** * The heading text string */ public FormattedString text; /** * The link ID */ public String id; /** * The hover lines */ public List<String> lines; /** * Creates a new Link element * * @param text The link's text value * @param id The unique identifier that it links to */ public Link(FormattedString text, String id) { this(text, id, null); } public Link(FormattedString text, String toUid, List<String> lines) { this.text = text; this.id = toUid; this.lines = lines; } @Override public void layout(ITracer trace, IPageWriter writer) throws IOException, LayoutException { IPage page = writer.current(); boxText(trace, writer, page.getProperties().headingFormat, text, AlignmentMode.LEFT, this); writer.cursor().pushDown(10); } @Override public boolean canUpdate() { return false; } @Override public void update() { /* No action required */ } @Override public boolean canCompileRender() { return true; } @Override public void render(GuiScreen gui, int mx, int my, float frame) { /* No action required */ } @Override public void clicked(IIndexed gui, int mx, int my) { gui.go(id); } @Override public void typed(GuiScreen gui, char val, int code) { /* No action required */ } @Override public void hover(GuiScreen gui, int mx, int my) { if (lines != null && !lines.isEmpty()) { gui.drawHoveringText(lines, mx, my); } } }
way2muchnoise/fontbox
src/main/java/net/afterlifelochie/fontbox/document/Link.java
Java
mit
2,258
import java.io.*; class perfect_square { public static void main()throws IOException { int i,j,n,b,d,c=0,m=0,k,l; double a; BufferedReader dr=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the last limit"); n=Integer.parseInt(dr.readLine()); for(i=1;i<=n;i++) { a=Math.sqrt(i); for(j=1;j<=i;j++) { if(a==j) { b=i; while(b!=0) { d=b%10; c=c+1; b=b/10; } b=i; int z[]=new int[c]; for(k=0;k<c;k++) { m=0; for(l=0;l<c;l++) { if(z[k]==z[l]) { m=m+1; } } if(m!=0) { System.out.println(i); } } } } } } }
shikhar29111996/Java-programs
pwefect_square.java
Java
mit
1,310
package cn.edu.gdut.zaoying; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by 祖荣 on 2016/2/19 0019. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface DuplexChart { String exportTo() default ""; String extendFrom() default ""; }
zaoying/EChartsAnnotation
src/cn/edu/gdut/zaoying/DuplexChart.java
Java
mit
406
package com.helospark.lightdi.it.customconditional; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; @Retention(RUNTIME) @Target({TYPE, METHOD}) public @interface ConditionalOnBeanNameContaining { public String nameContains(); }
helospark/light-di
src/test/java/com/helospark/lightdi/it/customconditional/ConditionalOnBeanNameContaining.java
Java
mit
432
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.09.27 at 07:46:05 PM BST // package org.purl.dc.terms; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;simpleContent> * &lt;extension base="&lt;http://www.w3.org/2001/XMLSchema>string"> * &lt;attribute ref="{http://www.w3.org/2000/01/rdf-schema#}label use="required""/> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @XmlRootElement(name = "replaces") public class Replaces { @XmlValue protected String value; @XmlAttribute(name = "label", namespace = "http://www.w3.org/2000/01/rdf-schema#", required = true) protected String label; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } /** * Gets the value of the label property. * * @return * possible object is * {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value * allowed object is * {@link String } * */ public void setLabel(String value) { this.label = value; } }
digitalheir/java-rechtspraak-library
src/main/java/org/purl/dc/terms/Replaces.java
Java
mit
2,334
package com.stripe; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import com.google.common.base.Joiner; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.regex.Pattern; import org.junit.jupiter.api.Test; public class DocumentationTest { private static String formatDateTime() { Calendar instance = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); String formattedDate = format.format(instance.getTime()); String result = "## " + Stripe.VERSION + " - " + formattedDate; return result; } @Test public void testChangeLogContainsStaticVersion() throws IOException { final File changelogFile = new File("CHANGELOG.md").getAbsoluteFile(); assertTrue( changelogFile.exists(), String.format( "Expected CHANGELOG file to exist, but it doesn't. (path is %s).", changelogFile.getAbsolutePath())); assertTrue( changelogFile.isFile(), String.format( "Expected CHANGELOG to be a file, but it isn't. (path is %s).", changelogFile.getAbsolutePath())); try (final BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(changelogFile), StandardCharsets.UTF_8))) { final String expectedLine = formatDateTime(); final String pattern = String.format( "^## %s - 20[12][0-9]-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$", Stripe.VERSION); final List<String> closeMatches = new ArrayList<String>(); String line; while ((line = reader.readLine()) != null) { if (line.contains(Stripe.VERSION)) { if (Pattern.matches(pattern, line)) { return; } closeMatches.add(line); } } fail( String.format( "Expected a line of the format '%s' in the CHANGELOG, but didn't find one.%n" + "The following lines were close, but didn't match exactly:%n'%s'", expectedLine, Joiner.on(", ").join(closeMatches))); } } @Test public void testReadMeContainsStripeVersionThatMatches() throws IOException { // this will be very flaky, but we want to ensure that the readme is correct. final File readmeFile = new File("README.md").getAbsoluteFile(); assertTrue( readmeFile.exists(), String.format( "Expected README.md file to exist, but it doesn't. (path is %s).", readmeFile.getAbsolutePath())); assertTrue( readmeFile.isFile(), String.format( "Expected README.md to be a file, but it doesn't. (path is %s).", readmeFile.getAbsolutePath())); try (final BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(readmeFile), StandardCharsets.UTF_8))) { final int expectedMentionsOfVersion = 2; // Currently two places mention the Stripe version: the sample pom and gradle files. final List<String> mentioningLines = new ArrayList<String>(); String line; while ((line = reader.readLine()) != null) { if (line.contains(Stripe.VERSION)) { mentioningLines.add(line); } } final String message = String.format( "Expected %d mentions of the stripe-java version in the Readme, but found %d:%n%s", expectedMentionsOfVersion, mentioningLines.size(), Joiner.on(", ").join(mentioningLines)); assertSame(expectedMentionsOfVersion, mentioningLines.size(), message); } } @Test public void testGradlePropertiesContainsVersionThatMatches() throws IOException { // we want to ensure that the pom's version matches the static version. final File gradleFile = new File("gradle.properties").getAbsoluteFile(); assertTrue( gradleFile.exists(), String.format( "Expected gradle.properties file to exist, but it doesn't. (path is %s).", gradleFile.getAbsolutePath())); try (final BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(gradleFile), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { if (line.contains(Stripe.VERSION)) { return; } } fail( String.format( "Expected the Stripe.VERSION (%s) to match up with the one listed in the " + "gradle.properties file. It wasn't found.", Stripe.VERSION)); } } }
stripe/stripe-java
src/test/java/com/stripe/DocumentationTest.java
Java
mit
5,017
package com.rion.traqt.model.repositories; import android.content.ContentValues; import android.database.Cursor; import com.rion.traqt.model.TraqtDbHelper; import com.rion.traqt.model.entities.EntityBase; import com.rion.traqt.model.helpers.SQLiteTableDefinition; import java.util.ArrayList; import java.util.List; /** * Criado por RioN em 02/03/2016 para o projeto Traqt. * Classe base de um repositório de dados. * O repositório base assume trabalhar com objetos que herdam da classe "BaseEntity" e que tem o campo ID como chave-primária. */ public abstract class RepositoryBase<T extends EntityBase> { // // -- CAMPOS protected TraqtDbHelper dbHelper; protected SQLiteTableDefinition tableDefinition; // // -- CONSTRUTORES /** * Cria uma instância desse repositório. * @param dbHelper Objeto dbHelper para manipulação do banco de dados. * @param tableDefinition Definição da tabela com a qual esse repositório irá trabalhar. */ public RepositoryBase(TraqtDbHelper dbHelper, SQLiteTableDefinition tableDefinition) { this.dbHelper = dbHelper; this.tableDefinition = tableDefinition; } /** * Adiciona um novo registro do objeto ao banco de dados, gerando um novo identificador. * @param obj Objeto que deseja inserir no banco de dados. * @return Identificador do registro inserido ou -1 caso tenha ocorrido alguma falha. */ public long insert(T obj) { ContentValues contentValues = obj.getContentValues(); return dbHelper.getWritableDatabase().insert(tableDefinition.getName(), null, contentValues); } /** * Atualiza um registro existente no banco de dados. * @param obj O objeto representando o registro * @return A quantidade de registros afetados por essa operação. */ public long update(T obj) { ContentValues contentValues = obj.getContentValues(); String whereClause = "id = ?"; String[] whereArgs = { String.valueOf(obj.getId()) }; return dbHelper.getWritableDatabase() .update(tableDefinition.getName(), contentValues, whereClause, whereArgs); } /** * Exclui um registro do banco de dados. * @param obj O registro que deseja excluir. * @return A quantidade de registros afetados por essa operação. */ public int delete(T obj) { String whereClause = "id = ?"; String[] whereArgs = { String.valueOf(obj.getId()) }; return dbHelper.getWritableDatabase().delete(tableDefinition.getName(), whereClause, whereArgs); } /** * Obtém um Cursor para enumerar todos os regitros dessa entidade. * @return Um objeto do tipo Cursor selecionando todos os registros da entidade. */ public Cursor getCursorForAll() { return dbHelper.getReadableDatabase().query(tableDefinition.getName(), tableDefinition.getColumnNames(), null, null, null, null, null); } /** * Obtém um Cursor para enumerar os registros de acordo com os critérios de seleção. * @param selection Um predicate definindo os critérios de busca. * @param selectionArgs Uma lista de valores correspondentes aos critérios de busca passados. * @return Um objeto do tipo Cursor selecionando os registros de acordo com os critérios. */ public Cursor getCursorWhere(String selection, String ... selectionArgs) { return dbHelper.getReadableDatabase().query(tableDefinition.getName(), tableDefinition.getColumnNames(), selection, selectionArgs, null, null, null); } /** * Obtém um registro a partir de seu identificador. * @param id O identificador do registro. * @return O registro conforme seu identificador ou nulo se não for encontrado. */ public T findById(int id) { String selection = "id = ?"; String[] selectionArgs = { String.valueOf(id) }; Cursor cursor = getCursorWhere(selection, selectionArgs); if (cursor.moveToFirst()) { return fromCursor(cursor); } return null; } /** * Obtém a lista completa de registros dessa entidade. * @return Uma lista com todos os registros da entidade. */ public List<T> findAll() { List<T> objects = new ArrayList<>(); Cursor cursor = getCursorForAll(); while (cursor.moveToNext()) { objects.add(fromCursor(cursor)); } return objects; } /** * Obtém a lista de registros de acordo com os critérios passados. * @param selection Um Predicate SQLite com os critério de seleção dos registros. * @param selectionArgs A lista de valores correspondentes aos critérios de seleção. * @return Uma lista com os registros obedecendo os critérios de busca. */ public List<T> findWhere(String selection, String ... selectionArgs) { List<T> objects = new ArrayList<>(); Cursor cursor = getCursorWhere(selection, selectionArgs); while (cursor.moveToNext()) { objects.add(fromCursor(cursor)); } return objects; } // // -- MÉTODOS ABSTRATOS /** * Obtém uma instância do objeto da entidade a partir de um cursor. * @param cursor O cursor que contém os dados para serem carregados na nova instância. * @return Uma nova instância contendo os dados do cursor. */ protected abstract T fromCursor(Cursor cursor); }
rogerioit/Traqt
app/src/main/java/com/rion/traqt/model/repositories/RepositoryBase.java
Java
mit
5,675
/****************************************************************************** * Copyright (c) 2016 TypeFox and others. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, * or the Eclipse Distribution License v. 1.0 which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause ******************************************************************************/ package org.eclipse.lsp4j.jsonrpc.services; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * A method annotated with {@link JsonDelegate} is treated as a delegate method. * As a result jsonrpc methods of the delegate will be considered, too. * If an annotated method returns `null` * then jsonrpc methods of the delegate are not considered. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface JsonDelegate { }
smarr/SOMns-vscode
server/org.eclipse.lsp4j.jsonrpc/org/eclipse/lsp4j/jsonrpc/services/JsonDelegate.java
Java
mit
1,137
package pl.tomaszdziurko.jvm_bloggers.metadata; public interface MetadataKeys { String MAILING_TEMPLATE = "MAILING_TEMPLATE"; String ADMIN_EMAIL = "ADMIN_EMAIL"; String DEFAULT_MAILING_TEMPLATE = "DEFAULT_MAILING_TEMPLATE"; String MAILING_GREETING = "MAILING_GREETING"; String HEADING_TEMPLATE = "HEADING_TEMPLATE"; String VARIA_TEMPLATE = "VARIA_TEMPLATE"; String MAILING_SIGNATURE = "MAILING_SIGNATURE"; String DATE_OF_LAST_FETCHING_BLOGGERS = "DATE_OF_LAST_FETCHING_BLOGGERS"; String DATE_OF_LAST_FETCHING_BLOG_POSTS = "DATE_OF_LAST_FETCHING_BLOG_POSTS"; }
sobkowiak/jvm-bloggers
src/main/java/pl/tomaszdziurko/jvm_bloggers/metadata/MetadataKeys.java
Java
mit
603
package operators.solution; import java.util.*; public class Ex4 { int distance = 100; float time = 9.88f; public static void main(String[] args){ Ex4 ob = new Ex4(); float speed = ob.distance / ob.time; System.out.println("Speed:" + speed); } }
shalk/TIJ4Code
operators/solution/Ex4.java
Java
mit
271
package net.minecraft.entity.ai; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import net.minecraft.block.Block; import net.minecraft.block.BlockTallGrass; import net.minecraft.block.state.pattern.BlockStateHelper; import net.minecraft.entity.EntityLiving; import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; public class EntityAIEatGrass extends EntityAIBase { private static final Predicate field_179505_b = BlockStateHelper.forBlock(Blocks.tallgrass).func_177637_a(BlockTallGrass.field_176497_a, Predicates.equalTo(BlockTallGrass.EnumType.GRASS)); /** The entity owner of this AITask */ private EntityLiving grassEaterEntity; /** The world the grass eater entity is eating from */ private World entityWorld; /** Number of ticks since the entity started to eat grass */ int eatingGrassTimer; private static final String __OBFID = "CL_00001582"; public EntityAIEatGrass(EntityLiving p_i45314_1_) { this.grassEaterEntity = p_i45314_1_; this.entityWorld = p_i45314_1_.worldObj; this.setMutexBits(7); } /** * Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (this.grassEaterEntity.getRNG().nextInt(this.grassEaterEntity.isChild() ? 50 : 1000) != 0) { return false; } else { BlockPos var1 = new BlockPos(this.grassEaterEntity.posX, this.grassEaterEntity.posY, this.grassEaterEntity.posZ); return field_179505_b.apply(this.entityWorld.getBlockState(var1)) ? true : this.entityWorld.getBlockState(var1.offsetDown()).getBlock() == Blocks.grass; } } /** * Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.eatingGrassTimer = 40; this.entityWorld.setEntityState(this.grassEaterEntity, (byte)10); this.grassEaterEntity.getNavigator().clearPathEntity(); } /** * Resets the task */ public void resetTask() { this.eatingGrassTimer = 0; } /** * Returns whether an in-progress EntityAIBase should continue executing */ public boolean continueExecuting() { return this.eatingGrassTimer > 0; } /** * Number of ticks since the entity started to eat grass */ public int getEatingGrassTimer() { return this.eatingGrassTimer; } /** * Updates the task */ public void updateTask() { this.eatingGrassTimer = Math.max(0, this.eatingGrassTimer - 1); if (this.eatingGrassTimer == 4) { BlockPos var1 = new BlockPos(this.grassEaterEntity.posX, this.grassEaterEntity.posY, this.grassEaterEntity.posZ); if (field_179505_b.apply(this.entityWorld.getBlockState(var1))) { if (this.entityWorld.getGameRules().getGameRuleBooleanValue("mobGriefing")) { this.entityWorld.destroyBlock(var1, false); } this.grassEaterEntity.eatGrassBonus(); } else { BlockPos var2 = var1.offsetDown(); if (this.entityWorld.getBlockState(var2).getBlock() == Blocks.grass) { if (this.entityWorld.getGameRules().getGameRuleBooleanValue("mobGriefing")) { this.entityWorld.playAuxSFX(2001, var2, Block.getIdFromBlock(Blocks.grass)); this.entityWorld.setBlockState(var2, Blocks.dirt.getDefaultState(), 2); } this.grassEaterEntity.eatGrassBonus(); } } } } }
Hexeption/Youtube-Hacked-Client-1.8
minecraft/net/minecraft/entity/ai/EntityAIEatGrass.java
Java
mit
3,846
/* * Copyright (C) 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 me.kglawrence.kerilawrence.book_park.ui.camera; import android.Manifest; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.graphics.ImageFormat; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.hardware.Camera.CameraInfo; import android.os.Build; import android.os.SystemClock; import android.support.annotation.Nullable; import android.support.annotation.RequiresPermission; import android.support.annotation.StringDef; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.WindowManager; import com.google.android.gms.common.images.Size; import com.google.android.gms.vision.Detector; import com.google.android.gms.vision.Frame; import java.io.IOException; import java.lang.Thread.State; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; // Note: This requires Google Play Services 8.1 or higher, due to using indirect byte buffers for // storing images. /** * Manages the camera in conjunction with an underlying * {@link com.google.android.gms.vision.Detector}. This receives preview frames from the camera at * a specified rate, sending those frames to the detector as fast as it is able to process those * frames. * <p/> * This camera source makes a best effort to manage processing on preview frames as fast as * possible, while at the same time minimizing lag. As such, frames may be dropped if the detector * is unable to keep up with the rate of frames generated by the camera. You should use * {@link CameraSource.Builder#setRequestedFps(float)} to specify a frame rate that works well with * the capabilities of the camera hardware and the detector options that you have selected. If CPU * utilization is higher than you'd like, then you may want to consider reducing FPS. If the camera * preview or detector results are too "jerky", then you may want to consider increasing FPS. * <p/> * The following Android permission is required to use the camera: * <ul> * <li>android.permissions.CAMERA</li> * </ul> */ @SuppressWarnings("deprecation") public class CameraSource { @SuppressLint("InlinedApi") public static final int CAMERA_FACING_BACK = CameraInfo.CAMERA_FACING_BACK; @SuppressLint("InlinedApi") public static final int CAMERA_FACING_FRONT = CameraInfo.CAMERA_FACING_FRONT; private static final String TAG = "OpenCameraSource"; /** * The dummy surface texture must be assigned a chosen name. Since we never use an OpenGL * context, we can choose any ID we want here. */ private static final int DUMMY_TEXTURE_NAME = 100; /** * If the absolute difference between a preview size aspect ratio and a picture size aspect * ratio is less than this tolerance, they are considered to be the same aspect ratio. */ private static final float ASPECT_RATIO_TOLERANCE = 0.01f; @StringDef({ Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE, Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO, Camera.Parameters.FOCUS_MODE_AUTO, Camera.Parameters.FOCUS_MODE_EDOF, Camera.Parameters.FOCUS_MODE_FIXED, Camera.Parameters.FOCUS_MODE_INFINITY, Camera.Parameters.FOCUS_MODE_MACRO }) @Retention(RetentionPolicy.SOURCE) private @interface FocusMode {} @StringDef({ Camera.Parameters.FLASH_MODE_ON, Camera.Parameters.FLASH_MODE_OFF, Camera.Parameters.FLASH_MODE_AUTO, Camera.Parameters.FLASH_MODE_RED_EYE, Camera.Parameters.FLASH_MODE_TORCH }) @Retention(RetentionPolicy.SOURCE) private @interface FlashMode {} private Context mContext; private final Object mCameraLock = new Object(); // Guarded by mCameraLock private Camera mCamera; private int mFacing = CAMERA_FACING_FRONT; /** * Rotation of the device, and thus the associated preview images captured from the device. * See {@link Frame.Metadata#getRotation()}. */ private int mRotation; private Size mPreviewSize; // These values may be requested by the caller. Due to hardware limitations, we may need to // select close, but not exactly the same values for these. private float mRequestedFps = 30.0f; private int mRequestedPreviewWidth = 1024; private int mRequestedPreviewHeight = 768; private String mFocusMode = null; private String mFlashMode = null; // These instances need to be held onto to avoid GC of their underlying resources. Even though // these aren't used outside of the method that creates them, they still must have hard // references maintained to them. private SurfaceView mDummySurfaceView; private SurfaceTexture mDummySurfaceTexture; /** * Dedicated thread and associated runnable for calling into the detector with frames, as the * frames become available from the camera. */ private Thread mProcessingThread; private FrameProcessingRunnable mFrameProcessor; /** * Map to convert between a byte array, received from the camera, and its associated byte * buffer. We use byte buffers internally because this is a more efficient way to call into * native code later (avoids a potential copy). */ private Map<byte[], ByteBuffer> mBytesToByteBuffer = new HashMap<>(); //============================================================================================== // Builder //============================================================================================== /** * Builder for configuring and creating an associated camera source. */ public static class Builder { private final Detector<?> mDetector; private CameraSource mCameraSource = new CameraSource(); /** * Creates a camera source builder with the supplied context and detector. Camera preview * images will be streamed to the associated detector upon starting the camera source. */ public Builder(Context context, Detector<?> detector) { if (context == null) { throw new IllegalArgumentException("No context supplied."); } if (detector == null) { throw new IllegalArgumentException("No detector supplied."); } mDetector = detector; mCameraSource.mContext = context; } /** * Sets the requested frame rate in frames per second. If the exact requested value is not * not available, the best matching available value is selected. Default: 30. */ public Builder setRequestedFps(float fps) { if (fps <= 0) { throw new IllegalArgumentException("Invalid fps: " + fps); } mCameraSource.mRequestedFps = fps; return this; } public Builder setFocusMode(@FocusMode String mode) { mCameraSource.mFocusMode = mode; return this; } public Builder setFlashMode(@FlashMode String mode) { mCameraSource.mFlashMode = mode; return this; } /** * Sets the desired width and height of the camera frames in pixels. If the exact desired * values are not available options, the best matching available options are selected. * Also, we try to select a preview size which corresponds to the aspect ratio of an * associated full picture size, if applicable. Default: 1024x768. */ public Builder setRequestedPreviewSize(int width, int height) { // Restrict the requested range to something within the realm of possibility. The // choice of 1000000 is a bit arbitrary -- intended to be well beyond resolutions that // devices can support. We bound this to avoid int overflow in the code later. final int MAX = 1000000; if ((width <= 0) || (width > MAX) || (height <= 0) || (height > MAX)) { throw new IllegalArgumentException("Invalid preview size: " + width + "x" + height); } mCameraSource.mRequestedPreviewWidth = width; mCameraSource.mRequestedPreviewHeight = height; return this; } /** * Sets the camera to use (either {@link #CAMERA_FACING_BACK} or * {@link #CAMERA_FACING_FRONT}). Default: back facing. */ public Builder setFacing(int facing) { if ((facing != CAMERA_FACING_BACK) && (facing != CAMERA_FACING_FRONT)) { throw new IllegalArgumentException("Invalid camera: " + facing); } mCameraSource.mFacing = facing; return this; } /** * Creates an instance of the camera source. */ public CameraSource build() { mCameraSource.mFrameProcessor = mCameraSource.new FrameProcessingRunnable(mDetector); return mCameraSource; } } //============================================================================================== // Bridge Functionality for the Camera1 API //============================================================================================== /** * Callback interface used to signal the moment of actual image capture. */ public interface ShutterCallback { /** * Called as near as possible to the moment when a photo is captured from the sensor. This * is a good opportunity to play a shutter sound or give other feedback of camera operation. * This may be some time after the photo was triggered, but some time before the actual data * is available. */ void onShutter(); } /** * Callback interface used to supply image data from a photo capture. */ public interface PictureCallback { /** * Called when image data is available after a picture is taken. The format of the data * is a jpeg binary. */ void onPictureTaken(byte[] data); } /** * Callback interface used to notify on completion of camera auto focus. */ public interface AutoFocusCallback { /** * Called when the camera auto focus completes. If the camera * does not support auto-focus and autoFocus is called, * onAutoFocus will be called immediately with a fake value of * <code>success</code> set to <code>true</code>. * <p/> * The auto-focus routine does not lock auto-exposure and auto-white * balance after it completes. * * @param success true if focus was successful, false if otherwise */ void onAutoFocus(boolean success); } /** * Callback interface used to notify on auto focus start and stop. * <p/> * <p>This is only supported in continuous autofocus modes -- {@link * Camera.Parameters#FOCUS_MODE_CONTINUOUS_VIDEO} and {@link * Camera.Parameters#FOCUS_MODE_CONTINUOUS_PICTURE}. Applications can show * autofocus animation based on this.</p> */ public interface AutoFocusMoveCallback { /** * Called when the camera auto focus starts or stops. * * @param start true if focus starts to move, false if focus stops to move */ void onAutoFocusMoving(boolean start); } //============================================================================================== // Public //============================================================================================== /** * Stops the camera and releases the resources of the camera and underlying detector. */ public void release() { synchronized (mCameraLock) { stop(); mFrameProcessor.release(); } } /** * Opens the camera and starts sending preview frames to the underlying detector. The preview * frames are not displayed. * * @throws IOException if the camera's preview texture or display could not be initialized */ @RequiresPermission(Manifest.permission.CAMERA) public CameraSource start() throws IOException { synchronized (mCameraLock) { if (mCamera != null) { return this; } mCamera = createCamera(); // SurfaceTexture was introduced in Honeycomb (11), so if we are running and // old version of Android. fall back to use SurfaceView. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mDummySurfaceTexture = new SurfaceTexture(DUMMY_TEXTURE_NAME); mCamera.setPreviewTexture(mDummySurfaceTexture); } else { mDummySurfaceView = new SurfaceView(mContext); mCamera.setPreviewDisplay(mDummySurfaceView.getHolder()); } mCamera.startPreview(); mProcessingThread = new Thread(mFrameProcessor); mFrameProcessor.setActive(true); mProcessingThread.start(); } return this; } /** * Opens the camera and starts sending preview frames to the underlying detector. The supplied * surface holder is used for the preview so frames can be displayed to the user. * * @param surfaceHolder the surface holder to use for the preview frames * @throws IOException if the supplied surface holder could not be used as the preview display */ @RequiresPermission(Manifest.permission.CAMERA) public CameraSource start(SurfaceHolder surfaceHolder) throws IOException { synchronized (mCameraLock) { if (mCamera != null) { return this; } mCamera = createCamera(); mCamera.setPreviewDisplay(surfaceHolder); mCamera.startPreview(); mProcessingThread = new Thread(mFrameProcessor); mFrameProcessor.setActive(true); mProcessingThread.start(); } return this; } /** * Closes the camera and stops sending frames to the underlying frame detector. * <p/> * This camera source may be restarted again by calling {@link #start()} or * {@link #start(SurfaceHolder)}. * <p/> * Call {@link #release()} instead to completely shut down this camera source and release the * resources of the underlying detector. */ public void stop() { synchronized (mCameraLock) { mFrameProcessor.setActive(false); if (mProcessingThread != null) { try { // Wait for the thread to complete to ensure that we can't have multiple threads // executing at the same time (i.e., which would happen if we called start too // quickly after stop). mProcessingThread.join(); } catch (InterruptedException e) { Log.d(TAG, "Frame processing thread interrupted on release."); } mProcessingThread = null; } // clear the buffer to prevent oom exceptions mBytesToByteBuffer.clear(); if (mCamera != null) { mCamera.stopPreview(); mCamera.setPreviewCallbackWithBuffer(null); try { // We want to be compatible back to Gingerbread, but SurfaceTexture // wasn't introduced until Honeycomb. Since the interface cannot use a SurfaceTexture, if the // developer wants to display a preview we must use a SurfaceHolder. If the developer doesn't // want to display a preview we use a SurfaceTexture if we are running at least Honeycomb. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mCamera.setPreviewTexture(null); } else { mCamera.setPreviewDisplay(null); } } catch (Exception e) { Log.e(TAG, "Failed to clear camera preview: " + e); } mCamera.release(); mCamera = null; } } } /** * Returns the preview size that is currently in use by the underlying camera. */ public Size getPreviewSize() { return mPreviewSize; } /** * Returns the selected camera; one of {@link #CAMERA_FACING_BACK} or * {@link #CAMERA_FACING_FRONT}. */ public int getCameraFacing() { return mFacing; } public int doZoom(float scale) { synchronized (mCameraLock) { if (mCamera == null) { return 0; } int currentZoom = 0; int maxZoom; Camera.Parameters parameters = mCamera.getParameters(); if (!parameters.isZoomSupported()) { Log.w(TAG, "Zoom is not supported on this device"); return currentZoom; } maxZoom = parameters.getMaxZoom(); currentZoom = parameters.getZoom() + 1; float newZoom; if (scale > 1) { newZoom = currentZoom + scale * (maxZoom / 10); } else { newZoom = currentZoom * scale; } currentZoom = Math.round(newZoom) - 1; if (currentZoom < 0) { currentZoom = 0; } else if (currentZoom > maxZoom) { currentZoom = maxZoom; } parameters.setZoom(currentZoom); mCamera.setParameters(parameters); return currentZoom; } } /** * Initiates taking a picture, which happens asynchronously. The camera source should have been * activated previously with {@link #start()} or {@link #start(SurfaceHolder)}. The camera * preview is suspended while the picture is being taken, but will resume once picture taking is * done. * * @param shutter the callback for image capture moment, or null * @param jpeg the callback for JPEG image data, or null */ public void takePicture(ShutterCallback shutter, PictureCallback jpeg) { synchronized (mCameraLock) { if (mCamera != null) { PictureStartCallback startCallback = new PictureStartCallback(); startCallback.mDelegate = shutter; PictureDoneCallback doneCallback = new PictureDoneCallback(); doneCallback.mDelegate = jpeg; mCamera.takePicture(startCallback, null, null, doneCallback); } } } /** * Gets the current focus mode setting. * * @return current focus mode. This value is null if the camera is not yet created. Applications should call {@link * #autoFocus(AutoFocusCallback)} to start the focus if focus * mode is FOCUS_MODE_AUTO or FOCUS_MODE_MACRO. * @see Camera.Parameters#FOCUS_MODE_AUTO * @see Camera.Parameters#FOCUS_MODE_INFINITY * @see Camera.Parameters#FOCUS_MODE_MACRO * @see Camera.Parameters#FOCUS_MODE_FIXED * @see Camera.Parameters#FOCUS_MODE_EDOF * @see Camera.Parameters#FOCUS_MODE_CONTINUOUS_VIDEO * @see Camera.Parameters#FOCUS_MODE_CONTINUOUS_PICTURE */ @Nullable @FocusMode public String getFocusMode() { return mFocusMode; } /** * Sets the focus mode. * * @param mode the focus mode * @return {@code true} if the focus mode is set, {@code false} otherwise * @see #getFocusMode() */ public boolean setFocusMode(@FocusMode String mode) { synchronized (mCameraLock) { if (mCamera != null && mode != null) { Camera.Parameters parameters = mCamera.getParameters(); if (parameters.getSupportedFocusModes().contains(mode)) { parameters.setFocusMode(mode); mCamera.setParameters(parameters); mFocusMode = mode; return true; } } return false; } } /** * Gets the current flash mode setting. * * @return current flash mode. null if flash mode setting is not * supported or the camera is not yet created. * @see Camera.Parameters#FLASH_MODE_OFF * @see Camera.Parameters#FLASH_MODE_AUTO * @see Camera.Parameters#FLASH_MODE_ON * @see Camera.Parameters#FLASH_MODE_RED_EYE * @see Camera.Parameters#FLASH_MODE_TORCH */ @Nullable @FlashMode public String getFlashMode() { return mFlashMode; } /** * Sets the flash mode. * * @param mode flash mode. * @return {@code true} if the flash mode is set, {@code false} otherwise * @see #getFlashMode() */ public boolean setFlashMode(@FlashMode String mode) { synchronized (mCameraLock) { if (mCamera != null && mode != null) { Camera.Parameters parameters = mCamera.getParameters(); if (parameters.getSupportedFlashModes().contains(mode)) { parameters.setFlashMode(mode); mCamera.setParameters(parameters); mFlashMode = mode; return true; } } return false; } } /** * Starts camera auto-focus and registers a callback function to run when * the camera is focused. This method is only valid when preview is active * (between {@link #start()} or {@link #start(SurfaceHolder)} and before {@link #stop()} or {@link #release()}). * <p/> * <p>Callers should check * {@link #getFocusMode()} to determine if * this method should be called. If the camera does not support auto-focus, * it is a no-op and {@link AutoFocusCallback#onAutoFocus(boolean)} * callback will be called immediately. * <p/> * <p>If the current flash mode is not * {@link Camera.Parameters#FLASH_MODE_OFF}, flash may be * fired during auto-focus, depending on the driver and camera hardware.<p> * * @param cb the callback to run * @see #cancelAutoFocus() */ public void autoFocus(@Nullable AutoFocusCallback cb) { synchronized (mCameraLock) { if (mCamera != null) { CameraAutoFocusCallback autoFocusCallback = null; if (cb != null) { autoFocusCallback = new CameraAutoFocusCallback(); autoFocusCallback.mDelegate = cb; } mCamera.autoFocus(autoFocusCallback); } } } /** * Cancels any auto-focus function in progress. * Whether or not auto-focus is currently in progress, * this function will return the focus position to the default. * If the camera does not support auto-focus, this is a no-op. * * @see #autoFocus(AutoFocusCallback) */ public void cancelAutoFocus() { synchronized (mCameraLock) { if (mCamera != null) { mCamera.cancelAutoFocus(); } } } /** * Sets camera auto-focus move callback. * * @param cb the callback to run * @return {@code true} if the operation is supported (i.e. from Jelly Bean), {@code false} otherwise */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public boolean setAutoFocusMoveCallback(@Nullable AutoFocusMoveCallback cb) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { return false; } synchronized (mCameraLock) { if (mCamera != null) { CameraAutoFocusMoveCallback autoFocusMoveCallback = null; if (cb != null) { autoFocusMoveCallback = new CameraAutoFocusMoveCallback(); autoFocusMoveCallback.mDelegate = cb; } mCamera.setAutoFocusMoveCallback(autoFocusMoveCallback); } } return true; } //============================================================================================== // Private //============================================================================================== /** * Only allow creation via the builder class. */ private CameraSource() { } /** * Wraps the camera1 shutter callback so that the deprecated API isn't exposed. */ private class PictureStartCallback implements Camera.ShutterCallback { private ShutterCallback mDelegate; @Override public void onShutter() { if (mDelegate != null) { mDelegate.onShutter(); } } } /** * Wraps the final callback in the camera sequence, so that we can automatically turn the camera * preview back on after the picture has been taken. */ private class PictureDoneCallback implements Camera.PictureCallback { private PictureCallback mDelegate; @Override public void onPictureTaken(byte[] data, Camera camera) { if (mDelegate != null) { mDelegate.onPictureTaken(data); } synchronized (mCameraLock) { if (mCamera != null) { mCamera.startPreview(); } } } } /** * Wraps the camera1 auto focus callback so that the deprecated API isn't exposed. */ private class CameraAutoFocusCallback implements Camera.AutoFocusCallback { private AutoFocusCallback mDelegate; @Override public void onAutoFocus(boolean success, Camera camera) { if (mDelegate != null) { mDelegate.onAutoFocus(success); } } } /** * Wraps the camera1 auto focus move callback so that the deprecated API isn't exposed. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private class CameraAutoFocusMoveCallback implements Camera.AutoFocusMoveCallback { private AutoFocusMoveCallback mDelegate; @Override public void onAutoFocusMoving(boolean start, Camera camera) { if (mDelegate != null) { mDelegate.onAutoFocusMoving(start); } } } /** * Opens the camera and applies the user settings. * * @throws RuntimeException if the method fails */ @SuppressLint("InlinedApi") private Camera createCamera() { int requestedCameraId = getIdForRequestedCamera(mFacing); if (requestedCameraId == -1) { throw new RuntimeException("Could not find requested camera."); } Camera camera = Camera.open(requestedCameraId); SizePair sizePair = selectSizePair(camera, mRequestedPreviewWidth, mRequestedPreviewHeight); if (sizePair == null) { throw new RuntimeException("Could not find suitable preview size."); } Size pictureSize = sizePair.pictureSize(); mPreviewSize = sizePair.previewSize(); int[] previewFpsRange = selectPreviewFpsRange(camera, mRequestedFps); if (previewFpsRange == null) { throw new RuntimeException("Could not find suitable preview frames per second range."); } Camera.Parameters parameters = camera.getParameters(); if (pictureSize != null) { parameters.setPictureSize(pictureSize.getWidth(), pictureSize.getHeight()); } parameters.setPreviewSize(mPreviewSize.getWidth(), mPreviewSize.getHeight()); parameters.setPreviewFpsRange( previewFpsRange[Camera.Parameters.PREVIEW_FPS_MIN_INDEX], previewFpsRange[Camera.Parameters.PREVIEW_FPS_MAX_INDEX]); parameters.setPreviewFormat(ImageFormat.NV21); setRotation(camera, parameters, requestedCameraId); if (mFocusMode != null) { if (parameters.getSupportedFocusModes().contains( mFocusMode)) { parameters.setFocusMode(mFocusMode); } else { Log.i(TAG, "Camera focus mode: " + mFocusMode + " is not supported on this device."); } } // setting mFocusMode to the one set in the params mFocusMode = parameters.getFocusMode(); if (mFlashMode != null) { if (parameters.getSupportedFlashModes() != null) { if (parameters.getSupportedFlashModes().contains( mFlashMode)) { parameters.setFlashMode(mFlashMode); } else { Log.i(TAG, "Camera flash mode: " + mFlashMode + " is not supported on this device."); } } } // setting mFlashMode to the one set in the params mFlashMode = parameters.getFlashMode(); camera.setParameters(parameters); // Four frame buffers are needed for working with the camera: // // one for the frame that is currently being executed upon in doing detection // one for the next pending frame to process immediately upon completing detection // two for the frames that the camera uses to populate future preview images camera.setPreviewCallbackWithBuffer(new CameraPreviewCallback()); camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize)); camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize)); camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize)); camera.addCallbackBuffer(createPreviewBuffer(mPreviewSize)); return camera; } /** * Gets the id for the camera specified by the direction it is facing. Returns -1 if no such * camera was found. * * @param facing the desired camera (front-facing or rear-facing) */ private static int getIdForRequestedCamera(int facing) { CameraInfo cameraInfo = new CameraInfo(); for (int i = 0; i < Camera.getNumberOfCameras(); ++i) { Camera.getCameraInfo(i, cameraInfo); if (cameraInfo.facing == facing) { return i; } } return -1; } /** * Selects the most suitable preview and picture size, given the desired width and height. * <p/> * Even though we may only need the preview size, it's necessary to find both the preview * size and the picture size of the camera together, because these need to have the same aspect * ratio. On some hardware, if you would only set the preview size, you will get a distorted * image. * * @param camera the camera to select a preview size from * @param desiredWidth the desired width of the camera preview frames * @param desiredHeight the desired height of the camera preview frames * @return the selected preview and picture size pair */ private static SizePair selectSizePair(Camera camera, int desiredWidth, int desiredHeight) { List<SizePair> validPreviewSizes = generateValidPreviewSizeList(camera); // The method for selecting the best size is to minimize the sum of the differences between // the desired values and the actual values for width and height. This is certainly not the // only way to select the best size, but it provides a decent tradeoff between using the // closest aspect ratio vs. using the closest pixel area. SizePair selectedPair = null; int minDiff = Integer.MAX_VALUE; for (SizePair sizePair : validPreviewSizes) { Size size = sizePair.previewSize(); int diff = Math.abs(size.getWidth() - desiredWidth) + Math.abs(size.getHeight() - desiredHeight); if (diff < minDiff) { selectedPair = sizePair; minDiff = diff; } } return selectedPair; } /** * Stores a preview size and a corresponding same-aspect-ratio picture size. To avoid distorted * preview images on some devices, the picture size must be set to a size that is the same * aspect ratio as the preview size or the preview may end up being distorted. If the picture * size is null, then there is no picture size with the same aspect ratio as the preview size. */ private static class SizePair { private Size mPreview; private Size mPicture; public SizePair(android.hardware.Camera.Size previewSize, android.hardware.Camera.Size pictureSize) { mPreview = new Size(previewSize.width, previewSize.height); if (pictureSize != null) { mPicture = new Size(pictureSize.width, pictureSize.height); } } public Size previewSize() { return mPreview; } @SuppressWarnings("unused") public Size pictureSize() { return mPicture; } } /** * Generates a list of acceptable preview sizes. Preview sizes are not acceptable if there is * not a corresponding picture size of the same aspect ratio. If there is a corresponding * picture size of the same aspect ratio, the picture size is paired up with the preview size. * <p/> * This is necessary because even if we don't use still pictures, the still picture size must be * set to a size that is the same aspect ratio as the preview size we choose. Otherwise, the * preview images may be distorted on some devices. */ private static List<SizePair> generateValidPreviewSizeList(Camera camera) { Camera.Parameters parameters = camera.getParameters(); List<android.hardware.Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes(); List<android.hardware.Camera.Size> supportedPictureSizes = parameters.getSupportedPictureSizes(); List<SizePair> validPreviewSizes = new ArrayList<>(); for (android.hardware.Camera.Size previewSize : supportedPreviewSizes) { float previewAspectRatio = (float) previewSize.width / (float) previewSize.height; // By looping through the picture sizes in order, we favor the higher resolutions. // We choose the highest resolution in order to support taking the full resolution // picture later. for (android.hardware.Camera.Size pictureSize : supportedPictureSizes) { float pictureAspectRatio = (float) pictureSize.width / (float) pictureSize.height; if (Math.abs(previewAspectRatio - pictureAspectRatio) < ASPECT_RATIO_TOLERANCE) { validPreviewSizes.add(new SizePair(previewSize, pictureSize)); break; } } } // If there are no picture sizes with the same aspect ratio as any preview sizes, allow all // of the preview sizes and hope that the camera can handle it. Probably unlikely, but we // still account for it. if (validPreviewSizes.size() == 0) { Log.w(TAG, "No preview sizes have a corresponding same-aspect-ratio picture size"); for (android.hardware.Camera.Size previewSize : supportedPreviewSizes) { // The null picture size will let us know that we shouldn't set a picture size. validPreviewSizes.add(new SizePair(previewSize, null)); } } return validPreviewSizes; } /** * Selects the most suitable preview frames per second range, given the desired frames per * second. * * @param camera the camera to select a frames per second range from * @param desiredPreviewFps the desired frames per second for the camera preview frames * @return the selected preview frames per second range */ private int[] selectPreviewFpsRange(Camera camera, float desiredPreviewFps) { // The camera API uses integers scaled by a factor of 1000 instead of floating-point frame // rates. int desiredPreviewFpsScaled = (int) (desiredPreviewFps * 1000.0f); // The method for selecting the best range is to minimize the sum of the differences between // the desired value and the upper and lower bounds of the range. This may select a range // that the desired value is outside of, but this is often preferred. For example, if the // desired frame rate is 29.97, the range (30, 30) is probably more desirable than the // range (15, 30). int[] selectedFpsRange = null; int minDiff = Integer.MAX_VALUE; List<int[]> previewFpsRangeList = camera.getParameters().getSupportedPreviewFpsRange(); for (int[] range : previewFpsRangeList) { int deltaMin = desiredPreviewFpsScaled - range[Camera.Parameters.PREVIEW_FPS_MIN_INDEX]; int deltaMax = desiredPreviewFpsScaled - range[Camera.Parameters.PREVIEW_FPS_MAX_INDEX]; int diff = Math.abs(deltaMin) + Math.abs(deltaMax); if (diff < minDiff) { selectedFpsRange = range; minDiff = diff; } } return selectedFpsRange; } /** * Calculates the correct rotation for the given camera id and sets the rotation in the * parameters. It also sets the camera's display orientation and rotation. * * @param parameters the camera parameters for which to set the rotation * @param cameraId the camera id to set rotation based on */ private void setRotation(Camera camera, Camera.Parameters parameters, int cameraId) { WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); int degrees = 0; int rotation = windowManager.getDefaultDisplay().getRotation(); switch (rotation) { case Surface.ROTATION_0: degrees = 0; break; case Surface.ROTATION_90: degrees = 90; break; case Surface.ROTATION_180: degrees = 180; break; case Surface.ROTATION_270: degrees = 270; break; default: Log.e(TAG, "Bad rotation value: " + rotation); } CameraInfo cameraInfo = new CameraInfo(); Camera.getCameraInfo(cameraId, cameraInfo); int angle; int displayAngle; if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { angle = (cameraInfo.orientation + degrees) % 360; displayAngle = (360 - angle) % 360; // compensate for it being mirrored } else { // back-facing angle = (cameraInfo.orientation - degrees + 360) % 360; displayAngle = angle; } // This corresponds to the rotation constants in {@link Frame}. mRotation = angle / 90; camera.setDisplayOrientation(displayAngle); parameters.setRotation(angle); } /** * Creates one buffer for the camera preview callback. The size of the buffer is based off of * the camera preview size and the format of the camera image. * * @return a new preview buffer of the appropriate size for the current camera settings */ private byte[] createPreviewBuffer(Size previewSize) { int bitsPerPixel = ImageFormat.getBitsPerPixel(ImageFormat.NV21); long sizeInBits = previewSize.getHeight() * previewSize.getWidth() * bitsPerPixel; int bufferSize = (int) Math.ceil(sizeInBits / 8.0d) + 1; // // NOTICE: This code only works when using play services v. 8.1 or higher. // // Creating the byte array this way and wrapping it, as opposed to using .allocate(), // should guarantee that there will be an array to work with. byte[] byteArray = new byte[bufferSize]; ByteBuffer buffer = ByteBuffer.wrap(byteArray); if (!buffer.hasArray() || (buffer.array() != byteArray)) { // I don't think that this will ever happen. But if it does, then we wouldn't be // passing the preview content to the underlying detector later. throw new IllegalStateException("Failed to create valid buffer for camera source."); } mBytesToByteBuffer.put(byteArray, buffer); return byteArray; } //============================================================================================== // Frame processing //============================================================================================== /** * Called when the camera has a new preview frame. */ private class CameraPreviewCallback implements Camera.PreviewCallback { @Override public void onPreviewFrame(byte[] data, Camera camera) { mFrameProcessor.setNextFrame(data, camera); } } /** * This runnable controls access to the underlying receiver, calling it to process frames when * available from the camera. This is designed to run detection on frames as fast as possible * (i.e., without unnecessary context switching or waiting on the next frame). * <p/> * While detection is running on a frame, new frames may be received from the camera. As these * frames come in, the most recent frame is held onto as pending. As soon as detection and its * associated processing are done for the previous frame, detection on the mostly recently * received frame will immediately start on the same thread. */ private class FrameProcessingRunnable implements Runnable { private Detector<?> mDetector; private long mStartTimeMillis = SystemClock.elapsedRealtime(); // This lock guards all of the member variables below. private final Object mLock = new Object(); private boolean mActive = true; // These pending variables hold the state associated with the new frame awaiting processing. private long mPendingTimeMillis; private int mPendingFrameId = 0; private ByteBuffer mPendingFrameData; FrameProcessingRunnable(Detector<?> detector) { mDetector = detector; } /** * Releases the underlying receiver. This is only safe to do after the associated thread * has completed, which is managed in camera source's release method above. */ @SuppressLint("Assert") void release() { assert (mProcessingThread.getState() == State.TERMINATED); mDetector.release(); mDetector = null; } /** * Marks the runnable as active/not active. Signals any blocked threads to continue. */ void setActive(boolean active) { synchronized (mLock) { mActive = active; mLock.notifyAll(); } } /** * Sets the frame data received from the camera. This adds the previous unused frame buffer * (if present) back to the camera, and keeps a pending reference to the frame data for * future use. */ void setNextFrame(byte[] data, Camera camera) { synchronized (mLock) { if (mPendingFrameData != null) { camera.addCallbackBuffer(mPendingFrameData.array()); mPendingFrameData = null; } if (!mBytesToByteBuffer.containsKey(data)) { Log.d(TAG, "Skipping frame. Could not find ByteBuffer associated with the image " + "data from the camera."); return; } // Timestamp and frame ID are maintained here, which will give downstream code some // idea of the timing of frames received and when frames were dropped along the way. mPendingTimeMillis = SystemClock.elapsedRealtime() - mStartTimeMillis; mPendingFrameId++; mPendingFrameData = mBytesToByteBuffer.get(data); // Notify the processor thread if it is waiting on the next frame (see below). mLock.notifyAll(); } } /** * As long as the processing thread is active, this executes detection on frames * continuously. The next pending frame is either immediately available or hasn't been * received yet. Once it is available, we transfer the frame info to local variables and * run detection on that frame. It immediately loops back for the next frame without * pausing. * <p/> * If detection takes longer than the time in between new frames from the camera, this will * mean that this loop will run without ever waiting on a frame, avoiding any context * switching or frame acquisition time latency. * <p/> * If you find that this is using more CPU than you'd like, you should probably decrease the * FPS setting above to allow for some idle time in between frames. */ @Override public void run() { Frame outputFrame; ByteBuffer data; while (true) { synchronized (mLock) { while (mActive && (mPendingFrameData == null)) { try { // Wait for the next frame to be received from the camera, since we // don't have it yet. mLock.wait(); } catch (InterruptedException e) { Log.d(TAG, "Frame processing loop terminated.", e); return; } } if (!mActive) { // Exit the loop once this camera source is stopped or released. We check // this here, immediately after the wait() above, to handle the case where // setActive(false) had been called, triggering the termination of this // loop. return; } outputFrame = new Frame.Builder() .setImageData(mPendingFrameData, mPreviewSize.getWidth(), mPreviewSize.getHeight(), ImageFormat.NV21) .setId(mPendingFrameId) .setTimestampMillis(mPendingTimeMillis) .setRotation(mRotation) .build(); // Hold onto the frame data locally, so that we can use this for detection // below. We need to clear mPendingFrameData to ensure that this buffer isn't // recycled back to the camera before we are done using that data. data = mPendingFrameData; mPendingFrameData = null; } // The code below needs to run outside of synchronization, because this will allow // the camera to add pending frame(s) while we are running detection on the current // frame. try { mDetector.receiveFrame(outputFrame); } catch (Throwable t) { Log.e(TAG, "Exception thrown from receiver.", t); } finally { mCamera.addCallbackBuffer(data.array()); } } } } }
kglawrence/book-park
app/src/main/java/me/kglawrence/kerilawrence/book_park/ui/camera/CameraSource.java
Java
mit
48,878
/* The MIT License (MIT) Copyright (c) 2016 Paul Campbell Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package net.kemitix.ldapmanager.ldap; import org.springframework.ldap.core.ContextMapper; import org.springframework.ldap.core.DirContextOperations; /** * Type wrapper for ContextMappers that can say if they can handle a given context. * * @param <T> The entity type. * * @author Paul Campbell ([email protected]) */ interface PreCheckContextMapper<T> extends ContextMapper<T> { /** * Checks if the mapper can map the context. * * @param ctx The context to be mapped. * * @return true if the mapper can map the context, otherwise false. */ boolean canMapContext(DirContextOperations ctx); }
kemitix/ldap-user-manager
app/src/main/java/net/kemitix/ldapmanager/ldap/PreCheckContextMapper.java
Java
mit
1,729
package com.bugsnag; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import com.bugsnag.delivery.Delivery; import com.bugsnag.delivery.HttpDelivery; import com.bugsnag.serialization.Serializer; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.net.Proxy; import java.util.LinkedList; import java.util.Map; import java.util.Queue; public class ConfigurationTest { private Configuration config; /** * Creates a config object with fake delivery objects * * @throws Throwable if setup failed */ @Before public void setUp() { config = new Configuration("foo"); config.delivery = new FakeHttpDelivery(); config.sessionDelivery = new FakeHttpDelivery(); } @Test public void testDefaults() { assertTrue(config.shouldAutoCaptureSessions()); } @Test public void testErrorApiHeaders() { Map<String, String> headers = config.getErrorApiHeaders(); assertEquals(config.apiKey, headers.get("Bugsnag-Api-Key")); assertNotNull(headers.get("Bugsnag-Sent-At")); assertNotNull(headers.get("Bugsnag-Payload-Version")); } @Test public void testSessionApiHeaders() { Map<String, String> headers = config.getSessionApiHeaders(); assertEquals(config.apiKey, headers.get("Bugsnag-Api-Key")); assertNotNull(headers.get("Bugsnag-Sent-At")); assertNotNull(headers.get("Bugsnag-Payload-Version")); } @Test public void testEndpoints() { String notify = "https://notify.myexample.com"; String sessions = "https://sessions.myexample.com"; config.setEndpoints(notify, sessions); assertEquals(notify, getDeliveryEndpoint(config.delivery)); assertEquals(sessions, getDeliveryEndpoint(config.sessionDelivery)); } @Test(expected = IllegalArgumentException.class) public void testNullNotifyEndpoint() { config.setEndpoints(null, "http://example.com"); } @Test(expected = IllegalArgumentException.class) public void testEmptyNotifyEndpoint() { config.setEndpoints("", "http://example.com"); } @Test public void testInvalidSessionEndpoint() { config.setAutoCaptureSessions(true); config.setEndpoints("http://example.com", null); assertFalse(config.shouldAutoCaptureSessions()); assertNull(getDeliveryEndpoint(config.sessionDelivery)); config.setAutoCaptureSessions(true); config.setEndpoints("http://example.com", ""); assertFalse(config.shouldAutoCaptureSessions()); assertNull(getDeliveryEndpoint(config.sessionDelivery)); config.setAutoCaptureSessions(true); config.setEndpoints("http://example.com", "http://sessions.example.com"); assertTrue(config.shouldAutoCaptureSessions()); assertEquals("http://sessions.example.com", getDeliveryEndpoint(config.sessionDelivery)); } @Test public void testInvalidSessionWarningLogged() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setErr(new PrintStream(baos)); config.setEndpoints("http://example.com", ""); String logMsg = new String(baos.toByteArray()); assertTrue(logMsg.contains("The session tracking endpoint " + "has not been set. Session tracking is disabled")); } @Test public void testAutoCaptureOverride() { config.setAutoCaptureSessions(false); config.setEndpoints("http://example.com", "http://example.com"); assertFalse(config.shouldAutoCaptureSessions()); } @Test public void testBaseDeliveryIgnoresEndpoint() { Delivery delivery = new Delivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { } @Override public void close() { } }; config.delivery = delivery; config.sessionDelivery = delivery; // ensure log message ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setErr(new PrintStream(baos)); config.setEndpoints("http://example.com", "http://sessions.example.com"); String logMsg = new String(baos.toByteArray()); assertTrue(logMsg.contains("Delivery is not instance of " + "HttpDelivery, cannot set notify endpoint")); assertTrue(logMsg.contains("Delivery is not instance of " + "HttpDelivery, cannot set sessions endpoint")); } private String getDeliveryEndpoint(Delivery delivery) { if (delivery instanceof FakeHttpDelivery) { return ((FakeHttpDelivery) delivery).endpoint; } return null; } static class FakeHttpDelivery implements HttpDelivery { String endpoint; Queue<Object> receivedObjects = new LinkedList<Object>(); @Override public void setEndpoint(String endpoint) { this.endpoint = endpoint; } @Override public void setTimeout(int timeout) { } @Override public void setProxy(Proxy proxy) { } @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { receivedObjects.add(object); } @Override public void close() { } } }
bugsnag/bugsnag-java
bugsnag/src/test/java/com/bugsnag/ConfigurationTest.java
Java
mit
5,657
package com.nicolas.coding.project.detail.topic; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.support.v4.widget.SwipeRefreshLayout; import android.text.Html; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import com.loopj.android.http.RequestParams; import com.nicolas.coding.BackActivity; import com.nicolas.coding.FootUpdate; import com.nicolas.coding.R; import com.nicolas.coding.common.ClickSmallImage; import com.nicolas.coding.common.CustomDialog; import com.nicolas.coding.common.Global; import com.nicolas.coding.common.MyImageGetter; import com.nicolas.coding.common.PhotoOperate; import com.nicolas.coding.common.StartActivity; import com.nicolas.coding.common.TextWatcherAt; import com.nicolas.coding.common.enter.EnterLayout; import com.nicolas.coding.common.enter.ImageCommentLayout; import com.nicolas.coding.common.photopick.ImageInfo; import com.nicolas.coding.common.umeng.UmengEvent; import com.nicolas.coding.maopao.item.ImageCommentHolder; import com.nicolas.coding.model.AttachmentFileObject; import com.nicolas.coding.model.TopicLabelObject; import com.nicolas.coding.model.TopicObject; import com.nicolas.coding.project.detail.TopicAddActivity_; import com.nicolas.coding.project.detail.TopicLabelActivity; import com.nicolas.coding.project.detail.TopicLabelActivity_; import com.nicolas.coding.project.detail.TopicLabelBar; import com.nicolas.coding.third.EmojiFilter; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.Extra; import org.androidannotations.annotations.InstanceState; import org.androidannotations.annotations.OnActivityResult; import org.androidannotations.annotations.OptionsItem; import org.androidannotations.annotations.ViewById; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @EActivity(R.layout.activity_topic_list_detail) public class TopicListDetailActivity extends BackActivity implements StartActivity, SwipeRefreshLayout.OnRefreshListener, FootUpdate.LoadMore { private static final String TAG_TOPIC_COMMENTS = "TAG_TOPIC_COMMENTS"; final int RESULT_AT = 1; final int RESULT_EDIT = 2; final int RESULT_LABEL = 3; final String HOST_MAOPAO_DELETE = Global.HOST_API + "/topic/%s"; final String TAG_DELETE_TOPIC_COMMENT = "TAG_DELETE_TOPIC_COMMENT"; final String TAG_DELETE_TOPIC = "TAG_DELETE_TOPIC"; private final String HOST_COMMENT_SEND = Global.HOST_API + "/project/%s/topic?parent=%s"; private final ClickSmallImage onClickImage = new ClickSmallImage(this); @InstanceState protected boolean saveTopicWhenLoaded; @Extra TopicObject topicObject; @Extra TopicDetailParam mJumpParam; @ViewById ListView listView; @ViewById SwipeRefreshLayout swipeRefreshLayout; // EnterLayout mEnterLayout; ImageCommentLayout mEnterComment; String owerGlobar = ""; String urlCommentSend = HOST_COMMENT_SEND; String URI_DELETE_TOPIC_LABEL = Global.HOST_API + "/topic/%s/label/%s"; String urlTopic = ""; ArrayList<TopicObject> mData = new ArrayList<>(); Intent mResultData = new Intent(); View mListHead; String tagUrlCommentPhoto = ""; HashMap<String, String> mSendedImages = new HashMap<>(); View.OnClickListener mOnClickSend = new View.OnClickListener() { @Override public void onClick(View v) { sendCommentAll(); } }; View.OnClickListener onClickComment = new View.OnClickListener() { @Override public void onClick(View v) { final TopicObject comment = (TopicObject) v.getTag(); if (comment.isMy()) { AlertDialog dialog = new AlertDialog.Builder(TopicListDetailActivity.this).setTitle("删除评论") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final String HOST_MAOPAO_DELETE = Global.HOST_API + "/topic/%s"; deleteNetwork(String.format(HOST_MAOPAO_DELETE, comment.id), TAG_DELETE_TOPIC_COMMENT, comment.id); } }) .setNegativeButton("取消", null) .show(); CustomDialog.dialogTitleLineColor(TopicListDetailActivity.this, dialog); } else { EnterLayout enterLayout = mEnterComment.getEnterLayout(); EditText message = enterLayout.content; message.setHint("回复 " + comment.owner.name); message.setTag(comment); enterLayout.popKeyboard(); enterLayout.restoreLoad(comment); } } }; MyImageGetter myImageGetter = new MyImageGetter(this); BaseAdapter baseAdapter = new BaseAdapter() { @Override public int getCount() { return mData.size(); } @Override public Object getItem(int position) { return mData.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageCommentHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.activity_task_comment_much_image_divide, parent, false); holder = new ImageCommentHolder(convertView, onClickComment, myImageGetter, getImageLoad(), mOnClickUser, onClickImage); convertView.setTag(R.id.layout, holder); } else { holder = (ImageCommentHolder) convertView.getTag(R.id.layout); } TopicObject data = (TopicObject) getItem(position); holder.setContent(data); // convertView.findViewById(R.id.customDivide) loadMore(); return convertView; } }; private TopicLabelBar labelBar; private int currentLabelId; private TextView textViewCommentCount; @AfterViews protected final void initTopicListDetailActivity() { swipeRefreshLayout.setOnRefreshListener(this); swipeRefreshLayout.setColorSchemeResources(R.color.green); mFootUpdate.init(listView, mInflater, this); loadData(); mEnterComment = new ImageCommentLayout(this, mOnClickSend, getImageLoad()); prepareComment(); } @Override public void onRefresh() { loadData(); } @Override public void loadMore() { getNextPageNetwork(topicObject.getHttpComments(), TAG_TOPIC_COMMENTS); } private void loadData() { if (mJumpParam != null) { urlTopic = String.format(Global.HOST_API + "/topic/%s?", mJumpParam.mTopic); getNetwork(urlTopic, urlTopic); } else if (topicObject != null) { owerGlobar = topicObject.owner.global_key; getSupportActionBar().setTitle(topicObject.project.name); urlTopic = String.format(Global.HOST_API + "/topic/%s?", topicObject.id); getNetwork(urlTopic, urlTopic); } else { finish(); } } private void initData() { getSupportActionBar().setTitle(topicObject.project.name); updateHeadData(); if (saveTopicWhenLoaded) { saveTopicWhenLoaded = false; mResultData.putExtra("topic", topicObject); } urlCommentSend = String.format(urlCommentSend, topicObject.project_id, topicObject.id); loadMore(); } @OnActivityResult(RESULT_AT) void onResultAt(int requestCode, Intent data) { if (requestCode == Activity.RESULT_OK) { String name = data.getStringExtra("name"); mEnterComment.getEnterLayout().insertText(name); mEnterComment.getEnterLayout().popKeyboard(); } } @OnActivityResult(RESULT_EDIT) void onResultEdit() { // 分支情况太多,如编辑状态下可进入标签管理删掉目前用的标签, // 回到编辑后又重复进入修改名字或者继续添加删除,最后还可以不保存返回 // 除非一直把全局labels的所有状态通过intents传递,否则原状态难以维持,这里只好直接重新刷新了, // 会慢一些但状态肯定是对的,可能影响回复列表页数 saveTopicWhenLoaded = true; onRefresh(); } @OnActivityResult(RESULT_LABEL) void onResultLabel(int code, @OnActivityResult.Extra ArrayList<TopicLabelObject> labels) { if (code == RESULT_OK) { topicObject.labels = labels; updateLabels(topicObject.labels); mResultData.putExtra("topic", topicObject); } } @OnActivityResult(ImageCommentLayout.RESULT_REQUEST_COMMENT_IMAGE) protected final void commentImage(int result, Intent data) { if (result == RESULT_OK) { mEnterComment.onActivityResult( ImageCommentLayout.RESULT_REQUEST_COMMENT_IMAGE, data); } } @OnActivityResult(ImageCommentLayout.RESULT_REQUEST_COMMENT_IMAGE_DETAIL) protected final void commentImageDetail(int result, Intent data) { if (result == RESULT_OK) { mEnterComment.onActivityResult( ImageCommentLayout.RESULT_REQUEST_COMMENT_IMAGE_DETAIL, data); } } @Override public boolean onCreateOptionsMenu(Menu menu) { if (topicObject != null) { int menuRes; if (topicObject.isMy()) { menuRes = R.menu.topic_detail_modify; } else { menuRes = R.menu.common_more_copy_link; } getMenuInflater().inflate(menuRes, menu); } return super.onCreateOptionsMenu(menu); } @OptionsItem void action_edit() { TopicAddActivity_.intent(this).projectObject(topicObject.project).topicObject(topicObject).startForResult(RESULT_EDIT); } @Override public void onBackPressed() { if (mResultData.getExtras() == null) { setResult(Activity.RESULT_CANCELED); } else { setResult(Activity.RESULT_OK, mResultData); } super.onBackPressed(); } @OptionsItem void action_delete() { showDialog("讨论", "删除讨论?", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteNetwork(String.format(HOST_MAOPAO_DELETE, topicObject.id), TAG_DELETE_TOPIC); } }); } @OptionsItem protected final void action_copy() { final String urlTemplate = Global.HOST + "/u/%s/p/%s/topic/%d"; String url = String.format(urlTemplate, topicObject.project.owner_user_name, topicObject.project.name, topicObject.id); Global.copy(this, url); showButtomToast("已复制 " + url); } void updateDisplayCommentCount() { String commentCount = String.format("评论(%d)", topicObject.child_count); textViewCommentCount.setText(commentCount); } private void updateHeadData() { mEnterComment.getEnterLayout().content.addTextChangedListener(new TextWatcherAt(this, this, RESULT_AT, topicObject.project)); if (mListHead == null) { mListHead = mInflater.inflate(R.layout.activity_project_topic_comment_list_head, listView, false); listView.addHeaderView(mListHead); } ImageView icon = (ImageView) mListHead.findViewById(R.id.icon); iconfromNetwork(icon, topicObject.owner.avatar); icon.setTag(topicObject.owner.global_key); icon.setOnClickListener(mOnClickUser); TextView topicTitleTextView = ((TextView) mListHead.findViewById(R.id.title)); topicTitleTextView.setText(topicObject.title); final String format = "<font color='#3bbd79'>%s</font> 发布于%s"; String timeString = String.format(format, topicObject.owner.name, Global.dayToNow(topicObject.updated_at)); ((TextView) mListHead.findViewById(R.id.time)).setText(Html.fromHtml(timeString)); ((TextView) mListHead.findViewById(R.id.referenceId)).setText(topicObject.getRefId()); updateLabels(topicObject.labels); WebView webView = (WebView) mListHead.findViewById(R.id.comment); Global.setWebViewContent(webView, "topic-android", topicObject.content); textViewCommentCount = (TextView) mListHead.findViewById(R.id.commentCount); updateDisplayCommentCount(); Spinner spinner = (Spinner) mListHead.findViewById(R.id.spinner); spinner.setAdapter(new TopicSortAdapter(this)); spinner.setSelection(0, true); // 一定要写,否则会自动调用一次 onItemSelected spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position == 0) { topicObject.setSortOld(TopicObject.SORT_OLD); } else { topicObject.setSortOld(TopicObject.SORT_NEW); } initSetting(); loadMore(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); mListHead.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { prepareComment(); mEnterComment.getEnterLayout().popKeyboard(); } }); listView.setAdapter(baseAdapter); } private void updateLabels(List<TopicLabelObject> labels) { if (labelBar == null) { labelBar = (TopicLabelBar) mListHead.findViewById(R.id.labelBar); } labelBar.bind(labels, new TopicLabelBar.Controller() { @Override public boolean canShowLabels() { return true; } @Override public boolean canEditLabels() { return true; } @Override public void onEditLabels(TopicLabelBar view) { TopicLabelActivity_.intent(TopicListDetailActivity.this) .labelType(TopicLabelActivity.LabelType.Topic) .projectPath(topicObject.project.getProjectPath()) .id(topicObject.id) .checkedLabels(topicObject.labels) .startForResult(RESULT_LABEL); } @Override public void onRemoveLabel(TopicLabelBar view, int labelId) { currentLabelId = labelId; String url = String.format(URI_DELETE_TOPIC_LABEL, topicObject.id, labelId); deleteNetwork(url, URI_DELETE_TOPIC_LABEL); } }); } private void prepareComment() { EditText message = mEnterComment.getEnterLayout().content; message.setHint("发表评论"); message.setTag(topicObject); mEnterComment.getEnterLayout().restoreLoad(topicObject); } private void sendCommentAll() { showProgressBar(true); ArrayList<ImageInfo> photos = mEnterComment.getPickPhotos(); for (ImageInfo item : photos) { String imagePath = item.path; if (!mSendedImages.containsKey(imagePath)) { try { String url = topicObject.project.getHttpUploadPhoto(); RequestParams params = new RequestParams(); params.put("dir", 0); File fileImage = new File(imagePath); if (!Global.isGifByFile(fileImage)) { Uri uri = Uri.parse(imagePath); fileImage = new PhotoOperate(this).scal(uri); } params.put("file", fileImage); tagUrlCommentPhoto = imagePath; // tag必须不同,否则无法调用下一次 postNetwork(url, params, tagUrlCommentPhoto, 0, imagePath); showProgressBar(true); } catch (Exception e) { showProgressBar(false); } return; } } String send = mEnterComment.getEnterLayout().getContent(); for (ImageInfo item : photos) { send += mSendedImages.get(item.path); } sendComment(send); } private void sendComment(String send) { if (urlCommentSend.equals(HOST_COMMENT_SEND)) { return; } String input = send; if (EmojiFilter.containsEmptyEmoji(this, input)) { showProgressBar(false); return; } RequestParams params = new RequestParams(); TopicObject comment = (TopicObject) mEnterComment.getEnterLayout().content.getTag(); if (comment != null && comment.parent_id != 0) { input = Global.encodeInput(comment.owner.name, input); } else { input = Global.encodeInput("", input); } params.put("content", input); postNetwork(urlCommentSend, params, urlCommentSend, 0, comment); showProgressBar(R.string.sending_comment); } @Override public void parseJson(int code, JSONObject respanse, String tag, int pos, Object data) throws JSONException { if (tag.equals(TAG_TOPIC_COMMENTS)) { if (code == 0) { if (isLoadingFirstPage(tag)) { mData.clear(); } JSONArray jsonArray = respanse.getJSONObject("data").getJSONArray("list"); for (int i = 0; i < jsonArray.length(); ++i) { TopicObject commnet = new TopicObject(jsonArray.getJSONObject(i)); mData.add(commnet); } } else { showErrorMsg(code, respanse); } baseAdapter.notifyDataSetChanged(); mFootUpdate.updateState(code, isLoadingLastPage(tag), mData.size()); } else if (tag.equals(urlCommentSend)) { showProgressBar(false); if (code == 0) { umengEvent(UmengEvent.TOPIC, "新建讨论评论"); JSONObject jsonObject = respanse.getJSONObject("data"); ++topicObject.child_count; mResultData.putExtra("child_count", topicObject.child_count); mResultData.putExtra("topic_id", topicObject.id); updateDisplayCommentCount(); mData.add(new TopicObject(jsonObject)); EnterLayout enterLayout = mEnterComment.getEnterLayout(); enterLayout.restoreDelete(data); mEnterComment.clearContent(); baseAdapter.notifyDataSetChanged(); showButtomToast("发送评论成功"); } else { showErrorMsg(code, respanse); baseAdapter.notifyDataSetChanged(); } } else if (tag.equals(urlTopic)) { swipeRefreshLayout.setRefreshing(false); if (code == 0) { topicObject = new TopicObject(respanse.getJSONObject("data")); initData(); invalidateOptionsMenu(); } else { showErrorMsg(code, respanse); } } else if (tag.equals(TAG_DELETE_TOPIC_COMMENT)) { int itemId = (int) data; if (code == 0) { umengEvent(UmengEvent.TOPIC, "删除讨论评论"); for (int i = 0; i < mData.size(); ++i) { if (itemId == mData.get(i).id) { mData.remove(i); --topicObject.child_count; mResultData.putExtra("child_count", topicObject.child_count); mResultData.putExtra("topic_id", topicObject.id); updateDisplayCommentCount(); baseAdapter.notifyDataSetChanged(); break; } } } else { showButtomToast(R.string.delete_fail); } } else if (tag.equals(TAG_DELETE_TOPIC)) { if (code == 0) { umengEvent(UmengEvent.TOPIC, "删除讨论"); mResultData.putExtra("id", topicObject.id); setResult(RESULT_OK, mResultData); finish(); } else { showButtomToast(R.string.delete_fail); } } else if (tag.equals(tagUrlCommentPhoto)) { if (code == 0) { String fileUri; if (topicObject.project.isPublic()) { fileUri = respanse.optString("data", ""); } else { AttachmentFileObject fileObject = new AttachmentFileObject(respanse.optJSONObject("data")); fileUri = fileObject.owner_preview; } String mdPhotoUri = String.format("\n![图片](%s)", fileUri); mSendedImages.put((String) data, mdPhotoUri); sendCommentAll(); } else { showErrorMsg(code, respanse); showProgressBar(false); } } else if (URI_DELETE_TOPIC_LABEL.equals(tag)) { if (code == 0) { umengEvent(UmengEvent.PROJECT, "删除标签"); labelBar.removeLabel(currentLabelId); if (topicObject.labels != null) { for (TopicLabelObject item : topicObject.labels) { if (item.id == currentLabelId) { topicObject.labels.remove(item); break; } } } mResultData.putExtra("topic", topicObject); } else { currentLabelId = -1; showErrorMsg(code, respanse); showProgressBar(false); } } } public static class TopicDetailParam implements Serializable { public String mUser; public String mProject; public String mTopic; public TopicDetailParam(String mUser, String mProject, String mTopic) { this.mUser = mUser; this.mProject = mProject; this.mTopic = mTopic; } } }
liwangadd/Coding
app/src/main/java/com/nicolas/coding/project/detail/topic/TopicListDetailActivity.java
Java
mit
23,437
package br.com.wcorrea.transport.api.exceptionHandler; import br.com.wcorrea.transport.api.exceptionHandler.defaultException.ApiError; import br.com.wcorrea.transport.api.exceptionHandler.defaultException.DefaultExceptionHandler; import br.com.wcorrea.transport.api.service.exception.UnidadeMedidaNaoEncontrada; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import java.util.Arrays; import java.util.List; import java.util.Locale; @ControllerAdvice public class UnidadeMedidaException extends DefaultExceptionHandler { @Autowired private MessageSource messageSource; @ExceptionHandler({UnidadeMedidaNaoEncontrada.class}) public ResponseEntity<Object> handleUnidadeMedidaUpdateNotFound(UnidadeMedidaNaoEncontrada ex, WebRequest request, Locale loc) { String userMessage = messageSource.getMessage("recurso.unidade-medida-nao-encontrada", null, loc); String developerMessage = ex.toString(); List<ApiError> errors = Arrays.asList(new ApiError(userMessage, developerMessage, HttpStatus.NOT_FOUND)); return handleExceptionInternal(ex, errors, new HttpHeaders(), HttpStatus.NOT_FOUND, request); } }
williancorrea/transport-api
src/main/java/br/com/wcorrea/transport/api/exceptionHandler/UnidadeMedidaException.java
Java
mit
1,544
package fi.ni.ifc2x3; import fi.ni.ifc2x3.interfaces.*; import fi.ni.*; import java.util.*; /* * IFC Java class * @author Jyrki Oraskari * @license This work is licensed under a Creative Commons Attribution 3.0 Unported License. * http://creativecommons.org/licenses/by/3.0/ */ public class IfcRelCoversBldgElements extends IfcRelConnects { // The property attributes IfcElement relatingBuildingElement; List<IfcCovering> relatedCoverings = new IfcSet<IfcCovering>(); // Getters and setters of properties public IfcElement getRelatingBuildingElement() { return relatingBuildingElement; } public void setRelatingBuildingElement(IfcElement value){ this.relatingBuildingElement=value; } public List<IfcCovering> getRelatedCoverings() { return relatedCoverings; } public void setRelatedCoverings(IfcCovering value){ this.relatedCoverings.add(value); } }
jyrkio/Open-IFC-to-RDF-converter
IFC_RDF/src/fi/ni/ifc2x3/IfcRelCoversBldgElements.java
Java
mit
894
package com.xmomen.module.system.entity; import com.xmomen.framework.mybatis.model.BaseMybatisModel; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Version; @Entity @Table(name = "sys_dictionary_parameter") public class SysDictionaryParameter extends BaseMybatisModel { /** * */ private Integer id; /** * 字典 */ private Integer sysDictionaryId; /** * 显示值 */ private String showValue; /** * 实际值 */ private String realValue; /** * 排位 */ private Integer sortValue; /** * 0-禁用,1-启用 */ private Integer available; @Column(name = "ID") @Id @GeneratedValue(generator = "UUIDGenerator") public Integer getId() { return id; } public void setId(Integer id) { this.id = id; if(id == null){ removeValidField("id"); return; } addValidField("id"); } @Column(name = "SYS_DICTIONARY_ID") public Integer getSysDictionaryId() { return sysDictionaryId; } public void setSysDictionaryId(Integer sysDictionaryId) { this.sysDictionaryId = sysDictionaryId; if(sysDictionaryId == null){ removeValidField("sysDictionaryId"); return; } addValidField("sysDictionaryId"); } @Column(name = "SHOW_VALUE") public String getShowValue() { return showValue; } public void setShowValue(String showValue) { this.showValue = showValue; if(showValue == null){ removeValidField("showValue"); return; } addValidField("showValue"); } @Column(name = "REAL_VALUE") public String getRealValue() { return realValue; } public void setRealValue(String realValue) { this.realValue = realValue; if(realValue == null){ removeValidField("realValue"); return; } addValidField("realValue"); } @Column(name = "SORT_VALUE") public Integer getSortValue() { return sortValue; } public void setSortValue(Integer sortValue) { this.sortValue = sortValue; if(sortValue == null){ removeValidField("sortValue"); return; } addValidField("sortValue"); } @Column(name = "AVAILABLE") public Integer getAvailable() { return available; } public void setAvailable(Integer available) { this.available = available; if(available == null){ removeValidField("available"); return; } addValidField("available"); } }
xmomen/dms-webapp
src/main/java/com/xmomen/module/system/entity/SysDictionaryParameter.java
Java
mit
2,876
package com.millerjb.stash.domain; public class PullRequestRef extends ErrorsEntity { String displayId; String latestChangeset; Repository repository; public String getDisplayId() { return displayId; } public void setDisplayId(String displayId) { this.displayId = displayId; } public String getLatestChangeset() { return latestChangeset; } public void setLatestChangeset(String latestChangeset) { this.latestChangeset = latestChangeset; } public Repository getRepository() { return repository; } public void setRepository(Repository repository) { this.repository = repository; } }
mllrjb/jenkins-stash-pull-request-builder
src/main/java/com/millerjb/stash/domain/PullRequestRef.java
Java
mit
697
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2013, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.core.joran.replay; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.List; import ch.qos.logback.core.joran.spi.ElementSelector; import org.junit.Test; import ch.qos.logback.core.joran.SimpleConfigurator; import ch.qos.logback.core.joran.action.Action; import ch.qos.logback.core.joran.action.NOPAction; import ch.qos.logback.core.util.CoreTestConstants; import ch.qos.logback.core.util.StatusPrinter; /** * The Fruit* code is intended to test Joran's replay capability * */ public class FruitConfigurationTest { FruitContext fruitContext = new FruitContext(); public List<FruitShell> doFirstPart(String filename) throws Exception { try { HashMap<ElementSelector, Action> rulesMap = new HashMap<ElementSelector, Action>(); rulesMap.put(new ElementSelector("group/fruitShell"), new FruitShellAction()); rulesMap.put(new ElementSelector("group/fruitShell/fruit"), new FruitFactoryAction()); rulesMap.put(new ElementSelector("group/fruitShell/fruit/*"), new NOPAction()); SimpleConfigurator simpleConfigurator = new SimpleConfigurator(rulesMap); simpleConfigurator.setContext(fruitContext); simpleConfigurator.doConfigure(CoreTestConstants.TEST_SRC_PREFIX + "input/joran/replay/" + filename); return fruitContext.getFruitShellList(); } catch (Exception je) { StatusPrinter.print(fruitContext); throw je; } } @Test public void fruit1() throws Exception { List<FruitShell> fsList = doFirstPart("fruit1.xml"); assertNotNull(fsList); assertEquals(1, fsList.size()); FruitShell fs0 = fsList.get(0); assertNotNull(fs0); assertEquals("fs0", fs0.getName()); Fruit fruit0 = fs0.fruitFactory.buildFruit(); assertTrue(fruit0 instanceof Fruit); assertEquals("blue", fruit0.getName()); } @Test public void fruit2() throws Exception { List<FruitShell> fsList = doFirstPart("fruit2.xml"); assertNotNull(fsList); assertEquals(2, fsList.size()); FruitShell fs0 = fsList.get(0); assertNotNull(fs0); assertEquals("fs0", fs0.getName()); Fruit fruit0 = fs0.fruitFactory.buildFruit(); assertTrue(fruit0 instanceof Fruit); assertEquals("blue", fruit0.getName()); FruitShell fs1 = fsList.get(1); assertNotNull(fs1); assertEquals("fs1", fs1.getName()); Fruit fruit1 = fs1.fruitFactory.buildFruit(); assertTrue(fruit1 instanceof WeightytFruit); assertEquals("orange", fruit1.getName()); assertEquals(1.2, ((WeightytFruit) fruit1).getWeight(), 0.01); } @Test public void withSubst() throws Exception { List<FruitShell> fsList = doFirstPart("fruitWithSubst.xml"); assertNotNull(fsList); assertEquals(1, fsList.size()); FruitShell fs0 = fsList.get(0); assertNotNull(fs0); assertEquals("fs0", fs0.getName()); int oldCount = FruitFactory.count; Fruit fruit0 = fs0.fruitFactory.buildFruit(); assertTrue(fruit0 instanceof WeightytFruit); assertEquals("orange-" + oldCount, fruit0.getName()); assertEquals(1.2, ((WeightytFruit) fruit0).getWeight(), 0.01); } }
OuZhencong/logback
logback-core/src/test/java/ch/qos/logback/core/joran/replay/FruitConfigurationTest.java
Java
mit
3,730
package team.cs6365.payfive.database; import java.util.ArrayList; import java.util.List; import team.cs6365.payfive.model.User; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; public class UserDataSource { private SQLiteDatabase db; private UserDatabaseHelper dbHelper; private String[] columns = {UserDatabaseContract.COLUMN_NAME_NAME, UserDatabaseContract.COLUMN_NAME_PAYPALID}; public UserDataSource(Context context) { dbHelper = new UserDatabaseHelper(context); } public void open() throws SQLException { db = dbHelper.getWritableDatabase(); } public void close() { dbHelper.close(); } public void addUser(String name, String paypalId) { ContentValues row = new ContentValues(); row.put(columns[0], name); row.put(columns[1], paypalId); db.insert(UserDatabaseContract.TABLE_NAME, null, row); } public void deleteUser(User user) { db.delete(UserDatabaseContract.TABLE_NAME, UserDatabaseContract.COLUMN_NAME_NAME + "='" + user.getName() + "' AND " + UserDatabaseContract.COLUMN_NAME_PAYPALID + "='" + user.getPaypalId(), null); } public User getUser(String name, String paypalId) { User u = new User(); Cursor cur = db.query(UserDatabaseContract.TABLE_NAME, columns, UserDatabaseContract.COLUMN_NAME_NAME + "='" + name + "' AND " + UserDatabaseContract.COLUMN_NAME_PAYPALID + "='" + paypalId + "'", null, null, null, null); if(cur != null && cur.getCount() > 0) { cur.moveToFirst(); u = cursorToUser(cur); } cur.close(); return u; } public List<User> getAllUser() { List<User> us = new ArrayList<User>(); Cursor cur = db.query(UserDatabaseContract.TABLE_NAME, columns, null, null, null, null, null); if(cur != null && cur.getCount() > 0) { cur.moveToFirst(); while(!cur.isAfterLast()) { us.add(cursorToUser(cur)); cur.moveToNext(); } } cur.close(); return us; } public User cursorToUser(Cursor cur) { User u = new User(cur.getString(1), cur.getString(2)); return u; } }
hoyin29/CS6365Project
PayFive/src/team/cs6365/payfive/database/UserDataSource.java
Java
mit
2,296
package com.example.renesansz.scrollview; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
renesansz/VogellaExercises
ScrollView/app/src/test/java/com/example/renesansz/scrollview/ExampleUnitTest.java
Java
mit
325
package net.violet.platform.datamodel; import net.violet.db.records.associations.AssoRecord; public interface MessageSent extends AssoRecord<Message, MessageSent> { /** * Gets the Recipient of the message * * @return */ Messenger getRecipient(); /** * Gets the sender of the message * * @return */ Messenger getSender(); /** * Gets the message * * @return */ Message getMessage(); /** * @return the message_id */ long getMessage_id(); /** * @return the recipient_id */ long getRecipient_id(); /** * @return the sender_id */ long getSender_id(); /** * @return the message_state */ String getMessage_state(); }
sebastienhouzet/nabaztag-source-code
server/OS/net/violet/platform/datamodel/MessageSent.java
Java
mit
676
package org.aksw.geostats.datacube; public enum Language { de, en }
GeoKnow/GeoStats
src/main/java/org/aksw/geostats/datacube/Language.java
Java
mit
72
/* * The MIT License * * Copyright (c) 2012, CloudBees, Inc. * * 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 jenkins.model.lazy; import hudson.model.Job; import hudson.model.Run; import hudson.model.RunMap; import org.apache.commons.collections.keyvalue.DefaultMapEntry; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.lang.ref.Reference; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.CheckForNull; import static jenkins.model.lazy.AbstractLazyLoadRunMap.Direction.*; import static jenkins.model.lazy.Boundary.*; /** * {@link SortedMap} that keeps build records by their build numbers, in the descending order * (newer ones first.) * * <p> * The main thing about this class is that it encapsulates the lazy loading logic. * That is, while this class looks and feels like a normal {@link SortedMap} from outside, * it actually doesn't have every item in the map instantiated yet. As items in the map get * requested, this class {@link #retrieve(File) retrieves them} on demand, one by one. * * <p> * The lookup is primarily done by using the build number as the key (hence the key type is {@link Integer}), * but this class also provides look up based on {@linkplain #getIdOf(Object) the build ID}. * * <p> * This class makes the following assumption about the on-disk layout of the data: * * <ul> * <li>Every build is stored in a directory, named after its ID. * <li>ID and build number are in the consistent order. That is, * if there are two builds #M and #N, {@code M>N <=> M.id > N.id}. * </ul> * * <p> * On certain platforms, there are symbolic links named after build numbers that link to the build ID. * If these are available, they are used as a hint to speed up the lookup. Otherwise * we rely on the assumption above and perform a binary search to locate the build. * (notice that we'll have to do linear search if we don't have the consistent ordering assumption, * which robs the whole point of doing lazy loading.) * * <p> * Some of the {@link SortedMap} operations are weakly implemented. For example, * {@link #size()} may be inaccurate because we only count the number of directories that look like * build records, without checking if they are loadable. But these weaknesses aren't distinguishable * from concurrent modifications, where another thread deletes a build while one thread iterates them. * * <p> * Some of the {@link SortedMap} operations are inefficiently implemented, by * {@linkplain #all() loading all the build records eagerly}. We hope to replace * these implementations by more efficient lazy-loading ones as we go. * * <p> * Object lock of {@code this} is used to make sure mutation occurs sequentially. * That is, ensure that only one thread is actually calling {@link #retrieve(File)} and * updating {@link jenkins.model.lazy.AbstractLazyLoadRunMap.Index#byNumber} and {@link jenkins.model.lazy.AbstractLazyLoadRunMap.Index#byId}. * * @author Kohsuke Kawaguchi * @since 1.485 */ public abstract class AbstractLazyLoadRunMap<R> extends AbstractMap<Integer,R> implements SortedMap<Integer,R> { /** * Used in {@link #all()} to quickly determine if we've already loaded everything. */ private boolean fullyLoaded; /** * Currently visible index. * Updated atomically. Once set to this field, the index object may not be modified. */ private volatile Index index = new Index(); /** * Pair of two maps into a single class, so that the changes can be made visible atomically, * and updates can happen concurrently to read. * * The idiom is that you put yourself in a synchronized block, {@linkplain #copy() make a copy of this}, * update the copy, then set it to {@link #index}. */ private class Index { /** * Stores the mapping from build number to build, for builds that are already loaded. */ private final TreeMap<Integer,BuildReference<R>> byNumber; /** * Stores the build ID to build number for builds that we already know. * * If we have known load failure of the given ID, we record that in the map * by using the null value (not to be confused with a non-null {@link BuildReference} * with null referent, which just means the record was GCed.) */ private final TreeMap<String,BuildReference<R>> byId; private Index() { byId = new TreeMap<String,BuildReference<R>>(); byNumber = new TreeMap<Integer,BuildReference<R>>(COMPARATOR); } private Index(Index rhs) { byId = new TreeMap<String, BuildReference<R>>(rhs.byId); byNumber = new TreeMap<Integer,BuildReference<R>>(rhs.byNumber); } /** * Returns the build record #M (<=n) */ private Map.Entry<Integer,BuildReference<R>> ceilingEntry(int n) { // switch to this once we depend on JDK6 // return byNumber.ceilingEntry(n); Set<Entry<Integer, BuildReference<R>>> s = byNumber.tailMap(n).entrySet(); if (s.isEmpty()) return null; else return s.iterator().next(); } /** * Returns the build record #M (>=n) */ // >= and not <= because byNumber is in the descending order private Map.Entry<Integer,BuildReference<R>> floorEntry(int n) { // switch to this once we depend on JDK6 // return byNumber.floorEntry(n); SortedMap<Integer, BuildReference<R>> sub = byNumber.headMap(n); if (sub.isEmpty()) return null; Integer k = sub.lastKey(); return new DefaultMapEntry(k,sub.get(k)); } } /** * Build IDs found as directories, in the ascending order. */ // copy on write private volatile SortedList<String> idOnDisk = new SortedList<String>(Collections.<String>emptyList()); /** * Build number shortcuts found on disk, in the ascending order. */ // copy on write private volatile SortedIntList numberOnDisk = new SortedIntList(0); /** * Base directory for data. * In effect this is treated as a final field, but can't mark it final * because the compatibility requires that we make it settable * in the first call after the constructor. */ private File dir; protected AbstractLazyLoadRunMap(File dir) { initBaseDir(dir); } @Restricted(NoExternalUse.class) protected void initBaseDir(File dir) { assert this.dir==null; this.dir = dir; if (dir!=null) loadIdOnDisk(); } /** * @return true if {@link AbstractLazyLoadRunMap#AbstractLazyLoadRunMap} was called with a non-null param, or {@link RunMap#load(Job, RunMap.Constructor)} was called */ @Restricted(NoExternalUse.class) public final boolean baseDirInitialized() { return dir != null; } /** * Let go of all the loaded references. * * This is a bit more sophisticated version of forcing GC. * Primarily for debugging and testing lazy loading behaviour. * @since 1.507 */ public void purgeCache() { index = new Index(); loadIdOnDisk(); } private void loadIdOnDisk() { String[] buildDirs = dir.list(createDirectoryFilter()); if (buildDirs==null) { // the job may have just been created buildDirs=EMPTY_STRING_ARRAY; } // wrap into ArrayList to enable mutation Arrays.sort(buildDirs); idOnDisk = new SortedList<String>(new ArrayList<String>(Arrays.asList(buildDirs))); // TODO: should we check that shortcuts is a symlink? String[] shortcuts = dir.list(); if (shortcuts==null) shortcuts=EMPTY_STRING_ARRAY; SortedIntList list = new SortedIntList(shortcuts.length/2); for (String s : shortcuts) { try { list.add(Integer.parseInt(s)); } catch (NumberFormatException e) { // this isn't a shortcut } } list.sort(); numberOnDisk = list; } public Comparator<? super Integer> comparator() { return COMPARATOR; } /** * If we have non-zero R in memory, we can return false right away. * If we have zero R in memory, try loading one and see if we can find something. */ @Override public boolean isEmpty() { return index.byId.isEmpty() && search(Integer.MAX_VALUE, DESC)==null; } @Override public Set<Entry<Integer, R>> entrySet() { assert baseDirInitialized(); return Collections.unmodifiableSet(new BuildReferenceMapAdapter<R>(this,all()).entrySet()); } /** * Returns a read-only view of records that has already been loaded. */ public SortedMap<Integer,R> getLoadedBuilds() { return Collections.unmodifiableSortedMap(new BuildReferenceMapAdapter<R>(this, index.byNumber)); } /** * @param fromKey * Biggest build number to be in the returned set. * @param toKey * Smallest build number-1 to be in the returned set (-1 because this is exclusive) */ public SortedMap<Integer, R> subMap(Integer fromKey, Integer toKey) { // TODO: if this method can produce a lazy map, that'd be wonderful // because due to the lack of floor/ceil/higher/lower kind of methods // to look up keys in SortedMap, various places of Jenkins rely on // subMap+firstKey/lastKey combo. R start = search(fromKey, DESC); if (start==null) return EMPTY_SORTED_MAP; R end = search(toKey, ASC); if (end==null) return EMPTY_SORTED_MAP; for (R i=start; i!=end; ) { i = search(getNumberOf(i)-1,DESC); assert i!=null; } return Collections.unmodifiableSortedMap(new BuildReferenceMapAdapter<R>(this, index.byNumber.subMap(fromKey, toKey))); } public SortedMap<Integer, R> headMap(Integer toKey) { return subMap(Integer.MAX_VALUE, toKey); } public SortedMap<Integer, R> tailMap(Integer fromKey) { return subMap(fromKey, Integer.MIN_VALUE); } public Integer firstKey() { R r = newestBuild(); if (r==null) throw new NoSuchElementException(); return getNumberOf(r); } public Integer lastKey() { R r = oldestBuild(); if (r==null) throw new NoSuchElementException(); return getNumberOf(r); } public R newestBuild() { return search(Integer.MAX_VALUE, DESC); } public R oldestBuild() { return search(Integer.MIN_VALUE, ASC); } @Override public R get(Object key) { if (key instanceof Integer) { int n = (Integer) key; return get(n); } return super.get(key); } public R get(int n) { return search(n,Direction.EXACT); } /** * Finds the build #M where M is nearby the given 'n'. * * <p> * * * @param n * the index to start the search from * @param d * defines what we mean by "nearby" above. * If EXACT, find #N or return null. * If ASC, finds the closest #M that satisfies M>=N. * If DESC, finds the closest #M that satisfies M&lt;=N. */ public @CheckForNull R search(final int n, final Direction d) { Entry<Integer, BuildReference<R>> c = index.ceilingEntry(n); if (c!=null && c.getKey()== n) { R r = c.getValue().get(); if (r!=null) return r; // found the exact #n } // at this point we know that we don't have #n loaded yet {// check numberOnDisk as a cache to see if we can find it there int npos = numberOnDisk.find(n); if (npos>=0) {// found exact match R r = load(numberOnDisk.get(npos), null); if (r!=null) return r; } switch (d) { case ASC: case DESC: // didn't find the exact match, but what's the nearest ascending value in the cache? int neighbor = (d==ASC?HIGHER:LOWER).apply(npos); if (numberOnDisk.isInRange(neighbor)) { R r = getByNumber(numberOnDisk.get(neighbor)); if (r!=null) { // make sure that the cache is accurate by looking at the previous ID // and it actually satisfies the constraint int prev = (d==ASC?LOWER:HIGHER).apply(idOnDisk.find(getIdOf(r))); if (idOnDisk.isInRange(prev)) { R pr = getById(idOnDisk.get(prev)); // sign*sign is making sure that #pr and #r sandwiches #n. if (pr!=null && signOfCompare(getNumberOf(pr),n)*signOfCompare(n,getNumberOf(r))>0) return r; else { // cache is lying. there's something fishy. // ignore the cache and do the slow search } } else { // r is the build with youngest ID return r; } } else { // cache says we should have a build but we didn't. // ignore the cache and do the slow search } } break; case EXACT: // fall through } // didn't find it in the cache, but don't give up yet // maybe the cache just doesn't exist. // so fall back to the slow search } // capture the snapshot and work off with it since it can be overwritten by other threads SortedList<String> idOnDisk = this.idOnDisk; boolean clonedIdOnDisk = false; // if we modify idOnDisk we need to write it back. this flag is set to true when we overwrit idOnDisk local var // slow path: we have to find the build from idOnDisk by guessing ID of the build. // first, narrow down the candidate IDs to try by using two known number-to-ID mapping if (idOnDisk.isEmpty()) return null; Entry<Integer, BuildReference<R>> f = index.floorEntry(n); // if bound is null, use a sentinel value String cid = c==null ? "\u0000" : c.getValue().id; String fid = f==null ? "\uFFFF" : f.getValue().id; // at this point, #n must be in (cid,fid) // We know that the build we are looking for exists in [lo,hi) --- it's "hi)" and not "hi]" because we do +1. // we will narrow this down via binary search final int initialSize = idOnDisk.size(); int lo = idOnDisk.higher(cid); int hi = idOnDisk.lower(fid)+1; final int initialLo = lo, initialHi = hi; if (!(0<=lo && lo<=hi && hi<=idOnDisk.size())) { // assertion error, but we are so far unable to get to the bottom of this bug. // but don't let this kill the loading the hard way String msg = String.format( "JENKINS-15652 Assertion error #1: failing to load %s #%d %s: lo=%d,hi=%d,size=%d,size2=%d", dir, n, d, lo, hi, idOnDisk.size(), initialSize); LOGGER.log(Level.WARNING, msg); return null; } while (lo<hi) { final int pivot = (lo+hi)/2; if (!(0<=lo && lo<=pivot && pivot<hi && hi<=idOnDisk.size())) { // assertion error, but we are so far unable to get to the bottom of this bug. // but don't let this kill the loading the hard way String msg = String.format( "JENKINS-15652 Assertion error #2: failing to load %s #%d %s: lo=%d,hi=%d,pivot=%d,size=%d (initial:lo=%d,hi=%d,size=%d)", dir, n, d, lo, hi, pivot, idOnDisk.size(), initialLo, initialHi, initialSize); LOGGER.log(Level.WARNING, msg); return null; } R r = load(idOnDisk.get(pivot), null); if (r==null) { // this ID isn't valid. get rid of that and retry pivot hi--; if (!clonedIdOnDisk) {// if we are making an edit, we need to own a copy idOnDisk = new SortedList<String>(idOnDisk); clonedIdOnDisk = true; } idOnDisk.remove(pivot); continue; } int found = getNumberOf(r); if (found==n) return r; // exact match if (found<n) lo = pivot+1; // the pivot was too small. look in the upper half else hi = pivot; // the pivot was too big. look in the lower half } if (clonedIdOnDisk) this.idOnDisk = idOnDisk; // feedback the modified result atomically assert lo==hi; // didn't find the exact match // both lo and hi point to the insertion point on idOnDisk switch (d) { case ASC: if (hi==idOnDisk.size()) return null; return getById(idOnDisk.get(hi)); case DESC: if (lo<=0) return null; if (lo-1>=idOnDisk.size()) { // assertion error, but we are so far unable to get to the bottom of this bug. // but don't let this kill the loading the hard way LOGGER.log(Level.WARNING, String.format( "JENKINS-15652 Assertion error #3: failing to load %s #%d %s: lo=%d,hi=%d,size=%d (initial:lo=%d,hi=%d,size=%d)", dir, n,d,lo,hi,idOnDisk.size(), initialLo,initialHi,initialSize)); return null; } return getById(idOnDisk.get(lo-1)); case EXACT: if (hi<=0) return null; R r = load(idOnDisk.get(hi-1), null); if (r==null) return null; int found = getNumberOf(r); if (found==n) return r; // exact match return null; default: throw new AssertionError(); } } /** * sign of (a-b). */ private static int signOfCompare(int a, int b) { if (a>b) return 1; if (a<b) return -1; return 0; } public R getById(String id) { Index snapshot = index; if (snapshot.byId.containsKey(id)) { BuildReference<R> ref = snapshot.byId.get(id); if (ref==null) return null; // known failure R v = unwrap(ref); if (v!=null) return v; // already in memory // otherwise fall through to load } return load(id,null); } public R getByNumber(int n) { return search(n,Direction.EXACT); } public R put(R value) { return _put(value); } protected R _put(R value) { return put(getNumberOf(value),value); } @Override public synchronized R put(Integer key, R r) { String id = getIdOf(r); int n = getNumberOf(r); Index copy = copy(); BuildReference<R> ref = createReference(r); BuildReference<R> old = copy.byId.put(id,ref); copy.byNumber.put(n,ref); index = copy; /* search relies on the fact that every object added via put() method be available in the xyzOnDisk index, so I'm adding them here however, this is awfully inefficient. I wonder if there's any better way to do this? */ if (!idOnDisk.contains(id)) { ArrayList<String> a = new ArrayList<String>(idOnDisk); a.add(id); Collections.sort(a); idOnDisk = new SortedList<String>(a); } if (!numberOnDisk.contains(n)) { SortedIntList a = new SortedIntList(numberOnDisk); a.add(n); a.sort(); numberOnDisk = a; } return unwrap(old); } private R unwrap(Reference<R> ref) { return ref!=null ? ref.get() : null; } @Override public synchronized void putAll(Map<? extends Integer,? extends R> rhs) { Index copy = copy(); for (R r : rhs.values()) { String id = getIdOf(r); BuildReference<R> ref = createReference(r); copy.byId.put(id,ref); copy.byNumber.put(getNumberOf(r),ref); } index = copy; } /** * Loads all the build records to fully populate the map. * Calling this method results in eager loading everything, * so the whole point of this class is to avoid this call as much as possible * for typical code path. * * @return * fully populated map. */ private TreeMap<Integer,BuildReference<R>> all() { if (!fullyLoaded) { synchronized (this) { if (!fullyLoaded) { Index copy = copy(); for (String id : idOnDisk) { if (!copy.byId.containsKey(id)) load(id,copy); } index = copy; fullyLoaded = true; } } } return index.byNumber; } /** * Creates a duplicate for the COW data structure in preparation for mutation. */ private Index copy() { return new Index(index); } /** * Tries to load the record #N by using the shortcut. * * @return null if the data failed to load. */ protected R load(int n, Index editInPlace) { R r = null; File shortcut = new File(dir,String.valueOf(n)); if (shortcut.isDirectory()) { synchronized (this) { r = load(shortcut,editInPlace); // make sure what we actually loaded is #n, // because the shortcuts can lie. if (r!=null && getNumberOf(r)!=n) r = null; if (r==null) { // if failed to locate, record that fact SortedIntList update = new SortedIntList(numberOnDisk); update.removeValue(n); numberOnDisk = update; } } } return r; } protected R load(String id, Index editInPlace) { assert dir != null; R v = load(new File(dir, id), editInPlace); if (v==null && editInPlace!=null) { // remember the failure. // if editInPlace==null, we can create a new copy for this, but not sure if it's worth doing, // given that we also update idOnDisk anyway. editInPlace.byId.put(id,null); } return v; } /** * @param editInPlace * If non-null, update this data structure. * Otherwise do a copy-on-write of {@link #index} */ protected synchronized R load(File dataDir, Index editInPlace) { try { R r = retrieve(dataDir); if (r==null) return null; Index copy = editInPlace!=null ? editInPlace : new Index(index); String id = getIdOf(r); BuildReference<R> ref = createReference(r); copy.byId.put(id,ref); copy.byNumber.put(getNumberOf(r),ref); if (editInPlace==null) index = copy; return r; } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to load "+dataDir,e); } return null; } /** * Subtype to provide {@link Run#getNumber()} so that this class doesn't have to depend on it. */ protected abstract int getNumberOf(R r); /** * Subtype to provide {@link Run#getId()} so that this class doesn't have to depend on it. */ protected abstract String getIdOf(R r); /** * Allow subtype to capture a reference. */ protected BuildReference<R> createReference(R r) { return new BuildReference<R>(getIdOf(r),r); } /** * Parses {@code R} instance from data in the specified directory. * * @return * null if the parsing failed. * @throws IOException * if the parsing failed. This is just like returning null * except the caller will catch the exception and report it. */ protected abstract R retrieve(File dir) throws IOException; public synchronized boolean removeValue(R run) { Index copy = copy(); int n = getNumberOf(run); copy.byNumber.remove(n); SortedIntList a = new SortedIntList(numberOnDisk); a.removeValue(n); numberOnDisk = a; BuildReference<R> old = copy.byId.remove(getIdOf(run)); this.index = copy; return unwrap(old)!=null; } /** * Replaces all the current loaded Rs with the given ones. */ public synchronized void reset(TreeMap<Integer,R> builds) { Index index = new Index(); for (R r : builds.values()) { String id = getIdOf(r); BuildReference<R> ref = createReference(r); index.byId.put(id,ref); index.byNumber.put(getNumberOf(r),ref); } this.index = index; } @Override public int hashCode() { return System.identityHashCode(this); } @Override public boolean equals(Object o) { return o==this; } /** * Lists the actual data directory */ protected abstract FilenameFilter createDirectoryFilter(); private static final Comparator<Comparable> COMPARATOR = new Comparator<Comparable>() { public int compare(Comparable o1, Comparable o2) { return -o1.compareTo(o2); } }; public enum Direction { ASC, DESC, EXACT } private static final String[] EMPTY_STRING_ARRAY = new String[0]; private static final SortedMap EMPTY_SORTED_MAP = Collections.unmodifiableSortedMap(new TreeMap()); static final Logger LOGGER = Logger.getLogger(AbstractLazyLoadRunMap.class.getName()); }
jspotanski/jenkins-master
core/src/main/java/jenkins/model/lazy/AbstractLazyLoadRunMap.java
Java
mit
28,042
package mezz.jei.ingredients; import java.util.Collection; import mezz.jei.config.Config; import mezz.jei.gui.ingredients.IIngredientListElement; import mezz.jei.suffixtree.GeneralizedSuffixTree; class PrefixedSearchTree { private final GeneralizedSuffixTree tree; private final IStringsGetter stringsGetter; private final IModeGetter modeGetter; public PrefixedSearchTree(GeneralizedSuffixTree tree, IStringsGetter stringsGetter, IModeGetter modeGetter) { this.tree = tree; this.stringsGetter = stringsGetter; this.modeGetter = modeGetter; } public GeneralizedSuffixTree getTree() { return tree; } public IStringsGetter getStringsGetter() { return stringsGetter; } public Config.SearchMode getMode() { return modeGetter.getMode(); } // TODO java 8 interface IStringsGetter { Collection<String> getStrings(IIngredientListElement<?> element); } //TODO java 8 interface IModeGetter { Config.SearchMode getMode(); } }
way2muchnoise/JustEnoughItems
src/main/java/mezz/jei/ingredients/PrefixedSearchTree.java
Java
mit
957
package edu.ualr.oyster.utilities.acma.string_matching; /** * The <code>Proximity</code> interface provides a general method for * defining closeness between two objects. Proximity is a similarity * measure, with two objects having higher proximity being more * similar to one another. It provides a single method {@link * #proximity(Object,Object)} returning the proximity between two * objects. The closer two objects are, the higher their proximity * value. * * <p>Proximity runs in the other direction from distance. With * distance, the closer two objects are, the lower their distance * value. Many classes implement both <code>Proximity</code> and * {@link Distance}, with one method defined in terms of the other. * For instance, negation converts a distance into a proximity. * * @author Bob Carpenter * @version 3.0 * @since LingPipe3.0 * @param <E> the type of objects between which proximity is defined */ public interface Proximity<E> { /** * Returns the distance between the specified pair of objects. * * @param e1 First object. * @param e2 Second object. * @return Proximity between the two objects. */ public double proximity(E e1, E e2); }
pmazzu/ACMA_OYSTER
src/string_matching/Proximity.java
Java
mit
1,229
/* * The MIT License * * Copyright 2017 Moritz Rieger. * * 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 gens.rft; import java.util.ArrayList; /** * * @author Moritz Rieger */ public interface TreeNode { TreeNode getParent(); TreeNode[] getChildren(); void setChildren(TreeNode[] nodes); void setParent(TreeNode node); int getChildrenCount(); }
peterorlowsky/ProPra4
src/gens/rft/TreeNode.java
Java
mit
1,410
package br.senac.tadsb.pi3.livrarianext.models; /** * * @author roger */ public class Cliente { private int id; private String nome; private String sobreNome; private String cpf; private String rg; private String nascimento;//Depois será alterado para data private String sexo; private String endereco; private String numero; private String bairro; private String email; private String telefone; private Loja loja; private Boolean ativo; public Cliente(){ } public Cliente(String nome, String sobreNome, String cpf, String rg, String nascimento, String sexo, String email, String telefone, Boolean ativo){ this.nome = nome; this.sobreNome = sobreNome; this.cpf = cpf; this.rg = rg; this.nascimento = nascimento; this.sexo = sexo; this.email = email; this.telefone = telefone; this.ativo = ativo; } public Cliente(String nome, String sobreNome, String cpf, String rg, String nascimento, String sexo, String email, String telefone, String endereco, String numero, String bairro, Boolean ativo){ this(nome, sobreNome, cpf, rg, nascimento, sexo, email, telefone, ativo); this.endereco = endereco; this.numero = numero; this.bairro = bairro; } public Cliente(int id, String nome, String sobreNome, String cpf, String rg, String nascimento, String sexo, String email, String telefone, String endereco, String numero, String bairro, Loja loja, Boolean ativo){ this(nome, sobreNome, cpf, rg, nascimento, sexo, email, telefone, endereco, numero, bairro, ativo); this.id = id; this.loja = loja; } public Cliente(String nome, String sobrenome, String cpf, String rg, String nascimento, String sexo, String email, String telefone, String endereco, String numero, String bairro) { //this.id = Integer.parseInt(id); this.nome = nome; this.sobreNome = sobrenome; this.cpf = cpf; this.rg = rg; this.nascimento = nascimento; this.sexo = sexo; this.email = email; this.telefone = telefone; this.endereco = endereco; this.numero = numero; this.bairro = bairro; } public void setId(int id) { this.id = id; } public void setNome(String nome) { this.nome = nome; } public void setSobreNome(String sobreNome) { this.sobreNome = sobreNome; } public void setCpf(String cpf) { this.cpf = cpf; } public void setRg(String rg) { this.rg = rg; } public void setNascimento(String nascimento) { this.nascimento = nascimento; } public void setSexo(String sexo) { this.sexo = sexo; } public void setEndereco(String endereco) { this.endereco = endereco; } public void setNumero(String numero) { this.numero = numero; } public void setBairro(String bairro) { this.bairro = bairro; } public void setEmail(String email) { this.email = email; } public void setTelefone(String telefone) { this.telefone = telefone; } public void setLoja(Loja loja) { this.loja = loja; } public int getId() { return id; } public String getNome() { return nome; } public String getSobreNome() { return sobreNome; } public String getCpf() { return cpf; } public String getRg() { return rg; } public String getNascimento() { return nascimento; } public String getSexo() { return sexo; } public String getEndereco() { return endereco; } public String getNumero() { return numero; } public String getBairro() { return bairro; } public String getEmail() { return email; } public String getTelefone() { return telefone; } public Loja getLoja() { return loja; } public Boolean getAtivo(){ return ativo; } }
Nuneez/LivrariaNext
LivrariaNext/src/main/java/br/senac/tadsb/pi3/livrarianext/models/Cliente.java
Java
mit
4,333
package aes.motive.tileentity; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.server.MinecraftServer; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityEnderChest; import net.minecraft.tileentity.TileEntityHopper; import net.minecraftforge.common.ForgeDirection; import aes.base.BlockBase; import aes.base.TileEntityBase; import aes.motive.Motive; import aes.motive.render.model.TextureBreakerConnection; import aes.utils.Vector3i; import aes.utils.WorldUtils; import cpw.mods.fml.common.FMLCommonHandler; public class TileEntityBreaker extends TileEntityBase { public static boolean DROP_IF_NO_ATTACHED_INVENTORY = false; public static boolean BREAK_IF_NO_ATTACHED_INVENTORY = false; List<IInventory> foundConnectedInventories = new LinkedList<IInventory>(); long connectedInventoriesFoundOnTick; private ConnectionMask connectionMask = new ConnectionMask(); private void addConnectedLocationsWithTileEntities(HashSet<Vector3i> locations, Vector3i location, HashSet<Vector3i> checkedLocations) { if (checkedLocations.contains(location) || !WorldUtils.isNonEmptyBlock(this.worldObj, location)) return; final TileEntity tileEntity = this.worldObj.getBlockTileEntity(location.x, location.y, location.z); if (tileEntity == null) return; locations.add(location); if (!(tileEntity instanceof TileEntityBreaker)) return; final ForgeDirection facing = ForgeDirection.getOrientation(this.worldObj.getBlockMetadata(location.x, location.y, location.z)); checkedLocations.add(location); for (final ForgeDirection direction : ForgeDirection.VALID_DIRECTIONS) { if (direction != facing) { addConnectedLocationsWithTileEntities(locations, location.increment(direction), checkedLocations); } } } private boolean checkIsConnected(ForgeDirection direction) { final Vector3i location = getLocation().increment(direction); final TileEntity tileEntity = this.worldObj.getBlockTileEntity(location.x, location.y, location.z); if (tileEntity instanceof TileEntityBreaker) return true; if (tileEntity instanceof IInventory) return true; else if (Minecraft.getMinecraft().isSingleplayer() && tileEntity instanceof TileEntityEnderChest) return true; return false; } private IInventory findConnectedInventoryFor(ItemStack stack) { IInventory inventoryToAddTo = null; int mostSpareSlots = -1; for (final IInventory inventory : getConnectedInventories()) { int spareSlots = 0; for (int i = 0; i < inventory.getSizeInventory(); i++) { final ItemStack stackInSlot = inventory.getStackInSlot(i); if (stackInSlot == null) { spareSlots++; continue; } if (stack.isStackable() && stackInSlot.itemID == stack.itemID && stackInSlot.getItemDamage() == stack.getItemDamage() && stackInSlot.stackSize + stack.stackSize <= inventory.getInventoryStackLimit()) return inventory; } if (spareSlots > mostSpareSlots) { mostSpareSlots = spareSlots; inventoryToAddTo = inventory; } } return inventoryToAddTo; } public List<IInventory> getConnectedInventories() { final long tick = this.worldObj.getWorldTime(); if (tick == this.connectedInventoriesFoundOnTick) return this.foundConnectedInventories; final HashSet<Vector3i> locationsWithTileEntities = getConnectedLocationsWithTileEntities(); final List<IInventory> connectedInventories = new LinkedList<IInventory>(); for (final Vector3i location : locationsWithTileEntities) { final TileEntity tileEntity = this.worldObj.getBlockTileEntity(location.x, location.y, location.z); if (tileEntity instanceof IInventory) { connectedInventories.add((IInventory) tileEntity); } else if (Minecraft.getMinecraft().isSingleplayer() && tileEntity instanceof TileEntityEnderChest) { final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); if (!server.getConfigurationManager().playerEntityList.isEmpty()) { connectedInventories.add(((EntityPlayerMP) server.getConfigurationManager().playerEntityList.get(0)).getInventoryEnderChest()); } } } for (final Vector3i location : locationsWithTileEntities) { final TileEntity tileEntity = this.worldObj.getBlockTileEntity(location.x, location.y, location.z); if (tileEntity instanceof TileEntityBreaker) { final TileEntityBreaker tileEntityBreaker = (TileEntityBreaker) tileEntity; tileEntityBreaker.foundConnectedInventories = connectedInventories; tileEntityBreaker.connectedInventoriesFoundOnTick = tick; } } return connectedInventories; } public HashSet<Vector3i> getConnectedLocationsWithTileEntities() { final HashSet<Vector3i> inventoryLocations = new HashSet<Vector3i>(); addConnectedLocationsWithTileEntities(inventoryLocations, new Vector3i(this.xCoord, this.yCoord, this.zCoord), new HashSet<Vector3i>()); return inventoryLocations; } public ConnectionMask getConnectionMask() { return this.connectionMask; } @Override public String getRenderCacheKey() { return "TileEntityBreaker_" + this.connectionMask.getValue(); } private boolean isBreakableBlock(Vector3i location) { if (!WorldUtils.isNonEmptyBlock(this.worldObj, location)) return false; final Block bl = Block.blocksList[this.worldObj.getBlockId(location.x, location.y, location.z)]; if (bl.getBlockHardness(this.worldObj, location.x, location.y, location.z) < 0.0F && bl.blockID != Motive.BlockMote.blockID) return false; return true; } @Override public void onBlockNeighborChange() { updateConnections(); } @Override public void readFromNBT(NBTTagCompound nbtTagCompound) { super.readFromNBT(nbtTagCompound); setConnectionMask(new ConnectionMask(nbtTagCompound.getInteger("connectionMask"))); } public void setBlockBounds() { final float strutHeight = (float) TextureBreakerConnection.strutHeight / 2; if (this.connectionMask.isConnectedBack()) { Motive.BlockBreaker.setBlockBounds(0, 0, 0, 1, 1, 1); return; } switch (getFacing()) { case NORTH: Motive.BlockBreaker.setBlockBounds(0, 0, 0, 1, 1, 0.5f + strutHeight); return; case SOUTH: Motive.BlockBreaker.setBlockBounds(0, 0, 0.5f - strutHeight, 1, 1, 1); return; case WEST: Motive.BlockBreaker.setBlockBounds(0, 0, 0, 0.5f + strutHeight, 1, 1); return; case EAST: Motive.BlockBreaker.setBlockBounds(0.5f - strutHeight, 0, 0, 1, 1, 1); return; case DOWN: Motive.BlockBreaker.setBlockBounds(0, 0, 0, 1, 0.5f + strutHeight, 1); return; case UP: Motive.BlockBreaker.setBlockBounds(0, 0.5f - strutHeight, 0, 1, 1, 1); return; default: Motive.BlockBreaker.setBlockBounds(0, 0, 0, 1, 1, 1); } } public void setConnectionMask(ConnectionMask connectionMask) { if (!getConnectionMask().equals(connectionMask)) { this.connectionMask = connectionMask; updateBlock(); } } protected void updateConnections() { boolean connectedLeft; boolean connectedRight; boolean connectedUp; boolean connectedDown; boolean connectedBack; switch (getFacing()) { case NORTH: connectedLeft = checkIsConnected(ForgeDirection.WEST); connectedRight = checkIsConnected(ForgeDirection.EAST); connectedUp = checkIsConnected(ForgeDirection.UP); connectedDown = checkIsConnected(ForgeDirection.DOWN); connectedBack = checkIsConnected(ForgeDirection.SOUTH); break; case SOUTH: connectedLeft = checkIsConnected(ForgeDirection.EAST); connectedRight = checkIsConnected(ForgeDirection.WEST); connectedUp = checkIsConnected(ForgeDirection.UP); connectedDown = checkIsConnected(ForgeDirection.DOWN); connectedBack = checkIsConnected(ForgeDirection.NORTH); break; case WEST: connectedLeft = checkIsConnected(ForgeDirection.SOUTH); connectedRight = checkIsConnected(ForgeDirection.NORTH); connectedUp = checkIsConnected(ForgeDirection.UP); connectedDown = checkIsConnected(ForgeDirection.DOWN); connectedBack = checkIsConnected(ForgeDirection.EAST); break; case EAST: connectedLeft = checkIsConnected(ForgeDirection.NORTH); connectedRight = checkIsConnected(ForgeDirection.SOUTH); connectedUp = checkIsConnected(ForgeDirection.UP); connectedDown = checkIsConnected(ForgeDirection.DOWN); connectedBack = checkIsConnected(ForgeDirection.WEST); break; case UP: connectedLeft = checkIsConnected(ForgeDirection.WEST); connectedRight = checkIsConnected(ForgeDirection.EAST); connectedUp = checkIsConnected(ForgeDirection.SOUTH); connectedDown = checkIsConnected(ForgeDirection.NORTH); connectedBack = checkIsConnected(ForgeDirection.DOWN); break; case DOWN: connectedLeft = checkIsConnected(ForgeDirection.WEST); connectedRight = checkIsConnected(ForgeDirection.EAST); connectedUp = checkIsConnected(ForgeDirection.NORTH); connectedDown = checkIsConnected(ForgeDirection.SOUTH); connectedBack = checkIsConnected(ForgeDirection.UP); break; default: return; } setConnectionMask(new ConnectionMask(connectedLeft, connectedRight, connectedUp, connectedDown, connectedBack)); } @Override public void updateEntity() { final Vector3i location = new Vector3i(this.xCoord, this.yCoord, this.zCoord).increment(BlockBase.getFacing(this.worldObj, this.xCoord, this.yCoord, this.zCoord)); if (!isBreakableBlock(location)) return; final Block block = Block.blocksList[this.worldObj.getBlockId(location.x, location.y, location.z)]; final ArrayList<ItemStack> blockDropped = block.getBlockDropped(this.worldObj, location.x, location.y, location.z, this.worldObj.getBlockMetadata(location.x, location.y, location.z), 0); boolean breakBlock = true; for (ItemStack stack : blockDropped) { final IInventory inventory = findConnectedInventoryFor(stack); if (inventory == null || (stack = TileEntityHopper.insertStack(inventory, stack, -1)) != null) { if (DROP_IF_NO_ATTACHED_INVENTORY) { WorldUtils.dropItem(this.worldObj, location.x, location.y, location.z, stack); } else if (!BREAK_IF_NO_ATTACHED_INVENTORY) { breakBlock = false; } } } if (breakBlock) { this.worldObj.setBlockToAir(location.x, location.y, location.z); } } @Override public void writeToNBT(NBTTagCompound nbtTagCompound) { super.writeToNBT(nbtTagCompound); nbtTagCompound.setInteger("connectionMask", getConnectionMask().getValue()); } }
AesGH/Motive
src/aes/motive/tileentity/TileEntityBreaker.java
Java
mit
10,688
package alec_wam.CrystalMod.api.estorage; import alec_wam.CrystalMod.tiles.pipes.estorage.EStorageNetwork; import alec_wam.CrystalMod.tiles.pipes.estorage.EStorageNetworkClient.SortType; import alec_wam.CrystalMod.tiles.pipes.estorage.EStorageNetworkClient.ViewType; import net.minecraft.util.math.BlockPos; public interface IPanelSource { public EStorageNetwork getNetwork(); public BlockPos getPanelPos(); public SortType getSortType(); public void setSortType(SortType type); public ViewType getViewType(); public void setViewType(ViewType type); public boolean getJEISync(); public void setJEISync(boolean sync); public String getSearchBar(); public void setSearchBar(String text); }
Alec-WAM/CrystalMod
src/main/java/alec_wam/CrystalMod/api/estorage/IPanelSource.java
Java
mit
751
package question_301; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Q349_Intersection_of_Two_Arrays { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set = new HashSet<>(); // Set<Integer> set2 = new HashSet<>(); for(int i : nums1){ set.add(i); } List<Integer> list = new ArrayList<>(); for(int i : nums2){ if(set.contains(i)){ list.add(i); set.remove(i); } } int[] arr = new int[list.size()]; for(int i =0; i< list.size(); i++){ arr[i] = list.get(i); } // return list.toArray(new Integer[list.size()]); return arr; } }
stingchang/CS_Java
src/question_301/Q349_Intersection_of_Two_Arrays.java
Java
mit
817
// @formatter:off /* * --------------------------------------------------------- * Copyright(C) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. See License.txt in the project root. * --------------------------------------------------------- * * --------------------------------------------------------- * Generated file, DO NOT EDIT * --------------------------------------------------------- * * See following wiki page for instructions on how to regenerate: * https://vsowiki.com/index.php?title=Rest_Client_Generation */ package com.microsoft.alm.teamfoundation.distributedtask.webapi; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.alm.visualstudio.services.webapi.ReferenceLinks; /** */ public class TaskAgentReference { private ReferenceLinks _links; /** * Gets or sets a value indicating whether or not this agent should be enabled for job execution. */ private boolean enabled; /** * Gets the identifier of the agent. */ private int id; /** * Gets the name of the agent. */ private String name; /** * Gets the current connectivity status of the agent. */ private TaskAgentStatus status; /** * Gets the version of the agent. */ private String version; @JsonProperty("_links") public ReferenceLinks getLinks() { return _links; } @JsonProperty("_links") public void setLinks(final ReferenceLinks _links) { this._links = _links; } /** * Gets or sets a value indicating whether or not this agent should be enabled for job execution. */ public boolean getEnabled() { return enabled; } /** * Gets or sets a value indicating whether or not this agent should be enabled for job execution. */ public void setEnabled(final boolean enabled) { this.enabled = enabled; } /** * Gets the identifier of the agent. */ public int getId() { return id; } /** * Gets the identifier of the agent. */ public void setId(final int id) { this.id = id; } /** * Gets the name of the agent. */ public String getName() { return name; } /** * Gets the name of the agent. */ public void setName(final String name) { this.name = name; } /** * Gets the current connectivity status of the agent. */ public TaskAgentStatus getStatus() { return status; } /** * Gets the current connectivity status of the agent. */ public void setStatus(final TaskAgentStatus status) { this.status = status; } /** * Gets the version of the agent. */ public String getVersion() { return version; } /** * Gets the version of the agent. */ public void setVersion(final String version) { this.version = version; } }
Microsoft/vso-httpclient-java
Rest/alm-distributedtask-client/src/main/generated/com/microsoft/alm/teamfoundation/distributedtask/webapi/TaskAgentReference.java
Java
mit
2,947
package com.drazendjanic.ebookrepository.assembler; import com.drazendjanic.ebookrepository.dto.EditedUserDto; import com.drazendjanic.ebookrepository.dto.NewUserDto; import com.drazendjanic.ebookrepository.entity.Category; import com.drazendjanic.ebookrepository.entity.User; public class UserAssembler { public static User toUser(NewUserDto newUserDto) { User user = new User(); user.setFirstName(newUserDto.getFirstName()); user.setLastName(newUserDto.getLastName()); user.setUsername(newUserDto.getUsername()); user.setPassword(newUserDto.getPassword()); user.setType(newUserDto.getType()); if (newUserDto.getCategoryId() != null) { Category category = new Category(); category.setId(newUserDto.getCategoryId()); user.setCategory(category); } return user; } public static User toUser(EditedUserDto editedUserDto) { User user = new User(); user.setFirstName(editedUserDto.getFirstName()); user.setLastName(editedUserDto.getLastName()); user.setUsername(editedUserDto.getUsername()); user.setType(editedUserDto.getType()); if (editedUserDto.getCategoryId() != null) { Category category = new Category(); category.setId(editedUserDto.getCategoryId()); user.setCategory(category); } return user; } }
DrazenRocket/EBookRepository
EBookRepositoryApp/src/main/java/com/drazendjanic/ebookrepository/assembler/UserAssembler.java
Java
mit
1,436
package com.bjzjns.hxplugin.fragment; import android.Manifest; import android.annotation.TargetApi; import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.AbsListView; import android.widget.AbsListView.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.bjzjns.hxplugin.activity.RecorderVideoActivity; import com.bjzjns.hxplugin.model.VideoEntityModel; import com.bjzjns.hxplugin.tools.video.ImageCache; import com.bjzjns.hxplugin.tools.video.ImageResizer; import com.bjzjns.hxplugin.tools.video.Utils; import com.bjzjns.hxplugin.view.RecyclingImageView; import com.hyphenate.util.DateUtils; import com.hyphenate.util.EMLog; import com.hyphenate.util.TextFormater; import java.util.ArrayList; import java.util.List; public class ImageGridFragment extends Fragment implements OnItemClickListener { private static final String TAG = "ImageGridFragment"; private int mImageThumbSize; private int mImageThumbSpacing; private ImageAdapter mAdapter; private ImageResizer mImageResizer; List<VideoEntityModel> mList; private static final int REQUEST_CODE_VIDEO = 100; private static final String[] PERMISSIONS_VIDEO = new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}; /** * Empty constructor as per the Fragment documentation */ public ImageGridFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mImageThumbSize = getResources().getDimensionPixelSize( getResources().getIdentifier("image_thumbnail_size", "dimen", getActivity().getPackageName())); mImageThumbSpacing = getResources().getDimensionPixelSize( getResources().getIdentifier("image_thumbnail_spacing", "dimen", getActivity().getPackageName())); mList = new ArrayList<VideoEntityModel>(); getVideoFile(); mAdapter = new ImageAdapter(getActivity()); ImageCache.ImageCacheParams cacheParams = new ImageCache.ImageCacheParams(); cacheParams.setMemCacheSizePercent(0.25f); // Set memory cache to 25% of // app memory // The ImageFetcher takes care of loading images into our ImageView // children asynchronously mImageResizer = new ImageResizer(getActivity(), mImageThumbSize); mImageResizer.setLoadingImage(getResources().getIdentifier("em_empty_photo", "drawable", getActivity().getPackageName())); mImageResizer.addImageCache(getActivity().getSupportFragmentManager(), cacheParams); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View v = inflater.inflate(getResources().getIdentifier("em_image_grid_fragment", "layout", getActivity().getPackageName()), container, false); final GridView mGridView = (GridView) v.findViewById(getResources().getIdentifier("gridView", "id", getActivity().getPackageName())); mGridView.setAdapter(mAdapter); mGridView.setOnItemClickListener(this); mGridView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int scrollState) { // Pause fetcher to ensure smoother scrolling when flinging if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) { // Before Honeycomb pause image loading on scroll to help // with performance if (!Utils.hasHoneycomb()) { mImageResizer.setPauseWork(true); } } else { mImageResizer.setPauseWork(false); } } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } }); // This listener is used to get the final width of the GridView and then // calculate the // number of columns and the width of each column. The width of each // column is variable // as the GridView has stretchMode=columnWidth. The column width is used // to set the height // of each view so we get nice square thumbnails. mGridView.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { @TargetApi(VERSION_CODES.JELLY_BEAN) @Override public void onGlobalLayout() { final int numColumns = (int) Math.floor(mGridView .getWidth() / (mImageThumbSize + mImageThumbSpacing)); if (numColumns > 0) { final int columnWidth = (mGridView.getWidth() / numColumns) - mImageThumbSpacing; mAdapter.setItemHeight(columnWidth); if (Utils.hasJellyBean()) { mGridView.getViewTreeObserver() .removeOnGlobalLayoutListener(this); } else { mGridView.getViewTreeObserver() .removeGlobalOnLayoutListener(this); } } } }); return v; } @Override public void onResume() { super.onResume(); mImageResizer.setExitTasksEarly(false); mAdapter.notifyDataSetChanged(); } @Override public void onDestroy() { super.onDestroy(); mImageResizer.closeCache(); mImageResizer.clearCache(); } @Override public void onItemClick(AdapterView<?> parent, View v, final int position, long id) { mImageResizer.setPauseWork(true); if (position == 0) { if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) || PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(getContext(), Manifest.permission.RECORD_AUDIO)) { requestPermissions(PERMISSIONS_VIDEO, REQUEST_CODE_VIDEO); } else { Intent intent = new Intent(); intent.setClass(getActivity(), RecorderVideoActivity.class); startActivityForResult(intent, 100); } } else { VideoEntityModel vEntty = mList.get(position - 1); // limit the size to 10M if (vEntty.size > 1024 * 1024 * 10) { String st = getResources().getString(getResources().getIdentifier("temporary_does_not", "string", getActivity().getPackageName())); Toast.makeText(getActivity(), st, Toast.LENGTH_SHORT).show(); return; } Intent intent = getActivity().getIntent().putExtra("path", vEntty.filePath).putExtra("dur", vEntty.duration); getActivity().setResult(Activity.RESULT_OK, intent); getActivity().finish(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); switch (requestCode) { case REQUEST_CODE_VIDEO: if (hasAllPermissionsGranted(grantResults)) { Intent intent = new Intent(); intent.setClass(getActivity(), RecorderVideoActivity.class); startActivityForResult(intent, 100); } break; default: break; } } private boolean hasAllPermissionsGranted(@NonNull int[] grantResults) { for (int grantResult : grantResults) { if (grantResult == PackageManager.PERMISSION_DENIED) { return false; } } return true; } private class ImageAdapter extends BaseAdapter { private final Context mContext; private int mItemHeight = 0; private RelativeLayout.LayoutParams mImageViewLayoutParams; public ImageAdapter(Context context) { super(); mContext = context; mImageViewLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } @Override public int getCount() { return mList.size() + 1; } @Override public Object getItem(int position) { return (position == 0) ? null : mList.get(position - 1); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup container) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); convertView = LayoutInflater.from(mContext).inflate(getResources().getIdentifier("em_choose_griditem", "layout", getActivity().getPackageName()), container, false); holder.imageView = (RecyclingImageView) convertView.findViewById(getResources().getIdentifier("imageView", "id", getActivity().getPackageName())); holder.icon = (ImageView) convertView.findViewById(getResources().getIdentifier("video_icon", "id", getActivity().getPackageName())); holder.tvDur = (TextView) convertView.findViewById(getResources().getIdentifier("chatting_length_iv", "id", getActivity().getPackageName())); holder.tvSize = (TextView) convertView.findViewById(getResources().getIdentifier("chatting_size_iv", "id", getActivity().getPackageName())); holder.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); holder.imageView.setLayoutParams(mImageViewLayoutParams); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } // Check the height matches our calculated column width if (holder.imageView.getLayoutParams().height != mItemHeight) { holder.imageView.setLayoutParams(mImageViewLayoutParams); } // Finally load the image asynchronously into the ImageView, this // also takes care of // setting a placeholder image while the background thread runs String st1 = getResources().getString(getResources().getIdentifier("Video_footage", "string", getActivity().getPackageName())); if (position == 0) { holder.icon.setVisibility(View.GONE); holder.tvDur.setVisibility(View.GONE); holder.tvSize.setText(st1); holder.imageView.setImageResource(getResources().getIdentifier("em_actionbar_camera_icon", "drawable", getActivity().getPackageName())); } else { holder.icon.setVisibility(View.VISIBLE); VideoEntityModel entty = mList.get(position - 1); holder.tvDur.setVisibility(View.VISIBLE); holder.tvDur.setText(DateUtils.toTime(entty.duration)); holder.tvSize.setText(TextFormater.getDataSize(entty.size)); holder.imageView.setImageResource(getResources().getIdentifier("em_empty_photo", "drawable", getActivity().getPackageName())); mImageResizer.loadImage(entty.filePath, holder.imageView); } return convertView; // END_INCLUDE(load_gridview_item) } /** * Sets the item height. Useful for when we know the column width so the * height can be set to match. * * @param height */ public void setItemHeight(int height) { if (height == mItemHeight) { return; } mItemHeight = height; mImageViewLayoutParams = new RelativeLayout.LayoutParams( LayoutParams.MATCH_PARENT, mItemHeight); mImageResizer.setImageSize(height); notifyDataSetChanged(); } class ViewHolder { RecyclingImageView imageView; ImageView icon; TextView tvDur; TextView tvSize; } } private void getVideoFile() { ContentResolver mContentResolver = getActivity().getContentResolver(); Cursor cursor = mContentResolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Video.DEFAULT_SORT_ORDER); if (cursor != null && cursor.moveToFirst()) { do { // ID:MediaStore.Audio.Media._ID int id = cursor.getInt(cursor .getColumnIndexOrThrow(MediaStore.Video.Media._ID)); // title:MediaStore.Audio.Media.TITLE String title = cursor.getString(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.TITLE)); // path:MediaStore.Audio.Media.DATA String url = cursor.getString(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.DATA)); // duration:MediaStore.Audio.Media.DURATION int duration = cursor .getInt(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)); // 大小:MediaStore.Audio.Media.SIZE int size = (int) cursor.getLong(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.SIZE)); VideoEntityModel entty = new VideoEntityModel(); entty.ID = id; entty.title = title; entty.filePath = url; entty.duration = duration; entty.size = size; mList.add(entty); } while (cursor.moveToNext()); } if (cursor != null) { cursor.close(); cursor = null; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { if (requestCode == 100) { Uri uri = data.getParcelableExtra("uri"); String[] projects = new String[]{MediaStore.Video.Media.DATA, MediaStore.Video.Media.DURATION}; Cursor cursor = getActivity().getContentResolver().query( uri, projects, null, null, null); int duration = 0; String filePath = null; if (cursor.moveToFirst()) { // path:MediaStore.Audio.Media.DATA filePath = cursor.getString(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.DATA)); // duration:MediaStore.Audio.Media.DURATION duration = cursor .getInt(cursor .getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)); EMLog.d(TAG, "duration:" + duration); } if (cursor != null) { cursor.close(); cursor = null; } getActivity().setResult(Activity.RESULT_OK, getActivity().getIntent().putExtra("path", filePath).putExtra("dur", duration)); getActivity().finish(); } } } }
gocodecamp/cordova-plugin-easemob
src/android/fragment/ImageGridFragment.java
Java
mit
16,874
package biz.pavonis.golservice.api.exception; public class PatternDoesNotFitException extends RuntimeException { private static final long serialVersionUID = -1801131706265452410L; public PatternDoesNotFitException(String arg0, Throwable arg1) { super(arg0, arg1); } }
adam-arold/game-of-life-as-service
src/main/java/biz/pavonis/golservice/api/exception/PatternDoesNotFitException.java
Java
mit
293
package vezzoni.jsf.spring.services.impl; import vezzoni.jsf.spring.services.GreetingsService; import org.springframework.stereotype.Service; @Service(value=GreetingsService.COMP_NAME) public class GreetingsServiceImpl implements GreetingsService { @Override public String sayHello() { return "hi there!"; } }
vezzoni/jsf-spring
src/main/java/vezzoni/jsf/spring/services/impl/GreetingsServiceImpl.java
Java
mit
334
package org.railwaystations.api.writer; import org.junit.jupiter.api.Test; import javax.ws.rs.WebApplicationException; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; public class PhotographersTxtWriterTest { @Test public void test() throws WebApplicationException, IOException { final Map<String, Long> photographers = new HashMap<>(); photographers.put("@foo", 10L); photographers.put("@bar", 5L); final PhotographersTxtWriter writer = new PhotographersTxtWriter(); final ByteArrayOutputStream entityStream = new ByteArrayOutputStream(); writer.writeTo(photographers, null, null, null, null, null, entityStream); final String txt = entityStream.toString("UTF-8"); final String[] lines = txt.split("\n"); assertThat(lines[0], is("count\tphotographer")); assertThat(lines[1], is("10\t@foo")); assertThat(lines[2], is("5\t@bar")); } }
pstorch/bahnhoefe.gpx
src/test/java/org/railwaystations/api/writer/PhotographersTxtWriterTest.java
Java
mit
1,105
package me.android.dochub.activities; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import me.android.dochub.R; import me.android.dochub.adapter.DocListAdapter; import me.android.dochub.app.AppController; import me.android.dochub.models.DocItem; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.android.volley.Cache; import com.android.volley.Cache.Entry; import com.android.volley.Request.Method; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.JsonObjectRequest; public class DocList extends Activity implements SwipeRefreshLayout.OnRefreshListener{ private static final String TAG = DocList.class.getSimpleName(); private SwipeRefreshLayout mSwipeLayout; private ListView listView; private DocListAdapter listAdapter; private List<DocItem> docItems; private String URL_DOC = "https://dhub.herokuapp.com/docs.json"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.doc_list); listView = (ListView) findViewById(R.id.my_list); docItems = new ArrayList<DocItem>(); listAdapter = new DocListAdapter(this, docItems); listView.setAdapter(listAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent i = new Intent(listView.getContext(), Reader.class); i.putExtra("url", docItems.get(position).getFilepicker_url()); startActivity(i); } }); mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container); mSwipeLayout.setOnRefreshListener(this); mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); // We first check for cached request Cache cache = AppController.getInstance().getRequestQueue().getCache(); Entry entry_doc = cache.get(URL_DOC); if (entry_doc != null){ // fetch the data from cache try { String data_doc = new String(entry_doc.data, "UTF-8"); try { parseJsonDoc(new JSONObject(data_doc)); } catch (JSONException e) { e.printStackTrace(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else{ refetch(); } } /** * Parsing json reponse and passing the data to doc view list adapter * */ private void parseJsonDoc(JSONObject response) { try { JSONArray docArray = response.getJSONArray("docs"); for (int i = 0; i < docArray.length(); i++) { JSONObject docObj = (JSONObject) docArray.get(i); DocItem item = new DocItem(); item.setId(docObj.getInt("id")); item.setTitle(docObj.getString("title")); item.setDescription(docObj.getString("description")); item.setLicense(docObj.getString("license")); item.setCreated_at(docObj.getString("created_at")); // url might be null sometimes String url = docObj.isNull("filepicker_url") ? null : docObj .getString("filepicker_url"); item.setFilepicker_url(url); //Image url might be null sometimes String image = docObj.isNull("filepicker_url") ? null : docObj .getString("filepicker_url") + "/convert?h=299&w=299"; item.setImage(image); docItems.add(item); } // notify data changes to list adapater listAdapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } } private void refetch() { final int no_before = docItems.size(); Log.d("no1", (String.valueOf(no_before))); // making fresh volley request and getting json JsonObjectRequest jsonReq_doc = new JsonObjectRequest(Method.GET, URL_DOC, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { VolleyLog.d(TAG, "Response: " + response.toString()); if (response != null) { docItems.clear(); parseJsonDoc(response); int no_after = docItems.size(); Log.d("no2", (String.valueOf(no_after))); Context context = getApplicationContext(); CharSequence text = (no_after-no_before)+" feeds updated!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); } }); // Adding request to volley request queue AppController.getInstance().addToRequestQueue(jsonReq_doc); } public void onRefresh() { new android.os.Handler().postDelayed(new Runnable() { @Override public void run() { mSwipeLayout.setRefreshing(false); refetch(); } }, 2000); } /* private class AsyncCaller extends AsyncTask<Void, Void, Void> { ProgressDialog pdLoading = new ProgressDialog(DocList.this); @Override protected void onPreExecute() { super.onPreExecute(); //this method will be running on UI thread // pdLoading.setMessage("Loading..."); // pdLoading.show(); } @Override protected Void doInBackground(Void... params) { //this method will be running on background thread so don't update UI from here //do your long running http tasks here,you don't want to pass argument and u can access the parent class' variable url over here // We first check for cached request return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); refetch(); recreate(); //this method will be running on UI thread pdLoading.dismiss(); } }*/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } public void exit(MenuItem item) { finish(); } }
Captain1/DocHub_Android
app/src/main/java/me/android/dochub/activities/DocList.java
Java
mit
7,808
package de.lathspell.test.ws.soap; public class TDO { private String name; @Override public String toString() { return name; } public TDO(String name) { this.name = name; } public TDO() { } }
lathspell/java_test
java_test_soap/src/main/java/de/lathspell/test/ws/soap/TDO.java
Java
cc0-1.0
246
package dbaApp; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.FlowLayout; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JCheckBox; import javax.swing.JButton; import javax.swing.UIManager; import java.awt.Window.Type; import javax.swing.JPasswordField; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.util.Scanner; public class LoginDisplay extends JFrame { private JPanel contentPane; private JTextField hostTextField; private JTextField sidTextField; private JTextField usernameTextField; private JPasswordField passwordField; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { LoginDisplay frame = new LoginDisplay(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public LoginDisplay() { setResizable(false); try { //Makes Gui look like a windows application UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } setTitle("Login"); setType(Type.UTILITY); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 250, 265); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); JLabel lblNewLabel = new JLabel("Host Address"); contentPane.add(lblNewLabel); hostTextField = new JTextField(); contentPane.add(hostTextField); hostTextField.setColumns(25); JLabel lblNewLabel_1 = new JLabel("SID "); contentPane.add(lblNewLabel_1); sidTextField = new JTextField(); contentPane.add(sidTextField); sidTextField.setColumns(25); JLabel lblNewLabel_2 = new JLabel("Username"); contentPane.add(lblNewLabel_2); usernameTextField = new JTextField(); contentPane.add(usernameTextField); usernameTextField.setColumns(25); JLabel lblNewLabel_3 = new JLabel("Password"); contentPane.add(lblNewLabel_3); passwordField = new JPasswordField(); passwordField.setColumns(25); contentPane.add(passwordField); final JCheckBox chckbxRememberInfo = new JCheckBox("Remember Info"); contentPane.add(chckbxRememberInfo); JButton btnLogin = new JButton("Login"); final JFrame f = this; btnLogin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DBConnector db = new DBConnector("jdbc:oracle:thin:@" + hostTextField.getText() +":1521:" + sidTextField.getText(), usernameTextField.getText(), new String(passwordField.getPassword())); if(db.connect()) { try { File infoFile = new File("login.prop"); PrintWriter p = new PrintWriter(infoFile); if(chckbxRememberInfo.isSelected()) { p.write("1\n" + hostTextField.getText() + "\n" + sidTextField.getText() + "\n" + usernameTextField.getText() + "\n" + new String(passwordField.getPassword())); } else { p.write("0"); } p.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } new TableDisplay(db).setVisible(true); f.dispose(); } } }); contentPane.add(btnLogin); JButton btnExit = new JButton("Exit"); btnExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f.dispose(); } }); contentPane.add(btnExit); try { File infoFile = new File("login.prop"); Scanner s = new Scanner(infoFile); if(s.nextLine().equals("1")) { hostTextField.setText(s.nextLine()); sidTextField.setText(s.nextLine()); usernameTextField.setText(s.nextLine()); passwordField.setText(s.nextLine()); chckbxRememberInfo.setSelected(true); } } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }
EpicNameBro/TeamBlueVanier
JAVA/Oracle/SRC/TESTCODE/dbaApp/src/dbaApp/LoginDisplay.java
Java
cc0-1.0
4,425
package com.ptsmods.morecommands.commands.client; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.ptsmods.morecommands.clientoption.BooleanClientOption; import com.ptsmods.morecommands.miscellaneous.ClientCommand; import com.ptsmods.morecommands.clientoption.ClientOptions; import net.minecraft.client.network.ClientCommandSource; public class ToggleOptionCommand extends ClientCommand { @Override public void cRegister(CommandDispatcher<ClientCommandSource> dispatcher) { LiteralArgumentBuilder<ClientCommandSource> toggleoption = cLiteral("toggleoption"); ClientOptions.getMappedOptions().entrySet().stream() .filter(entry -> entry.getValue() instanceof BooleanClientOption) .forEach(entry -> toggleoption.then(cLiteral(entry.getKey()).executes(ctx -> { BooleanClientOption option = (BooleanClientOption) entry.getValue(); boolean b = !option.getValueRaw(); option.setValue(b); sendMsg("The option " + SF + option + DF + " has been set to " + formatFromBool(b, "TRUE", "FALSE") + DF + "."); return 1; }))); dispatcher.register(toggleoption); } }
PlanetTeamSpeakk/MoreCommands
src/main/java/com/ptsmods/morecommands/commands/client/ToggleOptionCommand.java
Java
cc0-1.0
1,168
/* * Courtney Holsinger * 11/22/2015 * Chapter 11 * 11.18 */ package catching_exceptions_2; //import IO Exception import java.io.IOException; public class TestExceptions { public static void main( String[] args ){ //---------------------------------------------------------Throwing Exception_A try { //create new Exception_A object to throw throw new Exception_A ( "Exception A"); } //end try block catch( Exception exception ){ exception.printStackTrace(); } //end catching using Exception //---------------------------------------------------------Throwing Exception_B try { //create new exception b object to throw throw new Exception_B( "Exception B" ); } //end try block catch( Exception exception ) { exception.printStackTrace(); } //end catch using Exception_A //---------------------------------------------------------Throwing NullPointerException try { //create new NullPointerException throw new NullPointerException( "Null Pointer Exception" ); } //end try block catch( Exception exception ) { System.out.println( "Throwing Null Pointer Exception.\n" ); exception.printStackTrace(); } //end catch block //---------------------------------------------------------Throwing IOException try { //create new IO Exception throw new IOException( "IO Exception" ); } //end try block catch( Exception exception ) { System.out.println( "Throwing IO Exception.\n" ); exception.printStackTrace(); }//end catch block } //end main method } //end TestExceptions class
cholsi20/Java-Programming
JavaFiles/11.18/src/catching_exceptions_2/TestExceptions.java
Java
cc0-1.0
1,598
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package quickstore.ejb.entity; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.UniqueConstraint; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author root */ @Entity @Table(name = "DATOS_USUARIO",uniqueConstraints={@UniqueConstraint(columnNames = {"email"})}) @XmlRootElement @NamedQueries({ @NamedQuery(name = "DatosUsuario.findAll", query = "SELECT p FROM DatosUsuario p")}) public class DatosUsuario implements Serializable { @Size(max = 255) @Column(name = "IDIOMA") private String idioma; private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID_DATOS_USUARIO") private Integer idDatosUsuario; @Size(max = 20) @Column(name = "RECIBIR_MAIL") private String recibirMail; // @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation @Size(max = 255) @Column(name = "EMAIL", unique = true) private String email; @Size(max = 255) @Column(name = "APELLIDOS") private String apellidos; @Column(name = "FECHA_NACIMIENTO") @Temporal(TemporalType.DATE) private Date fechaNacimiento; @Size(max = 255) @Column(name = "SEXO") private String sexo; @Size(max = 255) @Column(name = "NOMBRES") private String nombres; @OneToMany(mappedBy = "idDatosUsuario") private List<Usuario> usuarioList; @JoinColumn(name = "ID_PAIS", referencedColumnName = "ID_SUB_TIPO") @ManyToOne private SubTipo idPais; @JoinColumn(name = "ID_ACTIVIDAD", referencedColumnName = "ID_SUB_TIPO") @ManyToOne private SubTipo idActividad; @Column(name = "FECHA_REGISTRO") @Temporal(TemporalType.DATE) private Date fechaRegistro; @Column(name = "FECHA_PROCESO") @Temporal(TemporalType.DATE) private Date fechaProceso; @Size(max = 255) @Column(name = "PROFESION") private String profesion; public DatosUsuario() { } public Integer getIdDatosUsuario() { return idDatosUsuario; } public void setIdDatosUsuario(Integer idDatosUsuario) { this.idDatosUsuario = idDatosUsuario; } public String getRecibirMail() { return recibirMail; } public void setRecibirMail(String recibirMail) { this.recibirMail = recibirMail; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getApellidos() { return apellidos; } public void setApellidos(String apellidos) { this.apellidos = apellidos; } public Date getFechaNacimiento() { return fechaNacimiento; } public void setFechaNacimiento(Date fechaNacimiento) { this.fechaNacimiento = fechaNacimiento; } public String getSexo() { return sexo; } public void setSexo(String sexo) { this.sexo = sexo; } public String getNombres() { return nombres; } public void setNombres(String nombres) { this.nombres = nombres; } public List<Usuario> getUsuarioList() { return usuarioList; } public void setUsuarioList(List<Usuario> usuarioList) { this.usuarioList = usuarioList; } public SubTipo getIdPais() { return idPais; } public void setIdPais(SubTipo idPais) { this.idPais = idPais; } public SubTipo getIdActividad() { return idActividad; } public void setIdActividad(SubTipo idActividad) { this.idActividad = idActividad; } public Date getFechaRegistro() { return fechaRegistro; } public void setFechaRegistro(Date fechaRegistro) { this.fechaRegistro = fechaRegistro; } public Date getFechaProceso() { return fechaProceso; } public void setFechaProceso(Date fechaProceso) { this.fechaProceso = fechaProceso; } public String getProfesion() { return profesion; } public void setProfesion(String profesion) { this.profesion = profesion; } @Override public int hashCode() { int hash = 0; hash += (idDatosUsuario != null ? idDatosUsuario.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof DatosUsuario)) { return false; } DatosUsuario other = (DatosUsuario) object; if ((this.idDatosUsuario == null && other.idDatosUsuario != null) || (this.idDatosUsuario != null && !this.idDatosUsuario.equals(other.idDatosUsuario))) { return false; } return true; } @Override public String toString() { return "dominio.plapy.DatosUsuario[ idDatosUsuario=" + idDatosUsuario + " ]"; } public String getIdioma() { return idioma; } public void setIdioma(String idioma) { this.idioma = idioma; } }
ferremarce/USABILITY-ONLINESTORE
src/main/java/quickstore/ejb/entity/DatosUsuario.java
Java
cc0-1.0
6,016
package com.github.themetalone.pandemic.analysis.exception; /** * @author Steffen * */ public class HeaderException extends Exception { /** * The constructor. */ public HeaderException() { } /** * The constructor. * @param message */ public HeaderException(String message) { super(message); } /** * The constructor. * @param cause */ public HeaderException(Throwable cause) { super(cause); } /** * The constructor. * @param message * @param cause */ public HeaderException(String message, Throwable cause) { super(message, cause); } /** * The constructor. * @param message * @param cause * @param enableSuppression * @param writableStackTrace */ public HeaderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
themetalone/WS1617-Masterarbeit
Simulation/PS-Analysis/src/main/java/com/github/themetalone/pandemic/analysis/exception/HeaderException.java
Java
cc0-1.0
935
package com.elementalessence.common.proxy; import com.elementalessence.common.References; import com.elementalessence.common.blocks.tile.machine.TECalefactor1; import com.elementalessence.common.blocks.tile.machine.TECalefactor2; import com.elementalessence.common.blocks.tile.machine.TECalefactor3; import com.elementalessence.common.blocks.tile.machine.TECalefactor4; import com.elementalessence.common.blocks.tile.machine.TECalefactor5; import com.elementalessence.common.blocks.tile.machine.TECalefactor6; import com.elementalessence.common.blocks.tile.machine.TECalefactor7; import com.elementalessence.common.blocks.tile.machine.TESkyForge; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.registry.GameRegistry; public class ServerProxy implements IEEProxy { @Override public void preInit(FMLPreInitializationEvent preEvent) { } @Override public void init(FMLInitializationEvent event) { } @Override public void postInit(FMLPostInitializationEvent postEvent) { } @Override public void registerRenderers() { } public void registerTileEntities() { GameRegistry.registerTileEntity(TESkyForge.class, References.MODID + "_skyforge"); GameRegistry.registerTileEntity(TECalefactor1.class, References.MODID + "_TECalefactor1"); GameRegistry.registerTileEntity(TECalefactor2.class, References.MODID + "_TECalefactor1"); GameRegistry.registerTileEntity(TECalefactor3.class, References.MODID + "_TECalefactor1"); GameRegistry.registerTileEntity(TECalefactor4.class, References.MODID + "_TECalefactor1"); GameRegistry.registerTileEntity(TECalefactor5.class, References.MODID + "_TECalefactor1"); GameRegistry.registerTileEntity(TECalefactor6.class, References.MODID + "_TECalefactor1"); GameRegistry.registerTileEntity(TECalefactor7.class, References.MODID + "_TECalefactor1"); } }
CuriousSkeptic/ElementalEssences
src/main/java/com/elementalessence/common/proxy/ServerProxy.java
Java
cc0-1.0
1,975
package org.junit.runner.manipulation; import java.util.Comparator; import org.junit.runner.Description; /** * A <code>Sorter</code> orders tests. In general you will not need * to use a <code>Sorter</code> directly. Instead, use {@link org.junit.runner.Request#sortWith(Comparator)}. * * @since 4.0 */ public class Sorter implements Comparator<Description> { /** * NULL is a <code>Sorter</code> that leaves elements in an undefined order */ public static Sorter NULL = new Sorter(new Comparator<Description>() { public int compare(Description o1, Description o2) { return 0; } }); private final Comparator<Description> fComparator; /** * Creates a <code>Sorter</code> that uses <code>comparator</code> * to sort tests * * @param comparator the {@link Comparator} to use when sorting tests */ public Sorter(Comparator<Description> comparator) { fComparator = comparator; } /** * Sorts the test in <code>runner</code> using <code>comparator</code> */ public void apply(Object object) { if (object instanceof Sortable) { Sortable sortable = (Sortable) object; sortable.sort(this); } } public int compare(Description o1, Description o2) { return fComparator.compare(o1, o2); } }
MattiasBuelens/junit
src/main/java/org/junit/runner/manipulation/Sorter.java
Java
epl-1.0
1,411
/******************************************************************************* * Copyright (C) 2007, Dave Watson <[email protected]> * Copyright (C) 2007, Jing Xue <[email protected]> * Copyright (C) 2007, Robin Rosenberg <[email protected]> * Copyright (C) 2008, Robin Rosenberg <[email protected]> * Copyright (C) 2008, Shawn O. Pearce <[email protected]> * Copyright (C) 2010, Stefan Lay <[email protected]> * Copyright (C) 2011, Jens Baumgart <[email protected]> * * 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.eclipse.egit.ui.internal.commit; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceVisitor; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.egit.core.EclipseGitProgressTransformer; import org.eclipse.egit.core.IteratorService; import org.eclipse.egit.core.op.CommitOperation; import org.eclipse.egit.core.project.RepositoryMapping; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.JobFamilies; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.internal.decorators.GitLightweightDecorator; import org.eclipse.egit.ui.internal.dialogs.BasicConfigurationDialog; import org.eclipse.egit.ui.internal.dialogs.CommitDialog; import org.eclipse.egit.ui.internal.trace.GitTraceLocation; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.IndexDiff; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.RepositoryState; import org.eclipse.jgit.lib.UserConfig; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; /** * UI component for performing a commit */ public class CommitUI { private Map<Repository, IndexDiff> indexDiffs; private Set<IFile> notIndexed; private Set<IFile> indexChanges; private Set<IFile> notTracked; private Set<IFile> files; private RevCommit previousCommit; private boolean amendAllowed; private boolean amending; private Shell shell; private Repository[] repos; private IResource[] selectedResources; /** * Constructs a CommitUI object * @param shell * Shell to use for UI interaction. Must not be null. * @param repos * Repositories to commit. Must not be null * @param selectedResources * Resources selected by the user. A file is preselected in the * commit dialog if the file is contained in selectedResources or * if selectedResources contains a resource that is parent of the * file. selectedResources must not be null. */ public CommitUI(Shell shell, Repository[] repos, IResource[] selectedResources) { this.shell = shell; this.repos = new Repository[repos.length]; // keep our own copy System.arraycopy(repos, 0, this.repos, 0, repos.length); this.selectedResources = new IResource[selectedResources.length]; // keep our own copy System.arraycopy(selectedResources, 0, this.selectedResources, 0, selectedResources.length); } /** * Performs a commit */ public void commit() { // let's see if there is any dirty editor around and // ask the user if they want to save or abort if (!PlatformUI.getWorkbench().saveAllEditors(true)) { return; } BasicConfigurationDialog.show(); resetState(); final IProject[] projects = getProjectsOfRepositories(); try { PlatformUI.getWorkbench().getProgressService().busyCursorWhile(new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { buildIndexHeadDiffList(projects, monitor); } catch (IOException e) { throw new InvocationTargetException(e); } } }); } catch (InvocationTargetException e) { Activator.handleError(UIText.CommitAction_errorComputingDiffs, e.getCause(), true); return; } catch (InterruptedException e) { return; } Repository repository = null; Repository mergeRepository = null; amendAllowed = repos.length == 1; boolean isMergedResolved = false; for (Repository repo : repos) { repository = repo; RepositoryState state = repo.getRepositoryState(); if (!state.canCommit()) { MessageDialog.openError(shell, UIText.CommitAction_cannotCommit, NLS.bind( UIText.CommitAction_repositoryState, state .getDescription())); return; } else if (state.equals(RepositoryState.MERGING_RESOLVED)) { isMergedResolved = true; mergeRepository = repo; } } if (amendAllowed) loadPreviousCommit(repos[0]); if (files.isEmpty()) { if (amendAllowed && previousCommit != null) { boolean result = MessageDialog.openQuestion(shell, UIText.CommitAction_noFilesToCommit, UIText.CommitAction_amendCommit); if (!result) return; amending = true; } else { MessageDialog.openWarning(shell, UIText.CommitAction_noFilesToCommit, UIText.CommitAction_amendNotPossible); return; } } String author = null; String committer = null; if (repository != null) { final UserConfig config = repository.getConfig().get(UserConfig.KEY); author = config.getAuthorName(); final String authorEmail = config.getAuthorEmail(); author = author + " <" + authorEmail + ">"; //$NON-NLS-1$ //$NON-NLS-2$ committer = config.getCommitterName(); final String committerEmail = config.getCommitterEmail(); committer = committer + " <" + committerEmail + ">"; //$NON-NLS-1$ //$NON-NLS-2$ } CommitDialog commitDialog = new CommitDialog(shell); commitDialog.setAmending(amending); commitDialog.setAmendAllowed(amendAllowed); commitDialog.setFiles(files, indexDiffs); commitDialog.setPreselectedFiles(getSelectedFiles()); commitDialog.setAuthor(author); commitDialog.setCommitter(committer); commitDialog.setAllowToChangeSelection(!isMergedResolved); if (previousCommit != null) { commitDialog.setPreviousCommitMessage(previousCommit.getFullMessage()); PersonIdent previousAuthor = previousCommit.getAuthorIdent(); commitDialog.setPreviousAuthor(previousAuthor.getName() + " <" + previousAuthor.getEmailAddress() + ">"); //$NON-NLS-1$ //$NON-NLS-2$ } if (isMergedResolved) { commitDialog.setCommitMessage(getMergeResolveMessage(mergeRepository)); } if (commitDialog.open() != IDialogConstants.OK_ID) return; final CommitOperation commitOperation = new CommitOperation( commitDialog.getSelectedFiles(), notIndexed, notTracked, commitDialog.getAuthor(), commitDialog.getCommitter(), commitDialog.getCommitMessage()); if (commitDialog.isAmending()) { commitOperation.setAmending(true); commitOperation.setRepos(repos); } commitOperation.setComputeChangeId(commitDialog.getCreateChangeId()); commitOperation.setCommitAll(isMergedResolved); if (isMergedResolved) commitOperation.setRepos(repos); String jobname = UIText.CommitAction_CommittingChanges; Job job = new Job(jobname) { @Override protected IStatus run(IProgressMonitor monitor) { try { commitOperation.execute(monitor); for (Repository repo : repos) { RepositoryMapping mapping = RepositoryMapping .findRepositoryMapping(repo); if (mapping != null) mapping.fireRepositoryChanged(); } } catch (CoreException e) { return Activator.createErrorStatus( UIText.CommitAction_CommittingFailed, e); } finally { GitLightweightDecorator.refresh(); } return Status.OK_STATUS; } @Override public boolean belongsTo(Object family) { if (family.equals(JobFamilies.COMMIT)) return true; return super.belongsTo(family); } }; job.setUser(true); job.schedule(); return; } private IProject[] getProjectsOfRepositories() { Set<IProject> ret = new HashSet<IProject>(); final IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() .getProjects(); for (IProject project : projects) { RepositoryMapping mapping = RepositoryMapping.getMapping(project); for (Repository repository : repos) { if (mapping != null && mapping.getRepository() == repository) { ret.add(project); break; } } } return ret.toArray(new IProject[ret.size()]); } private void resetState() { files = new LinkedHashSet<IFile>(); notIndexed = new LinkedHashSet<IFile>(); indexChanges = new LinkedHashSet<IFile>(); notTracked = new LinkedHashSet<IFile>(); amending = false; previousCommit = null; indexDiffs = new HashMap<Repository, IndexDiff>(); } /** * Retrieves a collection of files that may be committed based on the user's * selection when they performed the commit action. That is, even if the * user only selected one folder when the action was performed, if the * folder contains any files that could be committed, they will be returned. * * @return a collection of files that is eligible to be committed based on * the user's selection */ private Set<IFile> getSelectedFiles() { Set<IFile> preselectionCandidates = new LinkedHashSet<IFile>(); // iterate through all the files that may be committed for (IFile file : files) { for (IResource resource : selectedResources) { // if any selected resource contains the file, add it as a // preselection candidate if (resource.contains(file)) { preselectionCandidates.add(file); break; } } } return preselectionCandidates; } private void loadPreviousCommit(Repository repo) { try { ObjectId parentId = repo.resolve(Constants.HEAD); if (parentId != null) previousCommit = new RevWalk(repo).parseCommit(parentId); } catch (IOException e) { Activator.handleError(UIText.CommitAction_errorRetrievingCommit, e, true); } } private void buildIndexHeadDiffList(IProject[] selectedProjects, IProgressMonitor monitor) throws IOException, OperationCanceledException { HashMap<Repository, HashSet<IProject>> repositories = new HashMap<Repository, HashSet<IProject>>(); for (IProject project : selectedProjects) { RepositoryMapping repositoryMapping = RepositoryMapping .getMapping(project); assert repositoryMapping != null; Repository repository = repositoryMapping.getRepository(); HashSet<IProject> projects = repositories.get(repository); if (projects == null) { projects = new HashSet<IProject>(); repositories.put(repository, projects); } projects.add(project); } monitor.beginTask(UIText.CommitActionHandler_calculatingChanges, repositories.size() * 1000); for (Map.Entry<Repository, HashSet<IProject>> entry : repositories .entrySet()) { Repository repository = entry.getKey(); EclipseGitProgressTransformer jgitMonitor = new EclipseGitProgressTransformer(monitor); HashSet<IProject> projects = entry.getValue(); CountingVisitor counter = new CountingVisitor(); for (IProject p : projects) { try { p.accept(counter); } catch (CoreException e) { // ignore } } IndexDiff indexDiff = new IndexDiff(repository, Constants.HEAD, IteratorService.createInitialIterator(repository)); indexDiff.diff(jgitMonitor, counter.count, 0, NLS.bind( UIText.CommitActionHandler_repository, repository .getDirectory().getPath())); indexDiffs.put(repository, indexDiff); for (IProject project : projects) { includeList(project, indexDiff.getAdded(), indexChanges); includeList(project, indexDiff.getChanged(), indexChanges); includeList(project, indexDiff.getRemoved(), indexChanges); includeList(project, indexDiff.getMissing(), notIndexed); includeList(project, indexDiff.getModified(), notIndexed); includeList(project, indexDiff.getUntracked(), notTracked); } if (monitor.isCanceled()) throw new OperationCanceledException(); } monitor.done(); } static class CountingVisitor implements IResourceVisitor { int count; public boolean visit(IResource resource) throws CoreException { count++; return true; } } private void includeList(IProject project, Set<String> added, Set<IFile> category) { String repoRelativePath = RepositoryMapping.getMapping(project) .getRepoRelativePath(project); if (repoRelativePath.length() > 0) { repoRelativePath += "/"; //$NON-NLS-1$ } for (String filename : added) { try { if (!filename.startsWith(repoRelativePath)) continue; String projectRelativePath = filename .substring(repoRelativePath.length()); IFile member = project.getFile(projectRelativePath); if (!files.contains(member)) files.add(member); category.add(member); } catch (Exception e) { if (GitTraceLocation.UI.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.UI.getLocation(), e.getMessage(), e); continue; } // if it's outside the workspace, bad things happen } } private String getMergeResolveMessage(Repository mergeRepository) { File mergeMsg = new File(mergeRepository.getDirectory(), Constants.MERGE_MSG); FileReader reader; try { reader = new FileReader(mergeMsg); BufferedReader br = new BufferedReader(reader); try { StringBuilder message = new StringBuilder(); String s; String newLine = newLine(); while ((s = br.readLine()) != null) { message.append(s).append(newLine); } return message.toString(); } catch (IOException e) { MessageDialog.openError(shell, UIText.CommitAction_MergeHeadErrorTitle, UIText.CommitAction_ErrorReadingMergeMsg); throw new IllegalStateException(e); } finally { try { br.close(); } catch (IOException e) { // Empty } } } catch (FileNotFoundException e) { MessageDialog.openError(shell, UIText.CommitAction_MergeHeadErrorTitle, UIText.CommitAction_MergeHeadErrorMessage); throw new IllegalStateException(e); } } private String newLine() { return System.getProperty("line.separator"); //$NON-NLS-1$ } }
rickard-von-essen/egit
org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/commit/CommitUI.java
Java
epl-1.0
15,278
/* * This file is part of the Jikes RVM project (http://jikesrvm.org). * * This file is licensed to You under the Common Public License (CPL); * You may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.opensource.org/licenses/cpl1.0.php * * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. */ package org.mmtk.plan.semispace; import org.mmtk.policy.CopySpace; import org.mmtk.policy.Space; import org.mmtk.plan.*; import org.mmtk.utility.heap.VMRequest; import org.vmmagic.pragma.*; import org.vmmagic.unboxed.*; /** * This class implements a simple semi-space collector. See the Jones * & Lins GC book, section 2.2 for an overview of the basic * algorithm. This implementation also includes a large object space * (LOS), and an uncollected "immortal" space.<p> * * All plans make a clear distinction between <i>global</i> and * <i>thread-local</i> activities. Global activities must be * synchronized, whereas no synchronization is required for * thread-local activities. Instances of Plan map 1:1 to "kernel * threads" (aka CPUs or in Jikes RVM, VM_Processors). Thus instance * methods allow fast, unsychronized access to Plan utilities such as * allocation and collection. Each instance rests on static resources * (such as memory and virtual memory resources) which are "global" * and therefore "static" members of Plan. This mapping of threads to * instances is crucial to understanding the correctness and * performance proprties of this plan. */ @Uninterruptible public class SS extends StopTheWorld { /** Fraction of available virtual memory available to each semispace */ private static final float SEMISPACE_VIRT_MEM_FRAC = 0.30f; /**************************************************************************** * * Class variables */ /** True if allocating into the "higher" semispace */ public static boolean hi = false; // True if allocing to "higher" semispace /** One of the two semi spaces that alternate roles at each collection */ public static final CopySpace copySpace0 = new CopySpace("ss0", DEFAULT_POLL_FREQUENCY, false, VMRequest.create()); public static final int SS0 = copySpace0.getDescriptor(); /** One of the two semi spaces that alternate roles at each collection */ public static final CopySpace copySpace1 = new CopySpace("ss1", DEFAULT_POLL_FREQUENCY, true, VMRequest.create()); public static final int SS1 = copySpace1.getDescriptor(); public final Trace ssTrace; /**************************************************************************** * * Initialization */ /** * Class variables */ public static final int ALLOC_SS = Plan.ALLOC_DEFAULT; public static final int SCAN_SS = 0; /** * Constructor */ public SS() { ssTrace = new Trace(metaDataSpace); } /** * @return The to space for the current collection. */ @Inline public static CopySpace toSpace() { return hi ? copySpace1 : copySpace0; } /** * @return The from space for the current collection. */ @Inline public static CopySpace fromSpace() { return hi ? copySpace0 : copySpace1; } /**************************************************************************** * * Collection */ /** * Perform a (global) collection phase. * * @param phaseId Collection phase */ @Inline public void collectionPhase(short phaseId) { if (phaseId == SS.PREPARE) { hi = !hi; // flip the semi-spaces // prepare each of the collected regions copySpace0.prepare(hi); copySpace1.prepare(!hi); ssTrace.prepare(); super.collectionPhase(phaseId); return; } if (phaseId == CLOSURE) { ssTrace.prepare(); return; } if (phaseId == SS.RELEASE) { // release the collected region fromSpace().release(); super.collectionPhase(phaseId); return; } super.collectionPhase(phaseId); } /**************************************************************************** * * Accounting */ /** * Return the number of pages reserved for copying. * * @return The number of pages reserved given the pending * allocation, including space reserved for copying. */ public final int getCollectionReserve() { // we must account for the number of pages required for copying, // which equals the number of semi-space pages reserved return toSpace().reservedPages() + super.getCollectionReserve(); } /** * Return the number of pages reserved for use given the pending * allocation. This is <i>exclusive of</i> space reserved for * copying. * * @return The number of pages reserved given the pending * allocation, excluding space reserved for copying. */ public int getPagesUsed() { return super.getPagesUsed() + toSpace().reservedPages(); } /** * Return the number of pages available for allocation, <i>assuming * all future allocation is to the semi-space</i>. * * @return The number of pages available for allocation, <i>assuming * all future allocation is to the semi-space</i>. */ public final int getPagesAvail() { return(super.getPagesAvail()) >> 1; } /** * Calculate the number of pages a collection is required to free to satisfy * outstanding allocation requests. * * @return the number of pages a collection is required to free to satisfy * outstanding allocation requests. */ public int getPagesRequired() { return super.getPagesRequired() + (toSpace().requiredPages() << 1); } /** * @see org.mmtk.plan.Plan#willNeverMove * * @param object Object in question * @return True if the object will never move */ @Override public boolean willNeverMove(ObjectReference object) { if (Space.isInSpace(SS0, object) || Space.isInSpace(SS1, object)) return false; return super.willNeverMove(object); } }
rmcilroy/HeraJVM
MMTk/src/org/mmtk/plan/semispace/SS.java
Java
epl-1.0
6,031
/** * 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.activemq.leveldb.replicated.dto; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; /** * @author <a href="http://hiramchirino.com">Hiram Chirino</a> */ @XmlRootElement(name="transfer_request") @XmlAccessorType(XmlAccessType.FIELD) @JsonIgnoreProperties(ignoreUnknown = true) public class WalAck { @XmlAttribute(name="position") public long position; }
Mark-Booth/daq-eclipse
uk.ac.diamond.org.apache.activemq/org/apache/activemq/leveldb/replicated/dto/WalAck.java
Java
epl-1.0
1,392
/*- ******************************************************************************* * Copyright (c) 2011, 2014 Diamond Light Source Ltd. * 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 * * Contributors: * Peter Chang - initial API and implementation and/or initial documentation *******************************************************************************/ package org.eclipse.dataset.internal.dense; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.dataset.DatasetException; import org.eclipse.dataset.IDataset; import org.eclipse.dataset.ILazyDataset; import org.eclipse.dataset.MetadataException; import org.eclipse.dataset.SliceND; import org.eclipse.dataset.dense.BroadcastIterator; import org.eclipse.dataset.dense.DTypeUtils; import org.eclipse.dataset.dense.Dataset; import org.eclipse.dataset.dense.DatasetFactory; import org.eclipse.dataset.dense.DatasetUtils; import org.eclipse.dataset.metadata.ErrorMetadata; import org.eclipse.dataset.metadata.ErrorMetadataImpl; import org.eclipse.dataset.metadata.IMetadata; import org.eclipse.dataset.metadata.MetadataType; import org.eclipse.dataset.metadata.Reshapeable; import org.eclipse.dataset.metadata.Sliceable; import org.eclipse.dataset.metadata.Transposable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Common base for both lazy and normal dataset implementations */ public abstract class LazyDatasetBase implements ILazyDataset, Serializable { protected static final Logger logger = LoggerFactory.getLogger(LazyDatasetBase.class); protected static boolean catchExceptions; static { /** * Boolean to set to true if running jython scripts that utilise ScisoftPy in IDE */ catchExceptions = Boolean.getBoolean("run.in.eclipse"); } protected String name = ""; /** * The shape or dimensions of the dataset */ protected int[] shape; protected Map<Class<? extends MetadataType>, List<MetadataType>> metadata = null; /** * @return type of dataset item */ abstract public int getDType(); @Override public Class<?> getElementClass() { return DTypeUtils.elementClass(getDType()); } @Override public LazyDatasetBase clone() { return null; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!getClass().equals(obj.getClass())) { return false; } LazyDatasetBase other = (LazyDatasetBase) obj; if (getDType() != other.getDType()) { return false; } if (getElementsPerItem() != other.getElementsPerItem()) { return false; } if (!Arrays.equals(shape, other.shape)) { return false; } return true; } @Override public int hashCode() { int hash = getDType() * 17 + getElementsPerItem(); int rank = shape.length; for (int i = 0; i < rank; i++) { hash = hash*17 + shape[i]; } return hash; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public int[] getShape() { return shape.clone(); } @Override public int getRank() { return shape.length; } @SuppressWarnings("unchecked") @Override public <T extends MetadataType> void setMetadata(T metadata) { if (metadata == null) return; List<T> ml = null; try { ml = (List<T>) getMetadata(metadata.getClass()); } catch (MetadataException e) { logger.error("Problem retrieving metadata of class {}: {}", metadata.getClass().getCanonicalName(), e); } if (ml == null) { addMetadata(metadata); } else { ml.clear(); ml.add(metadata); } } @Override public IMetadata getMetadata() { List<IMetadata> ml = null; try { ml = getMetadata(IMetadata.class); } catch (MetadataException e) { logger.error("Problem retrieving metadata of class {}: {}", IMetadata.class.getCanonicalName(), e); } return ml == null ? null : ml.get(0); } @Override public <T extends MetadataType> void addMetadata(T metadata) { if (metadata == null) return; if (this.metadata == null) { this.metadata = new HashMap<Class<? extends MetadataType>, List<MetadataType>>(); } Class<? extends MetadataType> clazz = findMetadataTypeSubInterfaces(metadata.getClass()); if (!this.metadata.containsKey(clazz)) { this.metadata.put(clazz, new ArrayList<MetadataType>()); } this.metadata.get(clazz).add(metadata); } /** * Dig down to interface (or class) that directly extends (or implements) MetadataType * @param clazz * @return sub-interface */ @SuppressWarnings("unchecked") static Class<? extends MetadataType> findMetadataTypeSubInterfaces(Class<? extends MetadataType> clazz) { Class<?> sclazz = clazz.getSuperclass(); if (sclazz != null && !sclazz.equals(Object.class)) // recurse up class hierarchy return findMetadataTypeSubInterfaces((Class<? extends MetadataType>) sclazz); for (Class<?> c : clazz.getInterfaces()) { if (c.equals(MetadataType.class)) return clazz; if (MetadataType.class.isAssignableFrom(c)) { return findMetadataTypeSubInterfaces((Class<? extends MetadataType>) c); } } assert false; // should not be able to get here!!! logger.error("Somehow the search for metadata type interface ended in a bad place"); return null; } @SuppressWarnings("unchecked") @Override public <T extends MetadataType> List<T> getMetadata(Class<T> clazz) throws MetadataException { if (metadata == null) return null; if (clazz == null) { List<T> all = new ArrayList<T>(); for (Class<? extends MetadataType> c : metadata.keySet()) { all.addAll((Collection<? extends T>) metadata.get(c)); } return all; } return (List<T>) metadata.get(findMetadataTypeSubInterfaces(clazz)); } @Override public <T extends MetadataType> void clearMetadata(Class<T> clazz) { if (metadata == null) return; if (clazz == null) { metadata.clear(); return; } List<MetadataType> list = metadata.get(findMetadataTypeSubInterfaces(clazz)); if( list != null) { list.clear(); } } protected Map<Class<? extends MetadataType>, List<MetadataType>> copyMetadata() { return copyMetadata(metadata); } protected static Map<Class<? extends MetadataType>, List<MetadataType>> copyMetadata(Map<Class<? extends MetadataType>, List<MetadataType>> metadata) { if (metadata == null) return null; HashMap<Class<? extends MetadataType>, List<MetadataType>> map = new HashMap<Class<? extends MetadataType>, List<MetadataType>>(); for (Class<? extends MetadataType> c : metadata.keySet()) { List<MetadataType> l = metadata.get(c); List<MetadataType> nl = new ArrayList<MetadataType>(l.size()); map.put(c, nl); for (MetadataType m : l) { nl.add(m.clone()); } } return map; } interface MetadatasetAnnotationOperation { Object processField(Field f, Object o); Class<? extends Annotation> getAnnClass(); /** * @param axis * @return number of dimensions to insert or remove */ int change(int axis); /** * * @return rank or -1 to match */ int getNewRank(); ILazyDataset run(ILazyDataset lz); } class MdsSlice implements MetadatasetAnnotationOperation { private boolean asView; private int[] start; private int[] stop; private int[] step; private int[] oShape; private long oSize; public MdsSlice(boolean asView, final int[] start, final int[] stop, final int[] step, final int[] oShape) { this.asView = asView; this.start = start; this.stop = stop; this.step = step; this.oShape = oShape; oSize = DatasetUtils.calculateLongSize(oShape); } @Override public Object processField(Field field, Object o) { return o; } @Override public Class<? extends Annotation> getAnnClass() { return Sliceable.class; } @Override public int change(int axis) { return 0; } @Override public int getNewRank() { return -1; } @Override public ILazyDataset run(ILazyDataset lz) { int rank = lz.getRank(); if (start.length != rank) throw new IllegalArgumentException("Slice dimensions do not match dataset!"); int[] shape = lz.getShape(); int[] stt; int[] stp; int[] ste; if (lz.getSize() == oSize) { stt = start; stp = stop; ste = step; } else { stt = start.clone(); stp = stop.clone(); ste = step.clone(); for (int i = 0; i < rank; i++) { if (shape[i] == oShape[i]) continue; if (shape[i] == 1) { stt[i] = 0; stp[i] = 1; ste[1] = 1; } else { throw new IllegalArgumentException("Sliceable dataset has invalid size!"); } } } if (asView || (lz instanceof IDataset)) return lz.getSliceView(stt, stp, ste); return lz.getSlice(stt, stp, ste); } } class MdsReshape implements MetadatasetAnnotationOperation { private boolean matchRank; private int[] oldShape; private int[] newShape; boolean onesOnly; int[] differences; /* * if only ones then record differences (insertions and deletions) * * if shape changing, find broadcasted dimensions and disallow * merging that include those dimensions */ public MdsReshape(final int[] oldShape, final int[] newShape) { this.oldShape = oldShape; this.newShape = newShape; differences = null; } @Override public Object processField(Field field, Object o) { Annotation a = field.getAnnotation(getAnnClass()); if (a instanceof Reshapeable) { matchRank = ((Reshapeable) a).matchRank(); } return o; } @Override public Class<? extends Annotation> getAnnClass() { return Reshapeable.class; } @Override public int change(int axis) { if (matchRank) { if (differences == null) init(); if (onesOnly) { return differences[axis]; } throw new UnsupportedOperationException("TODO support other shape operations"); } return 0; } @Override public int getNewRank() { return matchRank ? newShape.length : -1; } private void init() { int or = oldShape.length - 1; int nr = newShape.length - 1; if (or < 0 || nr < 0) { // zero-rank shapes onesOnly = true; differences = new int[1]; differences[0] = or < 0 ? nr + 1 : or + 1; return; } int ob = 0; int nb = 0; onesOnly = true; do { while (oldShape[ob] == 1 && ob < or) { ob++; // next non-unit dimension } while (newShape[nb] == 1 && nb < nr) { nb++; } if (oldShape[ob++] != newShape[nb++]) { onesOnly = false; break; } } while (ob <= or && nb <= nr); ob = 0; nb = 0; differences = new int[or + 2]; if (onesOnly) { // work out unit dimensions removed from or add to old int j = 0; do { if (oldShape[ob] != 1 && newShape[nb] != 1) { ob++; nb++; } else { while (oldShape[ob] == 1 && ob < or) { ob++; differences[j]--; } while (newShape[nb] == 1 && nb < nr) { nb++; differences[j]++; } } j++; } while (ob <= or && nb <= nr && j <= or); while (ob <= or && oldShape[ob] == 1) { ob++; differences[j]--; } while (nb <= nr && newShape[nb] == 1) { nb++; differences[j]++; } } else { if (matchRank) { logger.error("Combining dimensions is currently not supported"); throw new IllegalArgumentException("Combining dimensions is currently not supported"); } // work out mapping: contiguous dimensions can be grouped or split while (ob <= or && nb <= nr) { int ol = oldShape[ob]; while (ol == 1 && ol <= or) { ob++; ol = oldShape[ob]; } int oe = ob + 1; int nl = newShape[nb]; while (nl == 1 && nl <= nr) { nb++; nl = newShape[nb]; } int ne = nb + 1; if (ol < nl) { differences[ob] = 1; do { // case where new shape combines several dimensions into one dimension if (oe == (or + 1)) { break; } differences[oe] = 1; ol *= oldShape[oe++]; } while (ol < nl); differences[oe - 1] = oe - ob; // signal end with difference if (nl != ol) { logger.error("Single dimension is incompatible with subshape"); throw new IllegalArgumentException("Single dimension is incompatible with subshape"); } } else if (ol > nl) { do { // case where new shape spreads single dimension over several dimensions if (ne == (nr + 1)) { break; } nl *= newShape[ne++]; } while (nl < ol); if (nl != ol) { logger.error("Subshape is incompatible with single dimension"); throw new IllegalArgumentException("Subshape is incompatible with single dimension"); } } ob = oe; nb = ne; } } } @Override public ILazyDataset run(ILazyDataset lz) { if (differences == null) init(); int[] lshape = lz.getShape(); if (Arrays.equals(newShape, lshape)) { return lz; } int or = lz.getRank(); int nr = newShape.length; int[] nshape = new int[nr]; Arrays.fill(nshape, 1); if (onesOnly) { // ignore omit removed dimensions for (int i = 0, si = 0, di = 0; i < (or+1) && si <= or && di < nr; i++) { int c = differences[i]; if (c == 0) { nshape[di++] = lshape[si++]; } else if (c > 0) { while (c-- > 0 && di < nr) { di++; } } else if (c < 0) { si -= c; // remove dimensions by skipping forward in source array } } } else { boolean[] broadcast = new boolean[or]; for (int ob = 0; ob < or; ob++) { broadcast[ob] = oldShape[ob] != 1 && lshape[ob] == 1; } int osize = lz.getSize(); // cannot do 3x5x... to 15x... if metadata is broadcasting (i.e. 1x5x...) int ob = 0; int nsize = 1; for (int i = 0; i < nr; i++) { if (ob < or && broadcast[ob]) { if (differences[ob] != 0) { logger.error("Metadata contains a broadcast axis which cannot be reshaped"); throw new IllegalArgumentException("Metadata contains a broadcast axis which cannot be reshaped"); } } else { nshape[i] = nsize < osize ? newShape[i] : 1; } nsize *= nshape[i]; ob++; } } ILazyDataset nlz = lz; //.clone(); nlz.setShape(nshape); return nlz; } } class MdsTranspose implements MetadatasetAnnotationOperation { int[] map; public MdsTranspose(final int[] axesMap) { map = axesMap; } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Object processField(Field f, Object o) { if (o.getClass().isArray()) { int l = Array.getLength(o); if (l == map.length) { Object narray = Array.newInstance(o.getClass().getComponentType(), l); for (int i = 0; i < l; i++) { Array.set(narray, i, Array.get(o, map[i])); } for (int i = 0; i < l; i++) { Array.set(o, i, Array.get(narray, i)); } } } else if (o instanceof List<?>) { List list = (List) o; int l = list.size(); if (l == map.length) { Object narray = Array.newInstance(o.getClass().getComponentType(), l); for (int i = 0; i < l; i++) { Array.set(narray, i, list.get(map[i])); } list.clear(); for (int i = 0; i < l; i++) { list.add(Array.get(narray, i)); } } } return o; } @Override public Class<? extends Annotation> getAnnClass() { return Transposable.class; } @Override public int change(int axis) { return 0; } @Override public int getNewRank() { return -1; } @Override public ILazyDataset run(ILazyDataset lz) { return lz.getTransposedView(map); } } /** * Slice all datasets in metadata that are annotated by @Sliceable. Call this on the new sliced * dataset after cloning the metadata * @param asView if true then just a view * @param slice */ protected void sliceMetadata(boolean asView, final SliceND slice) { processAnnotatedMetadata(new MdsSlice(asView, slice.getStart(), slice.getStop(), slice.getStep(), slice.getSourceShape()), true); } /** * Reshape all datasets in metadata that are annotated by @Reshapeable. Call this when squeezing * or setting the shape * * @param newShape */ protected void reshapeMetadata(final int[] oldShape, final int[] newShape) { processAnnotatedMetadata(new MdsReshape(oldShape, newShape), true); } /** * Transpose all datasets in metadata that are annotated by @Transposable. Call this on the transposed * dataset after cloning the metadata * @param axesMap */ protected void transposeMetadata(final int[] axesMap) { processAnnotatedMetadata(new MdsTranspose(axesMap), true); } @SuppressWarnings("unchecked") private void processAnnotatedMetadata(MetadatasetAnnotationOperation op, boolean throwException) { if (metadata == null) return; for (Class<? extends MetadataType> c : metadata.keySet()) { for (MetadataType m : metadata.get(c)) { if (m == null) continue; Class<? extends MetadataType> mc = m.getClass(); do { // iterate over super-classes processClass(op, m, mc, throwException); Class<?> sclazz = mc.getSuperclass(); if (!MetadataType.class.isAssignableFrom(sclazz)) break; mc = (Class<? extends MetadataType>) sclazz; } while (true); } } } @SuppressWarnings({ "unchecked", "rawtypes" }) private static void processClass(MetadatasetAnnotationOperation op, MetadataType m, Class<? extends MetadataType> mc, boolean throwException) { for (Field f : mc.getDeclaredFields()) { if (!f.isAnnotationPresent(op.getAnnClass())) continue; try { f.setAccessible(true); Object o = f.get(m); if (o == null) continue; o = op.processField(f, o); Object r = null; if (o instanceof ILazyDataset) { try { f.set(m, op.run((ILazyDataset) o)); } catch (Exception e) { logger.error("Problem processing " + o, e); if (!catchExceptions) throw e; } } else if (o.getClass().isArray()) { int l = Array.getLength(o); if (l <= 0) continue; for (int i = 0; r == null && i < l; i++) { r = Array.get(o, i); } int n = op.getNewRank(); if (r == null) { if (n < 0 || n != l) { // all nulls be need to match rank as necessary f.set(m, Array.newInstance(o.getClass().getComponentType(), n < 0 ? l : n)); } continue; } if (n < 0) n = l; Object narray = Array.newInstance(r.getClass(), n); for (int i = 0, si = 0, di = 0; di < n && si < l; i++) { int c = op.change(i); if (c == 0) { Array.set(narray, di++, processObject(op, Array.get(o, si++))); } else if (c > 0) { di += c; // add nulls by skipping forward in destination array } else if (c < 0) { si -= c; // remove dimensions by skipping forward in source array } } if (n == l) { for (int i = 0; i < l; i++) { Array.set(o, i, Array.get(narray, i)); } } else { f.set(m, narray); } } else if (o instanceof List<?>) { List list = (List) o; int l = list.size(); if (l <= 0) continue; for (int i = 0; r == null && i < l; i++) { r = list.get(i); } int n = op.getNewRank(); if (r == null) { if (n < 0 || n != l) { // all nulls be need to match rank as necessary list.clear(); for (int i = 0, imax = n < 0 ? l : n; i < imax; i++) { list.add(null); } } continue; } if (n < 0) n = l; Object narray = Array.newInstance(r.getClass(), n); for (int i = 0, si = 0, di = 0; i < l && si < l; i++) { int c = op.change(i); if (c == 0) { Array.set(narray, di++, processObject(op, list.get(si++))); } else if (c > 0) { di += c; // add nulls by skipping forward in destination array } else if (c < 0) { si -= c; // remove dimensions by skipping forward in source array } } list.clear(); for (int i = 0; i < n; i++) { list.add(Array.get(narray, i)); } } else if (o instanceof Map<?,?>) { Map map = (Map) o; for (Object k : map.keySet()) { map.put(k, processObject(op, map.get(k))); } } } catch (Exception e) { logger.error("Problem occurred when processing metadata of class {}: {}", mc.getCanonicalName(), e); if (throwException) throw new RuntimeException(e); } } } @SuppressWarnings({ "unchecked", "rawtypes" }) private static Object processObject(MetadatasetAnnotationOperation op, Object o) throws DatasetException { if (o == null) return o; if (o instanceof ILazyDataset) { try { return op.run((ILazyDataset) o); } catch (Exception e) { logger.error("Problem processing " + o, e); if (!catchExceptions) throw e; } } else if (o.getClass().isArray()) { int l = Array.getLength(o); for (int i = 0; i < l; i++) { Array.set(o, i, processObject(op, Array.get(o, i))); } } else if (o instanceof List<?>) { List list = (List) o; for (int i = 0, imax = list.size(); i < imax; i++) { list.set(i, processObject(op, list.get(i))); } } else if (o instanceof Map<?,?>) { Map map = (Map) o; for (Object k : map.keySet()) { map.put(k, processObject(op, map.get(k))); } } return o; } protected void restoreMetadata(Map<Class<? extends MetadataType>, List<MetadataType>> oldMetadata) { for (Class<? extends MetadataType> mc : oldMetadata.keySet()) { metadata.put(mc, oldMetadata.get(mc)); } } protected ILazyDataset createFromSerializable(Serializable blob, boolean keepLazy) { ILazyDataset d = null; if (blob instanceof ILazyDataset) { d = (ILazyDataset) blob; if (d instanceof IDataset) { Dataset ed = DatasetUtils.convertToDataset((IDataset) d); int is = ed.getElementsPerItem(); if (is != 1 && is != getElementsPerItem()) { throw new IllegalArgumentException("Dataset has incompatible number of elements with this dataset"); } d = ed.cast(is == 1 ? Dataset.FLOAT64 : Dataset.ARRAYFLOAT64); } else if (!keepLazy) { final int is = getElementsPerItem(); d = DatasetUtils.cast(d.getSlice(), is == 1 ? Dataset.FLOAT64 : Dataset.ARRAYFLOAT64); } } else { final int is = getElementsPerItem(); d = DatasetFactory.createFromObject(blob, is == 1 ? Dataset.FLOAT64 : Dataset.ARRAYFLOAT64); if (d.getSize() == getSize() && !Arrays.equals(d.getShape(), shape)) { d.setShape(shape.clone()); } } List<int[]> s = BroadcastIterator.broadcastShapesToMax(shape, d.getShape()); d.setShape(s.get(0)); return d; } @Override public void setError(Serializable errors) { if (errors == null) { clearMetadata(ErrorMetadata.class); return; } if (errors == this) { logger.warn("Ignoring setting error to itself as this will lead to infinite recursion"); return; } ILazyDataset errorData = createFromSerializable(errors, true); ErrorMetadata emd = getErrorMetadata(); if (emd == null || !(emd instanceof ErrorMetadataImpl)) { emd = new ErrorMetadataImpl(); setMetadata(emd); } ((ErrorMetadataImpl) emd).setError(errorData); } protected ErrorMetadata getErrorMetadata() { try { List<ErrorMetadata> el = getMetadata(ErrorMetadata.class); if (el != null && !el.isEmpty()) { return el.get(0); } } catch (MetadataException e) { } return null; } @Override public ILazyDataset getError() { ErrorMetadata emd = getErrorMetadata(); return emd == null ? null : emd.getError(); } /** * Check permutation axes * @param shape * @param axes * @return cleaned up axes or null if trivial */ public static int[] checkPermutatedAxes(int[] shape, int... axes) { int rank = shape.length; if (axes == null || axes.length == 0) { axes = new int[rank]; for (int i = 0; i < rank; i++) { axes[i] = rank - 1 - i; } } if (axes.length != rank) { logger.error("axis permutation has length {} that does not match dataset's rank {}", axes.length, rank); throw new IllegalArgumentException("axis permutation does not match shape of dataset"); } // check all permutation values are within bounds for (int d : axes) { if (d < 0 || d >= rank) { logger.error("axis permutation contains element {} outside rank of dataset", d); throw new IllegalArgumentException("axis permutation contains element outside rank of dataset"); } } // check for a valid permutation (is this an unnecessary restriction?) int[] perm = axes.clone(); Arrays.sort(perm); for (int i = 0; i < rank; i++) { if (perm[i] != i) { logger.error("axis permutation is not valid: it does not contain complete set of axes"); throw new IllegalArgumentException("axis permutation does not contain complete set of axes"); } } if (Arrays.equals(axes, perm)) return null; // signal identity or trivial permutation return axes; } }
PeterC-DLS/org.eclipse.dataset
org.eclipse.dataset/src/org/eclipse/dataset/internal/dense/LazyDatasetBase.java
Java
epl-1.0
25,351
/******************************************************************************* * Copyright (c) 2012-2017 Codenvy, S.A. * 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 * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.datasource.ide.newDatasource; import org.eclipse.che.datasource.shared.DatabaseConfigurationDTO; import javax.validation.constraints.NotNull; public interface NewDatasourceWizardFactory { @NotNull NewDatasourceWizard create(DatabaseConfigurationDTO dataObject); }
sudaraka94/che
wsagent/che-datasource-ide/src/main/java/org/eclipse/che/datasource/ide/newDatasource/NewDatasourceWizardFactory.java
Java
epl-1.0
822
/** * Copyright (c) 2015-2016 Kai Kreuzer 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.core.types; import java.util.SortedMap; /** * A complex type consists out of a sorted list of primitive constituents. * Each constituent can be referred to by a unique name. * * @author Kai Kreuzer * @since 0.1.0 * */ public interface ComplexType extends Type { /** * Returns all constituents with their names as a sorted map * * @return all constituents with their names */ public SortedMap<String, PrimitiveType> getConstituents(); }
reitermarkus/openhab-core
bundles/org.openhab.core.compat1x/src/main/java/org/openhab/core/types/ComplexType.java
Java
epl-1.0
819
package org.jboss.windup.reporting.model; import java.util.Collections; import java.util.Set; import org.jboss.windup.graph.model.WindupVertexFrame; import com.tinkerpop.blueprints.Direction; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.frames.Adjacency; import com.tinkerpop.frames.modules.javahandler.JavaHandler; import com.tinkerpop.frames.modules.javahandler.JavaHandlerContext; import com.tinkerpop.frames.modules.typedgraph.TypeValue; /** * @author <a href="mailto:[email protected]">Jesse Sightler</a> */ @TypeValue(TaggableModel.TYPE) public interface TaggableModel extends WindupVertexFrame { /** * This location for this tag is not ideal. TODO - Find a better place for this... */ String CATCHALL_TAG = "catchall"; String TYPE = "TaggableModel"; String TAG = "tag"; /** * Set the set of tags associated with this {@link ClassificationModel} */ @Adjacency(label = TAG, direction = Direction.OUT) void setTagModel(TagSetModel tags); /** * Get the set of tags associated with this {@link ClassificationModel} */ @Adjacency(label = TAG, direction = Direction.OUT) TagSetModel getTagModel(); @JavaHandler Set<String> getTags(); abstract class Impl implements TaggableModel, JavaHandlerContext<Vertex> { @Override public Set<String> getTags() { TagSetModel tagSetModel = getTagModel(); if (tagSetModel == null) return Collections.emptySet(); return tagSetModel.getTags(); } } }
Ladicek/windup
reporting/api/src/main/java/org/jboss/windup/reporting/model/TaggableModel.java
Java
epl-1.0
1,591
/* * Copyright (c) 2012-2018 Red Hat, Inc. * 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 * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.ide.ext.git.client.push; import static java.util.Collections.singletonList; import static org.eclipse.che.api.git.shared.BranchListMode.LIST_LOCAL; import static org.eclipse.che.api.git.shared.BranchListMode.LIST_REMOTE; import static org.eclipse.che.ide.api.notification.StatusNotification.DisplayMode.FLOAT_MODE; import static org.eclipse.che.ide.api.notification.StatusNotification.Status.FAIL; import static org.eclipse.che.ide.api.notification.StatusNotification.Status.PROGRESS; import static org.eclipse.che.ide.api.notification.StatusNotification.Status.SUCCESS; import static org.eclipse.che.ide.ext.git.client.compare.branchlist.BranchListPresenter.BRANCH_LIST_COMMAND_NAME; import static org.eclipse.che.ide.ext.git.client.remote.RemotePresenter.REMOTE_REPO_COMMAND_NAME; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.inject.Inject; import com.google.inject.Singleton; import java.util.Arrays; import java.util.List; import javax.validation.constraints.NotNull; import org.eclipse.che.api.core.rest.shared.dto.ServiceError; import org.eclipse.che.api.git.shared.Branch; import org.eclipse.che.api.git.shared.BranchListMode; import org.eclipse.che.api.git.shared.PushResponse; import org.eclipse.che.api.promises.client.Promise; import org.eclipse.che.ide.api.auth.Credentials; import org.eclipse.che.ide.api.auth.OAuthServiceClient; import org.eclipse.che.ide.api.notification.NotificationManager; import org.eclipse.che.ide.api.notification.StatusNotification; import org.eclipse.che.ide.api.resources.Project; import org.eclipse.che.ide.commons.exception.UnauthorizedException; import org.eclipse.che.ide.dto.DtoFactory; import org.eclipse.che.ide.ext.git.client.BranchFilterByRemote; import org.eclipse.che.ide.ext.git.client.BranchSearcher; import org.eclipse.che.ide.ext.git.client.GitAuthActionPresenter; import org.eclipse.che.ide.ext.git.client.GitLocalizationConstant; import org.eclipse.che.ide.ext.git.client.GitServiceClient; import org.eclipse.che.ide.ext.git.client.outputconsole.GitOutputConsole; import org.eclipse.che.ide.ext.git.client.outputconsole.GitOutputConsoleFactory; import org.eclipse.che.ide.processes.panel.ProcessesPanelPresenter; /** * Presenter for pushing changes to remote repository. * * @author Ann Zhuleva * @author Sergii Leschenko * @author Vlad Zhukovskyi */ @Singleton public class PushToRemotePresenter extends GitAuthActionPresenter implements PushToRemoteView.ActionDelegate { public static final String PUSH_COMMAND_NAME = "Git push"; public static final String CONFIG_COMMAND_NAME = "Git config"; private final GitOutputConsoleFactory gitOutputConsoleFactory; private final ProcessesPanelPresenter processesPanelPresenter; private final DtoFactory dtoFactory; private final BranchSearcher branchSearcher; private final PushToRemoteView view; private final GitServiceClient service; private Project project; @Inject public PushToRemotePresenter( DtoFactory dtoFactory, PushToRemoteView view, GitServiceClient service, GitLocalizationConstant constant, NotificationManager notificationManager, BranchSearcher branchSearcher, GitOutputConsoleFactory gitOutputConsoleFactory, ProcessesPanelPresenter processesPanelPresenter, OAuthServiceClient oAuthServiceClient) { super(notificationManager, constant, oAuthServiceClient); this.dtoFactory = dtoFactory; this.branchSearcher = branchSearcher; this.view = view; this.oAuthServiceClient = oAuthServiceClient; this.view.setDelegate(this); this.service = service; this.notificationManager = notificationManager; this.gitOutputConsoleFactory = gitOutputConsoleFactory; this.processesPanelPresenter = processesPanelPresenter; } public void showDialog(Project project) { this.project = project; updateRemotes(); } /** * Get the list of remote repositories for local one. If remote repositories are found, then get * the list of branches (remote and local). */ void updateRemotes() { service .remoteList(project.getLocation(), null, true) .then( remotes -> { updateLocalBranches(); view.setRepositories(remotes); view.setEnablePushButton(!remotes.isEmpty()); view.setSelectedForcePushCheckBox(false); view.showDialog(); }) .catchError( error -> { String errorMessage = error.getMessage() != null ? error.getMessage() : locale.remoteListFailed(); GitOutputConsole console = gitOutputConsoleFactory.create(REMOTE_REPO_COMMAND_NAME); console.printError(errorMessage); processesPanelPresenter.addCommandOutput(console); notificationManager.notify(locale.remoteListFailed(), FAIL, FLOAT_MODE); view.setEnablePushButton(false); }); } /** Update list of local and remote branches on view. */ void updateLocalBranches() { // getting local branches getBranchesForCurrentProject( LIST_LOCAL, new AsyncCallback<List<Branch>>() { @Override public void onSuccess(List<Branch> result) { List<String> localBranches = branchSearcher.getLocalBranchesToDisplay(result); view.setLocalBranches(localBranches); for (Branch branch : result) { if (branch.isActive()) { view.selectLocalBranch(branch.getDisplayName()); break; } } // getting remote branch only after selecting current local branch updateRemoteBranches(); } @Override public void onFailure(Throwable exception) { String errorMessage = exception.getMessage() != null ? exception.getMessage() : locale.localBranchesListFailed(); GitOutputConsole console = gitOutputConsoleFactory.create(BRANCH_LIST_COMMAND_NAME); console.printError(errorMessage); processesPanelPresenter.addCommandOutput(console); notificationManager.notify(locale.localBranchesListFailed(), FAIL, FLOAT_MODE); view.setEnablePushButton(false); } }); } /** Update list of remote branches on view. */ void updateRemoteBranches() { getBranchesForCurrentProject( LIST_REMOTE, new AsyncCallback<List<Branch>>() { @Override public void onSuccess(final List<Branch> result) { // Need to add the upstream of local branch in the list of remote branches // to be able to push changes to the remote upstream branch getUpstreamBranch( new AsyncCallback<Branch>() { @Override public void onSuccess(Branch upstream) { BranchFilterByRemote remoteRefsHandler = new BranchFilterByRemote(view.getRepository()); final List<String> remoteBranches = branchSearcher.getRemoteBranchesToDisplay(remoteRefsHandler, result); String selectedRemoteBranch = null; if (upstream != null && upstream.isRemote() && remoteRefsHandler.isLinkedTo(upstream)) { String simpleUpstreamName = remoteRefsHandler.getBranchNameWithoutRefs(upstream); if (!remoteBranches.contains(simpleUpstreamName)) { remoteBranches.add(simpleUpstreamName); } selectedRemoteBranch = simpleUpstreamName; } // Need to add the current local branch in the list of remote branches // to be able to push changes to the remote branch with same name final String currentBranch = view.getLocalBranch(); if (!remoteBranches.contains(currentBranch)) { remoteBranches.add(currentBranch); } if (selectedRemoteBranch == null) { selectedRemoteBranch = currentBranch; } view.setRemoteBranches(remoteBranches); view.selectRemoteBranch(selectedRemoteBranch); } @Override public void onFailure(Throwable caught) { GitOutputConsole console = gitOutputConsoleFactory.create(CONFIG_COMMAND_NAME); console.printError(locale.failedGettingConfig()); processesPanelPresenter.addCommandOutput(console); notificationManager.notify(locale.failedGettingConfig(), FAIL, FLOAT_MODE); } }); } @Override public void onFailure(Throwable exception) { String errorMessage = exception.getMessage() != null ? exception.getMessage() : locale.remoteBranchesListFailed(); GitOutputConsole console = gitOutputConsoleFactory.create(BRANCH_LIST_COMMAND_NAME); console.printError(errorMessage); processesPanelPresenter.addCommandOutput(console); notificationManager.notify(locale.remoteBranchesListFailed(), FAIL, FLOAT_MODE); view.setEnablePushButton(false); } }); } /** * Get upstream branch for selected local branch. Can invoke {@code onSuccess(null)} if upstream * branch isn't set */ private void getUpstreamBranch(final AsyncCallback<Branch> result) { final String configBranchRemote = "branch." + view.getLocalBranch() + ".remote"; final String configUpstreamBranch = "branch." + view.getLocalBranch() + ".merge"; service .config(project.getLocation(), Arrays.asList(configUpstreamBranch, configBranchRemote)) .then( configs -> { if (configs.containsKey(configBranchRemote) && configs.containsKey(configUpstreamBranch)) { String displayName = configs.get(configBranchRemote) + "/" + configs.get(configUpstreamBranch); Branch upstream = dtoFactory .createDto(Branch.class) .withActive(false) .withRemote(true) .withDisplayName(displayName) .withName("refs/remotes/" + displayName); result.onSuccess(upstream); } else { result.onSuccess(null); } }) .catchError( error -> { result.onFailure(error.getCause()); }); } /** * Get the list of branches. * * @param remoteMode is a remote mode */ void getBranchesForCurrentProject( @NotNull final BranchListMode remoteMode, final AsyncCallback<List<Branch>> asyncResult) { service .branchList(project.getLocation(), remoteMode) .then( branches -> { asyncResult.onSuccess(branches); }) .catchError( error -> { asyncResult.onFailure(error.getCause()); }); } /** {@inheritDoc} */ @Override public void onPushClicked() { final StatusNotification notification = notificationManager.notify(locale.pushProcess(), PROGRESS, FLOAT_MODE); final String repository = view.getRepository(); final GitOutputConsole console = gitOutputConsoleFactory.create(PUSH_COMMAND_NAME); performOperationWithTokenRequestIfNeeded( new RemoteGitOperation<PushResponse>() { @Override public Promise<PushResponse> perform(Credentials credentials) { return service.push( project.getLocation(), getRefs(), repository, view.isForcePushSelected(), credentials); } }) .then( response -> { console.print(response.getCommandOutput()); processesPanelPresenter.addCommandOutput(console); notification.setStatus(SUCCESS); if (response.getCommandOutput().contains("Everything up-to-date")) { notification.setTitle(locale.pushUpToDate()); } else { notification.setTitle(locale.pushSuccess(repository)); } }) .catchError( error -> { handleError(error.getCause(), notification, console); processesPanelPresenter.addCommandOutput(console); }); view.close(); } /** @return list of refs to push */ @NotNull private List<String> getRefs() { String localBranch = view.getLocalBranch(); String remoteBranch = view.getRemoteBranch(); return singletonList(localBranch + ":" + remoteBranch); } /** {@inheritDoc} */ @Override public void onCancelClicked() { view.close(); } /** {@inheritDoc} */ @Override public void onLocalBranchChanged() { view.addRemoteBranch(view.getLocalBranch()); view.selectRemoteBranch(view.getLocalBranch()); } @Override public void onRepositoryChanged() { updateRemoteBranches(); } /** * Handler some action whether some exception happened. * * @param throwable exception what happened */ void handleError( @NotNull Throwable throwable, StatusNotification notification, GitOutputConsole console) { notification.setStatus(FAIL); if (throwable instanceof UnauthorizedException) { console.printError(locale.messagesNotAuthorizedTitle()); console.print(locale.messagesNotAuthorizedContent()); notification.setTitle(locale.messagesNotAuthorizedTitle()); notification.setContent(locale.messagesNotAuthorizedContent()); return; } String errorMessage = throwable.getMessage(); if (errorMessage == null) { console.printError(locale.pushFail()); notification.setTitle(locale.pushFail()); return; } try { errorMessage = dtoFactory.createDtoFromJson(errorMessage, ServiceError.class).getMessage(); if (errorMessage.equals("Unable get private ssh key")) { console.printError(locale.messagesUnableGetSshKey()); notification.setTitle(locale.messagesUnableGetSshKey()); return; } console.printError(errorMessage); notification.setTitle(errorMessage); } catch (Exception e) { console.printError(errorMessage); notification.setTitle(errorMessage); } } }
sleshchenko/che
plugins/plugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/client/push/PushToRemotePresenter.java
Java
epl-1.0
15,280
/* // $Id: //open/mondrian-release/3.1/src/main/mondrian/rolap/aggmatcher/DefaultRules.java#2 $ // This software is subject to the terms of the Eclipse Public License v1.0 // Agreement, available at the following URL: // http://www.eclipse.org/legal/epl-v10.html. // Copyright (C) 2005-2009 Julian Hyde and others // All Rights Reserved. // You must accept the terms of that agreement to use this software. */ package mondrian.rolap.aggmatcher; import mondrian.olap.*; import mondrian.rolap.RolapStar; import mondrian.recorder.*; import mondrian.resource.MondrianResource; import org.apache.log4j.Logger; import org.eigenbase.xom.*; import org.eigenbase.xom.Parser; import org.eigenbase.util.property.*; import org.eigenbase.util.property.Property; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Map; /** * Container for the default aggregate recognition rules. * It is generated by parsing the default rule xml information found * in the {@link MondrianProperties#AggregateRules} value which normally is * a resource in the jar file (but can be a url). * * <p>It is a singleton since it is used to recognize tables independent of * database connection (each {@link mondrian.rolap.RolapSchema} uses the same * instance). * * @author Richard M. Emberson * @version $Id: //open/mondrian-release/3.1/src/main/mondrian/rolap/aggmatcher/DefaultRules.java#2 $ */ public class DefaultRules { private static final Logger LOGGER = Logger.getLogger(DefaultRules.class); private static final MondrianResource mres = MondrianResource.instance(); /** * There is a single instance of the {@link DefaultRecognizer} and the * {@link DefaultRules} class is a container of that instance. */ public static synchronized DefaultRules getInstance() { if (instance == null) { InputStream inStream = getAggRuleInputStream(); if (inStream == null) { return null; } DefaultDef.AggRules defs = makeAggRules(inStream); // validate the DefaultDef.AggRules object ListRecorder reclists = new ListRecorder(); try { defs.validate(reclists); } catch (RecorderException e) { // ignore } reclists.logWarningMessage(LOGGER); reclists.logErrorMessage(LOGGER); if (reclists.hasErrors()) { reclists.throwRTException(); } // make sure the tag name exists String tag = MondrianProperties.instance().AggregateRuleTag.get(); DefaultDef.AggRule aggrule = defs.getAggRule(tag); if (aggrule == null) { throw mres.MissingDefaultAggRule.ex(tag); } DefaultRules rules = new DefaultRules(defs); rules.setTag(tag); instance = rules; } return instance; } private static InputStream getAggRuleInputStream() { String aggRules = MondrianProperties.instance().AggregateRules.get(); InputStream inStream = DefaultRules.class.getResourceAsStream(aggRules); if (inStream == null) { try { URL url = new URL(aggRules); inStream = url.openStream(); } catch (MalformedURLException e) { // ignore } catch (IOException e) { // ignore } } if (inStream == null) { LOGGER.warn(mres.CouldNotLoadDefaultAggregateRules.str(aggRules)); } return inStream; } private static DefaultRules instance = null; static { // When the value of the AggregateRules property is changed, force // system to reload the DefaultRules. // There is no need to provide equals/hashCode methods for this // Trigger since it is a singleton and is never removed. Trigger trigger = new Trigger() { public boolean isPersistent() { return true; } public int phase() { return Trigger.PRIMARY_PHASE; } public void execute(Property property, String value) { synchronized (DefaultRules.class) { DefaultRules oldInstance = DefaultRules.instance; DefaultRules.instance = null; DefaultRules newInstance = null; Exception ex = null; try { newInstance = DefaultRules.getInstance(); } catch (Exception e) { ex = e; } if (ex != null) { DefaultRules.instance = oldInstance; throw new Trigger.VetoRT(ex); } else if (newInstance == null) { DefaultRules.instance = oldInstance; String msg = mres.FailedCreateNewDefaultAggregateRules.str( property.getPath(), value); throw new Trigger.VetoRT(msg); } else { instance = newInstance; } } } }; final MondrianProperties properties = MondrianProperties.instance(); properties.AggregateRules.addTrigger(trigger); properties.AggregateRuleTag.addTrigger(trigger); } protected static DefaultDef.AggRules makeAggRules(final File file) { DOMWrapper def = makeDOMWrapper(file); try { DefaultDef.AggRules rules = new DefaultDef.AggRules(def); return rules; } catch (XOMException e) { throw mres.AggRuleParse.ex(file.getName(), e); } } protected static DefaultDef.AggRules makeAggRules(final URL url) { DOMWrapper def = makeDOMWrapper(url); try { DefaultDef.AggRules rules = new DefaultDef.AggRules(def); return rules; } catch (XOMException e) { throw mres.AggRuleParse.ex(url.toString(), e); } } protected static DefaultDef.AggRules makeAggRules( final InputStream inStream) { DOMWrapper def = makeDOMWrapper(inStream); try { DefaultDef.AggRules rules = new DefaultDef.AggRules(def); return rules; } catch (XOMException e) { throw mres.AggRuleParse.ex("InputStream", e); } } protected static DefaultDef.AggRules makeAggRules( final String text, final String name) { DOMWrapper def = makeDOMWrapper(text, name); try { DefaultDef.AggRules rules = new DefaultDef.AggRules(def); return rules; } catch (XOMException e) { throw mres.AggRuleParse.ex(name, e); } } protected static DOMWrapper makeDOMWrapper(final File file) { try { return makeDOMWrapper(file.toURL()); } catch (MalformedURLException e) { throw mres.AggRuleParse.ex(file.getName(), e); } } protected static DOMWrapper makeDOMWrapper(final URL url) { try { final Parser xmlParser = XOMUtil.createDefaultParser(); DOMWrapper def = xmlParser.parse(url); return def; } catch (XOMException e) { throw mres.AggRuleParse.ex(url.toString(), e); } } protected static DOMWrapper makeDOMWrapper(final InputStream inStream) { try { final Parser xmlParser = XOMUtil.createDefaultParser(); DOMWrapper def = xmlParser.parse(inStream); return def; } catch (XOMException e) { throw mres.AggRuleParse.ex("InputStream", e); } } protected static DOMWrapper makeDOMWrapper( final String text, final String name) { try { final Parser xmlParser = XOMUtil.createDefaultParser(); DOMWrapper def = xmlParser.parse(text); return def; } catch (XOMException e) { throw mres.AggRuleParse.ex(name, e); } } private final DefaultDef.AggRules rules; private final Map<String, Recognizer.Matcher> factToPattern; private final Map<String, Recognizer.Matcher> foreignKeyMatcherMap; private Recognizer.Matcher ignoreMatcherMap; private Recognizer.Matcher factCountMatcher; private String tag; private DefaultRules(final DefaultDef.AggRules rules) { this.rules = rules; this.factToPattern = new HashMap<String, Recognizer.Matcher>(); this.foreignKeyMatcherMap = new HashMap<String, Recognizer.Matcher>(); this.tag = MondrianProperties.instance().AggregateRuleTag.getDefaultValue(); } public void validate(MessageRecorder msgRecorder) { rules.validate(msgRecorder); } /** * Sets the name (tag) of this rule. * * @param tag */ private void setTag(final String tag) { this.tag = tag; } /** * Gets the tag of this rule (this is the value of the * {@link MondrianProperties#AggregateRuleTag} property). */ public String getTag() { return this.tag; } /** * Returns the {@link mondrian.rolap.aggmatcher.DefaultDef.AggRule} whose * tag equals this rule's tag. */ public DefaultDef.AggRule getAggRule() { return getAggRule(getTag()); } /** * Returns the {@link mondrian.rolap.aggmatcher.DefaultDef.AggRule} whose * tag equals the parameter tag, or null if not found. * * @param tag * @return the AggRule with tag value equal to tag parameter, or null. */ public DefaultDef.AggRule getAggRule(final String tag) { return this.rules.getAggRule(tag); } /** * Gets the {@link mondrian.rolap.aggmatcher.Recognizer.Matcher} for this * tableName. * * @param tableName */ public Recognizer.Matcher getTableMatcher(final String tableName) { Recognizer.Matcher matcher = factToPattern.get(tableName); if (matcher == null) { // get default AggRule DefaultDef.AggRule rule = getAggRule(); DefaultDef.TableMatch tableMatch = rule.getTableMatch(); matcher = tableMatch.getMatcher(tableName); factToPattern.put(tableName, matcher); } return matcher; } /** * Gets the {@link mondrian.rolap.aggmatcher.Recognizer.Matcher} for the * fact count column. */ public Recognizer.Matcher getIgnoreMatcher() { if (ignoreMatcherMap == null) { // get default AggRule DefaultDef.AggRule rule = getAggRule(); DefaultDef.IgnoreMap ignoreMatch = rule.getIgnoreMap(); if (ignoreMatch == null) { ignoreMatcherMap = new Recognizer.Matcher() { public boolean matches(String name) { return false; } }; } else { ignoreMatcherMap = ignoreMatch.getMatcher(); } } return ignoreMatcherMap; } /** * Gets the {@link mondrian.rolap.aggmatcher.Recognizer.Matcher} for * columns that should be ignored. * * @return the {@link mondrian.rolap.aggmatcher.Recognizer.Matcher} for * columns that should be ignored. */ public Recognizer.Matcher getFactCountMatcher() { if (factCountMatcher == null) { // get default AggRule DefaultDef.AggRule rule = getAggRule(); DefaultDef.FactCountMatch factCountMatch = rule.getFactCountMatch(); factCountMatcher = factCountMatch.getMatcher(); } return factCountMatcher; } /** * Gets the {@link mondrian.rolap.aggmatcher.Recognizer.Matcher} for this * foreign key column name. * * @param foreignKeyName Name of a foreign key column */ public Recognizer.Matcher getForeignKeyMatcher(String foreignKeyName) { Recognizer.Matcher matcher = foreignKeyMatcherMap.get(foreignKeyName); if (matcher == null) { // get default AggRule DefaultDef.AggRule rule = getAggRule(); DefaultDef.ForeignKeyMatch foreignKeyMatch = rule.getForeignKeyMatch(); matcher = foreignKeyMatch.getMatcher(foreignKeyName); foreignKeyMatcherMap.put(foreignKeyName, matcher); } return matcher; } /** * Returns true if this candidate aggregate table name "matches" the * factTableName. * * @param factTableName Name of the fact table * @param name candidate aggregate table name */ public boolean matchesTableName( final String factTableName, final String name) { Recognizer.Matcher matcher = getTableMatcher(factTableName); return matcher.matches(name); } /** * Creates a {@link mondrian.rolap.aggmatcher.Recognizer.Matcher} for the * given measure name (symbolic name), column name and aggregate name * (sum, count, etc.). */ public Recognizer.Matcher getMeasureMatcher( final String measureName, final String measureColumnName, final String aggregateName) { DefaultDef.AggRule rule = getAggRule(); Recognizer.Matcher matcher = rule.getMeasureMap().getMatcher( measureName, measureColumnName, aggregateName); return matcher; } /** * Gets a {@link mondrian.rolap.aggmatcher.Recognizer.Matcher} for a given * level's hierarchy's name, level name and column name. */ public Recognizer.Matcher getLevelMatcher( final String usagePrefix, final String hierarchyName, final String levelName, final String levelColumnName) { DefaultDef.AggRule rule = getAggRule(); Recognizer.Matcher matcher = rule.getLevelMap().getMatcher( usagePrefix, hierarchyName, levelName, levelColumnName); return matcher; } /** * Uses the {@link DefaultRecognizer} Recognizer to determine if the * given aggTable's columns all match upto the dbFactTable's columns (where * present) making the column usages as a result. */ public boolean columnsOK( final RolapStar star, final JdbcSchema.Table dbFactTable, final JdbcSchema.Table aggTable, final MessageRecorder msgRecorder) { Recognizer cb = new DefaultRecognizer( this, star, dbFactTable, aggTable, msgRecorder); return cb.check(); } } // End DefaultRules.java
Twixer/mondrian-3.1.5
src/main/mondrian/rolap/aggmatcher/DefaultRules.java
Java
epl-1.0
15,228
package com.github.chroneus.juclipse.launch; import org.eclipse.debug.core.ILaunch; import org.eclipse.dltk.console.IScriptInterpreter; import org.eclipse.dltk.console.ui.IScriptConsole; import org.eclipse.dltk.console.ui.IScriptConsoleFactory; import org.eclipse.dltk.console.ui.ScriptConsole; import org.eclipse.dltk.console.ui.ScriptConsoleFactoryBase; public class JuliaConsoleFactory extends ScriptConsoleFactoryBase implements IScriptConsoleFactory { public IScriptConsole openConsole(IScriptInterpreter interpreter, String id, ILaunch launch) {return createConsoleInstance(); } protected ScriptConsole createConsoleInstance() { return null; } }
chroneus/juclipse
com.github.chroneus.juclipse/src/com/github/chroneus/juclipse/launch/JuliaConsoleFactory.java
Java
epl-1.0
684
package zephyr.plugin.core.privates.synchronization.binding; import zephyr.plugin.core.internal.async.events.CastedEventListener; import zephyr.plugin.core.internal.events.ClockEvent; import zephyr.plugin.core.privates.ZephyrPluginCore; public class ClockAddedListener extends CastedEventListener<ClockEvent> { @Override public void listenEvent(ClockEvent event) { ClockViews clockViews = new ClockViews(event.clock()); ZephyrPluginCore.viewBinder().register(clockViews); } }
zephyrplugins/zephyr
zephyr.plugin.core/src/zephyr/plugin/core/privates/synchronization/binding/ClockAddedListener.java
Java
epl-1.0
492
/* * Copyright (C) 2011, Google Inc. * and other copyright owners as documented in the project's IP log. * * This program and the accompanying materials are made available * under the terms of the Eclipse Distribution License v1.0 which * accompanies this distribution, is reproduced below, and is * available at http://www.eclipse.org/org/documents/edl-v10.php * * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * - Neither the name of the Eclipse Foundation, Inc. nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jboss.forge.jgit.storage.dfs; import java.util.Set; import org.jboss.forge.jgit.lib.ObjectId; import org.jboss.forge.jgit.storage.dfs.DfsPackDescription; import org.jboss.forge.jgit.storage.dfs.DfsRepositoryDescription; import org.jboss.forge.jgit.storage.pack.PackWriter; /** * Description of a DFS stored pack/index file. * <p> * Implementors may extend this class and add additional data members. * <p> * Instances of this class are cached with the DfsPackFile, and should not be * modified once initialized and presented to the JGit DFS library. */ public class DfsPackDescription implements Comparable<DfsPackDescription> { private final DfsRepositoryDescription repoDesc; private final String packName; private long lastModified; private long packSize; private long indexSize; private long objectCount; private long deltaCount; private Set<ObjectId> tips; private PackWriter.Statistics stats; /** * Initialize a description by pack name and repository. * <p> * The corresponding index file is assumed to exist and end with ".idx" * instead of ".pack". If this is not true implementors must extend the * class and override {@link #getIndexName()}. * <p> * Callers should also try to fill in other fields if they are reasonably * free to access at the time this instance is being initialized. * * @param name * name of the pack file. Must end with ".pack". * @param repoDesc * description of the repo containing the pack file. */ public DfsPackDescription(DfsRepositoryDescription repoDesc, String name) { this.repoDesc = repoDesc; this.packName = name; } /** @return description of the repository. */ public DfsRepositoryDescription getRepositoryDescription() { return repoDesc; } /** @return name of the pack file. */ public String getPackName() { return packName; } /** @return name of the index file. */ public String getIndexName() { String name = getPackName(); int dot = name.lastIndexOf('.'); if (dot < 0) dot = name.length(); return name.substring(0, dot) + ".idx"; } /** @return time the pack was created, in milliseconds. */ public long getLastModified() { return lastModified; } /** * @param timeMillis * time the pack was created, in milliseconds. 0 if not known. * @return {@code this} */ public DfsPackDescription setLastModified(long timeMillis) { lastModified = timeMillis; return this; } /** @return size of the pack, in bytes. If 0 the pack size is not yet known. */ public long getPackSize() { return packSize; } /** * @param bytes * size of the pack in bytes. If 0 the size is not known and will * be determined on first read. * @return {@code this} */ public DfsPackDescription setPackSize(long bytes) { packSize = Math.max(0, bytes); return this; } /** * @return size of the index, in bytes. If 0 the index size is not yet * known. */ public long getIndexSize() { return indexSize; } /** * @param bytes * size of the index in bytes. If 0 the size is not known and * will be determined on first read. * @return {@code this} */ public DfsPackDescription setIndexSize(long bytes) { indexSize = Math.max(0, bytes); return this; } /** * @return size of the reverse index, in bytes. */ public int getReverseIndexSize() { return (int) Math.min(objectCount * 8, Integer.MAX_VALUE); } /** @return number of objects in the pack. */ public long getObjectCount() { return objectCount; } /** * @param cnt * number of objects in the pack. * @return {@code this} */ public DfsPackDescription setObjectCount(long cnt) { objectCount = Math.max(0, cnt); return this; } /** @return number of delta compressed objects in the pack. */ public long getDeltaCount() { return deltaCount; } /** * @param cnt * number of delta compressed objects in the pack. * @return {@code this} */ public DfsPackDescription setDeltaCount(long cnt) { deltaCount = Math.max(0, cnt); return this; } /** @return the tips that created this pack, if known. */ public Set<ObjectId> getTips() { return tips; } /** * @param tips * the tips of the pack, null if it has no known tips. * @return {@code this} */ public DfsPackDescription setTips(Set<ObjectId> tips) { this.tips = tips; return this; } /** * @return statistics from PackWriter, if the pack was built with it. * Generally this is only available for packs created by * DfsGarbageCollector or DfsPackCompactor, and only when the pack * is being committed to the repository. */ public PackWriter.Statistics getPackStats() { return stats; } DfsPackDescription setPackStats(PackWriter.Statistics stats) { this.stats = stats; return this; } /** * Discard the pack statistics, if it was populated. * * @return {@code this} */ public DfsPackDescription clearPackStats() { stats = null; return this; } @Override public int hashCode() { return getPackName().hashCode(); } @Override public boolean equals(Object b) { if (b instanceof DfsPackDescription) { DfsPackDescription desc = (DfsPackDescription) b; return getPackName().equals(desc.getPackName()) && getRepositoryDescription().equals(desc.getRepositoryDescription()); } return false; } /** * Sort packs according to the optimal lookup ordering. * <p> * This method tries to position packs in the order readers should examine * them when looking for objects by SHA-1. The default tries to sort packs * with more recent modification dates before older packs, and packs with * fewer objects before packs with more objects. * * @param b * the other pack. */ public int compareTo(DfsPackDescription b) { // Newer packs should sort first. int cmp = Long.signum(b.getLastModified() - getLastModified()); if (cmp != 0) return cmp; // Break ties on smaller index. Readers may get lucky and find // the object they care about in the smaller index. This also pushes // big historical packs to the end of the list, due to more objects. return Long.signum(getObjectCount() - b.getObjectCount()); } @Override public String toString() { return getPackName(); } }
forge/plugin-undo
src/main/jgit/org/jboss/forge/jgit/storage/dfs/DfsPackDescription.java
Java
epl-1.0
8,290
/******************************************************************************* * Copyright (c) 2014 BSI Business Systems Integration AG. * 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 * * Contributors: * BSI Business Systems Integration AG - initial API and implementation ******************************************************************************/ package org.eclipsescout.rt.ui.fx.form.fields; import org.eclipse.scout.rt.client.ui.form.fields.GridData; import org.eclipsescout.rt.ui.fx.IFxEnvironment; import org.eclipsescout.rt.ui.fx.LogicalGridData; import org.eclipsescout.rt.ui.fx.FxLayoutUtility; /** * Provides methods to create {@link LogicalGridData} from {@link GridData} of the scout ui model. */ public class LogicalGridDataBuilder { /** * <p> * x-position of the field. * </p> * Position is 1 because there can be a label on the left side */ public static final int FIELD_GRID_X = 1; /** * <p> * y-position of the field. * </p> * Position is 1 because there can be a label on top */ public static final int FIELD_GRID_Y = 1; private LogicalGridDataBuilder() { } public static LogicalGridData createLabel(IFxEnvironment env, GridData correspondingFieldData) { LogicalGridData data = new LogicalGridData(); data.gridx = FIELD_GRID_X - 1; data.gridy = FIELD_GRID_Y; data.gridh = correspondingFieldData.h; data.weighty = 1.0; data.widthHint = env.getFieldLabelWidth(); data.topInset = FxLayoutUtility.getTextFieldTopInset(); data.useUiWidth = true; data.useUiHeight = true; data.fillVertical = false; return data; } public static LogicalGridData createLabelOnTop(GridData correspondingFieldData) { LogicalGridData data = new LogicalGridData(); data.gridx = FIELD_GRID_X; data.gridy = FIELD_GRID_Y - 1; data.weighty = 0.0; data.weightx = 1.0; data.useUiWidth = true; data.useUiHeight = true; data.fillVertical = true; data.fillHorizontal = true; return data; } /** * @param gd * is only used for the properties useUiWidth and useUiHeight and the * weights */ public static LogicalGridData createField(IFxEnvironment env, GridData correspondingFieldData) { LogicalGridData data = new LogicalGridData(); data.gridx = FIELD_GRID_X; data.gridy = FIELD_GRID_Y; data.weightx = 1.0; data.gridh = correspondingFieldData.h; if (correspondingFieldData.weightY == 0 || (correspondingFieldData.weightY < 0 && correspondingFieldData.h <= 1)) { data.weighty = 0; } else { data.weighty = 1.0; } data.useUiWidth = correspondingFieldData.useUiWidth; data.useUiHeight = correspondingFieldData.useUiHeight; return data; } public static LogicalGridData createButton1(IFxEnvironment env) { LogicalGridData data = new LogicalGridData(); data.gridx = FIELD_GRID_X + 1; data.gridy = FIELD_GRID_Y; data.fillVertical = false; data.useUiWidth = true; data.useUiHeight = true; return data; } public static LogicalGridData createButton2(IFxEnvironment env) { LogicalGridData data = new LogicalGridData(); data.gridx = FIELD_GRID_X + 2; data.gridy = FIELD_GRID_Y; data.useUiWidth = true; data.useUiHeight = true; data.fillVertical = false; return data; } }
jmini/org.eclipsescout.rt.ui.fx
org.eclipsescout.rt.ui.fx/src/org/eclipsescout/rt/ui/fx/form/fields/LogicalGridDataBuilder.java
Java
epl-1.0
3,559
package net.trajano.mojo.cleanpom.internal; import java.util.ResourceBundle; /** * Message constants. */ public final class Messages { /** * Resource bundle. */ private static final ResourceBundle R = ResourceBundle.getBundle("META-INF/Messages"); /** * Transformation failure. */ public static final String TRANSFORM_FAIL = R.getString("transformfail"); /** * Transformation failure due to I/O. */ public static final String TRANSFORM_FAIL_IO = R.getString("transformfailio"); /** * Prevent instantiation of messages class. */ private Messages() { } }
trajano/cleanpom-maven-plugin
src/main/java/net/trajano/mojo/cleanpom/internal/Messages.java
Java
epl-1.0
638
/** */ package org.nasdanika.cdo.security.util; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl; import org.eclipse.emf.ecore.EObject; import org.nasdanika.cdo.security.Action; import org.nasdanika.cdo.security.Group; import org.nasdanika.cdo.security.Guest; import org.nasdanika.cdo.security.LoginPasswordCredentials; import org.nasdanika.cdo.security.LoginPasswordHashUser; import org.nasdanika.cdo.security.LoginPasswordRealm; import org.nasdanika.cdo.security.LoginUser; import org.nasdanika.cdo.security.Permission; import org.nasdanika.cdo.security.Principal; import org.nasdanika.cdo.security.PrincipalPermission; import org.nasdanika.cdo.security.Protected; import org.nasdanika.cdo.security.ProtectedPermission; import org.nasdanika.cdo.security.Realm; import org.nasdanika.cdo.security.SecurityPackage; import org.nasdanika.cdo.security.Token; import org.nasdanika.cdo.security.User; /** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see org.nasdanika.cdo.security.SecurityPackage * @generated */ public class SecurityAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static SecurityPackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public SecurityAdapterFactory() { if (modelPackage == null) { modelPackage = SecurityPackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ @Override public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject)object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch that delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SecuritySwitch<Adapter> modelSwitch = new SecuritySwitch<Adapter>() { @Override public <CR> Adapter caseRealm(Realm<CR> object) { return createRealmAdapter(); } @Override public Adapter casePackage(org.nasdanika.cdo.security.Package object) { return createPackageAdapter(); } @Override public Adapter caseClass(org.nasdanika.cdo.security.Class object) { return createClassAdapter(); } @Override public Adapter caseAction(Action object) { return createActionAdapter(); } @Override public Adapter casePrincipal(Principal object) { return createPrincipalAdapter(); } @Override public Adapter casePermission(Permission object) { return createPermissionAdapter(); } @Override public Adapter casePrincipalPermission(PrincipalPermission object) { return createPrincipalPermissionAdapter(); } @Override public Adapter caseProtectedPermission(ProtectedPermission object) { return createProtectedPermissionAdapter(); } @Override public Adapter caseLoginPasswordCredentials(LoginPasswordCredentials object) { return createLoginPasswordCredentialsAdapter(); } @Override public Adapter caseLoginPasswordRealm(LoginPasswordRealm object) { return createLoginPasswordRealmAdapter(); } @Override public Adapter caseGroup(Group object) { return createGroupAdapter(); } @Override public <CR> Adapter caseUser(User<CR> object) { return createUserAdapter(); } @Override public Adapter caseToken(Token object) { return createTokenAdapter(); } @Override public <CR> Adapter caseLoginUser(LoginUser<CR> object) { return createLoginUserAdapter(); } @Override public Adapter caseLoginPasswordHashUser(LoginPasswordHashUser object) { return createLoginPasswordHashUserAdapter(); } @Override public Adapter caseGuest(Guest object) { return createGuestAdapter(); } @Override public Adapter caseProtected(Protected object) { return createProtectedAdapter(); } @Override public Adapter defaultCase(EObject object) { return createEObjectAdapter(); } }; /** * Creates an adapter for the <code>target</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param target the object to adapt. * @return the adapter for the <code>target</code>. * @generated */ @Override public Adapter createAdapter(Notifier target) { return modelSwitch.doSwitch((EObject)target); } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.Realm <em>Realm</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.Realm * @generated */ public Adapter createRealmAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.Package <em>Package</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.Package * @generated */ public Adapter createPackageAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.Class <em>Class</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.Class * @generated */ public Adapter createClassAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.Principal <em>Principal</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.Principal * @generated */ public Adapter createPrincipalAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.Group <em>Group</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.Group * @generated */ public Adapter createGroupAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.User <em>User</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.User * @generated */ public Adapter createUserAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.Token <em>Token</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.Token * @generated */ public Adapter createTokenAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.LoginUser <em>Login User</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.LoginUser * @generated */ public Adapter createLoginUserAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.LoginPasswordHashUser <em>Login Password Hash User</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.LoginPasswordHashUser * @generated */ public Adapter createLoginPasswordHashUserAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.Guest <em>Guest</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.Guest * @generated */ public Adapter createGuestAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.Protected <em>Protected</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.Protected * @generated */ public Adapter createProtectedAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.Action <em>Action</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.Action * @generated */ public Adapter createActionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.Permission <em>Permission</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.Permission * @generated */ public Adapter createPermissionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.PrincipalPermission <em>Principal Permission</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.PrincipalPermission * @generated */ public Adapter createPrincipalPermissionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.ProtectedPermission <em>Protected Permission</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.ProtectedPermission * @generated */ public Adapter createProtectedPermissionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.LoginPasswordCredentials <em>Login Password Credentials</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.LoginPasswordCredentials * @generated */ public Adapter createLoginPasswordCredentialsAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.nasdanika.cdo.security.LoginPasswordRealm <em>Login Password Realm</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.nasdanika.cdo.security.LoginPasswordRealm * @generated */ public Adapter createLoginPasswordRealmAdapter() { return null; } /** * Creates a new adapter for the default case. * <!-- begin-user-doc --> * This default implementation returns null. * <!-- end-user-doc --> * @return the new adapter. * @generated */ public Adapter createEObjectAdapter() { return null; } } //SecurityAdapterFactory
Nasdanika/server
org.nasdanika.cdo.security/src/org/nasdanika/cdo/security/util/SecurityAdapterFactory.java
Java
epl-1.0
13,822
package org.jboss.forge.addon.parser.java; /* * Copyright 2012 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import java.io.File; import javax.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.forge.addon.parser.java.resources.JavaResource; import org.jboss.forge.addon.resource.Resource; import org.jboss.forge.addon.resource.ResourceFactory; import org.jboss.forge.arquillian.AddonDependency; import org.jboss.forge.arquillian.Dependencies; import org.jboss.forge.arquillian.archive.ForgeArchive; import org.jboss.forge.furnace.repositories.AddonDependencyEntry; import org.jboss.forge.parser.JavaParser; import org.jboss.forge.parser.java.JavaClass; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) public class JavaParserResourcesTest { @Deployment @Dependencies({ @AddonDependency(name = "org.jboss.forge.furnace.container:cdi"), @AddonDependency(name = "org.jboss.forge.addon:resources"), @AddonDependency(name = "org.jboss.forge.addon:parser-java") }) public static ForgeArchive getDeployment() { ForgeArchive archive = ShrinkWrap .create(ForgeArchive.class) .addBeansXML() .addAsAddonDependencies( AddonDependencyEntry.create("org.jboss.forge.furnace.container:cdi"), AddonDependencyEntry.create("org.jboss.forge.addon:parser-java"), AddonDependencyEntry.create("org.jboss.forge.addon:resources") ); return archive; } @Inject private ResourceFactory factory; @Test public void testJavaResourceCreation() throws Exception { JavaClass javaClass = JavaParser.create(JavaClass.class).setPackage("org.jboss.forge.test").setName("Example"); JavaResource resource = factory.create(JavaResource.class, File.createTempFile("forge", ".java")); resource.createNewFile(); resource.setContents(javaClass); Assert.assertEquals("Example", resource.getJavaSource().getName()); Assert.assertEquals("org.jboss.forge.test", resource.getJavaSource().getPackage()); } @Test public void testJavaResourceCreationSpecialized() throws Exception { JavaClass javaClass = JavaParser.create(JavaClass.class).setPackage("org.jboss.forge.test").setName("Example"); JavaResource resource = factory.create(JavaResource.class, File.createTempFile("forge", ".java")); resource.createNewFile(); resource.setContents(javaClass); Resource<File> newResource = factory.create(resource.getUnderlyingResourceObject()); Assert.assertThat(newResource, is(instanceOf(JavaResource.class))); Assert.assertEquals(resource, newResource); } }
stalep/forge-core
parser-java/tests/src/test/java/org/jboss/forge/addon/parser/java/JavaParserResourcesTest.java
Java
epl-1.0
3,121
/* * Copyright (c) 2004 Nu Echo Inc. * * This is free software. For terms and warranty disclaimer, see ./COPYING */ package org.schemeway.plugins.schemescript.interpreter; import org.eclipse.core.resources.*; public interface Interpreter { boolean isRunning(); void start(); void stop(); void restart(); boolean supportInterruption(); void interrupt(); void eval(String code); void load(IFile file); void showConsole(); }
schemeway/SchemeScript
plugin/src/org/schemeway/plugins/schemescript/interpreter/Interpreter.java
Java
epl-1.0
475
package com.aractakipyazilimlari.service; import com.aractakipyazilimlari.model.Ogrenci; public class OgrenciServiceImpl implements OgrenciService { @Override public void smsAtilmaZamaniBelirle(Ogrenci ogrenciID, String sabahMiAksammi) { } @Override public void telefonGuncelle(Ogrenci ogrenciID, String sabahMiAksammi) { // TODO Auto-generated method stub } @Override public void okulaGitmemeDurumunuBildir(Ogrenci ogrenciID, String neGun) { // TODO Auto-generated method stub } @Override public void sikayetOneriBildir(Ogrenci ogrenciID, String mesaj) { // TODO Auto-generated method stub } @Override public void servisDetayGor(Ogrenci ogrenciID) { // TODO Auto-generated method stub } }
aliaksoy/ServisTakip
hibernate/src/main/java/com/aractakipyazilimlari/service/OgrenciServiceImpl.java
Java
epl-1.0
742
/* * Copyright (c) 2010-2012 Research In Motion Limited. All rights reserved. * * This program and the accompanying materials are made available * under the terms of the Eclipse Public License, Version 1.0, * which accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v10.html * */ package net.rim.ejde.internal.ui.launchers; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import net.rim.ejde.internal.core.IConstants; import net.rim.ejde.internal.launching.DeviceInfo; import net.rim.ejde.internal.launching.DeviceProfileManager; import net.rim.ejde.internal.launching.IDeviceLaunchConstants; import net.rim.ejde.internal.launching.IFledgeLaunchConstants; import net.rim.ejde.internal.launching.IRunningFledgeLaunchConstants; import net.rim.ejde.internal.model.BlackBerryVMInstallType; import net.rim.ejde.internal.util.Messages; import net.rim.ejde.internal.util.NatureUtils; import net.rim.ejde.internal.util.ProjectUtils; import net.rim.ejde.internal.util.StatusFactory; import net.rim.ejde.internal.util.VMUtils; import net.rim.ide.SettableProperty; import net.rim.ide.SettablePropertyGroup; import net.rim.ide.SimulatorProfiles; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationType; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.launching.AbstractVMInstall; import org.eclipse.jdt.launching.IVMInstall; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.osgi.util.NLS; /** * Utility class used by launch configuration. * * @author dmeng * */ public class LaunchUtils { private static Logger _logger = Logger.getLogger( LaunchUtils.class ); /** * Returns device info for the given VM. * * @param vm * The BlackBerry VM * @return List of <code>DeviceInfo</code> */ public static List< DeviceInfo > getDevicesInfo( IVMInstall vm ) { List< DeviceInfo > deviceList = DeviceProfileManager.getInstance().getDeviceProfiles( vm ); return deviceList; } /** * Returns the default device info in the given VM. * * @param vm * The VM * @return The default device info */ public static DeviceInfo getDefaultDeviceInfo( IVMInstall vm ) { DeviceInfo defaultDevice = DeviceProfileManager.getInstance().getDefaultDevice( vm ); return defaultDevice; } /** * Returns the device info for the given simulator profile. * * @param profiles * The <code>SimulatorProfiles</code> * @param profileName * The profile name * @return The device info in the given profile */ public static List< DeviceInfo > getDevicesInfo( SimulatorProfiles profiles, String profileName ) { List< DeviceInfo > deviceNames = new ArrayList< DeviceInfo >(); SettablePropertyGroup[] propGroups = profiles.getSettableProperties( profileName ); for( int groupIndex = 0; groupIndex < propGroups.length; groupIndex++ ) { SettableProperty[] properties = propGroups[ groupIndex ].getProperties(); for( int propIndex = 0; propIndex < properties.length; propIndex++ ) { if( properties[ propIndex ].getLabel().equals( IFledgeLaunchConstants.SETTABLE_PROPERTY_DEVICE ) ) { String[] choices = properties[ propIndex ].getChoices(); // filter out Default and blank for( int k = 0; k < choices.length; k++ ) { if( !choices[ k ].equals( IConstants.EMPTY_STRING ) && !choices[ k ].equals( IFledgeLaunchConstants.SETTABLE_PROPERTY_DEVICE_DEFAULT ) ) { // for default simulators, don't need set directory and config file name deviceNames.add( new DeviceInfo( IFledgeLaunchConstants.DEFAULT_SIMULATOR_BUNDLE_NAME, choices[ k ], "", choices[ k ] ) ); } } return deviceNames; } } } return Collections.emptyList(); } /** * Returns BlackBerry VM used to launch the given projects. * * @param projects * The list of <code>IProject</code> * @return The <code>IVMInstall</code> or <code>null</code> if not found. */ public static IVMInstall getDefaultLaunchVM( Collection< IProject > projects ) { IVMInstall targetVM = null; for( IProject project : projects ) { IVMInstall vm = ProjectUtils.getVMForProject( JavaCore.create( project ) ); if( vm != null ) { if( targetVM != null ) { // use the highest version of VM if( vm.getId().compareTo( targetVM.getId() ) > 0 ) { targetVM = vm; } } else { targetVM = vm; } } } return targetVM; } /** * Get the projects defined in the given launch configuration. * * @param configuration * The launch configuration * @return The collection of projects */ @SuppressWarnings("unchecked") public static Set< IProject > getProjectsFromConfiguration( ILaunchConfiguration configuration ) { List< String > checkedProjectNames; try { checkedProjectNames = configuration.getAttribute( IFledgeLaunchConstants.ATTR_DEPLOYED_PROJECTS, Collections.EMPTY_LIST ); } catch( CoreException e ) { _logger.error( e ); return Collections.emptySet(); } Set< IProject > checkedProjects = new HashSet< IProject >(); for( String name : checkedProjectNames ) { IResource ires = ResourcesPlugin.getWorkspace().getRoot().findMember( name ); if( ires != null && ires instanceof IProject ) { IProject project = (IProject) ires; // this also filters out closed projects if( project.isOpen() ) { checkedProjects.add( project ); } } } return checkedProjects; } /** * Get the highest VM in the given projects. * * @param projects * The projects * @return The highest version of VM or <code>null</code> if all VMs are uninstalled */ public static IVMInstall getHighestVMInProjects( Collection< IProject > projects ) { IVMInstall targetVM = null; for( IProject project : projects ) { IVMInstall vm = ProjectUtils.getVMForProject( JavaCore.create( project ) ); // The VM must be available if( vm != null ) { if( targetVM != null ) { if( vm.getId().compareTo( targetVM.getId() ) > 0 ) { targetVM = vm; } } else { targetVM = vm; } } } return targetVM; } /** * Returns current running BlackBerry launch, could be Simulator, Device or Running Simulator launch. * * @return The BlackBerry launch or <code>null</code> if running BB launch does not exist. */ public static ILaunch getRunningBBLaunch() { ILaunch[] launches = DebugPlugin.getDefault().getLaunchManager().getLaunches(); for( int i = 0; i < launches.length; i++ ) { if( !launches[ i ].isTerminated() ) { try { ILaunchConfiguration configuration = launches[ i ].getLaunchConfiguration(); if( configuration != null ) { ILaunchConfigurationType launchType = configuration.getType(); if( launchType.getIdentifier().equals( IFledgeLaunchConstants.LAUNCH_CONFIG_ID ) || launchType.getIdentifier().equals( IRunningFledgeLaunchConstants.LAUNCH_CONFIG_ID ) || launchType.getIdentifier().equals( IDeviceLaunchConstants.LAUNCH_CONFIG_ID ) ) { return launches[ i ]; } } } catch( CoreException e ) { _logger.error( e ); } } } return null; } /** * Get list of <code>IProject</code> from the selection. * * @param selection * @return The list of <code>IProject</code> */ public static List< IProject > getSelectedProjects( StructuredSelection selection ) { Object[] items = selection.toArray(); List< IProject > projects = new ArrayList< IProject >(); IProject iproject; for( int i = 0; i < items.length; i++ ) { iproject = null; if( items[ i ] instanceof IAdaptable ) { Object ires = ( (IAdaptable) items[ i ] ).getAdapter( IResource.class ); if( ires != null ) { iproject = ( (IResource) ires ).getProject(); } } if( iproject != null ) { if( NatureUtils.hasBBNature( iproject ) && !projects.contains( iproject ) ) { projects.add( iproject ); } } } return projects; } /** * Returns the VM in the given launch configuration. * * @param configuration * The <code>ILaunchConfiguration</code> * @return The <code>IVMInstall</code> or <code>null</code> if BB-VM is not found. */ public static IVMInstall getVMFromConfiguration( ILaunchConfiguration configuration ) { IVMInstall vm = null; try { int vmType = configuration.getAttribute( IFledgeLaunchConstants.ATTR_JRE_TYPE, IFledgeLaunchConstants.DEFAULT_JRE_TYPE ); if( vmType == IFledgeLaunchConstants.JRE_TYPE_PROJECT ) { Set< IProject > projects = getProjectsFromConfiguration( configuration ); vm = getDefaultLaunchVM( projects ); } else if( vmType == IFledgeLaunchConstants.JRE_TYPE_ALTERNATE ) { String vmId = configuration.getAttribute( IFledgeLaunchConstants.ATTR_JRE_ID, StringUtils.EMPTY ); if( !vmId.equals( StringUtils.EMPTY ) ) { vm = VMUtils.findVMById( vmId ); } } } catch( CoreException e ) { _logger.error( e ); } return vm; } /** * Returns the device name associated with the given launch configuration. * * @param configuration * The launch configuration * @return The device name or empty string if any error occurs */ public static DeviceInfo getDeviceInfo( ILaunchConfiguration configuration ) { try { String simDir = configuration.getAttribute( IFledgeLaunchConstants.ATTR_GENERAL_SIM_DIR, StringUtils.EMPTY ); String bundleName = configuration.getAttribute( IFledgeLaunchConstants.ATTR_GENERAL_BUNDLE, StringUtils.EMPTY ); String deviceName = configuration.getAttribute( IFledgeLaunchConstants.ATTR_GENERAL_DEVICE, StringUtils.EMPTY ); String configFile = configuration.getAttribute( IFledgeLaunchConstants.ATTR_GENERAL_CONFIG_FILE, StringUtils.EMPTY ); IVMInstall vm = LaunchUtils.getVMFromConfiguration( configuration ); List< DeviceInfo > devices = LaunchUtils.getDevicesInfo( vm ); DeviceInfo di = new DeviceInfo( bundleName, deviceName, simDir, configFile ); if( !devices.contains( di ) ) { return LaunchUtils.getDefaultDeviceInfo( vm ); } return di; } catch( CoreException e ) { _logger.error( e ); } return null; } /** * Returns the String attribute value stored in the launch configuration. * * @param configuration * The launch configuration * @param attribute * The attribute * @return The attribute value */ public static String getStringAttribute( ILaunchConfiguration configuration, String attribute, String defaultValue ) { String ret = defaultValue; try { ret = configuration.getAttribute( attribute, defaultValue ); } catch( CoreException e ) { _logger.error( e.getMessage() ); } return ret; } /** * Returns the boolean attribute value stored in the launch configuration. * * @param configuration * The launch configuration * @param attribute * The attribute * @return The attribute value */ public static boolean getBooleanAttribute( ILaunchConfiguration configuration, String attribute, boolean defaultValue ) { boolean ret = defaultValue; try { ret = configuration.getAttribute( attribute, defaultValue ); } catch( CoreException e ) { _logger.error( e.getMessage() ); } return ret; } /** * Returns the simulator path for the given VM. * * @param vm * The VM * @return The simulator path */ public static String getSimualtorPath( IVMInstall vm ) { String simulatorPath; String isInternal = ( (AbstractVMInstall) vm ).getAttribute( BlackBerryVMInstallType.ATTR_INTERNAL ); if( isInternal != null && Integer.parseInt( isInternal ) == 1 ) { simulatorPath = vm.getInstallLocation().getPath() + File.separator + "debug"; } else { simulatorPath = vm.getInstallLocation().getPath() + File.separator + "simulator"; } return simulatorPath; } /** * Returns the fledge.exe path for the given VM. * * @param vm * The VM * @return The fledge.exe path */ public static String getFledgeExePath( IVMInstall vm ) { String fledgePath; String isInternal = ( (AbstractVMInstall) vm ).getAttribute( BlackBerryVMInstallType.ATTR_INTERNAL ); if( isInternal != null && Integer.parseInt( isInternal ) == 1 ) { fledgePath = vm.getInstallLocation().getPath() + File.separator + "fledge" + File.separator + "bin"; } else { fledgePath = vm.getInstallLocation().getPath() + File.separator + "simulator"; } return fledgePath; } public static DeviceInfo getDeviceToLaunch( ILaunchConfiguration configuration ) throws CoreException { String bundleName = configuration.getAttribute( IFledgeLaunchConstants.ATTR_GENERAL_BUNDLE, StringUtils.EMPTY ); String simDir = configuration.getAttribute( IFledgeLaunchConstants.ATTR_GENERAL_SIM_DIR, StringUtils.EMPTY ); String deviceName = configuration.getAttribute( IFledgeLaunchConstants.ATTR_GENERAL_DEVICE, StringUtils.EMPTY ); String configFileName = configuration.getAttribute( IFledgeLaunchConstants.ATTR_GENERAL_CONFIG_FILE, StringUtils.EMPTY ); IVMInstall vm = LaunchUtils.getVMFromConfiguration( configuration ); List< DeviceInfo > devices = LaunchUtils.getDevicesInfo( vm ); if( devices.isEmpty() ) { throw new CoreException( StatusFactory.createErrorStatus( NLS.bind( Messages.Launch_Error_DeviceNotFound, vm.getId() ) ) ); } if( !devices.contains( new DeviceInfo( bundleName, deviceName, simDir, configFileName ) ) ) { // JRE is changed, choose the default device instead DeviceInfo di = LaunchUtils.getDefaultDeviceInfo( vm ); if( di != null ) { bundleName = di.getBundleName(); simDir = di.getDirectory(); deviceName = di.getDeviceName(); configFileName = di.getConfigName(); // save the changes ILaunchConfigurationWorkingCopy workingCopy = configuration.getWorkingCopy(); workingCopy.setAttribute( IFledgeLaunchConstants.ATTR_GENERAL_BUNDLE, bundleName ); workingCopy.setAttribute( IFledgeLaunchConstants.ATTR_GENERAL_SIM_DIR, simDir ); workingCopy.setAttribute( IFledgeLaunchConstants.ATTR_GENERAL_DEVICE, deviceName ); workingCopy.setAttribute( IFledgeLaunchConstants.ATTR_GENERAL_CONFIG_FILE, configFileName ); workingCopy.doSave(); } else { throw new CoreException( StatusFactory.createErrorStatus( NLS.bind( Messages.Launch_Error_DefaultDeviceNotFound, vm.getId() ) ) ); } } return new DeviceInfo( bundleName, deviceName, simDir, configFileName ); } /** * Close the given launch, it terminates the launch first (if supported) and remove it from launch manager. * * @param launch * The launch to be closed * @throws DebugException */ public static void closeLaunch( ILaunch launch ) throws DebugException { if( launch != null ) { if( launch.canTerminate() ) { launch.terminate(); } DebugPlugin.getDefault().getLaunchManager().removeLaunch( launch ); } } /** * Returns the VM name used in the given launch configuration. * * @param configuration * The launch configuration * @return The VM name or "undefined" if the vm has been removed */ public static String getVMNameFromConfiguration( ILaunchConfiguration configuration ) { String vmName = "undefined"; try { int vmType = configuration.getAttribute( IFledgeLaunchConstants.ATTR_JRE_TYPE, IFledgeLaunchConstants.DEFAULT_JRE_TYPE ); if( vmType == IFledgeLaunchConstants.JRE_TYPE_PROJECT ) { Set< IProject > projects = getProjectsFromConfiguration( configuration ); IVMInstall vm = getDefaultLaunchVM( projects ); if( vm != null ) { vmName = vm.getName(); } } else if( vmType == IFledgeLaunchConstants.JRE_TYPE_ALTERNATE ) { vmName = configuration.getAttribute( IFledgeLaunchConstants.ATTR_JRE_ID, StringUtils.EMPTY ); } } catch( CoreException e ) { _logger.error( e ); } return vmName; } }
blackberry/Eclipse-JDE
net.rim.ejde/src/net/rim/ejde/internal/ui/launchers/LaunchUtils.java
Java
epl-1.0
19,677
/* * Copyright (c) 2012-2017 Red Hat, Inc. * 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 * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.selenium.pageobject; import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.REDRAW_UI_ELEMENTS_TIMEOUT_SEC; import com.google.common.base.Predicate; import com.google.inject.Inject; import com.google.inject.Singleton; import java.util.List; import org.eclipse.che.selenium.core.SeleniumWebDriver; import org.eclipse.che.selenium.core.action.ActionsFactory; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; /** @author Aleksandr Shmaraev */ @Singleton public class FindText { private final SeleniumWebDriver seleniumWebDriver; private final Loader loader; private final ActionsFactory actionsFactory; @Inject public FindText( SeleniumWebDriver seleniumWebDriver, Loader loader, ActionsFactory actionsFactory) { this.seleniumWebDriver = seleniumWebDriver; this.loader = loader; this.actionsFactory = actionsFactory; PageFactory.initElements(seleniumWebDriver, this); } private interface Locators { String MAIN_FORM = "gwt-debug-text-search-mainPanel"; String FIND_TEXT_INPUT = "gwt-debug-text-search-text"; String WHOLE_WORD_CHECKLBOX_SPAN = "gwt-debug-wholeWordsOnly-selector"; String WHOLE_WORD_CHECKLBOX_INP = "gwt-debug-wholeWordsOnly-selector-input"; String SEARCH_ROOT_CHECKBOX_SPAN = "//div[text()='Scope']/following::span[1]"; String SEARCH_ROOT_CHECKBOX_INP = "//div[text()='Scope']/following::input[1]"; String SEARCH_DIR_FIELD = "gwt-debug-text-search-directory"; String SEARCH_DIR_BUTTON = "gwt-debug-text-search-directory-button"; String FILE_MASK_CHECKBOX_SPAN = "//div[text()='File name filter']/following::span[1]"; String FILE_MASK_CHECKBOX_INP = "//div[text()='File name filter']/following::input[1]"; String FILE_MASK_FIELD = "gwt-debug-text-search-files"; String CANCEL_BUTTON = "search-cancel-button"; String SEARCH_BUTTON = "search-button"; String FIND_INFO_PANEL = "gwt-debug-find-info-panel"; String FIND_TAB = "gwt-debug-partButton-Find"; String HIDE_FIND_PANEL = "//div[@id='gwt-debug-find-info-panel']//div[text()='Find']/following::div[3]"; String OCCURRENCE = "//span[@debugfilepath = '%s']"; } @FindBy(id = Locators.WHOLE_WORD_CHECKLBOX_INP) WebElement wholeWordCheckBox; @FindBy(xpath = Locators.SEARCH_ROOT_CHECKBOX_INP) WebElement searchRootCheckBox; @FindBy(xpath = Locators.FILE_MASK_CHECKBOX_INP) WebElement fileMaskCheckBox; @FindBy(id = Locators.FIND_INFO_PANEL) WebElement findInfoPanel; @FindBy(id = Locators.FIND_TAB) WebElement findTab; /** wait the 'Find Text' main form is open */ public void waitFindTextMainFormIsOpen() { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.visibilityOfElementLocated(By.id(Locators.MAIN_FORM))); } /** launch the 'Find' main form by keyboard */ public void launchFindFormByKeyboard() { loader.waitOnClosed(); Actions action = actionsFactory.createAction(seleniumWebDriver); action .keyDown(Keys.CONTROL) .keyDown(Keys.SHIFT) .sendKeys("f") .keyUp(Keys.SHIFT) .keyUp(Keys.CONTROL) .perform(); } /** wait the 'Find Text' main form is closed */ public void waitFindTextMainFormIsClosed() { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.invisibilityOfElementLocated(By.id(Locators.MAIN_FORM))); } /** close main form by pressing 'Ctrl' key */ public void closeFindTextFormByEscape() { loader.waitOnClosed(); actionsFactory.createAction(seleniumWebDriver).sendKeys(Keys.ESCAPE.toString()).perform(); waitFindTextMainFormIsClosed(); } /** close main form by pressing 'Cancel' button */ public void closeFindTextMainForm() { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.visibilityOfElementLocated(By.id(Locators.CANCEL_BUTTON))) .click(); waitFindTextMainFormIsClosed(); } /** wait the 'Search' button is disabled on the main form */ public void waitSearchBtnMainFormIsDisabled() { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until( ExpectedConditions.not( ExpectedConditions.elementToBeClickable(By.id(Locators.SEARCH_BUTTON)))); } /** press on the 'Search' button on the main form */ public void clickOnSearchButtonMainForm() { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.elementToBeClickable(By.id(Locators.SEARCH_BUTTON))) .click(); waitFindTextMainFormIsClosed(); } /** * type text into 'Text to find' field * * @param text is text that need to find */ public void typeTextIntoFindField(String text) { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.visibilityOfElementLocated(By.id(Locators.FIND_TEXT_INPUT))) .clear(); loader.waitOnClosed(); new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.visibilityOfElementLocated(By.id(Locators.FIND_TEXT_INPUT))) .sendKeys(text); } /** * wait text into 'Text to find' field * * @param expText is expected text */ public void waitTextIntoFindField(String expText) { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until( (ExpectedCondition<Boolean>) webDriver -> seleniumWebDriver .findElement(By.id(Locators.FIND_TEXT_INPUT)) .getAttribute("value") .equals(expText)); } /** * Set the 'Whole word only' checkbox to specified state and wait it state * * @param state state of checkbox (true if checkbox must be selected) */ public void setAndWaitWholeWordCheckbox(boolean state) { if (state) { if (!wholeWordCheckBox.isSelected()) { clickOnWholeWordCheckbox(); waitWholeWordIsSelected(); } } else { if (wholeWordCheckBox.isSelected()) { clickOnWholeWordCheckbox(); waitWholeWordIsNotSelected(); } } } /** click on the 'Whole word only' checkbox */ public void clickOnWholeWordCheckbox() { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until( ExpectedConditions.visibilityOfElementLocated( By.id(Locators.WHOLE_WORD_CHECKLBOX_SPAN))) .click(); } /** wait the 'Whole word only' checkbox is selected */ public void waitWholeWordIsSelected() { String locator = Locators.WHOLE_WORD_CHECKLBOX_INP; new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.elementSelectionStateToBe(By.id(locator), true)); } /** wait the 'Whole word only' checkbox is not selected */ public void waitWholeWordIsNotSelected() { String locator = Locators.WHOLE_WORD_CHECKLBOX_INP; new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.elementSelectionStateToBe(By.id(locator), false)); } /** * Set the 'Search root' checkbox to specified state and wait it state * * @param state state of checkbox (true if checkbox must be selected) */ public void setAndWaitStateSearchRootCheckbox(boolean state) { if (state) { if (!searchRootCheckBox.isSelected()) { clickOnSearchRootCheckbox(); waitSearchRootIsSelected(); } } else { if (searchRootCheckBox.isSelected()) { clickOnSearchRootCheckbox(); waitSearchRootIsNotSelected(); } } } /** click on the 'Search root' checkbox */ public void clickOnSearchRootCheckbox() { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until( ExpectedConditions.visibilityOfElementLocated( By.xpath(Locators.SEARCH_ROOT_CHECKBOX_SPAN))) .click(); } /** wait the 'Search root' checkbox is selected */ public void waitSearchRootIsSelected() { String locator = Locators.SEARCH_ROOT_CHECKBOX_INP; new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.elementSelectionStateToBe(By.xpath(locator), true)); } /** wait the 'Search root' checkbox is not selected */ public void waitSearchRootIsNotSelected() { String locator = Locators.SEARCH_ROOT_CHECKBOX_INP; new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.elementSelectionStateToBe(By.xpath(locator), false)); } /** * wait path into 'Search root' field * * @param path is the expected path */ public void waitPathIntoRootField(String path) { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until( (ExpectedCondition<Boolean>) webDriver -> seleniumWebDriver .findElement(By.id(Locators.SEARCH_DIR_FIELD)) .getAttribute("value") .equals(path)); } /** press on the search directory button */ public void clickSearchDirectoryBtn() { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.elementToBeClickable(By.id(Locators.SEARCH_DIR_BUTTON))) .click(); } /** * Set the 'File mask' checkbox to specified state and wait it state * * @param state state of checkbox (true if checkbox must be selected) */ public void setAndWaitFileMaskCheckbox(boolean state) { if (state) { if (!fileMaskCheckBox.isSelected()) { clickOnFileMaskCheckbox(); waitFileMaskIsSelected(); } } else { if (fileMaskCheckBox.isSelected()) { clickOnWholeWordCheckbox(); waitFileMaskIsNotSelected(); } } } /** click on the 'File mask' checkbox */ public void clickOnFileMaskCheckbox() { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until( ExpectedConditions.visibilityOfElementLocated( By.xpath(Locators.FILE_MASK_CHECKBOX_SPAN))) .click(); } /** wait the 'File mask' checkbox is selected */ public void waitFileMaskIsSelected() { String locator = Locators.FILE_MASK_CHECKBOX_INP; new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.elementSelectionStateToBe(By.xpath(locator), true)); } /** wait the 'File mask' checkbox is not selected */ public void waitFileMaskIsNotSelected() { String locator = Locators.FILE_MASK_CHECKBOX_INP; new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.elementSelectionStateToBe(By.xpath(locator), false)); } /** * type text into 'FileNameFilter' field * * @param text is symbol or string */ public void typeTextIntoFileNameFilter(String text) { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.visibilityOfElementLocated(By.id(Locators.FILE_MASK_FIELD))) .clear(); loader.waitOnClosed(); new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.visibilityOfElementLocated(By.id(Locators.FILE_MASK_FIELD))) .sendKeys(text); } /** * wait text into 'FileNameFilter' field * * @param expText is expected text */ public void waitTextIntoFileNameFilter(String expText) { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until( (ExpectedCondition<Boolean>) webDriver -> seleniumWebDriver .findElement(By.id(Locators.FILE_MASK_FIELD)) .getAttribute("value") .equals(expText)); } /** wait the 'Find' info panel is open */ public void waitFindInfoPanelIsOpen() { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.visibilityOfElementLocated(By.id(Locators.FIND_INFO_PANEL))); } /** press on the 'Hide' button on the 'Find' info panel */ public void clickHideBtnFindInfoPanel() { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.elementToBeClickable(By.xpath(Locators.HIDE_FIND_PANEL))) .click(); waitFindInfoPanelIsClosed(); } /** wait the 'Find' info panel is closed */ public void waitFindInfoPanelIsClosed() { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.invisibilityOfElementLocated(By.id(Locators.FIND_INFO_PANEL))); } /** click on the find tab */ public void clickFindTab() { loader.waitOnClosed(); new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until(ExpectedConditions.visibilityOf(findTab)) .click(); loader.waitOnClosed(); } /** * wait expected text in the 'Find' info panel * * @param expText expected value */ public void waitExpectedTextInFindInfoPanel(String expText) { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until((WebDriver driver) -> getTextFromFindInfoPanel().contains(expText)); } /** * wait expected text in the 'Find' info panel * * @param expText list of expected values */ public void waitExpectedTextInFindInfoPanel(List<String> expText) { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until( (Predicate<WebDriver>) input -> expText .stream() .allMatch( t -> { String textFromFindInfoPanel = getTextFromFindInfoPanel(); return textFromFindInfoPanel.contains(t); })); } /** * wait the text is not present in the 'Find' info panel * * @param expText expected value */ public void waitExpectedTextIsNotPresentInFindInfoPanel(String expText) { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until((WebDriver driver) -> !(getTextFromFindInfoPanel().contains(expText))); } /** * get text - representation content from 'Find' info panel * * @return text from 'find usages' panel */ public String getTextFromFindInfoPanel() { return findInfoPanel.getText(); } public void selectItemInFindInfoPanel(String fileName, String textToFind) { List<WebElement> webElementList = new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until( ExpectedConditions.visibilityOfAllElementsLocatedBy( By.xpath(String.format(Locators.OCCURRENCE, fileName)))); for (WebElement webElement : webElementList) { if (webElement.getText().equals(textToFind)) { webElement.click(); break; } } } public void selectItemInFindInfoPanelByDoubleClick(String fileName, String textToFind) { List<WebElement> webElementList = new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until( ExpectedConditions.visibilityOfAllElementsLocatedBy( By.xpath(String.format(Locators.OCCURRENCE, fileName)))); for (WebElement webElement : webElementList) { if (webElement.getText().equals(textToFind)) { actionsFactory.createAction(seleniumWebDriver).doubleClick(webElement).perform(); break; } } } /** * send a keys by keyboard in the 'Find' info panel * * @param command is the command by keyboard */ public void sendCommandByKeyboardInFindInfoPanel(String command) { loader.waitOnClosed(); actionsFactory.createAction(seleniumWebDriver).sendKeys(command).perform(); loader.waitOnClosed(); } }
TypeFox/che
selenium/che-selenium-test/src/main/java/org/eclipse/che/selenium/pageobject/FindText.java
Java
epl-1.0
16,930
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2 // 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: 2015.09.23 at 11:07:02 AM CEST // package org.cxml.catalog; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "unitOfMeasure", "description" }) @XmlRootElement(name = "PriceBasisQuantity") public class PriceBasisQuantity { @XmlAttribute(name = "quantity", required = true) @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String quantity; @XmlAttribute(name = "conversionFactor", required = true) @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String conversionFactor; @XmlElement(name = "UnitOfMeasure", required = true) protected String unitOfMeasure; @XmlElement(name = "Description") protected Description description; /** * Gets the value of the quantity property. * * @return * possible object is * {@link String } * */ public String getQuantity() { return quantity; } /** * Sets the value of the quantity property. * * @param value * allowed object is * {@link String } * */ public void setQuantity(String value) { this.quantity = value; } /** * Gets the value of the conversionFactor property. * * @return * possible object is * {@link String } * */ public String getConversionFactor() { return conversionFactor; } /** * Sets the value of the conversionFactor property. * * @param value * allowed object is * {@link String } * */ public void setConversionFactor(String value) { this.conversionFactor = value; } /** * Gets the value of the unitOfMeasure property. * * @return * possible object is * {@link String } * */ public String getUnitOfMeasure() { return unitOfMeasure; } /** * Sets the value of the unitOfMeasure property. * * @param value * allowed object is * {@link String } * */ public void setUnitOfMeasure(String value) { this.unitOfMeasure = value; } /** * Gets the value of the description property. * * @return * possible object is * {@link Description } * */ public Description getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link Description } * */ public void setDescription(Description value) { this.description = value; } }
bradsdavis/cxml-api
src/main/java/org/cxml/catalog/PriceBasisQuantity.java
Java
epl-1.0
3,424
/** */ package eu.mondo.collaboration.operationtracemodel.example.WTSpec.presentation; import java.util.ArrayList; import java.util.Collection; import org.eclipse.emf.common.ui.viewer.IViewerProvider; import org.eclipse.emf.edit.domain.EditingDomain; import org.eclipse.emf.edit.domain.IEditingDomainProvider; import org.eclipse.emf.edit.ui.action.ControlAction; import org.eclipse.emf.edit.ui.action.CreateChildAction; import org.eclipse.emf.edit.ui.action.CreateSiblingAction; import org.eclipse.emf.edit.ui.action.EditingDomainActionBarContributor; import org.eclipse.emf.edit.ui.action.LoadResourceAction; import org.eclipse.emf.edit.ui.action.ValidateAction; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.action.IContributionManager; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.action.SubContributionItem; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.PartInitException; /** * This is the action bar contributor for the WTSpec model editor. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class WTSpecActionBarContributor extends EditingDomainActionBarContributor implements ISelectionChangedListener { /** * This keeps track of the active editor. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IEditorPart activeEditorPart; /** * This keeps track of the current selection provider. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ISelectionProvider selectionProvider; /** * This action opens the Properties view. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IAction showPropertiesViewAction = new Action(WTSpec2EditorPlugin.INSTANCE.getString("_UI_ShowPropertiesView_menu_item")) { @Override public void run() { try { getPage().showView("org.eclipse.ui.views.PropertySheet"); } catch (PartInitException exception) { WTSpec2EditorPlugin.INSTANCE.log(exception); } } }; /** * This action refreshes the viewer of the current editor if the editor * implements {@link org.eclipse.emf.common.ui.viewer.IViewerProvider}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IAction refreshViewerAction = new Action(WTSpec2EditorPlugin.INSTANCE.getString("_UI_RefreshViewer_menu_item")) { @Override public boolean isEnabled() { return activeEditorPart instanceof IViewerProvider; } @Override public void run() { if (activeEditorPart instanceof IViewerProvider) { Viewer viewer = ((IViewerProvider)activeEditorPart).getViewer(); if (viewer != null) { viewer.refresh(); } } } }; /** * This will contain one {@link org.eclipse.emf.edit.ui.action.CreateChildAction} corresponding to each descriptor * generated for the current selection by the item provider. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Collection<IAction> createChildActions; /** * This is the menu manager into which menu contribution items should be added for CreateChild actions. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IMenuManager createChildMenuManager; /** * This will contain one {@link org.eclipse.emf.edit.ui.action.CreateSiblingAction} corresponding to each descriptor * generated for the current selection by the item provider. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Collection<IAction> createSiblingActions; /** * This is the menu manager into which menu contribution items should be added for CreateSibling actions. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IMenuManager createSiblingMenuManager; /** * This creates an instance of the contributor. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public WTSpecActionBarContributor() { super(ADDITIONS_LAST_STYLE); loadResourceAction = new LoadResourceAction(); validateAction = new ValidateAction(); controlAction = new ControlAction(); } /** * This adds Separators for editor additions to the tool bar. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void contributeToToolBar(IToolBarManager toolBarManager) { toolBarManager.add(new Separator("wtspec-settings")); toolBarManager.add(new Separator("wtspec-additions")); } /** * This adds to the menu bar a menu and some separators for editor additions, * as well as the sub-menus for object creation items. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void contributeToMenu(IMenuManager menuManager) { super.contributeToMenu(menuManager); IMenuManager submenuManager = new MenuManager(WTSpec2EditorPlugin.INSTANCE.getString("_UI_WTSpecEditor_menu"), "WTSpecMenuID"); menuManager.insertAfter("additions", submenuManager); submenuManager.add(new Separator("settings")); submenuManager.add(new Separator("actions")); submenuManager.add(new Separator("additions")); submenuManager.add(new Separator("additions-end")); // Prepare for CreateChild item addition or removal. // createChildMenuManager = new MenuManager(WTSpec2EditorPlugin.INSTANCE.getString("_UI_CreateChild_menu_item")); submenuManager.insertBefore("additions", createChildMenuManager); // Prepare for CreateSibling item addition or removal. // createSiblingMenuManager = new MenuManager(WTSpec2EditorPlugin.INSTANCE.getString("_UI_CreateSibling_menu_item")); submenuManager.insertBefore("additions", createSiblingMenuManager); // Force an update because Eclipse hides empty menus now. // submenuManager.addMenuListener (new IMenuListener() { public void menuAboutToShow(IMenuManager menuManager) { menuManager.updateAll(true); } }); addGlobalActions(submenuManager); } /** * When the active editor changes, this remembers the change and registers with it as a selection provider. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setActiveEditor(IEditorPart part) { super.setActiveEditor(part); activeEditorPart = part; // Switch to the new selection provider. // if (selectionProvider != null) { selectionProvider.removeSelectionChangedListener(this); } if (part == null) { selectionProvider = null; } else { selectionProvider = part.getSite().getSelectionProvider(); selectionProvider.addSelectionChangedListener(this); // Fake a selection changed event to update the menus. // if (selectionProvider.getSelection() != null) { selectionChanged(new SelectionChangedEvent(selectionProvider, selectionProvider.getSelection())); } } } /** * This implements {@link org.eclipse.jface.viewers.ISelectionChangedListener}, * handling {@link org.eclipse.jface.viewers.SelectionChangedEvent}s by querying for the children and siblings * that can be added to the selected object and updating the menus accordingly. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void selectionChanged(SelectionChangedEvent event) { // Remove any menu items for old selection. // if (createChildMenuManager != null) { depopulateManager(createChildMenuManager, createChildActions); } if (createSiblingMenuManager != null) { depopulateManager(createSiblingMenuManager, createSiblingActions); } // Query the new selection for appropriate new child/sibling descriptors // Collection<?> newChildDescriptors = null; Collection<?> newSiblingDescriptors = null; ISelection selection = event.getSelection(); if (selection instanceof IStructuredSelection && ((IStructuredSelection)selection).size() == 1) { Object object = ((IStructuredSelection)selection).getFirstElement(); EditingDomain domain = ((IEditingDomainProvider)activeEditorPart).getEditingDomain(); newChildDescriptors = domain.getNewChildDescriptors(object, null); newSiblingDescriptors = domain.getNewChildDescriptors(null, object); } // Generate actions for selection; populate and redraw the menus. // createChildActions = generateCreateChildActions(newChildDescriptors, selection); createSiblingActions = generateCreateSiblingActions(newSiblingDescriptors, selection); if (createChildMenuManager != null) { populateManager(createChildMenuManager, createChildActions, null); createChildMenuManager.update(true); } if (createSiblingMenuManager != null) { populateManager(createSiblingMenuManager, createSiblingActions, null); createSiblingMenuManager.update(true); } } /** * This generates a {@link org.eclipse.emf.edit.ui.action.CreateChildAction} for each object in <code>descriptors</code>, * and returns the collection of these actions. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Collection<IAction> generateCreateChildActions(Collection<?> descriptors, ISelection selection) { Collection<IAction> actions = new ArrayList<IAction>(); if (descriptors != null) { for (Object descriptor : descriptors) { actions.add(new CreateChildAction(activeEditorPart, selection, descriptor)); } } return actions; } /** * This generates a {@link org.eclipse.emf.edit.ui.action.CreateSiblingAction} for each object in <code>descriptors</code>, * and returns the collection of these actions. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected Collection<IAction> generateCreateSiblingActions(Collection<?> descriptors, ISelection selection) { Collection<IAction> actions = new ArrayList<IAction>(); if (descriptors != null) { for (Object descriptor : descriptors) { actions.add(new CreateSiblingAction(activeEditorPart, selection, descriptor)); } } return actions; } /** * This populates the specified <code>manager</code> with {@link org.eclipse.jface.action.ActionContributionItem}s * based on the {@link org.eclipse.jface.action.IAction}s contained in the <code>actions</code> collection, * by inserting them before the specified contribution item <code>contributionID</code>. * If <code>contributionID</code> is <code>null</code>, they are simply added. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void populateManager(IContributionManager manager, Collection<? extends IAction> actions, String contributionID) { if (actions != null) { for (IAction action : actions) { if (contributionID != null) { manager.insertBefore(contributionID, action); } else { manager.add(action); } } } } /** * This removes from the specified <code>manager</code> all {@link org.eclipse.jface.action.ActionContributionItem}s * based on the {@link org.eclipse.jface.action.IAction}s contained in the <code>actions</code> collection. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void depopulateManager(IContributionManager manager, Collection<? extends IAction> actions) { if (actions != null) { IContributionItem[] items = manager.getItems(); for (int i = 0; i < items.length; i++) { // Look into SubContributionItems // IContributionItem contributionItem = items[i]; while (contributionItem instanceof SubContributionItem) { contributionItem = ((SubContributionItem)contributionItem).getInnerItem(); } // Delete the ActionContributionItems with matching action. // if (contributionItem instanceof ActionContributionItem) { IAction action = ((ActionContributionItem)contributionItem).getAction(); if (actions.contains(action)) { manager.remove(contributionItem); } } } } } /** * This populates the pop-up menu before it appears. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void menuAboutToShow(IMenuManager menuManager) { super.menuAboutToShow(menuManager); MenuManager submenuManager = null; submenuManager = new MenuManager(WTSpec2EditorPlugin.INSTANCE.getString("_UI_CreateChild_menu_item")); populateManager(submenuManager, createChildActions, null); menuManager.insertBefore("edit", submenuManager); submenuManager = new MenuManager(WTSpec2EditorPlugin.INSTANCE.getString("_UI_CreateSibling_menu_item")); populateManager(submenuManager, createSiblingActions, null); menuManager.insertBefore("edit", submenuManager); } /** * This inserts global actions before the "additions-end" separator. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void addGlobalActions(IMenuManager menuManager) { menuManager.insertAfter("additions-end", new Separator("ui-actions")); menuManager.insertAfter("ui-actions", showPropertiesViewAction); refreshViewerAction.setEnabled(refreshViewerAction.isEnabled()); menuManager.insertAfter("ui-actions", refreshViewerAction); super.addGlobalActions(menuManager); } /** * This ensures that a delete action will clean up all references to deleted objects. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected boolean removeAllReferencesOnDelete() { return true; } }
FTSRG/mondo-collab-framework
archive/workspaceTracker/VA/ikerlanEMF.editor/src/eu/mondo/collaboration/operationtracemodel/example/WTSpec/presentation/WTSpecActionBarContributor.java
Java
epl-1.0
14,407
package link1234gamer.fnafmod.client.model.entity; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; import org.lwjgl.opengl.GL11; /** * FuntimeFoxy - Either Mojang or a mod author * Created using Tabula 4.1.1 */ public class ModelPre_Mangle extends ModelBase { public double[] modelScale = new double[] { 0.9D, 0.9D, 0.9D }; public ModelRenderer RightArm; public ModelRenderer Body; public ModelRenderer LeftArm; public ModelRenderer RightLeg; public ModelRenderer LeftLeg; public ModelRenderer Head; public ModelRenderer RightUnderArm; public ModelRenderer RightUpperArm; public ModelRenderer Hookpart1; public ModelRenderer Hookpart2; public ModelRenderer hookHandChildChild; public ModelRenderer hookHandChildChildChild; public ModelRenderer hookHandChildChildChildChild; public ModelRenderer hookHandChildChildChildChildChild; public ModelRenderer Panties; public ModelRenderer Neck; public ModelRenderer Middelcrouch; public ModelRenderer TopChest; public ModelRenderer LeftUpperArm; public ModelRenderer LeftUnderArm; public ModelRenderer LeftArmFingers; public ModelRenderer LeftArmThumb; public ModelRenderer RightKnee; public ModelRenderer RightUnderLeg; public ModelRenderer Rightfoot; public ModelRenderer RightToe2; public ModelRenderer RightToe1; public ModelRenderer RightToe3; public ModelRenderer LeftUnderLeg; public ModelRenderer LeftKnee; public ModelRenderer LeftFeet; public ModelRenderer LeftToe1; public ModelRenderer LeftToe3; public ModelRenderer LeftToe2; public ModelRenderer Jaw1; public ModelRenderer Snout; public ModelRenderer Leftcheekpart; public ModelRenderer Rightcheekpart; public ModelRenderer Head2; public ModelRenderer Righteye; public ModelRenderer Lefteye; public ModelRenderer Rightpupil; public ModelRenderer Leftpupil; public ModelRenderer Tophead; public ModelRenderer Leftearpart; public ModelRenderer Rightearpart; public ModelRenderer Jaw2; public ModelRenderer Jaw3; public ModelRenderer Snout2; public ModelRenderer Snout3; public ModelRenderer Nose; public ModelRenderer Leftearpart2; public ModelRenderer Leftearpart3; public ModelRenderer Leftearpart4; public ModelRenderer Rightearpart2; public ModelRenderer Rightearpart3; public ModelRenderer Rightearpart4; public ModelPre_Mangle() { this.textureWidth = 128; this.textureHeight = 64; this.LeftLeg = new ModelRenderer(this, 0, 34); this.LeftLeg.setRotationPoint(2.2F, 9.0F, 0.5F); this.LeftLeg.addBox(-1.5F, 0.0F, -2.0F, 3, 5, 3, 0.0F); this.setRotateAngle(LeftLeg, 0.0F, 0.0F, -0.045553093477052F); this.Panties = new ModelRenderer(this, 0, 53); this.Panties.setRotationPoint(-0.5F, 7.47F, 0.0F); this.Panties.addBox(-3.5F, 0.0F, -2.5F, 8, 2, 5, 0.0F); this.TopChest = new ModelRenderer(this, 5, 1); this.TopChest.setRotationPoint(-3.0F, -2.3F, -1.9F); this.TopChest.addBox(0.0F, 0.0F, 0.0F, 6, 3, 4, 0.0F); this.Head2 = new ModelRenderer(this, 50, 44); this.Head2.setRotationPoint(0.0F, 1.17F, 0.9F); this.Head2.addBox(-3.0F, -6.0F, -4.0F, 6, 4, 5, 0.0F); this.Righteye = new ModelRenderer(this, 42, 46); this.Righteye.mirror = true; this.Righteye.setRotationPoint(0.0F, -3.0F, -3.1F); this.Righteye.addBox(-2.47F, -1.0F, -0.13F, 2, 2, 1, 0.0F); this.hookHandChildChildChildChild = new ModelRenderer(this, 0, 5); this.hookHandChildChildChildChild.setRotationPoint(0.0F, 1.7000000476837158F, 0.10000000149011612F); this.hookHandChildChildChildChild.addBox(-0.5F, 0.0F, -0.5F, 1, 2, 1, 0.0F); this.setRotateAngle(hookHandChildChildChildChild, -0.9599310755729675F, 0.0F, 0.0F); this.Tophead = new ModelRenderer(this, 50, 38); this.Tophead.setRotationPoint(0.0F, 1.37F, 1.0F); this.Tophead.addBox(-2.5F, -7.0F, -3.5F, 5, 1, 4, 0.0F); this.LeftUpperArm = new ModelRenderer(this, 47, 5); this.LeftUpperArm.mirror = true; this.LeftUpperArm.setRotationPoint(0.5F, 0.8F, -0.5F); this.LeftUpperArm.addBox(0.0F, 0.53F, -1.0F, 2, 5, 2, 0.0F); this.Leftearpart = new ModelRenderer(this, 20, 9); this.Leftearpart.setRotationPoint(2.0F, -4.0F, -0.05F); this.Leftearpart.addBox(-1.0F, -2.0F, -1.0F, 2, 1, 1, 0.0F); this.setRotateAngle(Leftearpart, 0.0F, 0.0F, 0.8726646259971648F); this.Jaw3 = new ModelRenderer(this, 0, 9); this.Jaw3.setRotationPoint(0.0F, 0.45F, 0.33F); this.Jaw3.addBox(-1.5F, 0.1F, -9.0F, 3, 1, 1, 0.0F); this.setRotateAngle(Jaw3, -0.0651007810993885F, 0.0F, 0.0F); this.Hookpart1 = new ModelRenderer(this, 51, 24); this.Hookpart1.setRotationPoint(-0.4F, 5.0F, 0.0F); this.Hookpart1.addBox(-1.6F, -0.67F, -1.5F, 3, 2, 3, 0.0F); this.Leftcheekpart = new ModelRenderer(this, 30, 44); this.Leftcheekpart.setRotationPoint(2.77F, -0.5F, -1.5F); this.Leftcheekpart.addBox(0.0F, -1.0F, -1.5F, 2, 1, 3, 0.0F); this.setRotateAngle(Leftcheekpart, 0.0F, 0.0F, 0.22759093446006054F); this.Rightpupil = new ModelRenderer(this, 73, 46); this.Rightpupil.mirror = true; this.Rightpupil.setRotationPoint(0.0F, -3.0F, -3.1F); this.Rightpupil.addBox(-1.7F, -0.1F, -0.2F, 1, 1, 1, 0.0F); this.Jaw1 = new ModelRenderer(this, 66, 56); this.Jaw1.setRotationPoint(0.0F, 0.0F, 1.0F); this.Jaw1.addBox(-2.5F, 0.1F, -6.0F, 5, 1, 6, 0.0F); this.setRotateAngle(Jaw1, 0.08726646259971647F, 0.0F, 0.0F); this.LeftUnderArm = new ModelRenderer(this, 21, 43); this.LeftUnderArm.mirror = true; this.LeftUnderArm.setRotationPoint(1.1F, 5.6F, -0.5F); this.LeftUnderArm.addBox(-0.5F, 0.53F, -0.9F, 2, 5, 2, 0.0F); this.setRotateAngle(LeftUnderArm, -0.18203784098300857F, 0.0F, 0.19949113350295186F); this.LeftToe3 = new ModelRenderer(this, 87, 26); this.LeftToe3.setRotationPoint(0.7F, 10.62F, -1.9F); this.LeftToe3.addBox(0.0F, 0.0F, -3.0F, 1, 2, 2, 0.0F); this.setRotateAngle(LeftToe3, 0.0F, -0.18203784098300857F, 0.045553093477052F); this.Nose = new ModelRenderer(this, 36, 17); this.Nose.setRotationPoint(0.0F, -1.83F, -9.07F); this.Nose.addBox(-1.0F, -1.5F, -0.5F, 2, 1, 1, 0.0F); this.setRotateAngle(Nose, -0.3665191429188092F, 0.0F, 0.0F); this.LeftArmFingers = new ModelRenderer(this, 59, 31); this.LeftArmFingers.setRotationPoint(0.6F, 6.6F, 0.6F); this.LeftArmFingers.addBox(0.0F, -1.57F, -1.63F, 1, 3, 2, 0.0F); this.setRotateAngle(LeftArmFingers, -0.091106186954104F, 0.0F, 0.136659280431156F); this.Snout3 = new ModelRenderer(this, 36, 20); this.Snout3.setRotationPoint(0.0F, 0.05F, 0.33F); this.Snout3.addBox(-1.5F, -3.0F, -9.0F, 3, 2, 3, 0.0F); this.Rightearpart3 = new ModelRenderer(this, 20, 9); this.Rightearpart3.setRotationPoint(0.0F, 0.0F, 0.0F); this.Rightearpart3.addBox(-1.0F, -6.0F, -1.0F, 2, 1, 1, 0.0F); this.Lefteye = new ModelRenderer(this, 42, 46); this.Lefteye.mirror = true; this.Lefteye.setRotationPoint(0.0F, -3.0F, -3.1F); this.Lefteye.addBox(0.5F, -1.0F, -0.13F, 2, 2, 1, 0.0F); this.hookHandChildChildChildChildChild = new ModelRenderer(this, 0, 5); this.hookHandChildChildChildChildChild.setRotationPoint(0.0F, 1.7000000476837158F, 0.10000000149011612F); this.hookHandChildChildChildChildChild.addBox(-0.5F, 0.0F, -0.5F, 1, 2, 1, 0.0F); this.setRotateAngle(hookHandChildChildChildChildChild, -0.9599310755729675F, 0.0F, 0.0F); this.LeftUnderLeg = new ModelRenderer(this, 0, 18); this.LeftUnderLeg.setRotationPoint(-1.0F, 5.5F, -1.2F); this.LeftUnderLeg.addBox(-0.5F, 0.0F, -0.7F, 3, 6, 3, 0.0F); this.setRotateAngle(LeftUnderLeg, 0.045553093477052F, 0.0F, 0.0F); this.RightToe3 = new ModelRenderer(this, 74, 31); this.RightToe3.setRotationPoint(1.24F, 10.45F, -4.8F); this.RightToe3.addBox(0.0F, 0.0F, 0.0F, 1, 2, 2, 0.0F); this.setRotateAngle(RightToe3, 0.0F, -0.18203784098300857F, -0.045553093477052F); this.LeftArmThumb = new ModelRenderer(this, 51, 32); this.LeftArmThumb.setRotationPoint(-0.9F, 6.1F, 0.6F); this.LeftArmThumb.addBox(0.0F, -0.97F, -1.63F, 1, 2, 2, 0.0F); this.setRotateAngle(LeftArmThumb, -0.045553093477052F, 0.0F, 0.045553093477052F); this.Neck = new ModelRenderer(this, 18, 19); this.Neck.setRotationPoint(0.0F, -2.23F, 0.3F); this.Neck.addBox(-1.0F, -2.5F, -1.0F, 2, 3, 2, 0.0F); this.LeftFeet = new ModelRenderer(this, 48, 13); this.LeftFeet.setRotationPoint(-2.0F, 10.5F, -3.1F); this.LeftFeet.addBox(0.0F, 0.0F, 0.0F, 4, 2, 5, 0.0F); this.setRotateAngle(LeftFeet, 0.0F, 0.0F, 0.045553093477052F); this.Rightearpart4 = new ModelRenderer(this, 12, 9); this.Rightearpart4.setRotationPoint(0.0F, 0.0F, 0.0F); this.Rightearpart4.addBox(-0.5F, -7.0F, -1.0F, 1, 1, 1, 0.0F); this.Hookpart2 = new ModelRenderer(this, 67, 24); this.Hookpart2.setRotationPoint(0.0F, 4.8F, 0.0F); this.Hookpart2.addBox(-1.5F, 1.43F, -1.0F, 2, 1, 2, 0.0F); this.Snout2 = new ModelRenderer(this, 18, 14); this.Snout2.setRotationPoint(0.0F, 0.05F, -0.07F); this.Snout2.addBox(-2.0F, -3.0F, -6.0F, 4, 2, 2, 0.0F); this.Middelcrouch = new ModelRenderer(this, 28, 55); this.Middelcrouch.setRotationPoint(-0.5F, 6.87F, -0.3F); this.Middelcrouch.addBox(-2.5F, 0.0F, -1.6F, 6, 1, 4, 0.0F); this.Rightfoot = new ModelRenderer(this, 48, 13); this.Rightfoot.setRotationPoint(-2.0F, 10.6F, -3.1F); this.Rightfoot.addBox(0.0F, 0.0F, 0.0F, 4, 2, 5, 0.0F); this.setRotateAngle(Rightfoot, 0.0F, 0.0F, -0.04153883619746504F); this.RightLeg = new ModelRenderer(this, 7, 43); this.RightLeg.setRotationPoint(-2.2F, 9.0F, 0.5F); this.RightLeg.addBox(-1.5F, 0.0F, -2.0F, 3, 5, 3, 0.0F); this.setRotateAngle(RightLeg, -0.0F, 0.0F, 0.045553093477052F); this.RightUpperArm = new ModelRenderer(this, 47, 5); this.RightUpperArm.setRotationPoint(-0.5F, 0.8F, -0.5F); this.RightUpperArm.addBox(-2.0F, 0.53F, -1.0F, 2, 5, 2, 0.0F); this.LeftToe2 = new ModelRenderer(this, 80, 25); this.LeftToe2.setRotationPoint(0.3F, 10.6F, -2.0F); this.LeftToe2.addBox(-2.0F, 0.0F, -3.0F, 1, 2, 2, 0.0F); this.setRotateAngle(LeftToe2, 0.0F, 0.18203784098300857F, 0.045553093477052F); this.RightUnderArm = new ModelRenderer(this, 71, 39); this.RightUnderArm.setRotationPoint(-1.1F, 5.6F, -0.5F); this.RightUnderArm.addBox(-1.5F, 0.53F, -1.0F, 2, 4, 2, 0.0F); this.setRotateAngle(RightUnderArm, -0.136659280431156F, -0.045553093477052F, -0.18203784098300857F); this.LeftToe1 = new ModelRenderer(this, 83, 34); this.LeftToe1.setRotationPoint(0.52F, 10.61F, -1.8F); this.LeftToe1.addBox(-1.5F, 0.0F, -3.0F, 2, 2, 2, 0.0F); this.setRotateAngle(LeftToe1, 0.0F, 0.0F, 0.045553093477052F); this.LeftKnee = new ModelRenderer(this, 57, 1); this.LeftKnee.setRotationPoint(-1.0F, 4.3F, -1.2F); this.LeftKnee.addBox(0.0F, 0.0F, 0.0F, 2, 2, 2, 0.0F); this.Rightearpart2 = new ModelRenderer(this, 37, 3); this.Rightearpart2.setRotationPoint(0.0F, 0.0F, 0.0F); this.Rightearpart2.addBox(-1.5F, -5.0F, -1.0F, 3, 3, 1, 0.0F); this.Head = new ModelRenderer(this, 51, 56); this.Head.setRotationPoint(0.0F, -4.5F, 0.1F); this.Head.addBox(-2.0F, -0.8F, -1.2F, 4, 2, 3, 0.0F); this.Leftearpart2 = new ModelRenderer(this, 34, 11); this.Leftearpart2.setRotationPoint(0.1F, 0.0F, 0.0F); this.Leftearpart2.addBox(-1.5F, -5.0F, -1.0F, 3, 3, 1, 0.0F); this.hookHandChildChild = new ModelRenderer(this, 13, 16); this.hookHandChildChild.setRotationPoint(-0.5F, 6.3F, -0.4F); this.hookHandChildChild.addBox(-0.5F, 0.1F, -0.5F, 1, 3, 1, 0.0F); this.setRotateAngle(hookHandChildChild, 0.31869712141416456F, 0.0F, 0.0F); this.Rightcheekpart = new ModelRenderer(this, 30, 44); this.Rightcheekpart.setRotationPoint(-2.77F, -0.5F, -1.5F); this.Rightcheekpart.addBox(-2.0F, -1.0F, -1.5F, 2, 1, 3, 0.0F); this.setRotateAngle(Rightcheekpart, 0.0F, 0.0F, -0.22759093446006054F); this.Leftpupil = new ModelRenderer(this, 73, 46); this.Leftpupil.mirror = true; this.Leftpupil.setRotationPoint(0.0F, -3.0F, -3.1F); this.Leftpupil.addBox(0.7F, -0.1F, -0.2F, 1, 1, 1, 0.0F); this.RightToe2 = new ModelRenderer(this, 80, 25); this.RightToe2.setRotationPoint(0.3F, 10.49F, -2.0F); this.RightToe2.addBox(-2.0F, 0.0F, -3.0F, 1, 2, 2, 0.0F); this.setRotateAngle(RightToe2, 0.0F, 0.18203784098300857F, -0.045553093477052F); this.RightUnderLeg = new ModelRenderer(this, 0, 18); this.RightUnderLeg.setRotationPoint(-1.0F, 5.5F, -1.2F); this.RightUnderLeg.addBox(-0.5F, 0.0F, -0.7F, 3, 6, 3, 0.0F); this.setRotateAngle(RightUnderLeg, 0.045553093477052F, 0.0F, 0.0F); this.Rightearpart = new ModelRenderer(this, 20, 9); this.Rightearpart.setRotationPoint(-2.0F, -4.0F, 0.0F); this.Rightearpart.addBox(-1.0F, -2.0F, -1.0F, 2, 1, 1, 0.0F); this.setRotateAngle(Rightearpart, 0.0F, 0.0F, -0.8726646259971648F); this.Leftearpart4 = new ModelRenderer(this, 12, 9); this.Leftearpart4.setRotationPoint(0.0F, 0.0F, 0.0F); this.Leftearpart4.addBox(-0.5F, -7.0F, -1.0F, 1, 1, 1, 0.0F); this.Jaw2 = new ModelRenderer(this, 0, 13); this.Jaw2.setRotationPoint(0.0F, 0.2F, 0.13F); this.Jaw2.addBox(-2.0F, 0.1F, -8.0F, 4, 1, 2, 0.0F); this.setRotateAngle(Jaw2, -0.035255650890285456F, 0.0F, 0.0F); this.Body = new ModelRenderer(this, 19, 26); this.Body.setRotationPoint(0.0F, -0.2F, 0.0F); this.Body.addBox(-3.5F, 0.0F, -2.47F, 7, 7, 5, 0.0F); this.RightToe1 = new ModelRenderer(this, 83, 34); this.RightToe1.setRotationPoint(-0.95F, 10.55F, -4.9F); this.RightToe1.addBox(0.0F, 0.0F, 0.0F, 2, 2, 2, 0.0F); this.setRotateAngle(RightToe1, 0.0F, 0.0F, -0.045553093477052F); this.LeftArm = new ModelRenderer(this, 26, 2); this.LeftArm.setRotationPoint(2.7F, -2.4F, 0.5F); this.LeftArm.addBox(-1.0F, 0.0F, -1.5F, 3, 2, 2, 0.0F); this.setRotateAngle(LeftArm, 0.0F, 0.0F, -0.22759093446006054F); this.RightArm = new ModelRenderer(this, 26, 2); this.RightArm.setRotationPoint(-2.7F, -2.4F, 0.5F); this.RightArm.addBox(-2.0F, 0.0F, -1.5F, 3, 2, 2, 0.0F); this.setRotateAngle(RightArm, -0.0F, -0.026703537555513242F, 0.22759093446006054F); this.Snout = new ModelRenderer(this, 81, 44); this.Snout.setRotationPoint(0.0F, 1.0F, 0.9F); this.Snout.addBox(-5.0F, -2.0F, -4.0F, 10, 1, 3, 0.0F); this.hookHandChildChildChild = new ModelRenderer(this, 0, 5); this.hookHandChildChildChild.setRotationPoint(0.0F, 2.700000047683716F, 0.10000000149011612F); this.hookHandChildChildChild.addBox(-0.5F, 0.0F, -0.5F, 1, 2, 1, 0.0F); this.setRotateAngle(hookHandChildChildChild, -0.8726646304130553F, 0.0F, 0.0F); this.Leftearpart3 = new ModelRenderer(this, 20, 9); this.Leftearpart3.setRotationPoint(0.1F, 0.0F, 0.0F); this.Leftearpart3.addBox(-1.0F, -6.0F, -1.0F, 2, 1, 1, 0.0F); this.RightKnee = new ModelRenderer(this, 57, 7); this.RightKnee.setRotationPoint(-1.0F, 4.3F, -1.2F); this.RightKnee.addBox(0.0F, 0.0F, 0.0F, 2, 2, 2, 0.0F); this.Body.addChild(this.Panties); this.Body.addChild(this.TopChest); this.Head.addChild(this.Head2); this.Head.addChild(this.Righteye); this.hookHandChildChildChild.addChild(this.hookHandChildChildChildChild); this.Head.addChild(this.Tophead); this.LeftArm.addChild(this.LeftUpperArm); this.Head.addChild(this.Leftearpart); this.Jaw1.addChild(this.Jaw3); this.RightUnderArm.addChild(this.Hookpart1); this.Head.addChild(this.Leftcheekpart); this.Head.addChild(this.Rightpupil); this.Head.addChild(this.Jaw1); this.LeftArm.addChild(this.LeftUnderArm); this.LeftLeg.addChild(this.LeftToe3); this.Snout.addChild(this.Nose); this.LeftUnderArm.addChild(this.LeftArmFingers); this.Snout.addChild(this.Snout3); this.Rightearpart.addChild(this.Rightearpart3); this.Head.addChild(this.Lefteye); this.hookHandChildChildChildChild.addChild(this.hookHandChildChildChildChildChild); this.LeftLeg.addChild(this.LeftUnderLeg); this.RightLeg.addChild(this.RightToe3); this.LeftUnderArm.addChild(this.LeftArmThumb); this.Body.addChild(this.Neck); this.LeftLeg.addChild(this.LeftFeet); this.Rightearpart.addChild(this.Rightearpart4); this.RightUnderArm.addChild(this.Hookpart2); this.Snout.addChild(this.Snout2); this.Body.addChild(this.Middelcrouch); this.RightLeg.addChild(this.Rightfoot); this.RightArm.addChild(this.RightUpperArm); this.LeftLeg.addChild(this.LeftToe2); this.RightArm.addChild(this.RightUnderArm); this.LeftLeg.addChild(this.LeftToe1); this.LeftLeg.addChild(this.LeftKnee); this.Rightearpart.addChild(this.Rightearpart2); this.Leftearpart.addChild(this.Leftearpart2); this.RightUnderArm.addChild(this.hookHandChildChild); this.Head.addChild(this.Rightcheekpart); this.Head.addChild(this.Leftpupil); this.RightLeg.addChild(this.RightToe2); this.RightLeg.addChild(this.RightUnderLeg); this.Head.addChild(this.Rightearpart); this.Leftearpart.addChild(this.Leftearpart4); this.Jaw1.addChild(this.Jaw2); this.RightLeg.addChild(this.RightToe1); this.Head.addChild(this.Snout); this.hookHandChildChild.addChild(this.hookHandChildChildChild); this.Leftearpart.addChild(this.Leftearpart3); this.RightLeg.addChild(this.RightKnee); } @Override public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { /* Animation Start (Head) */ float prog1 = 0.9F; Head.rotateAngleY = f3 / (180F / (float)Math.PI); Head.rotateAngleX = f4 / (180F / (float)Math.PI); /* Animation Start (Arms) */ float prog = 0.1F; this.RightArm.rotateAngleX = MathHelper.cos(prog * 0.6662F + (float)Math.PI) * 1.4F * prog; this.LeftArm.rotateAngleX = MathHelper.cos(prog * 0.6662F + (float)Math.PI) * 1.4F * prog; this.RightArm.rotateAngleX = MathHelper.cos(f * 0.6662F) * 1.4F * f1; this.LeftArm.rotateAngleX = MathHelper.cos(f * 0.6662F + (float)Math.PI) * 1.4F * f1; /* Animation Start (Legs) */ this.LeftLeg.rotateAngleX = MathHelper.cos(prog * 0.6662F + (float)Math.PI) * 1.4F * prog; this.RightLeg.rotateAngleX = MathHelper.cos(prog * 0.6662F + (float)Math.PI) * 1.4F * prog; this.LeftLeg.rotateAngleX = MathHelper.cos(f * 0.6662F) * 1.4F * f1; this.RightLeg.rotateAngleX = MathHelper.cos(f * 0.6662F + (float)Math.PI) * 1.4F * f1; GL11.glPushMatrix(); GL11.glScaled(1D / modelScale[0], 1D / modelScale[1], 1D / modelScale[2]); this.LeftLeg.render(f5); this.RightLeg.render(f5); this.Head.render(f5); this.Body.render(f5); this.LeftArm.render(f5); this.RightArm.render(f5); GL11.glPopMatrix(); } public void setRotateAngle(ModelRenderer modelRenderer, float x, float y, float z) { modelRenderer.rotateAngleX = x; modelRenderer.rotateAngleY = y; modelRenderer.rotateAngleZ = z; } }
Link1234Gamer/FiveNightsAtFreddysUniverseMod
src/main/java/link1234gamer/fnafmod/client/model/entity/ModelPre_Mangle.java
Java
epl-1.0
19,349
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) braces deadcode package net.minecraft.src; import java.util.Random; // Referenced classes of package net.minecraft.src: // WorldGenerator, EnumSkyBlock, World, Material, // Block, BlockGrass public class WorldGenLakes extends WorldGenerator { public WorldGenLakes(int i) { field_15005_a = i; } public boolean generate(World world, Random random, int i, int j, int k) { i -= 8; for(k -= 8; j > 0 && world.isAirBlock(i, j, k); j--) { } j -= 4; boolean aflag[] = new boolean[2048]; int l = random.nextInt(4) + 4; for(int i1 = 0; i1 < l; i1++) { double d = random.nextDouble() * 6D + 3D; double d1 = random.nextDouble() * 4D + 2D; double d2 = random.nextDouble() * 6D + 3D; double d3 = random.nextDouble() * (16D - d - 2D) + 1.0D + d / 2D; double d4 = random.nextDouble() * (8D - d1 - 4D) + 2D + d1 / 2D; double d5 = random.nextDouble() * (16D - d2 - 2D) + 1.0D + d2 / 2D; for(int j4 = 1; j4 < 15; j4++) { for(int k4 = 1; k4 < 15; k4++) { for(int l4 = 1; l4 < 7; l4++) { double d6 = ((double)j4 - d3) / (d / 2D); double d7 = ((double)l4 - d4) / (d1 / 2D); double d8 = ((double)k4 - d5) / (d2 / 2D); double d9 = d6 * d6 + d7 * d7 + d8 * d8; if(d9 < 1.0D) { aflag[(j4 * 16 + k4) * 8 + l4] = true; } } } } } for(int j1 = 0; j1 < 16; j1++) { for(int j2 = 0; j2 < 16; j2++) { for(int j3 = 0; j3 < 8; j3++) { boolean flag = !aflag[(j1 * 16 + j2) * 8 + j3] && (j1 < 15 && aflag[((j1 + 1) * 16 + j2) * 8 + j3] || j1 > 0 && aflag[((j1 - 1) * 16 + j2) * 8 + j3] || j2 < 15 && aflag[(j1 * 16 + (j2 + 1)) * 8 + j3] || j2 > 0 && aflag[(j1 * 16 + (j2 - 1)) * 8 + j3] || j3 < 7 && aflag[(j1 * 16 + j2) * 8 + (j3 + 1)] || j3 > 0 && aflag[(j1 * 16 + j2) * 8 + (j3 - 1)]); if(!flag) { continue; } Material material = world.getBlockMaterial(i + j1, j + j3, k + j2); if(j3 >= 4 && material.getIsLiquid()) { return false; } if(j3 < 4 && !material.isSolid() && world.getBlockId(i + j1, j + j3, k + j2) != field_15005_a) { return false; } } } } for(int k1 = 0; k1 < 16; k1++) { for(int k2 = 0; k2 < 16; k2++) { for(int k3 = 0; k3 < 8; k3++) { if(aflag[(k1 * 16 + k2) * 8 + k3]) { world.setBlock(i + k1, j + k3, k + k2, k3 < 4 ? field_15005_a : 0); } } } } for(int l1 = 0; l1 < 16; l1++) { for(int l2 = 0; l2 < 16; l2++) { for(int l3 = 4; l3 < 8; l3++) { if(aflag[(l1 * 16 + l2) * 8 + l3] && world.getBlockId(i + l1, (j + l3) - 1, k + l2) == Block.dirt.blockID && world.getSavedLightValue(EnumSkyBlock.Sky, i + l1, j + l3, k + l2) > 0) { world.setBlock(i + l1, (j + l3) - 1, k + l2, Block.grass.blockID); } } } } if(Block.blocksList[field_15005_a].blockMaterial == Material.lava) { for(int i2 = 0; i2 < 16; i2++) { for(int i3 = 0; i3 < 16; i3++) { for(int i4 = 0; i4 < 8; i4++) { boolean flag1 = !aflag[(i2 * 16 + i3) * 8 + i4] && (i2 < 15 && aflag[((i2 + 1) * 16 + i3) * 8 + i4] || i2 > 0 && aflag[((i2 - 1) * 16 + i3) * 8 + i4] || i3 < 15 && aflag[(i2 * 16 + (i3 + 1)) * 8 + i4] || i3 > 0 && aflag[(i2 * 16 + (i3 - 1)) * 8 + i4] || i4 < 7 && aflag[(i2 * 16 + i3) * 8 + (i4 + 1)] || i4 > 0 && aflag[(i2 * 16 + i3) * 8 + (i4 - 1)]); if(flag1 && (i4 < 4 || random.nextInt(2) != 0) && world.getBlockMaterial(i + i2, j + i4, k + i3).isSolid()) { world.setBlock(i + i2, j + i4, k + i3, Block.stone.blockID); } } } } } return true; } private int field_15005_a; }
sehrgut/minecraft-smp-mocreatures
moCreatures/server/core/sources/net/minecraft/src/WorldGenLakes.java
Java
epl-1.0
5,162
/* * Copyright (c) 2018 AT&T Intellectual Property. 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.opendaylight.protocol.bgp.openconfig.routing.policy.statement; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.opendaylight.protocol.bgp.openconfig.routing.policy.spi.registry.RouteAttributeContainer.routeAttributeContainerFalse; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.opendaylight.protocol.bgp.openconfig.routing.policy.impl.PolicyRIBBaseParametersImpl; import org.opendaylight.protocol.bgp.openconfig.routing.policy.spi.registry.RouteAttributeContainer; import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRouteEntryExportParameters; import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.types.rev151009.IPV4UNICAST; import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.routing.policy.rev151009.routing.policy.top.routing.policy.policy.definitions.policy.definition.statements.Statement; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.path.attributes.AttributesBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.path.attributes.attributes.CommunitiesBuilder; import org.opendaylight.yangtools.yang.common.Uint16; public class MatchCommunityTest extends AbstractStatementRegistryConsumerTest { @Mock private BGPRouteEntryExportParameters exportParameters; private List<Statement> basicStatements; private PolicyRIBBaseParametersImpl baseAttributes; @Before @Override public void setUp() throws Exception { super.setUp(); this.basicStatements = loadStatement("community-statements-test"); this.baseAttributes = new PolicyRIBBaseParametersImpl(LOCAL_AS, IPV4, CLUSTER); } @Test public void testComAny() { Statement statement = this.basicStatements.stream() .filter(st -> st.getName().equals("community-any-test")).findFirst().get(); RouteAttributeContainer attributeContainer = routeAttributeContainerFalse( new AttributesBuilder().build()); RouteAttributeContainer result = this.statementRegistry.applyExportStatement( this.baseAttributes, IPV4UNICAST.class, this.exportParameters, attributeContainer, statement); assertNotNull(result.getAttributes()); attributeContainer = routeAttributeContainerFalse(new AttributesBuilder().setCommunities( Collections.singletonList(new CommunitiesBuilder() .setAsNumber(AsNumber.getDefaultInstance("65")) .setSemantics(Uint16.TEN) .build())).build()); result = this.statementRegistry.applyExportStatement( this.baseAttributes, IPV4UNICAST.class, this.exportParameters, attributeContainer, statement); assertNull(result.getAttributes()); } @Test public void testComInvert() { Statement statement = this.basicStatements.stream() .filter(st -> st.getName().equals("community-invert-test")).findFirst().get(); RouteAttributeContainer attributeContainer = routeAttributeContainerFalse( new AttributesBuilder().build()); RouteAttributeContainer result = this.statementRegistry.applyExportStatement( this.baseAttributes, IPV4UNICAST.class, this.exportParameters, attributeContainer, statement); assertNull(result.getAttributes()); attributeContainer = routeAttributeContainerFalse(new AttributesBuilder().setCommunities( Collections.singletonList(new CommunitiesBuilder() .setAsNumber(AsNumber.getDefaultInstance("65")) .setSemantics(Uint16.TEN) .build())).build()); result = this.statementRegistry.applyExportStatement( this.baseAttributes, IPV4UNICAST.class, this.exportParameters, attributeContainer, statement); assertNotNull(result.getAttributes()); } @Test public void testComAll() { Statement statement = this.basicStatements.stream() .filter(st -> st.getName().equals("community-all-test")).findFirst().get(); RouteAttributeContainer attributeContainer = routeAttributeContainerFalse( new AttributesBuilder().build()); RouteAttributeContainer result = this.statementRegistry.applyExportStatement( this.baseAttributes, IPV4UNICAST.class, this.exportParameters, attributeContainer, statement); assertNotNull(result.getAttributes()); attributeContainer = routeAttributeContainerFalse(new AttributesBuilder().setCommunities(Arrays.asList( new CommunitiesBuilder().setAsNumber(AsNumber.getDefaultInstance("65")) .setSemantics(Uint16.TEN).build(), new CommunitiesBuilder().setAsNumber(AsNumber.getDefaultInstance("66")) .setSemantics(Uint16.valueOf(11)).build())).build()); result = this.statementRegistry.applyExportStatement( this.baseAttributes, IPV4UNICAST.class, this.exportParameters, attributeContainer, statement); assertNull(result.getAttributes()); } }
opendaylight/bgpcep
bgp/openconfig-rp-statement/src/test/java/org/opendaylight/protocol/bgp/openconfig/routing/policy/statement/MatchCommunityTest.java
Java
epl-1.0
6,118
package com.intuit.tank.util; /* * #%L * JSF Support Beans * %% * Copyright (C) 2011 - 2015 Intuit Inc. * %% * 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 * #L% */ import java.util.List; import javax.enterprise.context.ApplicationScoped; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Named; /** * * Messages. Provides a drop in replacement for seam international status messages. * * @author Kevin McGoldrick * */ @Named @ApplicationScoped public class Messages { public void info(String s) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, s, "")); } public void warn(String s) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, s, "")); } public void error(String s) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, s, "")); } public void fatal(String s) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, s, "")); } public boolean isEmpty() { return FacesContext.getCurrentInstance().getMessageList().isEmpty(); } public void clear() { //Removed because it throws a UnsupportedOperationException on an unmodifiable list //FacesContext.getCurrentInstance().getMessageList().clear(); } }
intuit/Tank
web/web_support/src/main/java/com/intuit/tank/util/Messages.java
Java
epl-1.0
1,684
/* * Copyright (c) 2014 Cisco Systems, Inc. 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.opendaylight.controller.sal.binding.test.compat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.junit.Test; import org.opendaylight.controller.md.sal.common.api.TransactionStatus; import org.opendaylight.controller.md.sal.common.api.data.DataChangeEvent; import org.opendaylight.controller.sal.binding.api.data.DataChangeListener; import org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction; import org.opendaylight.controller.sal.binding.test.AbstractDataServiceTest; import org.opendaylight.controller.sal.binding.test.AugmentationVerifier; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.Counter32; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.Counter64; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterStatistics; import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterStatisticsBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.nodes.node.meter.MeterStatisticsBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId; import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.statistics.DurationBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.statistics.reply.MeterStats; import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.statistics.reply.MeterStatsBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.statistics.reply.MeterStatsKey; import org.opendaylight.yangtools.yang.binding.Augmentation; import org.opendaylight.yangtools.yang.binding.DataObject; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.RpcResult; import org.opendaylight.yangtools.yang.data.api.CompositeNode; public class MultipleAugmentationPutsTest extends AbstractDataServiceTest implements DataChangeListener { private static final QName NODE_ID_QNAME = QName.create(Node.QNAME, "id"); private static final String NODE_ID = "openflow:1"; private static final NodeKey NODE_KEY = new NodeKey(new NodeId(NODE_ID)); private static final Map<QName, Object> NODE_KEY_BI = Collections.<QName, Object> singletonMap(NODE_ID_QNAME, NODE_ID); private static final InstanceIdentifier<Nodes> NODES_INSTANCE_ID_BA = InstanceIdentifier.builder(Nodes.class) // .toInstance(); private static final InstanceIdentifier<Node> NODE_INSTANCE_ID_BA = NODES_INSTANCE_ID_BA.child(Node.class, NODE_KEY); private static final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier NODE_INSTANCE_ID_BI = // org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.builder() // .node(Nodes.QNAME) // .nodeWithKey(Node.QNAME, NODE_KEY_BI) // .toInstance(); private DataChangeEvent<InstanceIdentifier<?>, DataObject> receivedChangeEvent; /** * Test for Bug 148 * * @throws Exception */ @Test() public void testAugmentSerialization() throws Exception { baDataService.registerDataChangeListener(NODES_INSTANCE_ID_BA, this); Node flowCapableNode = createTestNode(FlowCapableNode.class, flowCapableNodeAugmentation()); commitNodeAndVerifyTransaction(flowCapableNode); assertNotNull(receivedChangeEvent); verifyNode((Nodes) receivedChangeEvent.getUpdatedOperationalSubtree(), flowCapableNode); Nodes nodes = checkForNodes(); verifyNode(nodes, flowCapableNode).assertHasAugmentation(FlowCapableNode.class); assertBindingIndependentVersion(NODE_INSTANCE_ID_BI); // Node meterStatsNode = createTestNode(NodeMeterStatistics.class, nodeMeterStatistics()); // commitNodeAndVerifyTransaction(meterStatsNode); // // assertNotNull(receivedChangeEvent); // verifyNode((Nodes) receivedChangeEvent.getUpdatedOperationalSubtree(), meterStatsNode); // // assertBindingIndependentVersion(NODE_INSTANCE_ID_BI); // // Node mergedNode = (Node) baDataService.readOperationalData(NODE_INSTANCE_ID_BA); // // AugmentationVerifier.from(mergedNode) // // .assertHasAugmentation(FlowCapableNode.class) // // .assertHasAugmentation(NodeMeterStatistics.class); // // assertBindingIndependentVersion(NODE_INSTANCE_ID_BI); // // Node meterStatsNodeWithDuration = createTestNode(NodeMeterStatistics.class, nodeMeterStatistics(5, true)); // commitNodeAndVerifyTransaction(meterStatsNodeWithDuration); // // // Node nodeWithUpdatedList = (Node) baDataService.readOperationalData(NODE_INSTANCE_ID_BA); // AugmentationVerifier.from(nodeWithUpdatedList) // // .assertHasAugmentation(FlowCapableNode.class) // // .assertHasAugmentation(NodeMeterStatistics.class); // // List<MeterStats> meterStats = nodeWithUpdatedList.getAugmentation(NodeMeterStatistics.class).getMeterStatistics().getMeterStats(); // assertNotNull(meterStats); // assertFalse(meterStats.isEmpty()); // assertBindingIndependentVersion(NODE_INSTANCE_ID_BI); testNodeRemove(); } private <T extends Augmentation<Node>> Node createTestNode(final Class<T> augmentationClass, final T augmentation) { NodeBuilder nodeBuilder = new NodeBuilder(); nodeBuilder.setId(new NodeId(NODE_ID)); nodeBuilder.setKey(NODE_KEY); nodeBuilder.addAugmentation(augmentationClass, augmentation); return nodeBuilder.build(); } private DataModificationTransaction commitNodeAndVerifyTransaction(final Node original) throws Exception { DataModificationTransaction transaction = baDataService.beginTransaction(); transaction.putOperationalData(NODE_INSTANCE_ID_BA, original); RpcResult<TransactionStatus> result = transaction.commit().get(); assertEquals(TransactionStatus.COMMITED, result.getResult()); return transaction; } private void testNodeRemove() throws Exception { DataModificationTransaction transaction = baDataService.beginTransaction(); transaction.removeOperationalData(NODE_INSTANCE_ID_BA); RpcResult<TransactionStatus> result = transaction.commit().get(); assertEquals(TransactionStatus.COMMITED, result.getResult()); Node node = (Node) baDataService.readOperationalData(NODE_INSTANCE_ID_BA); assertNull(node); } private AugmentationVerifier<Node> verifyNode(final Nodes nodes, final Node original) { assertNotNull(nodes); assertNotNull(nodes.getNode()); assertEquals(1, nodes.getNode().size()); Node readedNode = nodes.getNode().get(0); assertEquals(original.getId(), readedNode.getId()); assertEquals(original.getKey(), readedNode.getKey()); return new AugmentationVerifier<Node>(readedNode); } private void assertBindingIndependentVersion(final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier nodeId) { CompositeNode node = biDataService.readOperationalData(nodeId); assertNotNull(node); } private Nodes checkForNodes() { return (Nodes) baDataService.readOperationalData(NODES_INSTANCE_ID_BA); } private NodeMeterStatistics nodeMeterStatistics() { return nodeMeterStatistics(10, false); } private NodeMeterStatistics nodeMeterStatistics(final int count, final boolean setDuration) { NodeMeterStatisticsBuilder nmsb = new NodeMeterStatisticsBuilder(); MeterStatisticsBuilder meterStats = new MeterStatisticsBuilder(); List<MeterStats> stats = new ArrayList<>(count); for (int i = 0; i <= count; i++) { MeterStatsBuilder statistic = new MeterStatsBuilder(); statistic.setKey(new MeterStatsKey(new MeterId((long) i))); statistic.setByteInCount(new Counter64(BigInteger.valueOf(34590 + i))); statistic.setFlowCount(new Counter32(4569L + i)); if (setDuration) { DurationBuilder duration = new DurationBuilder(); duration.setNanosecond(new Counter32(70L)); statistic.setDuration(duration.build()); } stats.add(statistic.build()); } // meterStats.setMeterStats(stats); nmsb.setMeterStatistics(meterStats.build()); return nmsb.build(); } private FlowCapableNode flowCapableNodeAugmentation() { FlowCapableNodeBuilder fnub = new FlowCapableNodeBuilder(); fnub.setHardware("Hardware Foo"); fnub.setManufacturer("Manufacturer Foo"); fnub.setSerialNumber("Serial Foo"); fnub.setDescription("Description Foo"); fnub.setSoftware("JUnit emulated"); FlowCapableNode fnu = fnub.build(); return fnu; } @Override public void onDataChanged(final DataChangeEvent<InstanceIdentifier<?>, DataObject> change) { receivedChangeEvent = change; } }
aryantaheri/controller
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/compat/MultipleAugmentationPutsTest.java
Java
epl-1.0
10,386
package com.coverity.ws.v6; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for defectInstanceIdDataObj complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="defectInstanceIdDataObj"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}long"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "defectInstanceIdDataObj", propOrder = { "id" }) public class DefectInstanceIdDataObj { protected long id; /** * Gets the value of the id property. * */ public long getId() { return id; } /** * Sets the value of the id property. * */ public void setId(long value) { this.id = value; } }
christ66/coverity-plugin
src/main/java/com/coverity/ws/v6/DefectInstanceIdDataObj.java
Java
epl-1.0
1,144
package org.hl7.v3; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p> * Java class for POCD_MT000040.Component5 complex type. * * <p> * The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="POCD_MT000040.Component5"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="realmCode" type="{urn:hl7-org:v3}CS" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="typeId" type="{urn:hl7-org:v3}POCD_MT000040.InfrastructureRoot.typeId" minOccurs="0"/> * &lt;element name="templateId" type="{urn:hl7-org:v3}II" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="section" type="{urn:hl7-org:v3}POCD_MT000040.Section"/> * &lt;/sequence> * &lt;attribute name="nullFlavor" type="{urn:hl7-org:v3}NullFlavor" /> * &lt;attribute name="typeCode" type="{urn:hl7-org:v3}ActRelationshipHasComponent" fixed="COMP" /> * &lt;attribute name="contextConductionInd" type="{urn:hl7-org:v3}bl" fixed="true" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "POCD_MT000040.Component5", propOrder = { "realmCode", "typeId", "templateId", "section" }) public class POCDMT000040Component5 { protected List<CS> realmCode; protected POCDMT000040InfrastructureRootTypeId typeId; protected List<II> templateId; @XmlElement(required = true) protected POCDMT000040Section section; @XmlAttribute protected List<String> nullFlavor; @XmlAttribute protected ActRelationshipHasComponent typeCode; @XmlAttribute protected Boolean contextConductionInd; /** * Gets the value of the realmCode 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 realmCode property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getRealmCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link CS } * * */ public List<CS> getRealmCode(){ if (realmCode == null) { realmCode = new ArrayList<CS>(); } return this.realmCode; } /** * Gets the value of the typeId property. * * @return possible object is {@link POCDMT000040InfrastructureRootTypeId } * */ public POCDMT000040InfrastructureRootTypeId getTypeId(){ return typeId; } /** * Sets the value of the typeId property. * * @param value * allowed object is {@link POCDMT000040InfrastructureRootTypeId } * */ public void setTypeId(POCDMT000040InfrastructureRootTypeId value){ this.typeId = value; } /** * Gets the value of the templateId 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 templateId property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getTemplateId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link II } * * */ public List<II> getTemplateId(){ if (templateId == null) { templateId = new ArrayList<II>(); } return this.templateId; } /** * Gets the value of the section property. * * @return possible object is {@link POCDMT000040Section } * */ public POCDMT000040Section getSection(){ return section; } /** * Sets the value of the section property. * * @param value * allowed object is {@link POCDMT000040Section } * */ public void setSection(POCDMT000040Section value){ this.section = value; } /** * Gets the value of the nullFlavor 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 nullFlavor property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getNullFlavor().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link String } * * */ public List<String> getNullFlavor(){ if (nullFlavor == null) { nullFlavor = new ArrayList<String>(); } return this.nullFlavor; } /** * Gets the value of the typeCode property. * * @return possible object is {@link ActRelationshipHasComponent } * */ public ActRelationshipHasComponent getTypeCode(){ if (typeCode == null) { return ActRelationshipHasComponent.COMP; } else { return typeCode; } } /** * Sets the value of the typeCode property. * * @param value * allowed object is {@link ActRelationshipHasComponent } * */ public void setTypeCode(ActRelationshipHasComponent value){ this.typeCode = value; } /** * Gets the value of the contextConductionInd property. * * @return possible object is {@link Boolean } * */ public boolean isContextConductionInd(){ if (contextConductionInd == null) { return true; } else { return contextConductionInd; } } /** * Sets the value of the contextConductionInd property. * * @param value * allowed object is {@link Boolean } * */ public void setContextConductionInd(Boolean value){ this.contextConductionInd = value; } }
DavidGutknecht/elexis-3-base
bundles/ch.docbox.elexis/src/org/hl7/v3/POCDMT000040Component5.java
Java
epl-1.0
6,040
/** * Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ /* * Created on 23/07/2005 */ package com.python.pydev.analysis.builder; import java.io.File; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.text.IDocument; import org.python.pydev.builder.PyDevBuilderVisitor; import org.python.pydev.core.IModule; import org.python.pydev.core.IPythonNature; import org.python.pydev.core.MisconfigurationException; import org.python.pydev.core.concurrency.RunnableAsJobsPoolThread; import org.python.pydev.core.log.Log; import org.python.pydev.editor.codecompletion.revisited.PyCodeCompletionVisitor; import org.python.pydev.editor.codecompletion.revisited.modules.SourceModule; import org.python.pydev.logging.DebugSettings; import org.python.pydev.parser.fastparser.FastDefinitionsParser; import org.python.pydev.plugin.nature.PythonNature; import org.python.pydev.shared_core.callbacks.ICallback; import org.python.pydev.shared_core.callbacks.ICallback0; import com.python.pydev.analysis.additionalinfo.AbstractAdditionalDependencyInfo; import com.python.pydev.analysis.additionalinfo.AdditionalProjectInterpreterInfo; public class AnalysisBuilderVisitor extends PyDevBuilderVisitor { @Override protected int getPriority() { return PyCodeCompletionVisitor.PRIORITY_CODE_COMPLETION + 1; //just after the code-completion priority } @Override public void visitChangedResource(final IResource resource, final ICallback0<IDocument> document, final IProgressMonitor monitor) { visitChangedResource(resource, document, monitor, false); } public void visitChangedResource(final IResource resource, final ICallback0<IDocument> document, final IProgressMonitor monitor, boolean forceAnalysis) { //we may need to 'force' the analysis when a module is renamed, because the first message we receive is //a 'delete' and after that an 'add' -- which is later mapped to this method, so, if we don't have info //on the module we should analyze it because it is 'probably' a rename. final PythonNature nature = getPythonNature(resource); if (nature == null) { return; } //Put things from the memo to final variables as we might need them later on and we cannot get them from //the memo later. final String moduleName; final SourceModule[] module = new SourceModule[] { null }; final IDocument doc; doc = document.call(); if (doc == null) { return; } try { moduleName = getModuleName(resource, nature); } catch (MisconfigurationException e) { Log.log(e); return; } //depending on the level of analysis we have to do, we'll decide whether we want //to make the full parse (slower) or the definitions parse (faster but only with info //related to the definitions) ICallback<IModule, Integer> moduleCallback = new ICallback<IModule, Integer>() { @Override public IModule call(Integer arg) { //Note: we cannot get anything from the memo at this point because it'll be called later on from a thread //and the memo might have changed already (E.g: moduleName and module) if (arg == IAnalysisBuilderRunnable.FULL_MODULE) { if (module[0] != null) { return module[0]; } else { try { module[0] = getSourceModule(resource, doc, nature); } catch (MisconfigurationException e1) { throw new RuntimeException(e1); } if (module[0] != null) { return module[0]; } try { module[0] = createSoureModule(resource, doc, moduleName); } catch (MisconfigurationException e) { throw new RuntimeException(e); } return module[0]; } } else if (arg == IAnalysisBuilderRunnable.DEFINITIONS_MODULE) { if (DebugSettings.DEBUG_ANALYSIS_REQUESTS) { Log.toLogFile(this, "PyDevBuilderPrefPage.getAnalyzeOnlyActiveEditor()"); } IFile f = (IFile) resource; String file = f.getRawLocation().toOSString(); File f2 = new File(file); return new SourceModule(moduleName, f2, FastDefinitionsParser.parse(doc.get(), moduleName, f2), null, nature); } else { throw new RuntimeException("Unexpected parameter: " + arg); } } }; long documentTime = this.getDocumentTime(); if (documentTime == -1) { Log.log("Warning: The document time in the visitor is -1. Changing for current time."); documentTime = System.currentTimeMillis(); } doVisitChangedResource(nature, resource, doc, moduleCallback, null, monitor, forceAnalysis, AnalysisBuilderRunnable.ANALYSIS_CAUSE_BUILDER, documentTime, false); } /** * here we have to detect errors / warnings from the code analysis * Either the module callback or the module must be set. * @param forceAnalyzeInThisThread */ public void doVisitChangedResource(IPythonNature nature, IResource resource, IDocument document, ICallback<IModule, Integer> moduleCallback, final IModule module, IProgressMonitor monitor, boolean forceAnalysis, int analysisCause, long documentTime, boolean forceAnalyzeInThisThread) { if (DebugSettings.DEBUG_ANALYSIS_REQUESTS) { if (analysisCause == AnalysisBuilderRunnable.ANALYSIS_CAUSE_BUILDER) { System.out.println("doVisitChangedResource: BUILDER -- " + documentTime); } else { System.out.println("doVisitChangedResource: PARSER -- " + documentTime); } } if (module != null) { if (moduleCallback != null) { Log.log("Only the module or the moduleCallback must be specified for: " + resource); return; } setModuleInCache(resource, module); moduleCallback = new ICallback<IModule, Integer>() { @Override public IModule call(Integer arg) { return module; } }; } else { //don't set module in the cache if we only have the callback //moduleCallback is already defined if (moduleCallback == null) { Log.log("Either the module or the moduleCallback must be specified for: " + resource); return; } } String moduleName; try { moduleName = getModuleName(resource, nature); } catch (MisconfigurationException e) { Log.log(e); return; } final IAnalysisBuilderRunnable runnable = AnalysisBuilderRunnableFactory.createRunnable(document, resource, moduleCallback, isFullBuild(), moduleName, forceAnalysis, analysisCause, nature, documentTime, resource.getModificationStamp()); if (runnable == null) { //It may be null if the document version of the new one is lower than one already active. return; } execRunnable(moduleName, runnable, forceAnalyzeInThisThread); } /** * Depending on whether we're in a full build or delta build, this method will run the runnable directly * or schedule it as a job. * @param forceAnalyzeInThisThread */ private void execRunnable(final String moduleName, final IAnalysisBuilderRunnable runnable, boolean forceAnalyzeInThisThread) { if (isFullBuild() || forceAnalyzeInThisThread) { runnable.run(); } else { RunnableAsJobsPoolThread.getSingleton().scheduleToRun(runnable, "PyDev: Code Analysis:" + moduleName); } } @Override public void visitRemovedResource(IResource resource, ICallback0<IDocument> document, IProgressMonitor monitor) { PythonNature nature = getPythonNature(resource); if (nature == null) { return; } if (resource.getType() == IResource.FOLDER) { //We don't need to explicitly treat any folder (just its children -- such as __init__ and submodules) return; } if (!isFullBuild()) { //on a full build, it'll already remove all the info String moduleName; try { moduleName = getModuleName(resource, nature); } catch (MisconfigurationException e) { Log.log(e); return; } long documentTime = this.getDocumentTime(); if (documentTime == -1) { Log.log("Warning: The document time in the visitor for remove is -1. Changing for current time. " + "Resource: " + resource + ". Module name: " + moduleName); documentTime = System.currentTimeMillis(); } long resourceModificationStamp = resource.getModificationStamp(); final IAnalysisBuilderRunnable runnable = AnalysisBuilderRunnableFactory.createRunnable(moduleName, nature, isFullBuild(), false, AnalysisBuilderRunnable.ANALYSIS_CAUSE_BUILDER, documentTime, resourceModificationStamp); if (runnable == null) { //It may be null if the document version of the new one is lower than one already active. return; } execRunnable(moduleName, runnable, false); } } @Override public void visitingWillStart(IProgressMonitor monitor, boolean isFullBuild, IPythonNature nature) { if (isFullBuild) { AbstractAdditionalDependencyInfo info; try { info = AdditionalProjectInterpreterInfo.getAdditionalInfoForProject(nature); } catch (MisconfigurationException e) { Log.log(e); return; } info.clearAllInfo(); } } }
RandallDW/Aruba_plugin
plugins/com.python.pydev.analysis/src/com/python/pydev/analysis/builder/AnalysisBuilderVisitor.java
Java
epl-1.0
10,913