repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
lamatypus/Simulateur
src/elements/ElementReseauIP.java
9586
package elements; import elements.util.TableARP; import elements.util.TableNat; import elements.util.TableRoutage; import elements.util.TableRoutage.Methode; import elements.util.TableRoutage.Route; import exception.IPNonValide; import paquets.Paquet; import sockets.SocketRawHandler; import sockets.SocketTCPHandler; import sockets.SocketUDPHandler; import standards.IPv4; import standards.MAC; /********************************************************************** * <p> * But:<br> * Classe abtraite englobant les différents éléments réseaux IP héritant de la * classe d'élément réseau. * </p> * <p> * Description:<br> * Cette classe permet de gérer des éléments réseaux IP, d'obtenir leurs * interfaces, de les connecter entre eux et d'obtenir des informations sur * ceux-ci. * </p> * * @author Raphaël Buache * @author Magali Frölich * @author Cédric Rudareanu * @author Yann Malherbe * @version 1.0 * @modify 18.06.2014 ***********************************************************************/ @SuppressWarnings("serial") public abstract class ElementReseauIP extends ElementReseau { private SocketUDPHandler[] sockUDP = new SocketUDPHandler[65536]; private SocketTCPHandler[] sockTCP = new SocketTCPHandler[65536]; private SocketRawHandler sockRaw; private TableNat tableNatTcp = new TableNat(); private TableARP tableARP; protected TableRoutage tableRoutage = new TableRoutage(this); /** * Créer un élément réseau IP avec un nombre d'interfaces IP et le nom * utilisé pour le nom des interfaces IP * * @param nbInterface: le nombre d'interface * @param nom: le nom de l'interface */ public ElementReseauIP(int nbInterface, String nom) { super.nbInterfaces = nbInterface; Ilist = new InterfaceIP[nbInterface]; for (int i = 0; i < nbInterface; i++) { Ilist[i] = new InterfaceIP(i, nom + i); Ilist[i].setActive(true); } tableARP = new TableARP(this); } /** * Créer un élément réseau IP utilisé pour l'interface graphique * * @param nbInterface: le nombre d'interface * @param ghost */ public ElementReseauIP(int nbInterface, boolean ghost) { super(nbInterface, ghost); } /** * Permet d'obtenir la un tableau contenant toute les interfaces IP de * l'élément réseau IP * * @return le tableau d'interfaces IP */ public InterfaceIP[] getInterfacesIP() { return (InterfaceIP[]) getInterface(); } /** * Permet de trouver l'adresse MAC d'une IP dans la table ARP * * @param ip: l'adresse IP * @return l'adresse MAC trouvée */ public MAC getMac(IPv4 ip) { return tableARP.getMac(ip); } /** * Permet d'ajouter une entrée dans la talbe ARP avec une adresse MAC et son * IP correspondante * * @param mac: l'adresse MAC * @param ip: l'adresse IP */ public void ajouteEntree(MAC mac, IPv4 ip) { tableARP.ajouteEntree(mac, ip); } /** * Permet d'obtenir un tableau des sockets UDP * * @return les socket UDP */ public SocketUDPHandler[] getSocketUDP() { return sockUDP; } /** * Permet d'obtenir un tableau des sockets TCP * * @return les socket TCP */ public SocketTCPHandler[] getSocketTCP() { return sockTCP; } /** * Permet de configurer une socket RAW * * @param s */ public void setSocketRaw(SocketRawHandler s) { sockRaw = s; } /** * Permet d'obtenir le gestionnaire de socket RAW * * @return */ public SocketRawHandler getSocketRaw() { return sockRaw; } /** * Permet d'obtenir la table NAT de l'élément réseau IP * * @return */ public TableNat getTableTCP() { return tableNatTcp; } /** * Permet d'obtenir la table de routage de l'élément réseau * * @return la table de routage */ public TableRoutage getTableRoutage() { return tableRoutage; } /** * Permet d'obtenir l'interface IP correspondante avec l'adresse IP dans la * table de routage * * @param ip: l'adresse IP * @return l'interface IP */ public InterfaceIP getInterfaceIP(IPv4 ip) { return tableRoutage.getInterfaceIP(ip); } /** * Permet de créer une nouvelle route dans la table de routage avec une * adresse IP de destination, une interface de sortie, une méthode * d'apprentissage de route et un cout * * @param ip: l'adresse IP * @param i: l'interface IP * @param methode: la méthode * @param cout: le cout */ public void nouvelleRoute(IPv4 ip, InterfaceIP i, Methode methode, int cout) { nouvelleRoute(ip, i, null, methode, cout); } /** * Permet de créer une nouvelle route dans la table de routage avec une * adresse IP de destination, une adresse IP de prochain saut, une méthode * d'apprentissage de route et un cout * * @param ip: l'adresse IP * @param via: l'adresse IP de prochain saut * @param methode: la méthode * @param cout: le cout */ public void nouvelleRoute(IPv4 ip, IPv4 via, Methode methode, int cout) { nouvelleRoute(ip, null, via, methode, cout); } /** * Permet de créer une nouvelle route dans la table de routage avec une * adresse IP de destination, une interface de sortie, une adresse IP de * prochain saut, une méthode d'apprentissage de route et un cout * * @param ip: l'adresse IP * @param i: l'interface IP * @param via: l'adresse IP de prochain saut * @param methode: la méthode * @param cout: le cout */ public void nouvelleRoute(IPv4 ip, InterfaceIP i, IPv4 via, Methode methode, int cout) { tableRoutage.nouvelleRoute(ip, i, via, methode, cout); } /** * Permet de supprimer une route avec une adresse IP de destination et une * interface de sortie * * @param ip: l'adresse IP * @param i: l'interface IP */ public void supprimeRoute(IPv4 ip, InterfaceIP i) { tableRoutage.supprimeRoute(ip, i); } /** * Permet de supprimer une route avec une adresse IP de destination et une * adresse IP de prochain saut * * @param ip: l'adresse IP * @param via: l'adresse IP de prochain saut */ public void supprimeRoute(IPv4 ip, IPv4 via) { tableRoutage.supprimeRoute(ip, via); } /** * Permet de supprimer une route * * @param route: la route */ public void supprimeRoute(Route route) { tableRoutage.supprimeRoute(route); } /** * Permet d'obtenir une route pour une adresse IP de destination * * @param ip: l'adresse IP * @return la route */ public Route getRoute(IPv4 ip) { return tableRoutage.getRoute(ip); } /** * Permet de definir sur quelles interface IP une adresse IP peut-elle être * trouvée * * @param dest: l'adresse IP de destination * @return un tableau d'adresse IP */ public abstract InterfaceIP[] getInterfaceSortie(IPv4 dest); /** * Défini ce que fait un élément réseau IP lorsqu'il recoit un paquet sur * son interface IP au niveau de la couche réseau du modèle OSI * * @param p: le paquet * @param i: l'interface IP */ public abstract void recoitCoucheReseau(Paquet p, InterfaceIP i); /** * Défini ce que fait un élément réseau IP lorsqu'il recoit un paquet7 au * niveau de la couche transport du modèle OSI * * @param p: le paquet */ public abstract void recoitCoucheTransport(Paquet p); /********************************************************************** * <p> * But:<br> * Classe représentant les interfaces IP que les éléments réseaux IP * contiennent * </p> * <p> * Description:<br> * Cette classe permet de gérer des interfaces IP d'éléments réseaux. * </p> * * @author Raphaël Buache * @author Magali Frölich * @author Cédric Rudareanu * @author Yann Malherbe * @version 1.0 * @modify 18.06.2014 ***********************************************************************/ public class InterfaceIP extends Interface { private IPv4 ip; private MethodeApprentissageIP methodeApprentissageIP; /** * Permet de créer une interface IP en lui donnant un nom et son numéro. * L'adresse MAC est automatiquement générée * * @param i: le numéro de l'interface * @param nom: le nom de l'interface */ public InterfaceIP(int i, String nom) { super(i, nom); } /** * Permet d'obtenir l'adresse IP de l'interface IP * * @return l'adresse IP */ public IPv4 getIp() { return ip; } /** * Permet de connaître la méthode d'apprentissage de l'adreses IP * * @return la méthode d'apprentissage */ public MethodeApprentissageIP getMethodeApprentissageIP() { return methodeApprentissageIP; } /** * Permet de configurer une adresse IP sur une interface IP avec une * méthode d'apprentissage * * @param ip: l'adresse IP * @param methode: la méthode */ public void setIp(IPv4 ip, MethodeApprentissageIP methode) { if (this.ip != null){ try { supprimeRoute(new IPv4(this.ip.toString(), 32), this); } catch (IPNonValide e) { e.printStackTrace(); } supprimeRoute(this.ip, this); } this.ip = ip; methodeApprentissageIP = methode; if (ip != null){ nouvelleRoute(ip, this, Methode.DirectlyConnected, 1); try { nouvelleRoute(new IPv4(ip.toString(), 32), this, Methode.Local, 1); } catch (IPNonValide e) { } } } /** * Permet de supprimer l'adresse IP de l'interface IP */ public void supprimeIP() { try { tableRoutage.supprimeRoute(ip, this); tableRoutage.supprimeRoute(new IPv4(ip.toString(), 32), this); methodeApprentissageIP = null; ip = null; } catch (IPNonValide e) { } } } /** * Permet de définir comment une adresse IP d'interface IP a été apprise * */ public enum MethodeApprentissageIP { Manuel, DHCP; } }
mit
BTHM/u17Cartoon
app/src/main/java/com/pingan/u17/util/ActivityIntentTools.java
3349
package com.pingan.u17.util; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.v4.app.Fragment; import android.widget.Toast; import com.pingan.u17.base.U17Application; /** * 跳转Activity的工具类 * @author CHENZHIQIANG247 * */ public class ActivityIntentTools { public static void gotoActivity(Context context, Class<?> targetClass) { Intent intent = new Intent(context, targetClass); context.startActivity(intent); ((Activity) context).finish(); } public static void gotoActivityNotFinish(Context context, Class<?> targetClass) { Intent intent = new Intent(context, targetClass); context.startActivity(intent); } public static void gotoActivityWithBundle(Context context, Class<?> targetClass, Bundle bundle) { Intent intent = new Intent(context, targetClass); intent.putExtras(bundle); context.startActivity(intent); ((Activity) context).finish(); } public static void gotoActivityNotFinishWithBundle(Context context, Class<?> actClass, Bundle bundle) { Intent intent = new Intent(context, actClass); intent.putExtras(bundle); context.startActivity(intent); } public static void gotoActivityForResult(Activity activity, Class<?> actClass, int requestCode) { Intent intent = new Intent(activity, actClass); activity.startActivityForResult(intent, requestCode); } public static void gotoActivityForResult(Fragment fragment, Class<?> actClass, int requestCode) { Intent intent = new Intent(fragment.getActivity(), actClass); fragment.startActivityForResult(intent, requestCode); } public static void gotoActivityForResultWithBundle(Activity activity, Class<?> actClass, Bundle bundle, int requestCode) { Intent intent = new Intent(activity, actClass); intent.putExtras(bundle); activity.startActivityForResult(intent, requestCode); } public static void gotoActivityForResultWithBundle(Fragment fragment, Class<?> actClass, Bundle bundle, int requestCode) { Intent intent = new Intent(fragment.getActivity(), actClass); intent.putExtras(bundle); fragment.startActivityForResult(intent, requestCode); } /** * 使用手机浏览器打开网页 * * @param context * @param url */ public static void startViewUrl(Context context, String url) { try { Uri u = Uri.parse(url); Intent it = new Intent(Intent.ACTION_VIEW, u); it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(it); } catch (Exception e) { Toast.makeText(U17Application.getInstance(), "当前无可用浏览器", Toast.LENGTH_SHORT).show(); } } /** * 启动设置里的应用详情页(业务:设置权限等等) * @param context */ public static void startAppSettings(Context context) { Intent intent = new Intent(); intent.setAction(Settings.ACTION_SETTINGS); // intent.setData(Uri.fromParts("package", context.getPackageName(), null)); context.startActivity(intent); } }
mit
cacheflowe/haxademic
src/com/haxademic/core/draw/image/BufferThresholdMonitor.java
1901
package com.haxademic.core.draw.image; import com.haxademic.core.app.P; import com.haxademic.core.draw.color.ColorUtil; import com.haxademic.core.draw.context.PG; import com.haxademic.core.draw.filters.pshader.ThresholdFilter; import com.haxademic.core.math.easing.FloatBuffer; import processing.core.PGraphics; import processing.core.PImage; public class BufferThresholdMonitor { protected PGraphics thresholdBuffer; protected FloatBuffer thresholdCalc; protected float cutoff = 0.5f; public BufferThresholdMonitor(int w, int h, int bufferAvgSize) { // smoothed activity average thresholdCalc = new FloatBuffer(bufferAvgSize); // frame buffers thresholdBuffer = PG.newPG2DFast(w, h); } public BufferThresholdMonitor() { this(16, 16, 60); // defaults } public float thresholdCalc() { return thresholdCalc.average(); } public PGraphics thresholdBuffer() { return thresholdBuffer; } public void setCutoff(float cutoff) { this.cutoff = cutoff; } public float update(PImage newFrame) { // copy previous frame, and current frame to buffer thresholdBuffer.copy(newFrame, 0, 0, newFrame.width, newFrame.height, 0, 0, thresholdBuffer.width, thresholdBuffer.height); // run threshold filter ThresholdFilter.instance(P.p).setCutoff(cutoff); ThresholdFilter.instance(P.p).applyTo(thresholdBuffer); // analyze diff pixels float numPixels = thresholdBuffer.width * thresholdBuffer.height; float whitePixels = 0; thresholdBuffer.loadPixels(); for (int x = 0; x < thresholdBuffer.width; x++) { for (int y = 0; y < thresholdBuffer.height; y++) { int pixelColor = ImageUtil.getPixelColor(thresholdBuffer, x, y); float r = ColorUtil.redFromColorInt(pixelColor) / 255f; if(r > 0.5f) whitePixels += r; } } // update float buffer thresholdCalc.update(whitePixels / numPixels); return thresholdCalc.average(); } }
mit
jasondp/MyTest
MyTest/app/src/main/java/com/mytest/activity/WelcomeActivity.java
5101
package com.mytest.activity; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.view.ViewPager; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import com.mytest.R; import com.mytest.adapter.LooperImageAdapter; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by Jason on 2016/11/24. */ public class WelcomeActivity extends BaseActivity implements ViewPager.OnPageChangeListener { @Bind(R.id.tutorial_grad_view) ViewPager welcomeViewPager; @Bind(R.id.looper_point_group) LinearLayout pointGroup; private LooperImageAdapter looperAdapter; private List<ImageView> imageList; private Handler handler; private int[] ImageData = {R.mipmap.watch_1, R.mipmap.watch_2 , R.mipmap.watch_3, R.mipmap.watch_4, R.mipmap.watch_5, R.mipmap.watch_6}; private LooperTask looperTask = null; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.welcome_activity); ButterKnife.bind(this); handler = getObject().getPubicHandler(); initData(); } private void initData() { imageList = new ArrayList<>(); for (int i = 0; i < ImageData.length; i++) { ImageView imageView = new ImageView(this); imageView.setImageResource(ImageData[i]); imageList.add(imageView); } looperAdapter = new LooperImageAdapter(imageList); welcomeViewPager.setAdapter(looperAdapter); for (int i = 0; i < ImageData.length; i++) { ImageView pointImage = new ImageView(this); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams (ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); if (i == 0) { pointImage.setImageResource(R.drawable.welcome_pager_unselect_point_shape); } else { params.leftMargin = 8; pointImage.setImageResource(R.drawable.welcome_pager_select_point_shape); } pointImage.setLayoutParams(params); pointGroup.addView(pointImage); } int middlePosition = Integer.MAX_VALUE / 2; int middleSelectPosition = middlePosition % imageList.size(); int initIndex = middlePosition - middleSelectPosition; welcomeViewPager.setCurrentItem(initIndex); if (looperTask == null) { looperTask = new LooperTask(); } looperTask.start(); welcomeViewPager.addOnPageChangeListener(this); welcomeViewPager.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: looperTask.stop(); break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: looperTask.start(); break; } return false; } }); } @OnClick(R.id.welcome_login_button) public void toLogin() { startActivity(LoginActivity.class); finish(); } @OnClick(R.id.welcome_register_button) public void toRegisterAccount() { startActivity(RegisterActivity.class); finish(); } @OnClick(R.id.welcome_pear_button) public void toConnectWatch(){ startActivity(GuideActivity1.class); finish(); } class LooperTask implements Runnable { @Override public void run() { int currentItemIndex = welcomeViewPager.getCurrentItem(); welcomeViewPager.setCurrentItem(++currentItemIndex); handler.postDelayed(this, 1500); } public void start() { stop(); handler.postDelayed(this, 1500); } public void stop() { handler.removeCallbacks(this); } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { int childCount = pointGroup.getChildCount(); position = position % imageList.size(); for (int i = 0; i < childCount; i++) { ImageView childImage = (ImageView) pointGroup.getChildAt(i); if (position == i) { childImage.setImageResource(R.drawable.welcome_pager_unselect_point_shape); } else { childImage.setImageResource(R.drawable.welcome_pager_select_point_shape); } } } @Override public void onPageScrollStateChanged(int state) { } }
mit
atealxt/work-workspaces
PDMS/src/java/pdms/platform/action/A1000MyMissionAction.java
3191
package pdms.platform.action; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import pdms.components.vo.A1000MyMissionVo; import pdms.platform.core.EasyAction; import pdms.platform.core.PdmsException; import pdms.platform.service.A1000MyMissionService; /** * * @author LUSuo(atealxt@gmail.com) */ public class A1000MyMissionAction extends EasyAction { private static Log logger = LogFactory.getLog(A1000MyMissionAction.class); private A1000MyMissionService mymissionService; /** file json data */ private List<A1000MyMissionVo> items; /** 记录集 */ private long results; /** * main */ @Override public String execute() throws PdmsException { String str_start = getParamValue("start"); String str_limit = getParamValue("limit"); String conditions = getParamValue("conditions"); int start = 0; int limit = 10; if (str_start != null) { start = Integer.parseInt(getParamValue("start")); } if (str_limit != null) { limit = Integer.parseInt(getParamValue("limit")); } logger.info("start: " + start); logger.info("limit: " + limit); logger.info("conditions: " + conditions); String loginId = (String) getSession().get("loginId"); items = mymissionService.MakeVo(loginId, limit, start, conditions); results = mymissionService.getSumCount(loginId, conditions); logger.info("results: " + results); cleanSess(); return SUCCESS; } /** * 提交任务 */ public String submitMission() throws IOException, PdmsException { getResponse().setContentType("text/html;charset=UTF-8"); String id = getParamValue("id"); String content = getParamValue("content"); logger.info("id: " + id); logger.info("content: " + content); String f_id = getParamValue("file_id"); logger.info("f_id: " + f_id); getResponse().getWriter().write(mymissionService.submitMission(id, content, f_id)); cleanSess(); return null; } /** * 受取任务 */ public String receiveMission() throws IOException, PdmsException { getResponse().setContentType("text/html;charset=UTF-8"); String[] ids = getParamValue("ids").split("-"); List idList = Arrays.asList(ids); getResponse().getWriter().write(mymissionService.receiveMission(idList)); cleanSess(); return null; } public List<A1000MyMissionVo> getItems() { return items; } public void setItems(List<A1000MyMissionVo> items) { this.items = items; } public long getResults() { return results; } public void setResults(long results) { this.results = results; } // public A1000MyMissionService getMymissionService() { // return mymissionService; // } public void setMymissionService(A1000MyMissionService mymissionService) { this.mymissionService = mymissionService; } }
mit
FreeTymeKiyan/LeetCode-Sol-Res
src/main/java/com/freetymekiyan/algorithms/level/medium/UniquePaths2.java
1547
package com.freetymekiyan.algorithms.level.medium; /** * Follow up for "Unique Paths": * <p> * Now consider if some obstacles are added to the grids. How many unique paths * would there be? * <p> * An obstacle and empty space is marked as 1 and 0 respectively in the grid. * <p> * For example, * There is one obstacle in the middle of a 3x3 grid as illustrated below. * <p> * [ * [0,0,0], * [0,1,0], * [0,0,0] * ] * The total number of unique paths is 2. * <p> * Note: m and n will be at most 100. * <p> * Tags: Array, DP */ class UniquePaths2 { public static void main(String[] args) { int[][] obstacleGrid = new int[3][3]; obstacleGrid[1][1] = 1; System.out.println(uniquePathsWithObstacles(obstacleGrid)); } /** * DP, bottom-up approach * build from end point to start point * for the grid paths at the rth row and cth column * paths[r][c] = obstacleGrid[r][c] == 1 ? 0 * : paths[r + 1][c] + paths[r][c + 1]; */ public static int uniquePathsWithObstacles(int[][] obstacleGrid) { if (obstacleGrid == null) return 0; int m = obstacleGrid.length; if (m == 0) return 0; int n = obstacleGrid[0].length; int[][] paths = new int[m + 1][n + 1]; paths[m - 1][n] = 1; for (int r = m - 1; r >= 0; r--) { for (int c = n - 1; c >= 0; c--) { paths[r][c] = obstacleGrid[r][c] == 1 ? 0 : paths[r + 1][c] + paths[r][c + 1]; } } return paths[0][0]; } }
mit
brunogabriel/AndroidRealmNotes
AndroidRealmNotes/app/src/main/java/brunogabriel/github/io/androidrealmnotes/views/activities/SignupActivity.java
1208
package brunogabriel.github.io.androidrealmnotes.views.activities; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import brunogabriel.github.io.androidrealmnotes.R; import brunogabriel.github.io.androidrealmnotes.manager.BaseActivity; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by brunogabriel on 15/01/17. */ public class SignupActivity extends BaseActivity { @BindView(R.id.toolbar) protected Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); ButterKnife.bind(this); initUI(); } @Override protected void initUI() { super.initUI(); setupToolbar(toolbar, getString(R.string.app_login_activity_signup), null, true, true); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } }
mit
iorga-group/debattons
src/main/java/com/iorga/debattons/web/rest/vm/package-info.java
101
/** * View Models used by Spring MVC REST controllers. */ package com.iorga.debattons.web.rest.vm;
mit
hoqhuuep/IslandCraft
IslandCraft-Common/src/main/java/com/github/hoqhuuep/islandcraft/core/EmptyIslandGenerator.java
1034
package com.github.hoqhuuep.islandcraft.core; import com.github.hoqhuuep.islandcraft.api.ICBiome; import com.github.hoqhuuep.islandcraft.api.IslandGenerator; import com.github.hoqhuuep.islandcraft.util.StringUtils; public class EmptyIslandGenerator implements IslandGenerator { public EmptyIslandGenerator(final String[] args) { ICLogger.logger.info("Creating EmptyIslandGenerator with args: " + StringUtils.join(args, " ")); if (args.length != 0) { ICLogger.logger.error("EmptyIslandGenerator requrires 0 parameters, " + args.length + " given"); throw new IllegalArgumentException("EmptyIslandGenerator requrires 0 parameters, " + args.length + " given"); } } @Override public ICBiome[] generate(final int xSize, final int zSize, final long islandSeed) { ICLogger.logger.info(String.format("Generating island from EmptyIslandGenerator with xSize: %d, zSize: %d, islandSeed: %d", xSize, zSize, islandSeed)); return new ICBiome[xSize * zSize]; } }
mit
gervaisb/stackexchange-codereview
src/main/java/q192870/EntrepreneurModel.java
226
package q192870; import java.time.LocalDateTime; class EntrepreneurModel { public EntrepreneurModel(String lastName, String firstName, String s, String email, String password, LocalDateTime now) { // ... } }
mit
celestial-winter/vics
web-server/src/test/java/com/infinityworks/webapp/converter/PafToStreetResponseConverterTest.java
1352
package com.infinityworks.webapp.converter; import com.infinityworks.pafclient.dto.ImmutablePafStreetResponse; import com.infinityworks.webapp.rest.dto.Street; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class PafToStreetResponseConverterTest { @Test public void mapsTheStreetResponseFromPaf() { PafToStreetResponseConverter underTest = new PafToStreetResponseConverter(); Street streetResponse = underTest.apply(ImmutablePafStreetResponse.builder() .withDependentStreet("dependentStreet") .withMainStreet("mainStreet") .withCanvassed(10) .withVoters(20) .withDependentLocality("dependentLocality") .withPostTown("postTown") .withPriority(2) .build() ); assertThat(streetResponse.mainStreet(), is("mainStreet")); assertThat(streetResponse.dependentStreet(), is("dependentStreet")); assertThat(streetResponse.dependentLocality(), is("dependentLocality")); assertThat(streetResponse.numCanvassed(), is(10)); assertThat(streetResponse.numVoters(), is(20)); assertThat(streetResponse.postTown(), is("postTown")); assertThat(streetResponse.priority(), is(2)); } }
mit
CjHare/systematic-trading
systematic-trading-simulation-model/src/main/java/com/systematic/trading/simulation/brokerage/Brokerage.java
2558
/** * * Copyright (c) 2015-2018, CJ Hare 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 [project] 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 HOLDER 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 com.systematic.trading.simulation.brokerage; import com.systematic.trading.simulation.brokerage.event.BrokerageEventListener; import com.systematic.trading.simulation.equity.EquityManagementFee; import com.systematic.trading.simulation.equity.event.EquityEventListener; /** * The bringing together of the different aspects of a brokerage house. * * @author CJ Hare */ public interface Brokerage extends BrokerageBalance, BrokerageTransaction, BrokerageTransactionFee, EquityManagementFee { /** * Adds a listener interested in brokerage events. * * @param listener * to receive brokerage event notifications. */ void addListener( BrokerageEventListener listener ); /** * Adds a listener interested in equity events. * * @param listener * to receive equity event notifications. */ void addListener( EquityEventListener listener ); /** * Retrieves the identifier for the broker. * * @return name of the broker. */ String name(); }
mit
Damian3395/Contained
src/main/java/com/contained/game/entity/EntityAITeamHurtTarget.java
2209
package com.contained.game.entity; import java.util.ArrayList; import java.util.HashMap; import com.contained.game.util.EntityUtil; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.EntityAITarget; import net.minecraft.entity.player.EntityPlayer; /** * Variant of EntityAIOwnerHurtTarget for summoned monsters. Considers any player * of the same team to be the monster's owner. */ public class EntityAITeamHurtTarget extends EntityAITarget { EntityCreature theEntityTameable; EntityLivingBase theTarget; private HashMap<String, Integer> lastAttackerTimes; public EntityAITeamHurtTarget(EntityCreature thePet) { super(thePet, false); this.theEntityTameable = thePet; this.lastAttackerTimes = new HashMap<String, Integer>(); this.setMutexBits(1); } /** * Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { ArrayList<EntityPlayer> playersToDefend = EntityUtil.getAllTeamPlayersInRange(this.theEntityTameable, 15.0); String myTeam = ExtendedLivingBase.get(this.theEntityTameable).getTeam(); for (EntityPlayer p : playersToDefend) { EntityLivingBase possibleTarget = p.getLastAttacker(); boolean foundAttack = ( this.lastAttackerTimes.containsKey(p.getDisplayName()) && p.getLastAttackerTime() != this.lastAttackerTimes.get(p.getDisplayName()) && this.isSuitableTarget(possibleTarget, false) && EntityUtil.shouldAttack(possibleTarget, myTeam)); if (foundAttack) { this.theTarget = possibleTarget; return true; } } return false; } /** * Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.taskOwner.setAttackTarget(this.theTarget); ArrayList<EntityPlayer> playersToDefend = EntityUtil.getAllTeamPlayersInRange(this.theEntityTameable, 15.0); for(EntityPlayer player : playersToDefend) this.lastAttackerTimes.put(player.getDisplayName(), player.getLastAttackerTime()); super.startExecuting(); } }
mit
mr-xiangxu/ClinicSystem
ClinicDomain/src/edu/stevens/cs548/clinic/domain/ITreatmentDAO.java
452
package edu.stevens.cs548.clinic.domain; public interface ITreatmentDAO { public static class TreatmentExn extends Exception { private static final long serialVersionUID = 1L; public TreatmentExn(String msg) { super(msg); } } public Treatment getTreatmentByDbId(long id) throws TreatmentExn; public long addTreatment(Treatment t); public void deleteTreatment(Treatment t); // public void deleteTreatments (Patient patient); }
mit
low205/JavaTests
src/ru/sigma/test/learning/classes/DataStructure.java
1059
package ru.sigma.test.learning.classes; /** * Created with IntelliJ IDEA. * User: emaltsev * Date: 20.11.13 * Time: 15:48 * To change this template use File | Settings | File Templates. */ public class DataStructure { private final static int SIZE = 15; private int[] arrayOfInts = new int[SIZE]; public DataStructure() { for (int i = 0; i < SIZE; i++) { arrayOfInts[i] = i; } } public void printEven() { InnerEvenIterator iterator = this.new InnerEvenIterator(); while (iterator.hasNext()) { System.out.println(iterator.getNext() + " "); } } private class InnerEvenIterator { private int next = 0; public boolean hasNext() { return next < SIZE; } public int getNext() { int retValue = arrayOfInts[next]; next += 2; return retValue; } } public static void main(String[] args) { DataStructure ds = new DataStructure(); ds.printEven(); } }
mit
kevin-montrose/stacman-java
src/com/stackexchange/stacman/Filter.java
445
package com.stackexchange.stacman; import java.io.Serializable; public final class Filter implements Serializable { private String filter; public String getFilterName() { return filter; } private String filter_type; public FilterType getFilterType() { return StacManClient.parseEnum(FilterType.class, filter_type); } private String[] included_fields; public String[] getIncludedFields() { return included_fields; } }
mit
karim/adila
database/src/main/java/adila/db/u675_u675.java
203
// This file is automatically generated. package adila.db; /* * Teleepoch U675 * * DEVICE: U675 * MODEL: U675 */ final class u675_u675 { public static final String DATA = "Teleepoch|U675|"; }
mit
wolfgangmeyers/genomalysis
Genomalysis/src/main/java/org/genomalysis/ui/DiagnosticsTextDisplay.java
1976
package org.genomalysis.ui; import java.awt.BorderLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class DiagnosticsTextDisplay extends JPanel { private static final long serialVersionUID = 1L; private JButton btnClose; private JPanel jPanel1; private JScrollPane jScrollPane1; private JTextArea jTextArea1; public DiagnosticsTextDisplay(String text) { initComponents(); this.jTextArea1.setText(text); } public DiagnosticsTextDisplay() { this("Results of Diagnostics will appear in this window."); } private void initComponents() { this.jScrollPane1 = new JScrollPane(); this.jTextArea1 = new JTextArea(); this.jPanel1 = new JPanel(); this.btnClose = new JButton(); setLayout(new BorderLayout()); this.jTextArea1.setColumns(20); this.jTextArea1.setFont(new Font("Courier 10 Pitch", 0, 12)); this.jTextArea1.setLineWrap(true); this.jTextArea1.setRows(5); this.jTextArea1 .setText("aaaaaaaaaaaaaaaaaaaaaaa\nFFFFFFFFFFFFFFFFFFF\n...........................\n::::::::::::::::::::::::::::::::::::"); this.jTextArea1.setWrapStyleWord(true); this.jScrollPane1.setViewportView(this.jTextArea1); add(this.jScrollPane1, "Center"); this.btnClose.setText("Close"); this.btnClose.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { btnCloseActionPerformed(evt); } }); this.jPanel1.add(this.btnClose); add(this.jPanel1, "South"); } private void btnCloseActionPerformed(ActionEvent evt) { getParent().remove(this); } }
mit
yahoojapan/embulk-output-solr
src/main/java/org/embulk/output/solr/SolrOutputPlugin.java
15788
/** * The MIT License (MIT) * * Copyright (C) 2016 Yahoo Japan Corporation. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.embulk.output.solr; import java.io.IOException; import java.util.Date; import java.util.LinkedList; import java.util.List; import com.google.common.base.Optional; import com.google.inject.Inject; import org.embulk.config.TaskReport; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrClient; import org.apache.solr.common.SolrInputDocument; import org.embulk.config.Config; import org.embulk.config.ConfigDefault; import org.embulk.config.ConfigDiff; import org.embulk.config.ConfigSource; import org.embulk.config.Task; import org.embulk.config.TaskSource; import org.embulk.spi.Column; import org.embulk.spi.ColumnVisitor; import org.embulk.spi.Exec; import org.embulk.spi.OutputPlugin; import org.embulk.spi.Page; import org.embulk.spi.PageReader; import org.embulk.spi.Schema; import org.embulk.spi.TransactionalPageOutput; import org.embulk.spi.time.Timestamp; import org.embulk.spi.type.BooleanType; import org.embulk.spi.type.DoubleType; import org.embulk.spi.type.LongType; import org.embulk.spi.type.StringType; import org.embulk.spi.type.TimestampType; import org.embulk.spi.type.Type; import org.msgpack.value.Value; import org.slf4j.Logger; public class SolrOutputPlugin implements OutputPlugin { public interface PluginTask extends Task { @Config("host") public String getHost(); @Config("port") @ConfigDefault("8983") public int getPort(); @Config("collection") public String getCollection(); @Config("maxRetry") @ConfigDefault("5") public int getMaxRetry(); @Config("bulkSize") @ConfigDefault("1000") public int getBulkSize(); @Config("idColumnName") public String getIdColumnName(); @Config("multiValuedField") @ConfigDefault("null") public Optional<List<String>> getMultiValuedField(); } private final Logger logger; @Inject public SolrOutputPlugin() { logger = Exec.getLogger(getClass()); } @Override public ConfigDiff transaction(ConfigSource config, Schema schema, int taskCount, OutputPlugin.Control control) { PluginTask task = config.loadConfig(PluginTask.class); control.run(task.dump()); return Exec.newConfigDiff(); } @Override public ConfigDiff resume(TaskSource taskSource, Schema schema, int taskCount, OutputPlugin.Control control) { // TODO return Exec.newConfigDiff(); } @Override public void cleanup(TaskSource taskSource, Schema schema, int taskCount, List<TaskReport> successTaskReports) { } @Override public TransactionalPageOutput open(TaskSource taskSource, Schema schema, int taskIndex) { PluginTask task = taskSource.loadTask(PluginTask.class); SolrClient client = createSolrClient(task); TransactionalPageOutput pageOutput = new SolrPageOutput(client, schema, task); return pageOutput; } /** * create Solr Client. <br> * this method has not been supporting SolrCloud client using zookeeper * Host, yet. * * @param task * @return SolrClient instance. */ private SolrClient createSolrClient(PluginTask task) { HttpSolrClient solr = new HttpSolrClient( "http://" + task.getHost() + ":" + task.getPort() + "/solr/" + task.getCollection()); // solr.setConnectionTimeout(10000); // 10 seconds for timeout. return solr; } public static class SolrPageOutput implements TransactionalPageOutput { private Logger logger; private SolrClient client; private final PageReader pageReader; private final Schema schema; private PluginTask task; private final int bulkSize; private final int maxRetry; public SolrPageOutput(SolrClient client, Schema schema, PluginTask task) { this.logger = Exec.getLogger(getClass()); this.client = client; this.pageReader = new PageReader(schema); this.schema = schema; this.task = task; this.bulkSize = task.getBulkSize(); this.maxRetry = task.getMaxRetry(); } int totalCount = 0; private List<SolrInputDocument> documentList = new LinkedList<SolrInputDocument>(); private SolrInputDocument lastDoc = null; @Override public void add(Page page) { pageReader.setPage(page); while (pageReader.nextRecord()) { final boolean mergeDoc = isSameIDWithLastDoc(pageReader, lastDoc, task.getMultiValuedField().orNull()); final SolrInputDocument doc = new SolrInputDocument(); final List<String> multValuedField = task.getMultiValuedField().orNull(); schema.visitColumns(new ColumnVisitor() { @Override public void booleanColumn(Column column) { if (pageReader.isNull(column)) { // do nothing. } else { boolean value = pageReader.getBoolean(column); addFieldValue(mergeDoc, doc, multValuedField, column, value); } } @Override public void longColumn(Column column) { if (pageReader.isNull(column)) { // do nothing. } else { long value = pageReader.getLong(column); addFieldValue(mergeDoc, doc, multValuedField, column, value); } } @Override public void doubleColumn(Column column) { if (pageReader.isNull(column)) { // do nothing. } else { double value = pageReader.getDouble(column); addFieldValue(mergeDoc, doc, multValuedField, column, value); } } @Override public void stringColumn(Column column) { if (pageReader.isNull(column)) { // do nothing. } else { String value = pageReader.getString(column); if (value != null && !value.equals("")){ addFieldValue(mergeDoc, doc, multValuedField, column, value); } } } @Override public void timestampColumn(Column column) { if (pageReader.isNull(column)) { // do nothing. } else { Timestamp value = pageReader.getTimestamp(column); if (!value.equals("")) { Date dateValue = new Date(value.getEpochSecond() * 1000); addFieldValue(mergeDoc, doc, multValuedField, column, dateValue); } } } @Override public void jsonColumn(Column column) { if (pageReader.isNull(column)) { // do nothing. } else { Value value = pageReader.getJson(column); // send json as a string. if (!value.equals("")) { addFieldValue(mergeDoc, doc, multValuedField, column, value.toString()); } } } private void addFieldValue(final boolean mergeDoc, final SolrInputDocument doc, final List<String> multValuedField, Column column, Object value) { if (mergeDoc) { String n = column.getName(); for (String f : multValuedField) { if (n.equals(f)) { lastDoc.addField(column.getName(), value); return; } } } else { doc.addField(column.getName(), value); } } }); if(!mergeDoc) { documentList.add(doc); lastDoc = doc; } if (documentList.size() >= bulkSize) { sendDocumentToSolr(documentList); } } if (documentList.size() >= bulkSize) { sendDocumentToSolr(documentList); } } private boolean isSameIDWithLastDoc(PageReader pageReader, SolrInputDocument lastDoc, List<String> multiValuedFieldList) { if (multiValuedFieldList == null || multiValuedFieldList.size()==0){ return false; } boolean mergeDoc = false; List<Column> columnList = pageReader.getSchema().getColumns(); for (Column c : columnList) { if (c.getName().equals(task.getIdColumnName())) { Type type = c.getType(); if (type instanceof BooleanType) { boolean value = pageReader.getBoolean(c); if (lastDoc != null) { boolean b = (boolean) lastDoc.get(task.getIdColumnName()).getValue(); if (value==b) { mergeDoc = true; break; } } } else if (type instanceof LongType) { long value = pageReader.getLong(c); if (lastDoc != null) { long b = (long) lastDoc.get(task.getIdColumnName()).getValue(); if (value==b) { mergeDoc = true; break; } } } else if (type instanceof DoubleType) { double value = pageReader.getDouble(c); if (lastDoc != null) { double b = (double) lastDoc.get(task.getIdColumnName()).getValue(); if (value==b) { mergeDoc = true; break; } } } else if (type instanceof StringType) { String value = pageReader.getString(c); if (lastDoc != null) { String b = (String) lastDoc.get(task.getIdColumnName()).getValue(); if (value.equals(b)) { mergeDoc = true; break; } } } else if (type instanceof TimestampType) { Timestamp value = pageReader.getTimestamp(c); Date dateValue = new Date(value.getEpochSecond() * 1000); if (lastDoc != null) { Date b = (Date) lastDoc.get(task.getIdColumnName()).getValue(); if (dateValue.compareTo(b)==0) { mergeDoc = true; break; } } } else { throw new RuntimeException("Could not find column definition for name : " + task.getIdColumnName()); } } } return mergeDoc; } private void sendDocumentToSolr(List<SolrInputDocument> documentList) { int retrycount = 0; while(true) { try { logger.debug("start sending document to solr."); client.add(documentList); logger.debug("successfully load a bunch of documents to solr. batch count : " + documentList.size() + " current total count : " + totalCount); documentList.clear(); // when successfully add and commit, clear list. break; } catch (SolrServerException | IOException e) { if (retrycount < maxRetry) { retrycount++; logger.debug("RETRYing : " + retrycount); continue; } else { logger.error("failed to send document to solr. ", e); documentList.clear(); throw new RuntimeException(e); } } // if you get Bad request from server, then the thread will be die... //} catch (RemoteSolrException e) { // logger.error("bad request ? : ", e); //} } } @Override public void finish() { try { sendDocumentToSolr(documentList); client.commit(); logger.info("Done sending document to Solr in the thread! Total Count : " + totalCount); } catch (SolrServerException | IOException e) { logger.info("failed to commit document. ", e); } } @Override public void close() { pageReader.close(); try { client.close(); client = null; } catch (IOException e) { // do nothing. } } @Override public void abort() { } @Override public TaskReport commit() { TaskReport report = Exec.newTaskReport(); return report; } } }
mit
mplaine/xformsdb
src/fi/tkk/tml/xformsdb/error/XFormsDBException.java
1068
package fi.tkk.tml.xformsdb.error; /** * Abstract class that all XFormsDB exceptions must support. * * * @author Markku Laine * @version 1.0 Created on October 09, 2009 */ public abstract class XFormsDBException extends Exception { // PRIVATE STATIC FINAL VARIABLES private static final long serialVersionUID = 1; // PRIVATE VARIABLES private int code; // PUBLIC CONSTRUCTORS public XFormsDBException() { super(); } public XFormsDBException( String message ) { super( message ); } public XFormsDBException( int code, String message ) { super( message ); this.code = code; } public XFormsDBException( Throwable cause ) { super( cause ); } public XFormsDBException( int code, Throwable cause ) { super( cause ); this.code = code; } public XFormsDBException( String message, Throwable cause ) { super( message, cause ); } public XFormsDBException( int code, String message, Throwable cause ) { super( message, cause ); this.code = code; } // PUBLIC METHODS public int getCode() { return this.code; } }
mit
ymkjp/i219
12/PseudoSafeInc1.java
916
/* * Copyright (c) 3/6/17 11:27 PM, Kenta Yamamoto <ymkjp@jaist.ac.jp>, s1510756. */ public class PseudoSafeInc1 extends Thread { private PseudoAtomicCounter counter; private int times; public PseudoSafeInc1(PseudoAtomicCounter c,int n) { this.counter = c; this.times = n; } public void run() { for (int i = 0; i < times; i++) { counter.inc(); } } public static void main(String[] args) throws InterruptedException { PseudoAtomicCounter c1 = new PseudoAtomicCounter(); PseudoAtomicCounter c2 = new PseudoAtomicCounter(); PseudoAtomicCounter c3 = new PseudoAtomicCounter(); Thread t1 = new PseudoSafeInc1(c1,1000000); Thread t2 = new PseudoSafeInc1(c2,1000000); Thread t3 = new PseudoSafeInc1(c3,1000000); t1.start(); t2.start(); t3.start(); t1.join(); t2.join(); t3.join(); System.out.println("Counter: " + c1.get()); } }
mit
rupendrab/GreenplumJDBC
src/util/ParseParameters.java
898
package util; public class ParseParameters { public static String findAttribute (String attributeKey, String[] args) { String attributeValue = null; int i = 0; while (i < args.length) { if (args[i].toLowerCase().equals("-" + attributeKey)) { try { attributeValue = new String(args[i + 1]); } catch (Exception e) {} i++; break; } i++; } return attributeValue; } public static boolean existsAttribute (String attributeKey, String[] args) { int i = 0; while (i < args.length) { if (args[i].toLowerCase().equals("-" + attributeKey)) { return true; } i++; } return false; } }
mit
GameShopAdvance/GameShop-Advance
GameShop Advance Server/src/gameshop/advance/model/transazione/sconto/vendita/ScontoTotaleVenditaStrategy.java
1825
/* * 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 gameshop.advance.model.transazione.sconto.vendita; import gameshop.advance.interfaces.IScontoVenditaStrategy; import gameshop.advance.interfaces.ITransazione; import gameshop.advance.interfaces.remote.sales.IRigaDiTransazioneRemote; import gameshop.advance.interfaces.remote.utility.IIteratorWrapperRemote; import gameshop.advance.utility.IntervalloDiTempo; import gameshop.advance.utility.Money; import java.rmi.RemoteException; import org.joda.time.DateTime; /** * * @author Salx */ public class ScontoTotaleVenditaStrategy implements IScontoVenditaStrategy { private Money ammontare; private IntervalloDiTempo periodo; public ScontoTotaleVenditaStrategy(Money m, IntervalloDiTempo time){ this.ammontare = m; this.periodo = time; } public void setScontoTotale(Money m){ this.ammontare = m; } public Money getScontoTotale(){ return this.ammontare; } @Override public Money getTotal(ITransazione vendita) throws RemoteException{ IIteratorWrapperRemote<IRigaDiTransazioneRemote> righe = vendita.getRigheDiVendita(); Money totale = new Money(); while(righe.hasNext()) { totale = totale.add(righe.next().getSubTotal()); } totale = totale.subtract(this.ammontare); if(totale.greater(new Money())) return totale; return new Money(); } @Override public boolean isValid(DateTime period) { return this.periodo.isInPeriod(period); } }
mit
intronate67/Underground
src/main/java/net/huntersharpe/Underground/util/Configurable.java
1477
/* * This file is part of EssentialCmds, licensed under the MIT License (MIT). * * Copyright (c) 2015 - 2015 HassanS6000 * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.huntersharpe.Underground.util; import ninja.leaping.configurate.commented.CommentedConfigurationNode; public interface Configurable { void setup(); void load(); void save(); CommentedConfigurationNode get(); }
mit
selvasingh/azure-sdk-for-java
sdk/formrecognizer/azure-ai-formrecognizer/src/samples/java/com/azure/ai/formrecognizer/RecognizeCustomFormsAsync.java
3935
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.ai.formrecognizer; import com.azure.ai.formrecognizer.models.FormRecognizerOperationResult; import com.azure.ai.formrecognizer.models.RecognizedForm; import com.azure.core.credential.AzureKeyCredential; import com.azure.core.util.polling.PollerFlux; import reactor.core.publisher.Mono; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.util.List; import java.util.concurrent.TimeUnit; import static com.azure.ai.formrecognizer.implementation.Utility.toFluxByteBuffer; /** * Async sample to analyze a form from a document with a custom trained model. To learn how to train your own models, * look at TrainModelWithoutLabels.java and TrainModelWithLabels.java. */ public class RecognizeCustomFormsAsync { /** * Main method to invoke this demo. * * @param args Unused arguments to the program. * * @throws IOException Exception thrown when there is an error in reading all the bytes from the File. */ public static void main(String[] args) throws IOException { // Instantiate a client that will be used to call the service. FormRecognizerAsyncClient client = new FormRecognizerClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("https://{endpoint}.cognitiveservices.azure.com/") .buildAsyncClient(); // The form you are recognizing must be of the same type as the forms the custom model was trained on File sourceFile = new File("../formrecognizer/azure-ai-formrecognizer/src/samples/java/sample-forms/" + "forms/Invoice_6.pdf"); byte[] fileContent = Files.readAllBytes(sourceFile.toPath()); String modelId = "{modelId}"; PollerFlux<FormRecognizerOperationResult, List<RecognizedForm>> recognizeFormPoller; try (InputStream targetStream = new ByteArrayInputStream(fileContent)) { recognizeFormPoller = client.beginRecognizeCustomForms(modelId, toFluxByteBuffer(targetStream), sourceFile.length()); } Mono<List<RecognizedForm>> recognizeFormResult = recognizeFormPoller .last() .flatMap(pollResponse -> { if (pollResponse.getStatus().isComplete()) { // training completed successfully, retrieving final result. return pollResponse.getFinalResult(); } else { return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:" + pollResponse.getStatus())); } }); recognizeFormResult.subscribe(recognizedForms -> { for (int i = 0; i < recognizedForms.size(); i++) { final RecognizedForm form = recognizedForms.get(i); System.out.printf("----------- Recognized custom form info for page %d -----------%n", i); System.out.printf("Form type: %s%n", form.getFormType()); form.getFields().forEach((label, formField) -> { System.out.printf("Field '%s' has label '%s' with confidence score of %.2f.%n", label, formField.getLabelData().getText(), formField.getConfidence()); }); } }); // The .subscribe() creation and assignment is not a blocking call. For the purpose of this example, we sleep // the thread so the program does not end before the send operation is complete. Using .block() instead of // .subscribe() will turn this into a synchronous call. try { TimeUnit.MINUTES.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } }
mit
UkiyoESoragoto/JSP_E-commerce
src/ata/wx/shopping/servlet/BuyServlet.java
2434
package ata.wx.shopping.servlet; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import ata.wx.shopping.busbean.UserFormOBean; import ata.wx.shopping.factory.DAOFactory; import ata.wx.shopping.vo.Product; import ata.wx.shopping.vo.User; public class BuyServlet extends HttpServlet { List pList=new ArrayList(); public BuyServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pid=request.getParameter("pid"); System.out.println(pid); if("buy".equals(request.getParameter("option"))) { String[] pList2=request.getParameterValues("pids"); if(pList2==null) { response.sendRedirect(request.getContextPath()+"/buyfail.jsp"); return; } List<Product> pList3=new ArrayList<Product>(); for(int i=0;i<pList2.length;i++) { try { Product product=DAOFactory.getProductDAOInstance().selectById(pList2[i]); pList3.add(product); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } User user=(User)request.getSession().getAttribute("loginusername"); UserFormOBean.buyProcess(user.getUsername(), pList3); request.getSession().removeAttribute("pList"); pList.clear(); response.sendRedirect(request.getContextPath()+"/buyok.jsp"); } else if ("clean".equals(request.getParameter("option"))) { request.getSession().removeAttribute("pList"); pList.clear(); response.sendRedirect(request.getContextPath()+"/shopcart.jsp"); } else { if(pid!=null){ pList.add(pid); request.getSession().setAttribute("pList", pList); response.sendRedirect(request.getContextPath()+"/shopcart.jsp"); return; } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
mit
jwlin/web-apollo-dbdump
src/org/bbop/apollo/web/dataadapter/fasta/FastaJEDatabaseIO.java
2469
package org.bbop.apollo.web.dataadapter.fasta; import java.io.IOException; import java.util.Iterator; import java.util.Set; import org.bbop.apollo.editor.session.AnnotationSession; import org.bbop.apollo.web.datastore.JEDatabase; import org.bbop.apollo.web.util.FeatureIterator; import org.gmod.gbol.bioObject.SequenceAlteration; import org.gmod.gbol.bioObject.conf.BioObjectConfiguration; import org.gmod.gbol.bioObject.io.FastaHandler; import org.gmod.gbol.bioObject.util.BioObjectUtil; import org.gmod.gbol.simpleObject.Feature; import org.gmod.gbol.simpleObject.io.SimpleObjectIOException; import org.gmod.gbol.util.SequenceUtil.TranslationTable; public class FastaJEDatabaseIO extends FastaIO { private JEDatabase jeDatabase; public FastaJEDatabaseIO(String databaseDir, String path, String source, BioObjectConfiguration conf, TranslationTable translationTable) throws Exception { this(databaseDir, path, source, conf, true, FastaHandler.Format.GZIP, translationTable); } public FastaJEDatabaseIO(String databaseDir, String path, String source, BioObjectConfiguration conf, boolean readOnly, TranslationTable translationTable) throws Exception { this(databaseDir, path, source, conf, readOnly, FastaHandler.Format.GZIP, translationTable); } public FastaJEDatabaseIO(String databaseDir, String path, String seqType, BioObjectConfiguration conf, boolean readOnly, FastaHandler.Format format, TranslationTable translationTable) throws Exception { super(path, seqType, format, conf, null, translationTable); setJeDatabase(databaseDir, readOnly); session = new AnnotationSession(); for (Iterator<Feature> iter = jeDatabase.getSequenceAlterationIterator(); iter.hasNext(); ) { session.addSequenceAlteration((SequenceAlteration)BioObjectUtil.createBioObject(iter.next(), conf)); } } public void setJeDatabase(String databaseDir, boolean readOnly) { if (jeDatabase != null) { jeDatabase.close(); } jeDatabase = new JEDatabase(databaseDir, readOnly); } public void writeFeatures(Feature sourceFeature, String seqType, Set<String> featureTypes, Set<String> metaDataToExport) throws SimpleObjectIOException, IOException { FeatureIterator featureIterator = new FeatureIterator(jeDatabase.getFeatureIterator(), sourceFeature, conf); writeFeatures(featureIterator, seqType, featureTypes, metaDataToExport); } @Override public void close() { super.close(); if (jeDatabase != null) { jeDatabase.close(); } } }
mit
ribasco/async-gamequery-lib
core/src/main/java/com/ibasco/agql/core/AbstractRequest.java
1391
/* * MIT License * * Copyright (c) 2018 Asynchronous Game Query Library * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.ibasco.agql.core; import java.net.InetSocketAddress; abstract public class AbstractRequest<T> extends AbstractMessage<T> { public AbstractRequest(InetSocketAddress recipient) { super(null, recipient); } }
mit
schnalle/enrico
src/main/java/net/h34t/enrico/op/PrintOp.java
718
package net.h34t.enrico.op; import net.h34t.enrico.*; import java.io.IOException; public class PrintOp implements Operation { private final Ref r; public PrintOp(Ref r) { this.r = r; } @Override public Integer exec(VM vm) { try { vm.out.write(r.getValue(vm)); } catch (IOException e) { e.printStackTrace(); } vm.next(1); return null; } @Override public int length() { return 3; } @Override public int[] encode(LabelOffsetTranslator lot) { return Encoder.encode(lot, PRINT, r); } @Override public String toString() { return "print " + r.toString(); } }
mit
cucumber/cucumber-jvm
core/src/test/java/io/cucumber/core/stepexpression/StepTypeRegistryTest.java
2484
package io.cucumber.core.stepexpression; import com.fasterxml.jackson.databind.JsonNode; import io.cucumber.cucumberexpressions.Expression; import io.cucumber.cucumberexpressions.ExpressionFactory; import io.cucumber.cucumberexpressions.ParameterByTypeTransformer; import io.cucumber.cucumberexpressions.ParameterType; import io.cucumber.datatable.DataTable; import io.cucumber.datatable.DataTableType; import io.cucumber.datatable.TableCellByTypeTransformer; import io.cucumber.datatable.TableEntryByTypeTransformer; import io.cucumber.docstring.DocStringType; import org.junit.jupiter.api.Test; import java.util.Date; import static java.util.Locale.ENGLISH; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; class StepTypeRegistryTest { private final StepTypeRegistry registry = new StepTypeRegistry(ENGLISH); private final ExpressionFactory expressionFactory = new ExpressionFactory(registry.parameterTypeRegistry()); @Test void should_define_parameter_type() { ParameterType<Object> expected = new ParameterType<>( "example", ".*", Object.class, (String s) -> null); registry.defineParameterType(expected); Expression expresion = expressionFactory.createExpression("{example}"); assertThat(expresion.getRegexp().pattern(), is("^(.*)$")); } @Test void should_define_data_table_parameter_type() { DataTableType expected = new DataTableType(Date.class, (DataTable dataTable) -> null); registry.defineDataTableType(expected); } @Test void should_define_doc_string_parameter_type() { DocStringType expected = new DocStringType(JsonNode.class, "json", (String s) -> null); registry.defineDocStringType(expected); } @Test void should_set_default_parameter_transformer() { ParameterByTypeTransformer expected = (fromValue, toValueType) -> null; registry.setDefaultParameterTransformer(expected); } @Test void should_set_default_table_cell_transformer() { TableCellByTypeTransformer expected = (cell, toValueType) -> null; registry.setDefaultDataTableCellTransformer(expected); } @Test void should_set_default_table_entry_transformer() { TableEntryByTypeTransformer expected = (entry, toValueType, tableCellByTypeTransformer) -> null; registry.setDefaultDataTableEntryTransformer(expected); } }
mit
aviolette/foodtrucklocator
main/src/main/java/foodtruck/appengine/dao/appengine/MessageDAOAppEngine.java
2655
package foodtruck.appengine.dao.appengine; import java.util.List; import javax.annotation.Nullable; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Query; import com.google.inject.Inject; import com.google.inject.Provider; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; import foodtruck.dao.MessageDAO; import foodtruck.model.Message; import static com.google.appengine.api.datastore.Query.FilterOperator.GREATER_THAN_OR_EQUAL; import static com.google.appengine.api.datastore.Query.SortDirection.ASCENDING; /** * @author aviolette * @since 2/6/14 */ class MessageDAOAppEngine extends AppEngineDAO<Long, Message> implements MessageDAO { private static final String MESSAGE_KIND = "message"; private final DateTimeZone zone; @Inject public MessageDAOAppEngine(Provider<DatastoreService> provider, DateTimeZone zone) { super(MESSAGE_KIND, provider); this.zone = zone; } @Override protected void modifyFindAllQuery(Query q) { q.addSort("startTime", ASCENDING); } @Override protected Entity toEntity(Message obj, Entity entity) { entity.setProperty("message", obj.getMessage()); Attributes.setDateProperty("startTime", entity, obj.getStartTime()); Attributes.setDateProperty("endTime", entity, obj.getEndTime()); return entity; } @Override protected Message fromEntity(Entity entity) { return new Message(entity.getKey() .getId(), (String) entity.getProperty("message"), Attributes.getDateTime(entity, "startTime", zone), Attributes.getDateTime(entity, "endTime", zone)); } @Override public @Nullable Message findByDay(LocalDate day) { DateTime instant = day.toDateTimeAtStartOfDay(zone), tomorrowExclusive = instant.plusDays(1) .minusMillis(1); // TODO: this code is wildly inefficient for (Message m : aq().filter(predicate("endTime", GREATER_THAN_OR_EQUAL, instant.toDate())) .sort("endTime", ASCENDING) .execute()) { boolean endsAfterTomorrow = m.getEndTime() .plusDays(1) .isAfter(tomorrowExclusive); boolean startsBeforeToday = m.getStartTime() .isBefore(instant.plusMinutes(1)); if (endsAfterTomorrow && startsBeforeToday) { return m; } } return null; } @Override public List<Message> findExpiresAfter(LocalDate dateTime) { return aq().filter(predicate("endTime", GREATER_THAN_OR_EQUAL, dateTime.toDateTimeAtCurrentTime() .toDate())) .execute(); } }
mit
v1v/jenkinslint-plugin
src/main/java/org/jenkins/ci/plugins/jenkinslint/check/CleanupWorkspaceChecker.java
1057
package org.jenkins.ci.plugins.jenkinslint.check; import hudson.model.Descriptor; import hudson.model.Item; import hudson.model.Project; import jenkins.model.Jenkins; import org.jenkins.ci.plugins.jenkinslint.model.AbstractCheck; /** * @author Victor Martinez */ public class CleanupWorkspaceChecker extends AbstractCheck{ public CleanupWorkspaceChecker() { super(); this.setDescription("There are some builds which demand a lot of disc space. Some builds might run " + "out of space during the build itself and cause build errors.<br/>" + "It's recommended to wipe out those workspaces after building."); this.setSeverity("Medium"); } public boolean executeCheck(Item item) { if (Jenkins.getInstance().pluginManager.getPlugin("ws-cleanup")!=null) { return item instanceof Project && ((Project) item).getPublisher(Descriptor.find("hudson.plugins.ws_cleanup.WsCleanup")) == null; } else { return true; } } }
mit
stormj/OldProjects
ChatClient/src/client/ChatWindow.java
4212
package client; import java.awt.BorderLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class ChatWindow extends JFrame { /** * */ private static final long serialVersionUID = 1388544483060101676L; private static final String host = "82.170.206.79"; private static final int port = 60606; private static final String endl = "\n"; private Socket socket; private DataInputStream in; private DataOutputStream out; private boolean connected = false; private JTextField textField; private JTextArea chatText; public ChatWindow(int lobby) { setupUI(); setupNetwork(lobby); } private final void setupUI() { setSize(400, 400); setResizable(true); getContentPane().setLayout(new BorderLayout(5, 5)); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { disconnect(); } }); textField = new JTextField(); textField.addActionListener(event -> { String message = textField.getText(); textField.setText(""); try { out.writeUTF(message); } catch (IOException e) { disconnect(); } }); textField.setEditable(false); textField.setCaretPosition(0); textField.setFocusable(true); getContentPane().add(textField, BorderLayout.PAGE_START); chatText = new JTextArea(); chatText.setEditable(false); chatText.setVisible(true); JScrollPane scroll = new JScrollPane(chatText); getContentPane().add(scroll); } private final void setupNetwork(int lobbyId) { new Thread( () -> { chatText.append("Trying to connect..."); try { int lobby = lobbyId; socket = new Socket(host, port); in = new DataInputStream(socket.getInputStream()); out = new DataOutputStream(socket.getOutputStream()); if (lobby == -1) { lobby = getLobby(); } String username = getUsername(); setTitle("You are in lobby " + lobby + " as " + username); out.writeInt(lobby); out.writeUTF(username); connected = true; textField.setEditable(true); textField.getCaret().setVisible(true); chatText.append(endl + "Connected"); new Thread(() -> { while (connected) { try { String input = in.readUTF(); chatText.append(endl + input); chatText.setCaretPosition(chatText .getDocument().getLength()); } catch (IOException e) { chatText.append(endl + "Connection lost"); disconnect(); } } }).start(); } catch (Exception e) { chatText.append(endl + "Something went wrong while connecting. Please restart to try again"); disconnect(); } }).start(); } private int getLobby() { String input = JOptionPane.showInputDialog("Enter a lobby number"); try { int lobbyid = Integer.parseInt(input); if (lobbyid != Math.abs(lobbyid)) { throw new NumberFormatException(); } return lobbyid; } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "You must enter a positive number"); return getLobby(); } } private String getUsername() { String input = JOptionPane.showInputDialog("Enter a username"); if (input.contains(":")) { JOptionPane.showMessageDialog(null, "The username cannot contain semicolons"); return getUsername(); } else if (input.contains(" ")) { JOptionPane.showMessageDialog(null, "The username cannot contain whitespaces"); return getUsername(); } else if (input.equals("")) { JOptionPane.showMessageDialog(null, "The username cannot be empty"); return getUsername(); } else { return input; } } private void disconnect() { textField.setText(""); connected = false; textField.setEditable(false); try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } try { socket.close(); } catch (Exception e) { } } }
mit
compasses/elastic-rabbitmq
app/src/main/java/ElasticRabbitApp.java
1730
import http.Config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.Banner; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ComponentScan; import rabbitmq.ListenerJobBuilder; import rabbitmq.MQListenerAdmin; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReadWriteLock; /** * Created by I311352 on 12/28/2016. */ @SpringBootConfiguration @EnableAutoConfiguration @EnableHystrix @EnableCircuitBreaker @EnableHystrixDashboard @ComponentScan({ "elasticsearch","rabbitmq", "sync"}) public class ElasticRabbitApp implements CommandLineRunner { @Autowired private ConfigurableApplicationContext context; public static void main(String[] args) { SpringApplication.run(ElasticRabbitApp.class, args); } @Override public void run(String... args) throws Exception { MQListenerAdmin listenerAdmin = ListenerJobBuilder.buildMQListenerAdmin(context); listenerAdmin.start(); new HttpServerBoot(context).run(); } }
mit
EDACC/edacc_gui
src/edacc/model/NoComputationMethodBinarySpecifiedException.java
313
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edacc.model; /** * * @author rretz */ public class NoComputationMethodBinarySpecifiedException extends Exception{ public NoComputationMethodBinarySpecifiedException() { super(); } }
mit
PHILIP-2014/rapid-framework-easy
generator/src/cn/org/rapid_framework/generator/provider/java/model/JavaProperty.java
812
package cn.org.rapid_framework.generator.provider.java.model; import java.beans.PropertyDescriptor; import cn.org.rapid_framework.generator.util.ActionScriptDataTypesUtils; public class JavaProperty { PropertyDescriptor propertyDescriptor; JavaClass clazz; public JavaProperty(PropertyDescriptor pd, JavaClass javaClass) { this.propertyDescriptor = pd; this.clazz = javaClass; } public String getName() { return propertyDescriptor.getName(); } public String getJavaType() { return propertyDescriptor.getPropertyType().getName(); } public String getAsType() { return ActionScriptDataTypesUtils.getPreferredAsType(propertyDescriptor.getPropertyType().getName()); } public String toString() { return "JavaClass:"+clazz+" JavaProperty:"+getName(); } }
mit
sundayliu/peony
Android/X509CertTest/src/com/sundayliu/io/Streams.java
7241
/* * Copyright (C) 2010 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 com.sundayliu.io; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringWriter; import java.util.Arrays; import java.util.concurrent.atomic.AtomicReference; public final class Streams { private static AtomicReference<byte[]> skipBuffer = new AtomicReference<byte[]>(); private Streams() {} /** * Implements InputStream.read(int) in terms of InputStream.read(byte[], int, int). * InputStream assumes that you implement InputStream.read(int) and provides default * implementations of the others, but often the opposite is more efficient. */ public static int readSingleByte(InputStream in) throws IOException { byte[] buffer = new byte[1]; int result = in.read(buffer, 0, 1); return (result != -1) ? buffer[0] & 0xff : -1; } /** * Implements OutputStream.write(int) in terms of OutputStream.write(byte[], int, int). * OutputStream assumes that you implement OutputStream.write(int) and provides default * implementations of the others, but often the opposite is more efficient. */ public static void writeSingleByte(OutputStream out, int b) throws IOException { byte[] buffer = new byte[1]; buffer[0] = (byte) (b & 0xff); out.write(buffer); } /** * Fills 'dst' with bytes from 'in', throwing EOFException if insufficient bytes are available. */ public static void readFully(InputStream in, byte[] dst) throws IOException { readFully(in, dst, 0, dst.length); } /** * Reads exactly 'byteCount' bytes from 'in' (into 'dst' at offset 'offset'), and throws * EOFException if insufficient bytes are available. * * Used to implement {@link java.io.DataInputStream#readFully(byte[], int, int)}. */ public static void readFully(InputStream in, byte[] dst, int offset, int byteCount) throws IOException { if (byteCount == 0) { return; } if (in == null) { throw new NullPointerException("in == null"); } if (dst == null) { throw new NullPointerException("dst == null"); } //Arrays.checkOffsetAndCount(dst.length, offset, byteCount); while (byteCount > 0) { int bytesRead = in.read(dst, offset, byteCount); if (bytesRead < 0) { throw new EOFException(); } offset += bytesRead; byteCount -= bytesRead; } } /** * Returns a byte[] containing the remainder of 'in', closing it when done. */ public static byte[] readFully(InputStream in) throws IOException { try { return readFullyNoClose(in); } finally { in.close(); } } /** * Returns a byte[] containing the remainder of 'in'. */ public static byte[] readFullyNoClose(InputStream in) throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int count; while ((count = in.read(buffer)) != -1) { bytes.write(buffer, 0, count); } return bytes.toByteArray(); } /** * Returns the remainder of 'reader' as a string, closing it when done. */ public static String readFully(Reader reader) throws IOException { try { StringWriter writer = new StringWriter(); char[] buffer = new char[1024]; int count; while ((count = reader.read(buffer)) != -1) { writer.write(buffer, 0, count); } return writer.toString(); } finally { reader.close(); } } public static void skipAll(InputStream in) throws IOException { do { in.skip(Long.MAX_VALUE); } while (in.read() != -1); } /** * Call {@code in.read()} repeatedly until either the stream is exhausted or * {@code byteCount} bytes have been read. * * <p>This method reuses the skip buffer but is careful to never use it at * the same time that another stream is using it. Otherwise streams that use * the caller's buffer for consistency checks like CRC could be clobbered by * other threads. A thread-local buffer is also insufficient because some * streams may call other streams in their skip() method, also clobbering the * buffer. */ public static long skipByReading(InputStream in, long byteCount) throws IOException { // acquire the shared skip buffer. byte[] buffer = skipBuffer.getAndSet(null); if (buffer == null) { buffer = new byte[4096]; } long skipped = 0; while (skipped < byteCount) { int toRead = (int) Math.min(byteCount - skipped, buffer.length); int read = in.read(buffer, 0, toRead); if (read == -1) { break; } skipped += read; if (read < toRead) { break; } } // release the shared skip buffer. skipBuffer.set(buffer); return skipped; } /** * Copies all of the bytes from {@code in} to {@code out}. Neither stream is closed. * Returns the total number of bytes transferred. */ public static int copy(InputStream in, OutputStream out) throws IOException { int total = 0; byte[] buffer = new byte[8192]; int c; while ((c = in.read(buffer)) != -1) { total += c; out.write(buffer, 0, c); } return total; } /** * Returns the ASCII characters up to but not including the next "\r\n", or * "\n". * * @throws java.io.EOFException if the stream is exhausted before the next newline * character. */ public static String readAsciiLine(InputStream in) throws IOException { // TODO: support UTF-8 here instead StringBuilder result = new StringBuilder(80); while (true) { int c = in.read(); if (c == -1) { throw new EOFException(); } else if (c == '\n') { break; } result.append((char) c); } int length = result.length(); if (length > 0 && result.charAt(length - 1) == '\r') { result.setLength(length - 1); } return result.toString(); } }
mit
dhild/jcollada
jcollada-schema-1.5/src/main/java/net/dryanhild/collada/schema15/data/fx/AbstractAddressableAndScoped.java
502
package net.dryanhild.collada.schema14.data.fx; import net.dryanhild.collada.data.ScopeAddressableType; import net.dryanhild.collada.schema14.data.AbstractAddressable; public abstract class AbstractAddressableAndScoped extends AbstractAddressable implements ScopeAddressableType { private final String sid; public AbstractAddressableAndScoped(String id, String sid) { super(id); this.sid = sid; } @Override public String getSID() { return sid; } }
mit
RathinakumarVisweswaran/MeetCI
Java/JAVA_Plugin/src/xess/Rule.java
8363
// // $Id: $ // package xess; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; /** * An {@link Xess} system is composed of a knowledge base (which itself is * composed from {@link Fact Facts}), and a set of {@link Rule Rules} that * operate on those {@link Fact Facts}. The {@link Rule} class defines the * properties that make up an {@link Xess} {@link Rule}. * * @author rstjacques */ public class Rule implements XmlElement { /** * Each {@link Rule} has a single <i>if {@link Clause}</i>. If the <i>if * {@link Clause}</i> is satisfied, the {@link #getThenActions() then * action(s)} will be executed. If the <i>if {@link Clause}</i> fails to * be satisfied, the {@link #getElseActions() else action(s)} will be * executed (if any). */ private Clause ifClause; /** * A {@link Collection} of {@link Parameter Parameters} that define the * expected input to the {@link Rule}. */ private final Collection<Parameter> parameters; /** * A {@link Collection} of {@link Action Actions} that will be taken if * the <i>if {@link Clause}</i> is satisfied. */ private final Collection<Action> thenActions; /** * A {@link Collection} of {@link Action Actions} that will be taken if * the <i>if {@link Clause}</i> fails to be satisfied. */ private final Collection<Action> elseActions; /** * The name of the {@link Rule}; this name must be unique within the * {@link Xess} to which the {@link Rule} belongs. */ private final String name; /** * Creates a new {@link Rule} with the specified name. * * @param n The name of the new {@link Rule}. */ public Rule( String n ) { name = n; parameters = new HashSet<Parameter>(); thenActions = new LinkedList<Action>(); elseActions = new LinkedList<Action>(); } public String toXml() { //open the rule tag StringBuffer buf = new StringBuffer( "<" ); buf.append( RULE ); buf.append( " " ); buf.append( NAME ); buf.append( "=\"" ); buf.append( getName()); buf.append( "\">" ); //parameters synchronized( parameters ) { for( Parameter p : parameters ) { buf.append( p.toXml()); } } //if clause Clause c = getIfClause(); buf.append( "<" ); buf.append( IF ); buf.append( ">" ); buf.append( c.toXml()); buf.append( "</" ); buf.append( IF ); buf.append( ">" ); //then synchronized( thenActions ) { Iterator<Action> it = thenActions.iterator(); if( it.hasNext()) { buf.append( "<" ); buf.append( THEN ); buf.append( ">" ); while( it.hasNext()) { Action action = it.next(); buf.append( action.toXml()); } buf.append( "</" ); buf.append( THEN ); buf.append( ">" ); } } //else synchronized( elseActions ) { Iterator<Action> it = elseActions.iterator(); if( it.hasNext()) { buf.append( "<" ); buf.append( ELSE ); buf.append( ">" ); while( it.hasNext()) { Action action = it.next(); buf.append( action.toXml()); } buf.append( "</" ); buf.append( ELSE ); buf.append( ">" ); } } //close the rule tag buf.append( "</" ); buf.append( RULE ); buf.append( ">" ); return buf.toString(); } public String getName() { return name; } // // parameters // /** * Sets the specified {@link Parameter} on the {@link Rule}. If no other * {@link Parameter Parameters} with the specified name exist, the new * {@link Parameter} is added. If a {@link Parameter} with the specified * name does already exist, it is replaced by the new {@link Parameter}. * * @param p The {@link Parameter} to set on the {@link Rule}. */ public void setParameter( Parameter p ) { synchronized( parameters ) { parameters.add( p ); } } /** * Returns a {@link Collection} containing the current {@link Parameter * Parameters} for the {@link Rule}. * * @return A {@link Collection} containing the current {@link Parameter * Parameters} for the {@link Rule}. */ public Collection<Parameter> getParameters() { synchronized( parameters ) { return new HashSet<Parameter>( parameters ); } } /** * Removes the specified {@link Parameter} from the set of * {@link Parameter Parameters} for the {@link Rule}. * * @param p The {@link Parameter} to remove from the {@link Rule}. */ public void removeParameter( Parameter p ) { synchronized( parameters ) { parameters.remove( p ); } } // // if clause // /** * Sets the <i>if {@link Clause}</i> for the {@link Rule}. Each * {@link Rule} has a single <i>if {@link Clause}</i>. If the <i>if * {@link Clause}</i> is satisfied, the {@link #getThenActions() then * action(s)} will be executed. If the <i>if {@link Clause}</i> fails to * be satisfied, the {@link #getElseActions() else action(s)} will be * executed (if any). * * @param ifc The value to which the <i>if {@link Clause}</i> should be * set. This value should not be null. */ public void setIfClause( Clause ifc ) { ifClause = ifc; } /** * Returns the <i>if {@link Clause}</i> for the {@link Rule}. * * @return The <i>if {@link Clause}</i> for the {@link Rule}. * * @see #setIfClause(Clause). */ public Clause getIfClause() { return ifClause; } // // then actions // /** * Adds the specified {@link Action} to the {@link Collection} of * {@link Action Actions} that will be executed in the event that the * {@link #getIfClause() if clause} is satisfied. * * @param a The {@link Action} that should be added to the * {@link Collection} of <i>then {@link Action Actions}</i>. */ public void addThenAction( Action a ) { synchronized( thenActions ) { thenActions.add( a ); } } /** * Removes the specified {@link Action} from the {@link Collection} of * {@link Action Actions} that will be executed in the event that the * {@link #getIfClause() if clause} is satisfied. * * @param a The {@link Action} that should be removed from the * {@link Collection} of <i>then {@link Action Actions}</i>. */ public void removeThenAction( Action a ) { synchronized( thenActions ) { thenActions.remove( a ); } } /** * Returns the {@link Collection} of {@link Action Actions} that will be * executed in the event that the {@link #getIfClause() if clause} is * satisfied. * * @return The {@link Collection} of <i>then {@link Action Actions}</i>. */ public Collection<Action> getThenActions() { synchronized( thenActions ) { return new ArrayList<Action>( thenActions ); } } /** * Clears all of the current <i>then {@link Action Actions}</i> from the * {@link Rule}. */ public void clearThenActions() { synchronized( thenActions ) { thenActions.clear(); } } // // else actions // /** * Adds the specified {@link Action} to the {@link Collection} of * {@link Action Actions} that will be executed in the event that the * {@link #getIfClause() if clause} fails to be satisfied. * * @param a The {@link Action} that should be added to the * {@link Collection} of <i>else {@link Action Actions}</i>. */ public void addElseAction( Action a ) { synchronized( elseActions ) { elseActions.add( a ); } } /** * Removes the specified {@link Action} from the {@link Collection} of * {@link Action Actions} that will be executed in the event that the * {@link #getIfClause() if clause} fails to be satisfied. * * @param a The {@link Action} that should be removed from the * {@link Collection} of <i>else {@link Action Actions}</i>. */ public void removeElseAction( Action a ) { synchronized( elseActions ) { elseActions.remove( a ); } } /** * Returns the {@link Collection} of {@link Action Actions} that will be * executed in the event that the {@link #getIfClause() if clause} fails * to be satisfied. * * @return The {@link Collection} of <i>else {@link Action Actions}</i>. */ public Collection<Action> getElseActions() { synchronized( elseActions ) { return new ArrayList<Action>( elseActions ); } } /** * Clears all of the current <i>else {@link Action Actions}</i> from the * {@link Rule}. */ public void clearElseActions() { synchronized( elseActions ) { elseActions.clear(); } } } // Rule
mit
chrrasmussen/NTNU-Master-Project
no.ntnu.assignmentsystem.model/src/no/ntnu/assignmentsystem/services/coderunner/RuntimeExecutor.java
171
package no.ntnu.assignmentsystem.services.coderunner; import java.io.IOException; public interface RuntimeExecutor { Process exec(String command) throws IOException; }
mit
dingxwsimon/codingquestions
src/suffixtree/Suffix.java
2193
/** * This is a Java-port of Mark Nelson's C++ implementation of Ukkonen's * algorithm. * http://illya-keeplearning.blogspot.com/2009/04/suffix-trees-java-ukkonens- * algorithm.html */ package suffixtree; /** * Defines suffix. * <p/> * When a new tree is added to the table, we step through all the currently * defined suffixes from the active point to the end point. This structure * defines a <b>Suffix</b> by its final character. In the canonical * representation, we define that last character by starting at a node in the * tree, and following a string of characters, represented by * <b>first_char_index</b> and <b>last_char_index</b>. The two indices point * into the input string. Note that if a suffix ends at a node, there are no * additional characters needed to characterize its last character position. * When this is the case, we say the node is <b>explicit</b>, and set * <b>first_char_index > last_char_index<b> to flag that. */ public class Suffix { public int origin_node; public int first_char_index; public int last_char_index; public Suffix(int node, int start, int stop) { this.origin_node = node; this.first_char_index = start; this.last_char_index = stop; } public boolean explicit() { return this.first_char_index > this.last_char_index; } public boolean implicit() { return last_char_index >= first_char_index; } public void canonize() { if (!explicit()) { Edge edge = Edge.find(origin_node, SuffixTree.T[first_char_index]); int edge_span = edge.last_char_index - edge.first_char_index; while (edge_span <= (last_char_index - first_char_index)) { first_char_index = first_char_index + edge_span + 1; origin_node = edge.end_node; if (first_char_index <= last_char_index) { edge = Edge.find(edge.end_node, SuffixTree.T[first_char_index]); edge_span = edge.last_char_index - edge.first_char_index; } } } } }
mit
smarr/SOMns
src/tools/dym/MetricsCsvWriter.java
24289
package tools.dym; import java.io.File; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import org.graalvm.collections.EconomicMap; import org.graalvm.collections.EconomicSet; import com.oracle.truffle.api.source.Source; import com.oracle.truffle.api.source.SourceSection; import bd.tools.structure.StructuralProbe; import som.compiler.MixinDefinition; import som.compiler.MixinDefinition.SlotDefinition; import som.compiler.Variable; import som.interpreter.Invokable; import som.interpreter.nodes.dispatch.Dispatchable; import som.interpreter.objectstorage.ClassFactory; import som.vm.NotYetImplementedException; import som.vmobjects.SInvokable; import som.vmobjects.SSymbol; import tools.dym.Tags.ArrayRead; import tools.dym.Tags.ArrayWrite; import tools.dym.Tags.OpArithmetic; import tools.dym.Tags.OpClosureApplication; import tools.dym.Tags.OpComparison; import tools.dym.Tags.OpLength; import tools.dym.Tags.StringAccess; import tools.dym.profiles.AllocationProfile; import tools.dym.profiles.Arguments; import tools.dym.profiles.ArrayCreationProfile; import tools.dym.profiles.BranchProfile; import tools.dym.profiles.CallsiteProfile; import tools.dym.profiles.ClosureApplicationProfile; import tools.dym.profiles.Counter; import tools.dym.profiles.InvocationProfile; import tools.dym.profiles.LoopProfile; import tools.dym.profiles.OperationProfile; import tools.dym.profiles.ReadValueProfile; public final class MetricsCsvWriter { private final Map<String, Map<SourceSection, ? extends JsonSerializable>> data; private final String metricsFolder; // TODO: not sure, we should probably not depend on the probe here private final StructuralProbe<SSymbol, MixinDefinition, SInvokable, SlotDefinition, Variable> structuralProbe; private final int maxStackHeight; private final List<SourceSection> allStatements; private MetricsCsvWriter( final Map<String, Map<SourceSection, ? extends JsonSerializable>> data, final String metricsFolder, final StructuralProbe<SSymbol, MixinDefinition, SInvokable, SlotDefinition, Variable> probe, final int maxStackHeight, final List<SourceSection> allStatements) { this.data = data; this.metricsFolder = metricsFolder; this.structuralProbe = probe; this.maxStackHeight = maxStackHeight; this.allStatements = allStatements; } public static void fileOut( final Map<String, Map<SourceSection, ? extends JsonSerializable>> data, final String metricsFolder, // TODO: remove direct StructuralProbe passing hack final StructuralProbe<SSymbol, MixinDefinition, SInvokable, SlotDefinition, Variable> structuralProbe, final int maxStackHeight, final List<SourceSection> allStatements) { new MetricsCsvWriter(data, metricsFolder, structuralProbe, maxStackHeight, allStatements).createCsvFiles(); } private void createCsvFiles() { new File(metricsFolder).mkdirs(); methodActivations(); methodCallsites(); closureApplications(); newObjectCount(); newArrayCount(); fieldAccesses(); localAccesses(); usedClassesAndMethods(); generalStats(); branchProfiles(); operationProfiles(); loopProfiles(); } private static void processCoverage(final long counterVal, final SourceSection sourceSection, final Map<Source, Long[]> coverageMap) { Long[] array; Source src = sourceSection.getSource(); if (coverageMap.containsKey(src)) { array = coverageMap.get(src); } else if (src.getLineCount() == 0) { return; } else { array = new Long[src.getLineCount()]; coverageMap.put(src, array); } int line = sourceSection.getStartLine() - 1; if (array[line] == null) { array[line] = counterVal; } else { array[line] = Math.max(counterVal, array[line]); } } private void extractCoverageFromData(final Map<Source, Long[]> coverageMap) { for (Entry<String, Map<SourceSection, ? extends JsonSerializable>> e : data.entrySet()) { for (Entry<SourceSection, ? extends JsonSerializable> ee : e.getValue().entrySet()) { if (ee.getValue() instanceof Counter) { Counter c = (Counter) ee.getValue(); processCoverage(c.getValue(), c.getSourceSection(), coverageMap); } } } } private Map<Source, Long[]> getCoverageMap() { Map<Source, Long[]> coverageMap = new HashMap<>(); // cover executed lines extractCoverageFromData(coverageMap); // cover not executed lines for (SourceSection sourceSection : allStatements) { processCoverage(0, sourceSection, coverageMap); } return coverageMap; } private static final class CovStats { final int linesLoaded; final int linesExecuted; final int linesWithStatements; CovStats(final int linesLoaded, final int linesExecuted, final int linesWithStatements) { this.linesLoaded = linesLoaded; this.linesExecuted = linesExecuted; this.linesWithStatements = linesWithStatements; } } private CovStats getCoverageStats(final Map<Source, Long[]> coverageMap) { int linesLoaded = 0; int linesExecuted = 0; int linesWithStatements = 0; for (Entry<Source, Long[]> e : coverageMap.entrySet()) { Long[] lines = e.getValue(); linesLoaded += lines.length; for (Long l : lines) { if (l != null) { linesWithStatements += 1; long val = l; if (val > 0) { linesExecuted += 1; } } } } return new CovStats(linesLoaded, linesExecuted, linesWithStatements); } private void generalStats() { CovStats stats = getCoverageStats(getCoverageMap()); try (CsvWriter file = new CsvWriter(metricsFolder, "general-stats.csv", "Statistic", "Value")) { file.write("Max Stack Height", maxStackHeight); file.write("Lines Loaded", stats.linesLoaded); file.write("Lines Executed", stats.linesExecuted); file.write("Lines With Statements", stats.linesWithStatements); } } private String typeCategory(final String typeName) { switch (typeName) { case "Integer": return "int"; case "Double": return "float"; case "String": return "str"; case "Symbol": return "Symbol"; // TODO: keep this? case "Array": return "arr"; case "True": case "False": return "bool"; default: return "ref"; } } private String operationType(final OperationProfile p, final Arguments a) { Set<Class<?>> tags = p.getTags(); if (tags.contains(OpArithmetic.class)) { if (p.getOperation().equals("not")) { assert "bool".equals(typeCategory(a.getArgType(0))); assert "bool".equals(typeCategory(a.getArgType(1))); return "bool"; } else if (p.getOperation().equals("abs") || p.getOperation().equals("sqrt") || p.getOperation().equals("sin") || p.getOperation().equals("cos") || p.getOperation().equals("asInteger") || p.getOperation().equals("round")) { return typeCategory(a.getArgType(1)); } else if (p.getOperation().equals("as32BitUnsignedValue") || p.getOperation().equals("as32BitSignedValue")) { assert "int".equals(typeCategory(a.getArgType(0))); assert "int".equals(typeCategory(a.getArgType(1))); return "int"; } String left = typeCategory(a.getArgType(1)); String right = typeCategory(a.getArgType(2)); if (left.equals(right)) { return left; } String result = typeCategory(a.getArgType(0)); if (result.equals(right)) { return right; } else if (result.equals(left)) { return left; } throw new NotYetImplementedException(); } else if (tags.contains(OpComparison.class)) { if (p.getNumArgsAndResult() == 2) { return typeCategory(a.getArgType(1)); } String left = typeCategory(a.getArgType(1)); String right = typeCategory(a.getArgType(2)); if (left.equals(right)) { return left; } if ("ref".equals(left) || "ref".equals(right)) { return "ref"; } if ("float".equals(left) && "int".equals(right) || "int".equals(left) && "float".equals(right)) { return "float"; } throw new NotYetImplementedException(); } else if (tags.contains(ArrayRead.class) || tags.contains(ArrayWrite.class)) { assert a.argTypeIs(1, "Array") || a.argTypeIs(1, "ValueArray"); assert a.argTypeIs(2, "Integer"); if (tags.contains(ArrayRead.class)) { return typeCategory(a.getArgType(0)); } else { return typeCategory(a.getArgType(3)); } } else if (tags.contains(OpClosureApplication.class)) { return typeCategory(a.getArgType(0)); } else if (tags.contains(OpLength.class)) { return typeCategory(a.getArgType(1)); } else if (tags.contains(StringAccess.class)) { return "str"; } else if (p.getOperation().equals("ticks")) { return "int"; } throw new NotYetImplementedException(); } private static String[] toNameArray(final Set<Class<?>> tags) { String[] tagArr = tags.stream().map(c -> c.getSimpleName()).toArray(size -> new String[size]); Arrays.sort(tagArr); return tagArr; } private void operationProfiles() { @SuppressWarnings("unchecked") Map<SourceSection, OperationProfile> ops = (Map<SourceSection, OperationProfile>) data.get(JsonWriter.OPERATIONS); try (CsvWriter file = new CsvWriter(metricsFolder, "operations.csv", "Source Section", "Operation", "Category", "Type", "Invocations")) { for (Entry<SourceSection, OperationProfile> e : sortSS(ops)) { for (Entry<Arguments, Integer> a : sortArg(e.getValue().getArgumentTypes())) { file.write( getSourceSectionAbbrv(e.getKey()), e.getValue().getOperation(), String.join(" ", toNameArray(e.getValue().getTags())), operationType(e.getValue(), a.getKey()), // a.getKey().getOperationType() a.getValue()); } file.write( getSourceSectionAbbrv(e.getKey()), e.getValue().getOperation(), String.join(" ", toNameArray(e.getValue().getTags())), "TOTAL", e.getValue().getValue()); } } } private void methodActivations() { @SuppressWarnings("unchecked") Map<SourceSection, InvocationProfile> profiles = (Map<SourceSection, InvocationProfile>) data.get(JsonWriter.METHOD_INVOCATION_PROFILE); try (CsvWriter file = new CsvWriter(metricsFolder, "method-activations.csv", "Source Identifier", "Activation Count")) { for (Entry<SourceSection, InvocationProfile> e : sortSS(profiles)) { file.write( e.getValue().getMethod().getRootNode().getName(), e.getValue().getValue()); } } } private void methodCallsites() { @SuppressWarnings("unchecked") Map<SourceSection, CallsiteProfile> profiles = (Map<SourceSection, CallsiteProfile>) data.get(JsonWriter.METHOD_CALLSITE); try (CsvWriter file = new CsvWriter(metricsFolder, "method-callsites.csv", "Source Section", "Call Count", "Num Rcvrs", "Num Targets")) { for (Entry<SourceSection, CallsiteProfile> e : sortSS(profiles)) { CallsiteProfile p = e.getValue(); if (data.get(JsonWriter.FIELD_READS).containsKey(p.getSourceSection()) || data.get(JsonWriter.FIELD_WRITES).containsKey(p.getSourceSection()) || data.get(JsonWriter.CLASS_READS).containsKey(p.getSourceSection())) { continue; // filter out field reads, writes, and accesses to class objects } String abbrv = getSourceSectionAbbrv(p.getSourceSection()); Map<ClassFactory, Integer> receivers = p.getReceivers(); // int numRcvrsRecorded = receivers.values().stream().reduce(0, Integer::sum); Map<Invokable, Integer> calltargets = p.getCallTargets(); // int numCalltargetsInvoked = calltargets.values().stream().reduce(0, Integer::sum); file.write( abbrv, p.getValue(), receivers.values().size(), calltargets.values().size()); } } } private void closureApplications() { @SuppressWarnings("unchecked") Map<SourceSection, ClosureApplicationProfile> profiles = (Map<SourceSection, ClosureApplicationProfile>) data.get( JsonWriter.CLOSURE_APPLICATIONS); try (CsvWriter file = new CsvWriter(metricsFolder, "closure-applications.csv", "Source Section", "Call Count", "Num Targets")) { for (Entry<SourceSection, ClosureApplicationProfile> e : sortSS(profiles)) { ClosureApplicationProfile p = e.getValue(); String abbrv = getSourceSectionAbbrv(p.getSourceSection()); Map<Invokable, Integer> calltargets = p.getCallTargets(); file.write(abbrv, p.getValue(), calltargets.values().size()); } } } private void newObjectCount() { @SuppressWarnings("unchecked") Map<SourceSection, AllocationProfile> profiles = (Map<SourceSection, AllocationProfile>) data.get(JsonWriter.NEW_OBJECT_COUNT); try (CsvWriter file = new CsvWriter(metricsFolder, "new-objects.csv", "Source Section", "New Objects", "Number of Fields", "Class")) { for (Entry<SourceSection, AllocationProfile> e : sortSS(profiles)) { AllocationProfile p = e.getValue(); String abbrv = getSourceSectionAbbrv(p.getSourceSection()); file.write(abbrv, p.getValue(), p.getNumberOfObjectFields(), p.getTypeName()); } } } private void newArrayCount() { @SuppressWarnings("unchecked") Map<SourceSection, ArrayCreationProfile> profiles = (Map<SourceSection, ArrayCreationProfile>) data.get(JsonWriter.NEW_ARRAY_COUNT); try (CsvWriter file = new CsvWriter(metricsFolder, "new-arrays.csv", "Source Section", "New Arrays", "Size")) { for (Entry<SourceSection, ArrayCreationProfile> ee : sortSS(profiles)) { ArrayCreationProfile p = ee.getValue(); String abbrv = getSourceSectionAbbrv(p.getSourceSection()); for (Entry<Integer, Integer> e : sortInt(p.getSizes())) { file.write(abbrv, e.getValue(), e.getKey()); } } } } private void fieldAccesses() { @SuppressWarnings("unchecked") Map<SourceSection, ReadValueProfile> reads = (Map<SourceSection, ReadValueProfile>) data.get(JsonWriter.FIELD_READS); @SuppressWarnings("unchecked") Map<SourceSection, Counter> writes = (Map<SourceSection, Counter>) data.get(JsonWriter.FIELD_WRITES); try (CsvWriter file = new CsvWriter(metricsFolder, "field-accesses.csv", "Source Section", "Access Type", "Data Type", "Count")) { for (Entry<SourceSection, ReadValueProfile> ee : sortSS(reads)) { ReadValueProfile p = ee.getValue(); String abbrv = getSourceSectionAbbrv(p.getSourceSection()); for (Entry<ClassFactory, Integer> e : sortCF(p.getTypeProfile())) { file.write(abbrv, "read", e.getKey().getClassName().getString(), e.getValue()); } file.write(abbrv, "read", "ALL", p.getValue()); } for (Entry<SourceSection, Counter> e : sortSS(writes)) { Counter p = e.getValue(); String abbrv = getSourceSectionAbbrv(p.getSourceSection()); file.write(abbrv, "write", "ALL", p.getValue()); } } } private void localAccesses() { @SuppressWarnings("unchecked") Map<SourceSection, ReadValueProfile> reads = (Map<SourceSection, ReadValueProfile>) data.get(JsonWriter.LOCAL_READS); @SuppressWarnings("unchecked") Map<SourceSection, Counter> writes = (Map<SourceSection, Counter>) data.get(JsonWriter.LOCAL_WRITES); try (CsvWriter file = new CsvWriter(metricsFolder, "local-accesses.csv", "Source Section", "Access Type", "Data Type", "Count")) { for (Entry<SourceSection, ReadValueProfile> ee : sortSS(reads)) { ReadValueProfile p = ee.getValue(); String abbrv = getSourceSectionAbbrv(p.getSourceSection()); for (Entry<ClassFactory, Integer> e : sortCF(p.getTypeProfile())) { file.write( abbrv, "read", e.getKey().getClassName().getString(), e.getValue()); } file.write(abbrv, "read", "ALL", p.getValue()); } for (Entry<SourceSection, Counter> e : sortSS(writes)) { Counter p = e.getValue(); String abbrv = getSourceSectionAbbrv(p.getSourceSection()); file.write(abbrv, "write", "ALL", p.getValue()); } } } private static String getSourceSectionAbbrv(final SourceSection source) { String result = source.getSource().getName() + " pos=" + source.getCharIndex() + " len=" + source.getCharLength(); return result; } private int methodInvocationCount(final SInvokable method, final Collection<InvocationProfile> profiles) { InvocationProfile profile = null; for (InvocationProfile p : profiles) { if (p.getMethod() == method.getInvokable()) { profile = p; break; } } if (profile == null) { return 0; } else { return profile.getValue(); } } private int numExecutedMethods(final MixinDefinition mixin, final Collection<InvocationProfile> profiles) { int numMethodsExecuted = 0; EconomicMap<SSymbol, Dispatchable> disps = mixin.getInstanceDispatchables(); for (Dispatchable d : disps.getValues()) { if (d instanceof SInvokable) { int invokeCount = methodInvocationCount(((SInvokable) d), profiles); if (invokeCount > 0) { numMethodsExecuted += 1; } } } return numMethodsExecuted; } private void usedClassesAndMethods() { @SuppressWarnings("unchecked") Map<SourceSection, InvocationProfile> profiles = (Map<SourceSection, InvocationProfile>) data.get(JsonWriter.METHOD_INVOCATION_PROFILE); try (CsvWriter file = new CsvWriter(metricsFolder, "defined-classes.csv", "Class Name", "Source Section", "Methods Executed")) { for (MixinDefinition clazz : sortMD(structuralProbe.getClasses())) { file.write( clazz.getName().getString(), // TODO: get fully qualified name getSourceSectionAbbrv(clazz.getSourceSection()), numExecutedMethods(clazz, profiles.values())); } } try (CsvWriter file = new CsvWriter(metricsFolder, "defined-methods.csv", "Name", "Executed", "Execution Count")) { for (SInvokable i : sortInv(structuralProbe.getMethods())) { int numInvokations = methodInvocationCount(i, profiles.values()); String executed = (numInvokations == 0) ? "false" : "true"; file.write(i.toString(), executed, numInvokations); } } } private void branchProfiles() { @SuppressWarnings("unchecked") Map<SourceSection, BranchProfile> branches = (Map<SourceSection, BranchProfile>) data.get(JsonWriter.BRANCH_PROFILES); try (CsvWriter file = new CsvWriter(metricsFolder, "branches.csv", "Source Section", "TrueCnt", "FalseCnt", "Total")) { for (Entry<SourceSection, BranchProfile> e : sortSS(branches)) { file.write( getSourceSectionAbbrv(e.getKey()), e.getValue().getTrueCount(), e.getValue().getFalseCount(), e.getValue().getValue()); } } } private void loopProfiles() { @SuppressWarnings("unchecked") Map<SourceSection, LoopProfile> loops = (Map<SourceSection, LoopProfile>) data.get(JsonWriter.LOOPS); try (CsvWriter file = new CsvWriter(metricsFolder, "loops.csv", "Source Section", "Loop Activations", "Num Iterations")) { for (Entry<SourceSection, LoopProfile> e : sortSS(loops)) { for (Entry<Integer, Integer> l : sortInt(e.getValue().getIterations())) { file.write( getSourceSectionAbbrv(e.getKey()), l.getKey(), l.getValue()); } file.write( getSourceSectionAbbrv(e.getKey()), "TOTAL", e.getValue().getValue()); } } } private static int compare(final SourceSection a, final SourceSection b) { if (a == b) { return 0; } if (a.getSource() != b.getSource()) { return a.getSource().getName().compareTo(b.getSource().getName()); } if (a.getCharIndex() != b.getCharIndex()) { return a.getCharIndex() - b.getCharIndex(); } return b.getCharEndIndex() - a.getCharEndIndex(); } private static int compare(final MixinDefinition a, final MixinDefinition b) { if (a == null && b == null) { return 0; } else if (a == null) { return -1; } else if (b == null) { return 1; } int result = a.getName().getString().compareTo(b.getName().getString()); if (result != 0) { return result; } result = a.getSourceSection().getSource().getPath().compareTo( b.getSourceSection().getSource().getPath()); if (result != 0) { return result; } return Integer.compare( a.getSourceSection().getCharIndex(), b.getSourceSection().getCharIndex()); } private static SortedSet<MixinDefinition> sortMD(final EconomicSet<MixinDefinition> set) { TreeSet<MixinDefinition> sortedSet = new TreeSet<>((a, b) -> compare(a, b)); for (MixinDefinition m : set) { sortedSet.add(m); } assert sortedSet.size() == set.size(); return sortedSet; } private static <K, V> boolean contains(final EconomicMap<K, V> map, final V val) { for (V v : map.getValues()) { if (v.equals(val)) { return true; } } return false; } private static int compare(final SInvokable a, final SInvokable b) { if (a.getHolder() == b.getHolder()) { int result = a.toString().compareTo(b.toString()); if (result == 0 && a != b) { assert a.getHolder() != null : "TODO: need to handle this case"; if (contains(a.getHolder().getInstanceDispatchables(), a)) { return -1; } else { return 1; } } return result; } return compare(a.getHolder(), b.getHolder()); } private static SortedSet<SInvokable> sortInv(final EconomicSet<SInvokable> set) { TreeSet<SInvokable> sortedSet = new TreeSet<>((a, b) -> compare(a, b)); for (SInvokable i : set) { sortedSet.add(i); } assert sortedSet.size() == set.size(); return sortedSet; } private static <V> SortedSet<Entry<SourceSection, V>> sortSS( final Map<SourceSection, V> map) { return sort(map, (a, b) -> compare(a.getKey(), b.getKey())); } private static <V> SortedSet<Entry<Integer, V>> sortInt(final Map<Integer, V> map) { return sort(map, (a, b) -> a.getKey().compareTo(b.getKey())); } private static <V> SortedSet<Entry<Arguments, V>> sortArg(final Map<Arguments, V> map) { return sort(map, (a, b) -> a.getKey().toString().compareTo(b.getKey().toString())); } private static int compare(final ClassFactory a, final ClassFactory b) { if (a == b) { return 0; } int cmp = a.toString().compareTo(b.toString()); assert cmp != 0 : "Need to add that case"; return cmp; } private static <V> SortedSet<Entry<ClassFactory, V>> sortCF(final Map<ClassFactory, V> map) { return sort(map, (a, b) -> compare(a.getKey(), b.getKey())); } private static <K, V> SortedSet<Entry<K, V>> sort(final Map<K, V> map, final Comparator<Entry<K, V>> comparator) { SortedSet<Entry<K, V>> sortedSet = new TreeSet<>(comparator); sortedSet.addAll(map.entrySet()); assert sortedSet.size() == map.size(); return sortedSet; } }
mit
qanwi1970/jms
entry/src/test/java/com/example/jms/entry/jms/ArticleSenderTests.java
1510
package com.example.jms.entry.jms; import com.example.jms.entry.model.Article; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.jms.core.JmsTemplate; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class ArticleSenderTests { @MockBean private JmsTemplate mockJmsTemplate; @MockBean private ObjectMapper mockObjectMapper; @Autowired private ArticleSender articleSender; @Test public void articleSenderLoads() { // Arrange // Act // Assert Assert.assertNotNull(articleSender); } @Test public void sendArticleForAdd_convertsArticle() throws JsonProcessingException { // Arrange Article article = new Article(); String articleJson = "{\"articleId\": 1}"; Mockito.when(mockObjectMapper.writeValueAsString(article)).thenReturn(articleJson); // Act articleSender.sendArticleForAdd(article); // Assert Mockito.verify(mockObjectMapper).writeValueAsString(article); } }
mit
FelixCao/blackjacktrainer
Blackjack/Card.java
497
package Blackjack; /* * Class for a single Card */ public class Card { String suit; String rank; public Card(String cardRank, String cardSuit){ this.rank = cardRank; this.suit = cardSuit; } public String toString() { return this.getRank() +" of "+ this.getSuit(); } public String getSuit() { return suit; } public void setSuit(String suit) { this.suit = suit; } public String getRank() { return rank; } public void setRank(String rank) { this.rank = rank; } }
mit
ktisha/TheRPlugin
test/com/jetbrains/ther/run/debug/mock/MockXVarNode.java
1776
package com.jetbrains.ther.run.debug.mock; import com.intellij.icons.AllIcons; import com.intellij.xdebugger.frame.XFullValueEvaluator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; public class MockXVarNode extends IllegalXValueNode { @NotNull private final String myType; @NotNull private final String myShortValue; @Nullable private final String myFullValue; private int myPres; private int myEval; public MockXVarNode(@NotNull final String type, @NotNull final String shortValue, @Nullable final String fullValue) { myType = type; myShortValue = shortValue; myFullValue = fullValue; myPres = 0; myEval = 0; } @Override public void setPresentation(@Nullable final Icon icon, @Nullable final String type, @NotNull final String value, final boolean hasChildren) { myPres++; assertEquals(AllIcons.Debugger.Value, icon); assertEquals(myType, type); assertEquals(myShortValue, value); assertFalse(hasChildren); } @Override public void setFullValueEvaluator(@NotNull final XFullValueEvaluator fullValueEvaluator) { if (myFullValue == null) { throw new IllegalStateException("SetFullValueEvaluator shouldn't be called"); } myEval++; final MockXFullValueEvaluationCallback callback = new MockXFullValueEvaluationCallback(myFullValue); fullValueEvaluator.startEvaluation(callback); assertEquals(1, callback.getCounter()); } public int getPres() { return myPres; } public int getEval() { return myEval; } }
mit
fvasquezjatar/fermat-unused
OSA/addon/android/fermat-osa-addon-android-device-connectivity-bitdubai/src/main/java/com/bitdubai/fermat_osa_addon/layer/android/device_conectivity/developer/bitdubai/version_1/interfaces/ConnectivityManager.java
1127
package com.bitdubai.fermat_osa_addon.layer.android.device_conectivity.developer.bitdubai.version_1.interfaces; import com.bitdubai.fermat_osa_addon.layer.android.device_conectivity.developer.bitdubai.version_1.exceptions.CantGetActiveConnectionException; import com.bitdubai.fermat_osa_addon.layer.android.device_conectivity.developer.bitdubai.version_1.exceptions.CantGetConnectionsException; import com.bitdubai.fermat_osa_addon.layer.android.device_conectivity.developer.bitdubai.version_1.exceptions.CantGetIsConnectedException; import java.util.List; /** * * <p>The abstract class <code>ConnectivityManager</code> is a interface * that define the methods to manage device connection network. * * * @author Natalia * @version 1.0.0 * @since 04/05/15. * */ public interface ConnectivityManager { public List<Network> getConnections() throws CantGetConnectionsException; public Network getActiveConnection() throws CantGetActiveConnectionException; public boolean isConnected(ConnectionType redType) throws CantGetIsConnectedException; public void setContext (Object context); }
mit
sprinklr-inc/twitter4j-ads
twitter4j-ads/src/twitter4jads/auth/OAuthSupport.java
8728
/* * Copyright 2007 Yusuke Yamamoto * * 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 twitter4jads.auth; import twitter4jads.internal.models4j.TwitterException; /** * @author Yusuke Yamamoto - yusuke at mac.com * @since Twitter4J 2.1.0 */ public interface OAuthSupport { /** * sets the OAuth consumer key and consumer secret * * @param consumerKey OAuth consumer key * @param consumerSecret OAuth consumer secret * @throws IllegalStateException when OAuth consumer has already been set, or the instance is using basic authorization * @since Twitter 2.0.0 */ void setOAuthConsumer(String consumerKey, String consumerSecret); /** * Retrieves a request token * * @return generated request token. * @throws TwitterException when Twitter service or network is unavailable * @throws IllegalStateException access token is already available * @see <a href="https://dev.twitter.com/docs/auth/oauth/faq">OAuth FAQ | Twitter Developers</a> * @see <a href="http://oauth.net/core/1.0a/#auth_step1">OAuth Core 1.0a - 6.1. Obtaining an Unauthorized Request Token</a> * @see <a href="https://dev.twitter.com/docs/api/1.1/post/oauth/request_token">POST oauth/request_token | Twitter Developers</a> * @since Twitter4J 2.0.0 */ RequestToken getOAuthRequestToken() throws TwitterException; /** * Retrieves a request token * * @param callbackURL callback URL * @return generated request token * @throws TwitterException when Twitter service or network is unavailable * @throws IllegalStateException access token is already available * @see <a href="https://dev.twitter.com/docs/auth/oauth/faq">OAuth FAQ | Twitter Developers</a> * @see <a href="http://oauth.net/core/1.0a/#auth_step1">OAuth Core 1.0a - 6.1. Obtaining an Unauthorized Request Token</a> * @see <a href="https://dev.twitter.com/docs/api/1.1/post/oauth/request_token">POST oauth/request_token | Twitter Developers</a> * @since Twitter4J 2.0.0 */ RequestToken getOAuthRequestToken(String callbackURL) throws TwitterException; /** * Retrieves a request token * * @param callbackURL callback URL * @param xAuthAccessType Overrides the access level an application requests to a users account. Supported values are read or write. This parameter is intended to allow a developer to register a read/write application but also request read only access when appropriate. * @return generated request token * @throws TwitterException when Twitter service or network is unavailable * @throws IllegalStateException access token is already available * @see <a href="https://dev.twitter.com/docs/auth/oauth/faq">OAuth FAQ | Twitter Developers</a> * @see <a href="http://oauth.net/core/1.0a/#auth_step1">OAuth Core 1.0a - 6.1. Obtaining an Unauthorized Request Token</a> * @see <a href="https://dev.twitter.com/docs/api/1.1/post/oauth/request_token">POST oauth/request_token | Twitter Developers</a> * @since Twitter4J 2.2.3 */ RequestToken getOAuthRequestToken(String callbackURL, String xAuthAccessType) throws TwitterException; /** * Returns an access token associated with this instance.<br> * If no access token is associated with this instance, this will retrieve a new access token. * * @return access token * @throws TwitterException when Twitter service or network is unavailable, or the user has not authorized * @throws IllegalStateException when RequestToken has never been acquired * @see <a href="https://dev.twitter.com/docs/auth/oauth/faq">OAuth FAQ | dev.twitter.com - How long does an access token last?</a> * @see <a href="http://oauth.net/core/1.0a/#auth_step2">OAuth Core 1.0a - 6.2. Obtaining User Authorization</a> * @see <a href="https://dev.twitter.com/docs/api/1.1/post/oauth/access_token">POST oauth/access_token | Twitter Developers</a> * @since Twitter4J 2.0.0 */ AccessToken getOAuthAccessToken() throws TwitterException; /** * Retrieves an access token. * * @param oauthVerifier OAuth verifier. AKA pin. * @return access token * @throws TwitterException when Twitter service or network is unavailable, or the user has not authorized * @see <a href="https://dev.twitter.com/docs/auth/oauth/faq">OAuth FAQ | dev.twitter.com - How long does an access token last?</a> * @see <a href="http://oauth.net/core/1.0a/#auth_step2">OAuth Core 1.0a - 6.2. Obtaining User Authorization</a> * @see <a href="https://dev.twitter.com/docs/api/1.1/post/oauth/access_token">POST oauth/access_token | Twitter Developers</a> * @since Twitter4J 2.0.0 */ AccessToken getOAuthAccessToken(String oauthVerifier) throws TwitterException; /** * Retrieves an access token associated with the supplied request token and sets userId. * * @param requestToken the request token * @return access token associated with the supplied request token. * @throws TwitterException when Twitter service or network is unavailable, or the user has not authorized * @see <a href="https://dev.twitter.com/docs/auth/oauth/faq">OAuth FAQ | dev.twitter.com - How long does an access token last?</a> * @see <a href="http://oauth.net/core/1.0a/#auth_step2">OAuth Core 1.0a - 6.2. Obtaining User Authorization</a> * @see <a href="https://dev.twitter.com/docs/api/1.1/post/oauth/access_token">POST oauth/access_token | Twitter Developers</a> * @since Twitter4J 2.0.0 */ AccessToken getOAuthAccessToken(RequestToken requestToken) throws TwitterException; /** * Retrieves an access token associated with the supplied request token and sets userId. * * @param requestToken the request token * @param oauthVerifier OAuth verifier. AKA pin. * @return access token associated with the supplied request token. * @throws TwitterException when Twitter service or network is unavailable, or the user has not authorized * @see <a href="http://oauth.net/core/1.0a/#auth_step2">OAuth Core 1.0a - 6.2. Obtaining User Authorization</a> * @see <a href="https://dev.twitter.com/docs/api/1.1/post/oauth/access_token">POST oauth/access_token | Twitter Developers</a> * @since Twitter 2.1.1 */ AccessToken getOAuthAccessToken(RequestToken requestToken, String oauthVerifier) throws TwitterException; /** * Retrieves an access token associated with the supplied screen name and password using xAuth.<br> * In order to get access acquire AccessToken using xAuth, you must apply by sending an email to api@twitter.com - all other applications will receive an HTTP 401 error. Web-based applications will not be granted access, except on a temporary basis for when they are converting from basic-authentication support to full OAuth support.<br> * Storage of Twitter usernames and passwords is forbidden. By using xAuth, you are required to store only access tokens and access token secrets. If the access token expires or is expunged by a user, you must ask for their login and password again before exchanging the credentials for an access token. * * @param screenName the screen name * @param password the password * @return access token associated with the supplied request token. * @throws TwitterException when Twitter service or network is unavailable, or the user has not authorized * @see <a href="https://dev.twitter.com/docs/auth/oauth/faq">OAuth FAQ | dev.twitter.com - How long does an access token last?</a> * @see <a href="https://dev.twitter.com/docs/oauth/xauth">xAuth | Twitter Developers</a> * @see <a href="https://dev.twitter.com/docs/api/1.1/post/oauth/access_token">POST oauth/access_token | Twitter Developers</a> * @since Twitter 2.1.1 */ AccessToken getOAuthAccessToken(String screenName, String password) throws TwitterException; /** * Sets the access token * * @param accessToken accessToken * @since Twitter4J 2.0.0 */ void setOAuthAccessToken(AccessToken accessToken); }
mit
kazyx/wirespider
wirespider/core/src/main/java/net/kazyx/wirespider/exception/ProtocolViolationException.java
347
/* * WireSpider * * Copyright (c) 2016 kazyx * * This software is released under the MIT License. * http://opensource.org/licenses/mit-license.php */ package net.kazyx.wirespider.exception; public class ProtocolViolationException extends Exception { public ProtocolViolationException(String message) { super(message); } }
mit
zhqhzhqh/FbreaderJ
app/src/main/java/org/geometerplus/fbreader/book/BookmarkUtil.java
2346
/* * Copyright (C) 2009-2015 FBReader.ORG Limited <contact@fbreader.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.geometerplus.fbreader.book; import org.geometerplus.zlibrary.core.resources.ZLResource; import org.geometerplus.zlibrary.text.view.*; public abstract class BookmarkUtil { public static String getStyleName(HighlightingStyle style) { final String name = style.getNameOrNull(); return (name != null && name.length() > 0) ? name : defaultName(style); } public static void setStyleName(HighlightingStyle style, String name) { style.setName(defaultName(style).equals(name) ? null : name); } private static String defaultName(HighlightingStyle style) { return ZLResource.resource("style").getValue().replace("%s", String.valueOf(style.Id)); } public static void findEnd(Bookmark bookmark, ZLTextView view) { if (bookmark.getEnd() != null) { return; } ZLTextWordCursor cursor = view.getStartCursor(); if (cursor.isNull()) { cursor = view.getEndCursor(); } if (cursor.isNull()) { return; } cursor = new ZLTextWordCursor(cursor); cursor.moveTo(bookmark); ZLTextWord word = null; mainLoop: for (int count = bookmark.getLength(); count > 0; cursor.nextWord()) { while (cursor.isEndOfParagraph()) { if (!cursor.nextParagraph()) { break mainLoop; } } final ZLTextElement element = cursor.getElement(); if (element instanceof ZLTextWord) { if (word != null) { --count; } word = (ZLTextWord)element; count -= word.Length; } } if (word != null) { bookmark.setEnd(cursor.getParagraphIndex(), cursor.getElementIndex(), word.Length); } } }
mit
Marketo/REST-Sample-Code
java/Asset/Tokens/DeleteTokenByName.java
3854
/* DeleteTokenByName.java Marketo REST API Sample Code Copyright (C) 2016 Marketo, Inc. This software may be modified and distributed under the terms of the MIT license. See the LICENSE file for details. */ package dev.marketo.samples.Tokens; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.util.NoSuchElementException; import java.util.Scanner; import javax.net.ssl.HttpsURLConnection; import com.eclipsesource.json.JsonObject; //the Java sample code on dev.marketo.com uses the minimal-json package //minimal-json provides easy and fast representations of JSON //for more information check out https://github.com/ralfstx/minimal-json public class Tokens { public String marketoInstance = ;//Replace this with the host from Admin Web Services public String marketoIdURL = marketoInstance + "/identity"; public String clientId = ; //Obtain from your Custom Service in Admin>Launchpoint public String clientSecret = ; //Obtain from your Custom Service in Admin>Launchpoint public String idEndpoint = marketoIdURL + "/oauth/token?grant_type=client_credentials&client_id=" + clientId + "&client_secret=" + clientSecret; public int folderId;//id of folder to retrieve from, required public String folderType;//type of folder, Program or Folder, required public static void main(String[] args){ Tokens tokens = new Tokens(); tokens.folderId = 1071; tokens.folderType = "Program"; String result = tokens.getData(); System.out.println(result); } //Make Request private String getData() { String data = null; try { //Assemble the URL StringBuilder endpoint = new StringBuilder(marketoInstance + "/rest/asset/v1/folder/"+ folderId + "/tokens.json?access_token=" + getToken() + "&folderType=" + folderType); URL url = new URL(endpoint.toString()); HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection(); urlConn.setRequestMethod("GET"); urlConn.setRequestProperty("accept", "text/json"); int responseCode = urlConn.getResponseCode(); if (responseCode == 200) { InputStream inStream = urlConn.getInputStream(); data = convertStreamToString(inStream); } else { data = "Status:" + responseCode; } } catch (MalformedURLException e) { System.out.println("URL not valid."); } catch (IOException e) { System.out.println("IOException: " + e.getMessage()); e.printStackTrace(); } return data; } public String getToken(){ String token = null; try { URL url = new URL(idEndpoint); HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection(); urlConn.setRequestMethod("GET"); urlConn.setRequestProperty("accept", "application/json"); int responseCode = urlConn.getResponseCode(); if (responseCode == 200) { InputStream inStream = urlConn.getInputStream(); Reader reader = new InputStreamReader(inStream); JsonObject jsonObject = JsonObject.readFrom(reader); token = jsonObject.get("access_token").asString(); }else { throw new IOException("Status: " + responseCode); } } catch (MalformedURLException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } return token; } private String convertStreamToString(InputStream inputStream) { try { return new Scanner(inputStream).useDelimiter("\\A").next(); } catch (NoSuchElementException e) { return ""; } } }
mit
Unarmed/internet-on-a-stick
src/main/java/se/carlengstrom/internetonastick/job/Job.java
2108
/* * 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 se.carlengstrom.internetonastick.job; import se.carlengstrom.internetonastick.model.Markov; /** * * @author Eng */ public abstract class Job implements Runnable { private Markov markov; private String statusString; private String sample; private JobState status; private long startTime; private long endTime; protected Job(Markov m) { this.markov = m; this.statusString = "Not Started"; this.sample = "Samples not available until job is running"; this.status = JobState.QUEUED; } public Markov getMarkov() { return markov; } public void setStatus(String status) { this.statusString = status; } public String getStatusString() { return statusString; } public void setSample(String sample) { this.sample = sample; } public String getSample() { return sample; } public JobState getStaus() { return status; } public long getDuration() { switch(status) { case QUEUED: return 0; case IN_PROGRESS: return System.currentTimeMillis() - startTime; case DONE: return endTime - startTime; default: //Why java, why!? return 0; } } @Override public void run() { startTime = System.currentTimeMillis(); status = JobState.IN_PROGRESS; try { jobRun(); status = JobState.DONE; } catch (Exception e) { status = JobState.FAILED; statusString = "Job failed due to " + e.getClass().getName() + ": " + e.getMessage(); e.printStackTrace(); } finally { endTime = System.currentTimeMillis(); } } protected abstract void jobRun() throws Exception; }
mit
jonfryd/tifoon
tifoon-plugin-api/src/main/java/com/elixlogic/tifoon/plugin/scanner/AbstractScannerPlugin.java
381
package com.elixlogic.tifoon.plugin.scanner; import com.elixlogic.tifoon.plugin.DefaultMetadataProvider; import org.springframework.plugin.metadata.PluginMetadata; public abstract class AbstractScannerPlugin implements ScannerPlugin { @Override public PluginMetadata getMetadata() { return new DefaultMetadataProvider(getClass().getName()).getMetadata(); } }
mit
uhef/Oskari-Routing
service-map/src/main/java/fi/nls/oskari/map/userlayer/domain/MIFGeoJsonCollection.java
4378
package fi.nls.oskari.map.userlayer.domain; import fi.nls.oskari.log.LogFactory; import fi.nls.oskari.log.Logger; import fi.nls.oskari.map.userlayer.service.GeoJsonWorker; import fi.nls.oskari.util.JSONHelper; import org.geotools.data.DataStore; import org.geotools.data.ogr.OGRDataStoreFactory; import org.geotools.data.ogr.bridj.BridjOGRDataStoreFactory; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.geojson.feature.FeatureJSON; import org.geotools.referencing.CRS; import org.geotools.geometry.jts.JTS; import org.geotools.geometry.jts.ReferencedEnvelope; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.MathTransform; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.FeatureType; import com.vividsolutions.jts.geom.Geometry; import org.json.JSONArray; import org.json.JSONObject; import java.io.File; import java.util.HashMap; import java.util.Map; public class MIFGeoJsonCollection extends GeoJsonCollection implements GeoJsonWorker { final FeatureJSON io = new FeatureJSON(); private static final Logger log = LogFactory .getLogger(MIFGeoJsonCollection.class); /** * Parse MapInfo file set to geojson features * Coordinate transformation is executed, if shape .prj file is within * @param file .mif import file * @param target_epsg target CRS * @return */ public boolean parseGeoJSON(File file, String target_epsg) { OGRDataStoreFactory factory = new BridjOGRDataStoreFactory(); Map<String, String> connectionParams = new HashMap<String, String>(); connectionParams.put("DriverName", "MapInfo File"); connectionParams.put("DatasourceName", file.getAbsolutePath()); DataStore store = null; String typeName = null; SimpleFeatureSource source; SimpleFeatureCollection collection; SimpleFeatureType schema = null; SimpleFeatureIterator it = null; CoordinateReferenceSystem sourceCrs = null; CoordinateReferenceSystem targetCrs = null; MathTransform transform = null; JSONArray features = null; ReferencedEnvelope bounds = null; try { store = factory.createDataStore(connectionParams); typeName = store.getTypeNames()[0]; source = store.getFeatureSource(typeName); collection = source.getFeatures(); it = collection.features(); schema = collection.getSchema(); //Coordinate transformation support bounds = source.getBounds(); if (bounds != null) { sourceCrs = bounds.getCoordinateReferenceSystem(); } if (sourceCrs == null) { sourceCrs = schema.getCoordinateReferenceSystem(); } // Oskari crs //(oskari OL map crs) targetCrs = CRS.decode(target_epsg, true); // TODO: better check algorithm - name is not 100% proof if ((sourceCrs != null)&&(!targetCrs.getName().equals(sourceCrs.getName()))) { transform = CRS.findMathTransform(sourceCrs, targetCrs, true); } features = new JSONArray(); while (it.hasNext()) { SimpleFeature feature = it.next(); if (transform != null) { Geometry geometry = (Geometry) feature.getDefaultGeometry(); feature.setDefaultGeometry(JTS.transform(geometry, transform)); } JSONObject geojs = JSONHelper.createJSONObject(io.toString(feature)); if (geojs != null) { features.put(geojs); } } it.close(); setGeoJson(JSONHelper.createJSONObject("features",features)); setFeatureType((FeatureType)schema); setTypeName(typeName); return true; } catch (Exception e) { log.error("Couldn't create geoJSON from the MapInfo file ", file.getName(), e); return false; } finally { store.dispose(); } } }
mit
Vovas11/courses
src/main/java/com/devproserv/courses/form/CourseHandling.java
4256
/* * The MIT License (MIT) * * Copyright (c) 2019 Vladimir * * 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.devproserv.courses.form; import com.devproserv.courses.jooq.tables.StudentCourses; import com.devproserv.courses.model.Db; import com.devproserv.courses.model.Response; import com.devproserv.courses.model.users.Student; import java.sql.Connection; import java.sql.SQLException; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Prepares request for further forwarding. * * @since 0.5.0 */ abstract class CourseHandling { /** * Logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(CourseHandling.class); /** * Database. */ private final Db dbase; /** * Primary constructor. * * @param dbase Database */ CourseHandling(final Db dbase) { this.dbase = dbase; } /** * Returns course ID parameter. * * @return Course ID */ public abstract String courseIdParameter(); /** * Returns error message. * * @return Error message */ public abstract String errorMessageParameter(); /** * Changes entry. * * @param courseid Course ID * @param studentid Student ID */ public abstract void changeEntry(int courseid, int studentid); /** * Returns response. * * @param courseid Course ID * @param student Student * @return Response */ public Response response(final int courseid, final Student student) { this.changeEntry(courseid, student.getId()); return student.response(); } /** * Enrolls the given user to the given course. * * @param courseid Course ID * @param userid User ID */ void insertUserCourse(final int courseid, final int userid) { try (Connection con = this.dbase.dataSource().getConnection(); DSLContext ctx = DSL.using(con, SQLDialect.MYSQL) ) { ctx.insertInto( StudentCourses.STUDENT_COURSES, StudentCourses.STUDENT_COURSES.COURSE_ID, StudentCourses.STUDENT_COURSES.STUD_ID, StudentCourses.STUDENT_COURSES.STATUS ).values(courseid, userid, "STARTED").execute(); } catch (final SQLException exc) { LOGGER.error("User not inserted!", exc); } } /** * Unrolls the given user from the given course. * * @param courseid Course ID * @param userid User ID */ void deleteUserCourse(final int courseid, final int userid) { try (Connection con = this.dbase.dataSource().getConnection(); DSLContext ctx = DSL.using(con, SQLDialect.MYSQL) ) { ctx.deleteFrom(StudentCourses.STUDENT_COURSES) .where( StudentCourses.STUDENT_COURSES.COURSE_ID.eq(courseid) .and(StudentCourses.STUDENT_COURSES.STUD_ID.eq(userid)) ).execute(); } catch (final SQLException exc) { LOGGER.error("User not deleted!", exc); } } }
mit
Raphfrk/Simple-Portal
com/raphfrk/bukkit/serverportsimpleportal/MiscUtils.java
5371
/******************************************************************************* * Copyright (C) 2012 Raphfrk * * 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.raphfrk.bukkit.serverportsimpleportal; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Logger; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.plugin.Plugin; public class MiscUtils { public static LogInstance getLogger(String prefix) { return new LogInstance(prefix); } public static LogInstance defaultLog = new LogInstance(); public static class LogInstance { public LogInstance() { this.log = Logger.getLogger("Minecraft"); this.logPrefix = "[EventLink-Default Log]"; } public LogInstance(String prefix) { this.log = Logger.getLogger("Minecraft"); this.logPrefix = prefix; } public LogInstance(Logger log, String prefix) { this.log = log; this.logPrefix = prefix; } final private Object logSync = new Object(); private Logger log = Logger.getLogger("Minecraft"); private String logPrefix = ""; public void setLogPrefix(Logger log, String prefix) { synchronized(logSync) { this.log = log; this.logPrefix = prefix; } } public void log( String message ) { synchronized(logSync) { log.info( logPrefix + " " + message); } } } public static void sendAsyncMessage(Plugin plugin, Server server, CommandSender commandSender, String message) { sendAsyncMessage(plugin, server, commandSender, message, 0); } public static void sendAsyncMessage(Plugin plugin, Server server, CommandSender commandSender, String message, long delay) { if( commandSender == null ) return; final CommandSender finalCommandSender = commandSender; final String finalMessage = message; server.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { public void run() { finalCommandSender.sendMessage(finalMessage); } }, delay); } public static void stringToFile( ArrayList<String> string , String filename ) { File portalFile = new File( filename ); BufferedWriter bw; try { bw = new BufferedWriter(new FileWriter(portalFile)); } catch (FileNotFoundException fnfe ) { defaultLog.log("Unable to write to file: " + filename ); return; } catch (IOException ioe) { defaultLog.log("Unable to write to file: " + filename ); return; } try { for( Object line : string.toArray() ) { bw.write((String)line); bw.newLine(); } bw.close(); } catch (IOException ioe) { defaultLog.log("Unable to write to file: " + filename ); return; } } public static String[] fileToString( String filename ) { File portalFile = new File( filename ); BufferedReader br; try { br = new BufferedReader(new FileReader(portalFile)); } catch (FileNotFoundException fnfe ) { defaultLog.log("[Serverport] Unable to open file: " + filename ); return null; } StringBuffer sb = new StringBuffer(); String line; try { while( (line=br.readLine()) != null ) { sb.append( line ); sb.append( "\n" ); } br.close(); } catch (IOException ioe) { defaultLog.log("Error reading file: " + filename ); return null; } return( sb.toString().split("\n") ); } public static boolean checkText( String text ) { if( text.length() > 15 ) { return false; } return text.matches("^[a-zA-Z0-9\\.\\-]+$"); } static boolean isInt (String string) { try { Integer.parseInt(string.trim()); } catch (NumberFormatException nfe ) { return false; } return true; } static int getInt( String var ) { try { var = var.trim(); int x = Integer.parseInt(var.trim()); return x; } catch (NumberFormatException nfe ) { SimplePortal.log("[ServerPortSimplePortal] Unable to parse " + var + " as integer" ); return 0; } } }
mit
SpongePowered/SpongeAPI
src/main/java/org/spongepowered/api/Game.java
6428
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api; import org.checkerframework.checker.nullness.qual.NonNull; import org.spongepowered.api.config.ConfigManager; import org.spongepowered.api.data.DataManager; import org.spongepowered.api.data.persistence.DataBuilder; import org.spongepowered.api.data.persistence.DataSerializable; import org.spongepowered.api.event.EventManager; import org.spongepowered.api.network.channel.ChannelManager; import org.spongepowered.api.plugin.PluginManager; import org.spongepowered.api.registry.BuilderProvider; import org.spongepowered.api.registry.FactoryProvider; import org.spongepowered.api.registry.RegistryHolder; import org.spongepowered.api.scheduler.Scheduler; import org.spongepowered.api.service.ServiceProvider; import org.spongepowered.api.sql.SqlManager; import org.spongepowered.api.util.metric.MetricsConfigManager; import java.nio.file.Path; import java.util.Locale; /** * The core accessor of the API. The implementation uses this to pass * constructed objects. */ public interface Game extends RegistryHolder { /** * Gets the async {@link Scheduler}. * * @return The async scheduler */ Scheduler asyncScheduler(); /** * Gets the directory where the game's files are located. * * @return The game directory */ Path gameDirectory(); /** * Returns if the {@link Server} is available for use. The result of this method is entirely * dependent on the implementation. * * @return True if the Server is available, false if not */ boolean isServerAvailable(); /** * Gets the {@link Server}. * * @return The server * @throws IllegalStateException If the Server isn't currently available */ Server server(); /** * Gets the {@link SystemSubject}. Depending on the implementation, this * may also represent the game console. * * @return The {@link SystemSubject} */ SystemSubject systemSubject(); /** * Gets a locale for the specified locale code, e.g. {@code en_US}. * * @param locale The locale to lookup (e.g. {@code en_US}. * @return The locale */ Locale locale(@NonNull String locale); /** * Returns if the {@link Client} is available for use. The result of this method is entirely * dependent on the implementation. * * @return True if the Client is available, false if not */ default boolean isClientAvailable() { return false; } /** * Gets the {@link Client}. * * @return The client * @throws UnsupportedEngineException If the client engine is not supported * @throws IllegalStateException If the Client isn't currently available */ default Client client() { throw new UnsupportedEngineException("The client engine is not supported."); } /** * Returns the current platform, or implementation, this {@link Game} is running on. * * @return The current implementation */ Platform platform(); /** * Retrieves the {@link BuilderProvider}. * * @return The builder provider */ BuilderProvider builderProvider(); /** * Retrieves the {@link FactoryProvider}. * * @return The factory provider */ FactoryProvider factoryProvider(); /** * Gets the {@link DataManager} instance to register * {@link DataSerializable}s, and get the related {@link DataBuilder}s. * * @return The serialization service */ DataManager dataManager(); /** * Gets the {@link PluginManager}. * * @return The plugin manager */ PluginManager pluginManager(); /** * Gets the {@link EventManager}. * * @return The event manager */ EventManager eventManager(); /** * Gets the {@link ConfigManager} used to load and manage configuration files * for plugins. * * @return The configuration manager */ ConfigManager configManager(); /** * Gets the {@link ChannelManager} for creating network channels. * * @return The channel manager */ ChannelManager channelManager(); /** * Gets the {@link MetricsConfigManager} instance, allowing data/metric gathering * systems to determine whether they have permission to gather server * metrics. * * @return The {@link MetricsConfigManager} instance */ MetricsConfigManager metricsConfigManager(); /** * Gets the {@link SqlManager} for grabbing sql data sources. * * @return The {@link SqlManager} instance. */ SqlManager sqlManager(); /** * Gets the {@link ServiceProvider.GameScoped}, used to provide Sponge * services that plugins may provide. Services provided here are * scoped to the lifetime of the Game. * * <p>The provider will not be available during plugin construction and will * throw an {@link IllegalStateException} if there is an attempt to access * this before the provider is ready.</p> * * @return The service manager */ ServiceProvider.GameScoped serviceProvider(); }
mit
jalves94/azure-sdk-for-java
azure/src/main/java/com/microsoft/azure/Azure.java
16261
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure; import com.microsoft.azure.credentials.ApplicationTokenCredentials; import com.microsoft.azure.credentials.AzureTokenCredentials; import com.microsoft.azure.management.batch.BatchAccounts; import com.microsoft.azure.management.batch.implementation.BatchManager; import com.microsoft.azure.management.compute.AvailabilitySets; import com.microsoft.azure.management.compute.VirtualMachineImages; import com.microsoft.azure.management.compute.VirtualMachineScaleSets; import com.microsoft.azure.management.compute.VirtualMachines; import com.microsoft.azure.management.compute.implementation.ComputeManager; import com.microsoft.azure.management.keyvault.Vaults; import com.microsoft.azure.management.keyvault.implementation.KeyVaultManager; import com.microsoft.azure.management.network.LoadBalancers; import com.microsoft.azure.management.network.NetworkInterfaces; import com.microsoft.azure.management.network.NetworkSecurityGroups; import com.microsoft.azure.management.network.Networks; import com.microsoft.azure.management.network.PublicIpAddresses; import com.microsoft.azure.management.network.implementation.NetworkManager; import com.microsoft.azure.management.resources.Deployments; import com.microsoft.azure.management.resources.Features; import com.microsoft.azure.management.resources.GenericResources; import com.microsoft.azure.management.resources.Providers; import com.microsoft.azure.management.resources.ResourceGroups; import com.microsoft.azure.management.resources.Subscription; import com.microsoft.azure.management.resources.Subscriptions; import com.microsoft.azure.management.resources.Tenants; import com.microsoft.azure.management.resources.fluentcore.arm.AzureConfigurable; import com.microsoft.azure.management.resources.fluentcore.arm.implementation.AzureConfigurableImpl; import com.microsoft.azure.management.resources.implementation.ResourceManagementClientImpl; import com.microsoft.azure.management.resources.implementation.ResourceManager; import com.microsoft.azure.management.storage.StorageAccounts; import com.microsoft.azure.management.storage.Usages; import com.microsoft.azure.management.storage.implementation.StorageManager; import com.microsoft.rest.credentials.ServiceClientCredentials; import java.io.File; import java.io.IOException; /** * The entry point for accessing resource management APIs in Azure. */ public final class Azure { private final ResourceManager resourceManager; private final StorageManager storageManager; private final ComputeManager computeManager; private final NetworkManager networkManager; private final KeyVaultManager keyVaultManager; private final BatchManager batchManager; private final String subscriptionId; /** * Authenticate to Azure using a credentials object. * * @param credentials the credentials object * @param tenantId the tenantId in Active Directory * @return the authenticated Azure client */ public static Authenticated authenticate(ServiceClientCredentials credentials, String tenantId) { return new AuthenticatedImpl( AzureEnvironment.AZURE.newRestClientBuilder() .withCredentials(credentials) .build(), tenantId); } /** * Authenticate to Azure using an Azure credentials object. * * @param credentials the credentials object * @return the authenticated Azure client */ public static Authenticated authenticate(AzureTokenCredentials credentials) { return new AuthenticatedImpl( AzureEnvironment.AZURE.newRestClientBuilder() .withCredentials(credentials) .build(), credentials.getDomain()); } /** * Authenticates API access using a properties file containing the required credentials. * @param credentialsFile the file containing the credentials in the standard Java properties file format, * with the following keys:<p> * <code> * subscription= #subscription ID<br> * tenant= #tenant ID<br> * client= #client id<br> * key= #client key<br> * managementURI= #management URI<br> * baseURL= #base URL<br> * authURL= #authentication URL<br> *</code> * @return authenticated Azure client * @throws IOException exception thrown from file access */ public static Authenticated authenticate(File credentialsFile) throws IOException { ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credentialsFile); return new AuthenticatedImpl(AzureEnvironment.AZURE.newRestClientBuilder() .withCredentials(credentials) .build(), credentials.getDomain()).withDefaultSubscription(credentials.defaultSubscriptionId()); } /** * Authenticates API access using a {@link RestClient} instance. * @param restClient the {@link RestClient} configured with Azure authentication credentials * @param tenantId the tenantId in Active Directory * @return authenticated Azure client */ public static Authenticated authenticate(RestClient restClient, String tenantId) { return new AuthenticatedImpl(restClient, tenantId); } private static Authenticated authenticate(RestClient restClient, String tenantId, String subscriptionId) throws IOException { return new AuthenticatedImpl(restClient, tenantId).withDefaultSubscription(subscriptionId); } /** * @return an interface allow configurations on the client. */ public static Configurable configure() { return new ConfigurableImpl(); } /** * The interface allowing configurations to be made on the client. */ public interface Configurable extends AzureConfigurable<Configurable> { /** * Authenticates API access based on the provided credentials. * * @param credentials The credentials to authenticate API access with * @param tenantId the tenantId in Active Directory * @return the authenticated Azure client */ Authenticated authenticate(ServiceClientCredentials credentials, String tenantId); /** * Authenticates API access based on the provided credentials. * * @param credentials The credentials to authenticate API access with * @return the authenticated Azure client */ Authenticated authenticate(AzureTokenCredentials credentials); /** * Authenticates API access using a properties file containing the required credentials. * * @param credentialsFile the file containing the credentials in the standard Java properties file format following * the same schema as {@link Azure#authenticate(File)}.<p> * @return Authenticated Azure client * @throws IOException exceptions thrown from file access */ Authenticated authenticate(File credentialsFile) throws IOException; } /** * The implementation for {@link Configurable}. */ private static final class ConfigurableImpl extends AzureConfigurableImpl<Configurable> implements Configurable { @Override public Authenticated authenticate(ServiceClientCredentials credentials, String tenantId) { return Azure.authenticate(buildRestClient(credentials), tenantId); } @Override public Authenticated authenticate(AzureTokenCredentials credentials) { return Azure.authenticate(buildRestClient(credentials), credentials.getDomain()); } @Override public Authenticated authenticate(File credentialsFile) throws IOException { ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credentialsFile); return Azure.authenticate(buildRestClient(credentials), credentials.getDomain(), credentials.defaultSubscriptionId()); } } /** * Provides authenticated access to a subset of Azure APIs that do not require a specific subscription. * <p> * To access the subscription-specific APIs, use {@link Authenticated#withSubscription(String)}, * or {@link Authenticated#withDefaultSubscription()} if a default subscription has already been previously specified * (for example, in a previously specified authentication file). * @see Azure#authenticate(File) */ public interface Authenticated { /** * Entry point to subscription management APIs. * * @return Subscriptions interface providing access to subscription management */ Subscriptions subscriptions(); /** * Entry point to tenant management APIs. * * @return Tenants interface providing access to tenant management */ Tenants tenants(); /** * Selects a specific subscription for the APIs to work with. * <p> * Most Azure APIs require a specific subscription to be selected. * @param subscriptionId the ID of the subscription * @return an authenticated Azure client configured to work with the specified subscription */ Azure withSubscription(String subscriptionId); /** * Selects the default subscription as the subscription for the APIs to work with. * <p> * The default subscription can be specified inside the authentication file using {@link Azure#authenticate(File)}. * If no default subscription has been previously provided, the first subscription as * returned by {@link Authenticated#subscriptions()} will be selected. * @return an authenticated Azure client configured to work with the default subscription * @throws CloudException exception thrown from Azure * @throws IOException exception thrown from serialization/deserialization */ Azure withDefaultSubscription() throws CloudException, IOException; } /** * The implementation for {@link Authenticated}. */ private static final class AuthenticatedImpl implements Authenticated { private final RestClient restClient; private final ResourceManager.Authenticated resourceManagerAuthenticated; private String defaultSubscription; private String tenantId; private AuthenticatedImpl(RestClient restClient, String tenantId) { this.resourceManagerAuthenticated = ResourceManager.authenticate(restClient); this.restClient = restClient; this.tenantId = tenantId; } private AuthenticatedImpl withDefaultSubscription(String subscriptionId) throws IOException { this.defaultSubscription = subscriptionId; return this; } @Override public Subscriptions subscriptions() { return resourceManagerAuthenticated.subscriptions(); } @Override public Tenants tenants() { return resourceManagerAuthenticated.tenants(); } @Override public Azure withSubscription(String subscriptionId) { return new Azure(restClient, subscriptionId, tenantId); } @Override public Azure withDefaultSubscription() throws CloudException, IOException { if (this.defaultSubscription != null) { return withSubscription(this.defaultSubscription); } else { PagedList<Subscription> subs = this.subscriptions().list(); if (!subs.isEmpty()) { return withSubscription(subs.get(0).subscriptionId()); } else { return withSubscription(null); } } } } private Azure(RestClient restClient, String subscriptionId, String tenantId) { ResourceManagementClientImpl resourceManagementClient = new ResourceManagementClientImpl(restClient); resourceManagementClient.withSubscriptionId(subscriptionId); this.resourceManager = ResourceManager.authenticate(restClient).withSubscription(subscriptionId); this.storageManager = StorageManager.authenticate(restClient, subscriptionId); this.computeManager = ComputeManager.authenticate(restClient, subscriptionId); this.networkManager = NetworkManager.authenticate(restClient, subscriptionId); this.keyVaultManager = KeyVaultManager.authenticate(restClient, tenantId, subscriptionId); this.batchManager = BatchManager.authenticate(restClient, subscriptionId); this.subscriptionId = subscriptionId; } /** * @return the currently selected subscription ID this client is configured to work with */ public String subscriptionId() { return this.subscriptionId; } /** * @return entry point to managing resource groups */ public ResourceGroups resourceGroups() { return this.resourceManager.resourceGroups(); } /** * @return entry point to managing deployments */ public Deployments deployments() { return this.resourceManager.deployments(); } /** * @return entry point to management generic resources */ public GenericResources genericResources() { return resourceManager.genericResources(); } /** * @return entry point to managing features */ public Features features() { return resourceManager.features(); } /** * @return entry point to managing resource providers */ public Providers providers() { return resourceManager.providers(); } /** * @return entry point to managing storage accounts */ public StorageAccounts storageAccounts() { return storageManager.storageAccounts(); } /** * @return entry point to managing storage account usages */ public Usages storageUsages() { return storageManager.usages(); } /** * @return entry point to managing availability sets */ public AvailabilitySets availabilitySets() { return computeManager.availabilitySets(); } /** * @return entry point to managing virtual networks */ public Networks networks() { return networkManager.networks(); } /** * @return entry point to managing load balancers */ public LoadBalancers loadBalancers() { return networkManager.loadBalancers(); } /** * @return entry point to managing network security groups */ public NetworkSecurityGroups networkSecurityGroups() { return networkManager.networkSecurityGroups(); } /** * @return entry point to managing virtual machines */ public VirtualMachines virtualMachines() { return computeManager.virtualMachines(); } /** * @return entry point to managing virtual machine scale sets. */ public VirtualMachineScaleSets virtualMachineScaleSets() { return computeManager.virtualMachineScaleSets(); } /** * @return entry point to managing virtual machine images */ public VirtualMachineImages virtualMachineImages() { return computeManager.virtualMachineImages(); } /** * @return entry point to managing public IP addresses */ public PublicIpAddresses publicIpAddresses() { return this.networkManager.publicIpAddresses(); } /** * @return entry point to managing network interfaces */ public NetworkInterfaces networkInterfaces() { return this.networkManager.networkInterfaces(); } /** * @return entry point to managing key vaults */ public Vaults vaults() { return this.keyVaultManager.vaults(); } /** * @return entry point to managing batch accounts. */ public BatchAccounts batchAccounts() { return batchManager.batchAccounts(); } }
mit
chen0040/java-leetcode
src/main/java/com/github/chen0040/leetcode/day19/medium/LongestWordInDictionaryThroughDeleting.java
1260
package com.github.chen0040.leetcode.day19.medium; import java.util.Collections; import java.util.List; /** * Created by xschen on 14/8/2017. * * link: https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/description/ */ public class LongestWordInDictionaryThroughDeleting { public class Solution { public String findLongestWord(String s, List<String> d) { Collections.sort(d); int maxLength = 0; String result = ""; for(String w : d){ int k = 0; boolean matched = true; for(int i=0; i < w.length(); ++i) { int c = w.charAt(i); boolean found = false; while(k < s.length()) { if(s.charAt(k) == c) { found = true; break; } k++; } if(found) k++; else { matched = false; break; } } if(matched) { if(maxLength < w.length()) { maxLength = w.length(); result = w; } } } return result; } } }
mit
zzwwws/RxZhihuDaily
app/src/main/java/com/github/zzwwws/rxzhihudaily/model/entities/CommentEntities.java
1423
package com.github.zzwwws.rxzhihudaily.model.entities; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "comments" }) public class CommentEntities { @JsonProperty("comments") private List<Comment> comments = new ArrayList<Comment>(); @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); /** * * @return * The comments */ @JsonProperty("comments") public List<Comment> getComments() { return comments; } /** * * @param comments * The comments */ @JsonProperty("comments") public void setComments(List<Comment> comments) { this.comments = comments; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
mit
albalitz/save-android
Save/app/src/main/java/com/github/albalitz/save/activities/MainActivity.java
13793
package com.github.albalitz.save.activities; import android.app.DialogFragment; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.github.albalitz.save.R; import com.github.albalitz.save.SaveApplication; import com.github.albalitz.save.fragments.LinkActionsDialogFragment; import com.github.albalitz.save.fragments.SaveLinkDialogFragment; import com.github.albalitz.save.persistence.Link; import com.github.albalitz.save.persistence.SavePersistenceOption; import com.github.albalitz.save.persistence.Storage; import com.github.albalitz.save.persistence.importexport.SavedLinksExporter; import com.github.albalitz.save.persistence.importexport.SavedLinksImporter; import com.github.albalitz.save.persistence.importexport.ViewExportedFileListener; import com.github.albalitz.save.persistence.offline_queue.OfflineQueue; import com.github.albalitz.save.utils.ActivityUtils; import com.github.albalitz.save.utils.LinkAdapter; import com.github.albalitz.save.utils.Utils; import com.github.albalitz.save.utils.temporary_sharedpreference.TemporaryPreference; import com.github.albalitz.save.utils.temporary_sharedpreference.TemporarySharedPreferenceHandler; import org.json.JSONException; import java.io.IOException; import java.util.ArrayList; import static com.github.albalitz.save.SaveApplication.setAppContext; public class MainActivity extends AppCompatActivity implements ApiActivity, LinkActionsDialogFragment.LinkActionListener, SnackbarActivity, SwipeRefreshLayout.OnRefreshListener { private Context context; private SwipeRefreshLayout swipeRefreshLayout; private ListView listViewSavedLinks; private LinkAdapter adapter; private ArrayList<Link> savedLinks; private Link selectedLink; private SavePersistenceOption storage; private OfflineQueue offlineQueue; private SharedPreferences prefs = SaveApplication.getSharedPreferences(); private Button saveQueuedLinksButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); this.context = this; setAppContext(this.context); // assign content swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout); listViewSavedLinks = (ListView) findViewById(R.id.listViewSavedLinks); saveQueuedLinksButton = (Button) findViewById(R.id.saveQueuedLinksButton); saveQueuedLinksButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { offlineQueue.saveQueuedLinks(); } }); // prepare stuff prepareListViewListeners(); swipeRefreshLayout.setOnRefreshListener(this); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SaveLinkDialogFragment saveLinkDialogFragment = new SaveLinkDialogFragment(); saveLinkDialogFragment.show(getFragmentManager(), "save"); } }); // do actual stuff /* * Check for configuration and let the user know what to do accordingly: * - ask to register * - ask to configure api url */ if (prefs.getBoolean("pref_key_use_api_or_local", false)) { if (prefs.getString("pref_key_api_url", "").isEmpty()) { Utils.showToast(context, "Please configure the API's URL."); ActivityUtils.openSettings(this); } else { if (prefs.getString("pref_key_api_username", "").isEmpty() || prefs.getString("pref_key_api_password", "").isEmpty()) { Log.w(this.toString(), "No credentials found. Opening registration."); Utils.showToast(context, "No credentials found for API. Please register."); Intent intent = new Intent(this, RegisterActivity.class); startActivity(intent); } } } } @Override public void onResume() { super.onResume(); storage = Storage.getStorageSettingChoice(this); offlineQueue = new OfflineQueue(this); try { storage.updateSavedLinks(); } catch (IllegalArgumentException e) { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } setOfflineQueueButtonVisibility(); setMessageTextView(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case R.id.action_settings: ActivityUtils.openSettings(this); return true; case R.id.action_about: ActivityUtils.showAboutDialog(this); return true; } return super.onOptionsItemSelected(item); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { switch (requestCode) { case SaveApplication.PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { showExportConfirmation(SavedLinksExporter.export(this, savedLinks)); } else { Utils.showToast(context, "Please grant external storage permission to export."); } return; } case SaveApplication.PERMISSION_REQUEST_READ_EXTERNAL_STORAGE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { importLinks(); } else { Utils.showToast(context, "Please grant external storage permission to import."); } return; } } } private void showExportConfirmation(boolean successfullyExported) { if (successfullyExported) { Snackbar.make(listViewSavedLinks, "Exported " + savedLinks.size() + " links.", Snackbar.LENGTH_LONG) .setAction("View", new ViewExportedFileListener()).show(); } } private void showImportConfirmation(ArrayList importedLinks) { if (importedLinks != null && importedLinks.size() > 0) { Snackbar.make(listViewSavedLinks, "Imported " + importedLinks.size() + " links.", Snackbar.LENGTH_LONG).show(); } } private void setOfflineQueueButtonVisibility() { Log.d(this.toString(), "Updating offline queue button..."); int queueSize = offlineQueue.queuedCount(); if (Utils.storageSettingChoiceIsAPI() && queueSize > 0 && Utils.networkAvailable(this)) { saveQueuedLinksButton.setVisibility(View.VISIBLE); String linkPluralized = queueSize == 1 ? "link" : "links"; String buttonText = "Save " + offlineQueue.queuedCount() + " queued " + linkPluralized; saveQueuedLinksButton.setText(buttonText); } else { saveQueuedLinksButton.setVisibility(View.GONE); } } private void setMessageTextView() { Log.d(this.toString(), "Updating message text view..."); TextView messageTextView = (TextView) findViewById(R.id.messageTextView); if (Utils.storageSettingChoiceIsAPI() && !Utils.networkAvailable(this)) { messageTextView.setText(getString(R.string.no_connection_message)); } else if (savedLinks != null && savedLinks.isEmpty()) { messageTextView.setText(getString(R.string.no_link_message)); } else { messageTextView.setText(""); messageTextView.setVisibility(View.GONE); return; } messageTextView.setVisibility(View.VISIBLE); } private void handleTempPrefs() { if (TemporarySharedPreferenceHandler.popTemporarySharedPreferenceValue(TemporaryPreference.EXPORT)) { boolean exportResult = SavedLinksExporter.export(this, savedLinks); showExportConfirmation(exportResult); } if (TemporarySharedPreferenceHandler.popTemporarySharedPreferenceValue(TemporaryPreference.IMPORT)) { importLinks(); } if (TemporarySharedPreferenceHandler.popTemporarySharedPreferenceValue(TemporaryPreference.DELETE_ALL)) { Utils.showToast(this, "Deleting all saved links..."); // todo: do this in the storage option with one call for (Link link : savedLinks) { storage.deleteLink(link); } } } private void importLinks() { try { ArrayList<Link> importResult = SavedLinksImporter.importLinks(this.context, this.storage); showImportConfirmation(importResult); } catch (JSONException e) { e.printStackTrace(); Utils.showToast(this.context, "Can't import links. Please check your exported file for correct JSON syntax."); } catch (IOException e) { e.printStackTrace(); Utils.showToast(this.context, "Error while reading file. Please check the app's permissions and if the file exists."); } } @Override public void onSavedLinksUpdate(ArrayList<Link> savedLinks) { this.savedLinks = savedLinks; adapter = new LinkAdapter(this, savedLinks); this.listViewSavedLinks.setAdapter(adapter); this.swipeRefreshLayout.setRefreshing(false); setOfflineQueueButtonVisibility(); setMessageTextView(); handleTempPrefs(); } @Override public void onSaveDialogDone() {} @Override public void onRegistrationError(String errorMessage) {} @Override public void onRegistrationSuccess() {} private void prepareListViewListeners() { listViewSavedLinks.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Link clickedLink = savedLinks.get(position); Utils.showSnackbar(MainActivity.this, "Opening link..."); Utils.openInExternalBrowser(context, clickedLink.url()); } }); listViewSavedLinks.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { selectedLink = savedLinks.get(position); LinkActionsDialogFragment linkActionsDialogFragment = new LinkActionsDialogFragment(); linkActionsDialogFragment.show(getFragmentManager(), "actions"); return true; } }); } public SavePersistenceOption getStorage() { return this.storage; } /* * Implement link dialog actions */ @Override public void onSelectLinkOpen(DialogFragment dialog) { if (selectedLink == null) { return; } Utils.openInExternalBrowser(context, selectedLink.url()); } @Override public void onSelectLinkShare(DialogFragment dialog) { if (selectedLink == null) { return; } Intent shareLinkIntent = new Intent(); shareLinkIntent.setAction(Intent.ACTION_SEND); shareLinkIntent.putExtra(Intent.EXTRA_TEXT, selectedLink.url()); shareLinkIntent.setType("text/plain"); startActivity(Intent.createChooser(shareLinkIntent, getResources().getText(R.string.share_destination_chooser))); } @Override public void onSelectLinkDelete(DialogFragment dialog) { if (selectedLink == null) { return; } storage.deleteLink(selectedLink); } @Override public void onDialogDismiss(DialogFragment dialog) { selectedLink = null; } /* * Implement SnackbarActivity */ @Override public View viewFromActivity() { return findViewById(R.id.listViewSavedLinks); } /* * SwipeRefreshLayout.OnRefreshListener methods */ @Override public void onRefresh() { storage.updateSavedLinks(); } }
mit
Sukora-Stas/JavaRushTasks
1.JavaSyntax/src/com/javarush/task/task10/task1001/Solution.java
393
package com.javarush.task.task10.task1001; /* Задача №1 на преобразование целых типов */ public class Solution { public static void main(String[] args) { int a = 0; int b = (byte) a + 46; byte c = (byte) (a * b); double f = (char) 1234.15; long d = (char) (a + f / c + b); System.out.println(d); } }
mit
jaamal/overclocking
sources/Trees/src/cartesianTree/CartesianTreeManagerFactory.java
2886
package cartesianTree; import tree.nodeProviders.INodeAllocator; import tree.nodeProviders.ITreeNodeBuilder; import tree.nodeProviders.ITreeNodeProvider; import tree.nodeProviders.NodeAllocator; import tree.nodeProviders.TreeNodeProvider; import tree.nodeProviders.indexSets.FreeNodesSet; import cartesianTree.heapKeyResolvers.IHeapKeyResolver; import cartesianTree.heapKeyResolvers.RandomGeneratorFactory; import cartesianTree.heapKeyResolvers.RandomHeapKeyResolver; import cartesianTree.nodes.CartesianTreeNode; import cartesianTree.nodes.CartesianTreeNodeBuilder; import cartesianTree.nodes.CartesianTreeNodeSerializer; import commons.files.FileManager; import commons.files.IFileManager; import commons.settings.ISettings; import data.enumerableData.IEnumerableData; import data.enumerableData.InMemoryEnumerableData; import data.enumerableData.MemoryMappedFileEnumerableData; import data.longArray.LongSerializer; import dataContracts.DataFactoryType; public class CartesianTreeManagerFactory implements ICartesianTreeManagerFactory { private DataFactoryType dataFactoryType; private ISettings settings; public CartesianTreeManagerFactory(ISettings settings, DataFactoryType dataFactoryType) { this.settings = settings; this.dataFactoryType = dataFactoryType; } @Override public ICartesianTreeManager create() { IEnumerableData<CartesianTreeNode> nodeStorage; IEnumerableData<Long> innerReferencesStorage; if (dataFactoryType == DataFactoryType.memory) { nodeStorage = new InMemoryEnumerableData<>(CartesianTreeNode.class); innerReferencesStorage = new InMemoryEnumerableData<>(Long.class); } else if (dataFactoryType == DataFactoryType.file) { CartesianTreeNodeSerializer serializer = new CartesianTreeNodeSerializer(); IFileManager fileManager = new FileManager(settings); nodeStorage = new MemoryMappedFileEnumerableData<>(serializer, fileManager, settings); innerReferencesStorage = new MemoryMappedFileEnumerableData<>(new LongSerializer(), fileManager, settings); } else { throw new RuntimeException(String.format("Unknown DataFactoryType '%s'", dataFactoryType)); } ITreeNodeBuilder<CartesianTreeNode> cartesianTreeNodeBuilder = new CartesianTreeNodeBuilder(nodeStorage); IHeapKeyResolver heapKeyResolver = new RandomHeapKeyResolver(new RandomGeneratorFactory()); INodeAllocator<CartesianTreeNode> nodeAllocator = new NodeAllocator<>(nodeStorage, innerReferencesStorage, new FreeNodesSet()); ITreeNodeProvider<CartesianTreeNode> nodeProvider = new TreeNodeProvider<>(nodeStorage, cartesianTreeNodeBuilder, nodeAllocator); return new CartesianTreeManager(nodeProvider, heapKeyResolver); } }
mit
adelolmo/biblio
biblio-install/src/main/java/org/ado/biblio/install/UnzipService.java
1903
package org.ado.biblio.install; import javafx.concurrent.Service; import javafx.concurrent.Task; import org.ado.biblio.util.ZipUtils; import java.io.File; /* * The MIT License (MIT) * * Copyright (c) 2015 Andoni del Olmo * * 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. */ /** * @author Andoni del Olmo, * @since 31.01.15 */ public class UnzipService extends Service<Void> { private File zipFile; private File destDirectory; public UnzipService(File zipFile, File destDirectory) { this.zipFile = zipFile; this.destDirectory = destDirectory; } @Override protected Task<Void> createTask() { return new Task<Void>() { @Override protected Void call() throws Exception { ZipUtils.extractFolder(zipFile, destDirectory); return null; } }; } }
mit
mihaihuminiuc/pos_project
src/main/java/com/newwordpress/hum/service/PageCreatorImpl.java
1343
package com.newwordpress.hum.service; import com.newwordpress.hum.persistence.model.Text; import com.newwordpress.hum.persistence.repository.ContentRepository; import org.springframework.beans.factory.annotation.Autowired; public class PageCreatorImpl implements PageCreator { @Autowired ContentRepository contentRepository; @Override public Text pageContentbyIndex(int index) { Text webPageContent = new Text(); webPageContent = contentRepository.findByAuthorId(index); return webPageContent; } @Override public Text pageContentByPageName(String name) { Text webPageContent = new Text(); webPageContent = contentRepository.findByPageName(name); return webPageContent; } @Override public Text pageContentByAuthorId(int authorId) { Text webPageContent = new Text(); webPageContent = contentRepository.findByAuthorId(authorId); return webPageContent; } @Override public void savePageContent(String pageContent, int authorId) { Text webPageContent = new Text(); webPageContent.setAuthorId(authorId); webPageContent.setTextContent(pageContent); contentRepository.save(webPageContent); } @Override public void editPageContent(String pageContent, int authorId) { } }
mit
eriklupander/bos-fullparser-frp
src/main/java/se/lu/bosmp/rest/AdminServiceBean.java
970
package se.lu.bosmp.rest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import se.lu.bosmp.scanner.ReportFileScanner; /** * Created with IntelliJ IDEA. * User: Erik * Date: 2014-12-09 * Time: 21:46 * To change this template use File | Settings | File Templates. */ @RestController @RequestMapping("/rest/admin") public class AdminServiceBean { @Autowired ReportFileScanner reportFileScanner; @RequestMapping(method = RequestMethod.POST, value = "/parse/test") public ResponseEntity<String> parseTest() { int scan = reportFileScanner.scan(); return new ResponseEntity("Scan successful, " + scan + " items", HttpStatus.OK); } }
mit
simpleci/simpleci
src/backend/shared/src/main/java/simpleci/shared/utils/TestServicesUtils.java
3425
package simpleci.shared.utils; import com.rabbitmq.client.Connection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import redis.clients.jedis.exceptions.JedisConnectionException; import simpleci.shared.utils.ConnectionUtils; import java.io.IOException; import java.sql.SQLException; import java.util.concurrent.TimeoutException; public class TestServicesUtils { private final static Logger logger = LoggerFactory.getLogger(TestServicesUtils.class); public static boolean testRedis(String host, int port) { final int tryCount = 10; for (int i = 1; i <= tryCount; i++) { logger.info(String.format("redis: connecting to %s:%s, try %d of %d", host, port, i, tryCount)); try { Jedis connection = new Jedis(host, port); connection.connect(); connection.close(); logger.info("Connection to redis established successfully"); return true; } catch (JedisConnectionException e) { logger.info("Failed to connect: " + e.getMessage()); try { Thread.sleep(1000); } catch (InterruptedException e1) { logger.error("", e); } } } logger.info(String.format("Failed connect to redis on %s:%d", host, port)); return false; } public static boolean testDatabase(String host, int port, String name, String user, String password) { final int tryCount = 10; for (int i = 1; i <= tryCount; i++) { try { logger.info(String.format("database: connecting to %s:%d, try %d of %d", host, port, i, tryCount)); java.sql.Connection connection = ConnectionUtils.createDataSource(host, port, name, user, password).getConnection(); connection.close(); logger.info("Connection to database established successfully"); return true; } catch (SQLException e) { logger.info("Failed to connect"); try { Thread.sleep(1000); } catch (InterruptedException e1) { logger.error("", e); } } } logger.info(String.format("Failed connect to database on %s:%d", host, port)); return false; } public static boolean testRabbitmq(String host, int port, String user, String password) { final int tryCount = 10; for (int i = 1; i <= tryCount; i++) { try { logger.info(String.format("rabbitmq: connecting to %s:%s, try %d of %d", host, port, i, tryCount)); Connection connection = ConnectionUtils.createRabbitmqConnection(host, port, user, password); connection.close(); logger.info("Connection to rabbitmq established successfully"); return true; } catch (Throwable e) { logger.info("Failed to connect: " + e.getMessage()); try { Thread.sleep(1000); } catch (InterruptedException e1) { logger.error("", e); } } } logger.info(String.format("Failed connect to rabbitmq on %s:%d", host, port)); return false; } }
mit
mcfallcl/Lol-API-lib
src/riotapiwrapper/request/LolStaticData.java
14683
package riotapiwrapper.request; import riotapiwrapper.Locales; import riotapiwrapper.LolAPI; /** * Implements the lol-static-data-v1.2 end point for the League of Legends * public API. * <p> * This class consists of static methods only, which build the API request to * be sent when {@code this.send()} is called. This enables you to have multiple * requests built without sending the calls to the API, letting you throttle * the requests or save them for later. * <p> * All requests to this endpoint do not count against your API key's rate limit. * * @author Christopher McFall * @see riotapiwrapper.util.RequestArbiter * @see Request#send() */ public class LolStaticData extends Request { private final static String base1 = "static-data/"; private final static String base2 = "/v1.2/"; private static Locales locale; private static String version; private Subtype subtype; /** * Creates an API request for the full list of current champions' data * based on the currently selected version and the default region. * <p> * Additional data beyond the default should be specified in the champData * parameter. Having "all" in the champData parameter retrieves all * additional champion data. If no additional data is requested in * champData, the minimum data will be retrieved from the API server. * * @param byId Flag indicating weather the champions should be * ordered by their championId's. * @param champData List of additional data to be requested from the * API server. * @return An API request for all champions' data and in game statistics. */ public static LolStaticData champions(boolean byId, String... champData) { Subtype type = Subtype.CHAMPION; LolStaticData data = new LolStaticData(type); data.build(type, byId, champData); return data; } /** * Creates an API request for a specific champion's data, requested by the * champion's id based on the current version and the default region. * Additional data beyond the default should be specified in * the champData parameter. Having "all" in the champData parameter * retrieves all additional champion data. If no additional data is * requested in champData, the minimum data will be retrieved from the API * server. * * @param id The id of the champion requested. * @param champData List of additional data to be requested from the * API server. * @return An API request for all champions' data and in game statistics. */ public static LolStaticData champion(int id, String... champData) { Subtype type = Subtype.CHAMPION; LolStaticData data = new LolStaticData(type); data.build(type, id, champData); return data; } /** * Creates an API request for all items' data based on the current region's * version and its default locale. Additional data beyond the default should * be specified in the itemData parameter. Having "all" in the itemData * parameter retrieves all additional item data. If no additional data is * requested in itemData, the minimum data will be retrieved from the API * server. * * @param itemData List of additional data to be requested from the * API server. * @return an API request for all items' data and in game statistics. */ public static LolStaticData items(String... itemData) { Subtype type = Subtype.ITEM; LolStaticData data = new LolStaticData(type); data.build(type, false, itemData); return data; } /** * Creates an API request for a specific item's data based on the current * region's version and its default locale. Additional data beyond the * default should be specified in the itemData parameter. Having "all" in * the itemData parameter retrieves all additional item data. If no * additional data is request in itemData, the minimum data will be * retrieved from the API server. * * @param id id of the item requested * @param itemData List of additional data to be requested from the API * server. * @return An API request for a specific item's data and in game * statistics. */ public static LolStaticData item(int id, String... itemData) { Subtype type = Subtype.ITEM; LolStaticData data = new LolStaticData(type); data.build(type, id, itemData); return data; } /** * Creates an API request for the language strings for the current region's * default locale. * * @return An API request for the language strings for the current region's * default locale. */ public static LolStaticData languageStrings() { Subtype type = Subtype.LANGUAGE_STRINGS; LolStaticData data = new LolStaticData(type); data.bareBuild(type); return data; } /** * Creates an API request for all languages the API supports. * * @return An API request for all languages the API supports. */ public static LolStaticData languages() { Subtype type = Subtype.LANGUAGES; LolStaticData data = new LolStaticData(type); data.bareBuild(type); return data; } /** * Creates an API request for the current region's data for all in-game * maps. * * @return An API request for the current region's data for all in-game * maps. */ public static LolStaticData map() { Subtype type = Subtype.MAP; LolStaticData data = new LolStaticData(type); data.bareBuild(type); return data; } /** * Creates an API request for the current region's and current version's * masteries. * * @return A request for the current region's and version's masteries. */ public static LolStaticData masteries() { Subtype type = Subtype.MASTERY; LolStaticData data = new LolStaticData(type); data.build(type); return data; } /** * Creates an API request for a specified matery's data for the current * region and version. * * @param id id of the requested mastery. * @return A request for a specific mastery. */ public static LolStaticData mastery(int id) { Subtype type = Subtype.MASTERY; LolStaticData data = new LolStaticData(type); data.build(type, id); return data; } /** * Creates an API request for the current region's realm data. * * @return An API request for the current region's realm data. */ public static LolStaticData realm() { Subtype type = Subtype.REALM; LolStaticData data = new LolStaticData(type); data.bareBuild(type); return data; } /** * Creates an API request for the current region's and current version's * runes. * * @return A request for the current region's and version's runes. */ public static LolStaticData runes() { Subtype type = Subtype.RUNE; LolStaticData data = new LolStaticData(type); data.build(type); return data; } /** * Creates an API request for a specified rune's data for the current * region and version. * * @param id id of the requested rune. * @return A request for a specific rune. */ public static LolStaticData rune(int id) { Subtype type = Subtype.RUNE; LolStaticData data = new LolStaticData(type); data.build(type, id); return data; } /** * Creates an API request for the current region's and current version's * summoner spells. * * @return A request for the current region's and version's summoner spells. */ public static LolStaticData summonerSpells() { Subtype type = Subtype.SUMMONER_SPELL; LolStaticData data = new LolStaticData(type); data.build(type); return data; } /** * Creates an API request for a specified summoner spell's data for the * current region and version. * * @param id id of the requested summoner spell. * @return A request for a specific summoner spell. */ public static LolStaticData summonerSpell(int id) { Subtype type = Subtype.SUMMONER_SPELL; LolStaticData data = new LolStaticData(type); data.build(type, id); return data; } /** * Creates an API request for all versions for the current region. * * @return An API request for all versions for the current region. */ public static LolStaticData versions() { Subtype type = Subtype.VERSIONS; LolStaticData data = new LolStaticData(type); data.bareBuild(type); return data; } /** * Sets the locale for future requests to the specified locale. * * @param locale Language locale to be used for future requests. If null, * future requests will be made with the current region's * default locale. * @see Locales */ public static void setLocale(Locales locale) { LolStaticData.locale = locale; } /** * Sets the version for future requests to the specified version. * * @param version Version for future requests. If null, future requests * will be made with the most recent version for the * current region. */ public static void setVersion(String version) { //verify version is valid here. LolStaticData.version = version; } public RequestType type() { return RequestType.LOL_STATIC_DATA; } /** * Returns the subtype of the request. * * @return The subtype of the request. */ public String subtype() { return subtype.toString(); } public boolean hasSubtype() { return true; } private void build(Subtype type, int id, String... data) { begin(); url.append(base1) .append(LolAPI.getCurrentRegion().ABREV) .append(base2) .append(type) .append('/') .append(id) .append('?'); evaluateLocale(); evaluateVersion(); if (type == Subtype.ITEM) evaluateItemData(data); if (type == Subtype.CHAMPION) evaluateChampData(data); end(); } private void build(Subtype type) { begin(); url.append(base1) .append(LolAPI.getCurrentRegion().ABREV) .append(base2) .append(type) .append('?'); evaluateLocale(); evaluateVersion(); end(); } private void build(Subtype type, int id) { begin(); url.append(base1) .append(LolAPI.getCurrentRegion().ABREV) .append(base2) .append(type) .append('/') .append(id) .append('?'); evaluateLocale(); evaluateVersion(); end(); } private void build(Subtype type, boolean byId, String... data) { begin(); url.append(base1) .append(LolAPI.getCurrentRegion().ABREV) .append(base2) .append(type) .append('?'); evaluateLocale(); evaluateVersion(); if (byId) { url.append("dataById=true&"); } if (type == Subtype.ITEM) evaluateItemData(data); if (type == Subtype.CHAMPION) evaluateChampData(data); end(); } /* * Used for requests that do not base their response on versions or locale. */ private void bareBuild(Subtype type) { begin(); url.append(base1) .append(LolAPI.getCurrentRegion().ABREV) .append(base2) .append(type) .append('?'); end(); } private void evaluateLocale() { if (locale == null) return; url.append("locale=") .append(locale.toString()) .append('&'); } private void evaluateVersion() { if (version == null || version == "") return; url.append("version=") .append(version) .append('&'); } private void evaluateChampData(String... data) { if (data.length == 0) return; url.append("champData=") .append(data[0]); for (int i = 1; i < data.length; i++) { url.append(',') .append(data[i]); } url.append('&'); } private void evaluateItemData(String... data) { if (data.length == 0) return; url.append("itemData=") .append(data[0]); for (int i = 1; i < data.length; i++) { url.append(',') .append(data[i]); } url.append('&'); } private LolStaticData(Subtype subtype) { rateLimited = false; this.subtype = subtype; } private enum Subtype { CHAMPION, ITEM, LANGUAGE_STRINGS, LANGUAGES, MAP, MASTERY, REALM, RUNE, SUMMONER_SPELL, VERSIONS; @Override public String toString() { switch (this) { case LANGUAGE_STRINGS: return "language-strings"; case SUMMONER_SPELL: return "summoner-spell"; default: return this.name().toLowerCase(); } } } }
mit
FutureProcessing/document-juggler
src/test/java/com/futureprocessing/documentjuggler/example/cars/model/Engine.java
729
package com.futureprocessing.documentjuggler.example.cars.model; import com.futureprocessing.documentjuggler.annotation.DbField; import com.futureprocessing.documentjuggler.annotation.Unset; import com.futureprocessing.documentjuggler.example.cars.CarsDBModel; public interface Engine { @DbField(CarsDBModel.Car.Engine.FUEL) String getFuel(); @DbField(CarsDBModel.Car.Engine.CYLINDERS_NUMBER) int getCylindersNumber(); @DbField(CarsDBModel.Car.Engine.FUEL) Engine withFuel(String fuel); @DbField(CarsDBModel.Car.Engine.CYLINDERS_NUMBER) Engine withCylindersNumber(int cylindersNumber); @DbField(CarsDBModel.Car.Engine.CYLINDERS_NUMBER) @Unset void withoutCylindersNumber(); }
mit
cubedservers/CSTweaks
src/main/java/org/cubedservers/cstweaks/events/CSTCommonEvents.java
4079
package org.cubedservers.cstweaks.events; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ChatComponentText; import net.minecraft.world.World; import net.minecraftforge.event.world.BlockEvent; import org.cubedservers.cstweaks.api.enums.EnumProfessions; import org.cubedservers.cstweaks.api.helpers.ProfessionHelper; import org.cubedservers.cstweaks.api.main.ProfessionData; import org.cubedservers.cstweaks.api.registries.BlockProfessionRegistry; import org.cubedservers.cstweaks.api.registries.ExperienceRegistry; import org.cubedservers.cstweaks.api.registries.LevelBlockRegistry; import org.cubedservers.cstweaks.api.registries.ToolProfessionRegistry; import org.cubedservers.cstweaks.helpers.ItemHelper; import cpw.mods.fml.common.eventhandler.SubscribeEvent; public class CSTCommonEvents { @SubscribeEvent public void onBlockMined(BlockEvent.HarvestDropsEvent e){ Minecraft mc = Minecraft.getMinecraft(); EntityPlayer player = e.harvester; World world = e.world; int x = e.x; int y = e.y; int z = e.z; if(player != null){ ItemStack heldStack = player.getHeldItem(); if(heldStack != null){ Item heldItem = heldStack.getItem(); String name = ItemHelper.getItemName(heldItem); if(name != null && ToolProfessionRegistry.toolProfessions.containsKey(name) && e.block != null && BlockProfessionRegistry.blocksProfessions.containsKey(e.block)){ EnumProfessions blockProfession = BlockProfessionRegistry.blocksProfessions.get(e.block); EnumProfessions toolProfession = ToolProfessionRegistry.toolProfessions.get(name); if(toolProfession != null && blockProfession != null && toolProfession == blockProfession){ if(ExperienceRegistry.professionXP.containsKey(e.block)){ int xpValue = ExperienceRegistry.professionXP.get(e.block); if((ProfessionHelper.convertExperienceToLevel(ProfessionData.getProfessionExperience(player, toolProfession) + xpValue) <= ProfessionHelper.getMaxLevel())) ProfessionData.increaseProfessionsExperience(player, toolProfession, xpValue); }else{ if((ProfessionHelper.convertExperienceToLevel(ProfessionData.getProfessionExperience(player, toolProfession) + 1) <= ProfessionHelper.getMaxLevel())) ProfessionData.increaseProfessionsExperience(player, toolProfession, 1); } /** Debug Messages */ player.addChatComponentMessage(new ChatComponentText(ProfessionData.getProfessionExperience(player, toolProfession) + " XP")); player.addChatComponentMessage(new ChatComponentText(toolProfession.name + " Level: " + ProfessionHelper.getProfessionLevel(player, toolProfession))); } } } } } @SubscribeEvent public void canBreak(BlockEvent.BreakEvent e){ Minecraft mc = Minecraft.getMinecraft(); EntityPlayer player = e.getPlayer(); World world = e.world; int x = e.x; int y = e.y; int z = e.z; if(player != null){ ItemStack heldStack = player.getHeldItem(); if(heldStack != null){ Item heldItem = heldStack.getItem(); String name = ItemHelper.getItemName(heldItem); if(name != null && ToolProfessionRegistry.toolProfessions.containsKey(name) && e.block != null && BlockProfessionRegistry.blocksProfessions.containsKey(e.block)){ EnumProfessions blockProfession = BlockProfessionRegistry.blocksProfessions.get(e.block); EnumProfessions toolProfession = ToolProfessionRegistry.toolProfessions.get(name); if(toolProfession != null && blockProfession != null && toolProfession == blockProfession && LevelBlockRegistry.levelBlocks.containsKey(e.block)){ int xpRequired = LevelBlockRegistry.levelBlocks.get(e.block); if(ProfessionHelper.getProfessionLevel(player, toolProfession) < xpRequired){ player.addChatComponentMessage(new ChatComponentText("You need to be atleast level " + LevelBlockRegistry.levelBlocks.get(e.block) + " to destroy this block.")); e.setCanceled(true); } } } } } } }
mit
voostindie/consul-registrator
src/main/java/nl/ulso/consul/registrator/XmlClasspathCatalogLoader.java
6532
package nl.ulso.consul.registrator; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; /** * Creates a {@link Catalog} by parsing an XML file on the classpath. * <p> * This class has very limited error checking, on purpose: * </p> * <ul> * <li>Within the XML only the elements and attributes known by this agent are accessed. Anything else is ignored.</li> * <li>Validation of attribute values is in the {@link nl.ulso.consul.registrator.Catalog.Builder} class</li> * </ul> */ class XmlClasspathCatalogLoader implements CatalogLoader { private static final String DEFAULT_CATALOG_LOCATION = "META-INF/consul-catalog.xml"; private static final String CATALOG_ELEMENT = "catalog"; private static final String CATALOG_DELAY = "delay"; private static final String SERVICE_ELEMENT = "service"; private static final String SERVICE_NAME = "name"; private static final String SERVICE_ID = "id"; private static final String SERVICE_ADDRESS = "address"; private static final String SERVICE_PORT = "port"; private static final String HTTP_CHECK_ELEMENT = "http-check"; private static final String HTTP_CHECK_URL = "url"; private static final String HTTP_CHECK_INTERVAL = "interval"; private static final String TAG_ELEMENT = "tag"; private static final String TAG_NAME = "name"; private static final String KEY_ELEMENT = "key"; private static final String KEY_NAME = "name"; private static final String KEY_VALUE = "value"; private final String classpathResource; XmlClasspathCatalogLoader(final String classpathResource) { this.classpathResource = classpathResource; } XmlClasspathCatalogLoader() { this(DEFAULT_CATALOG_LOCATION); } @Override public Catalog load() { final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try (InputStream inputStream = classLoader.getResourceAsStream(classpathResource)) { if (inputStream == null) { throw new RegistratorException("No catalog found file at '" + classpathResource + "'"); } return extractCatalog(loadDocument(inputStream)); } catch (IOException e) { throw new RegistratorException("Could not load catalog from '" + classpathResource + "': " + e.getMessage(), e); } } private Document loadDocument(InputStream inputStream) { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setExpandEntityReferences(false); try { return factory.newDocumentBuilder().parse(inputStream); } catch (SAXException | IOException | ParserConfigurationException e) { throw new RegistratorException("Error while parsing XML from '" + classpathResource + "': " + e.getMessage(), e); } } private Catalog extractCatalog(Document document) { final Element catalog = document.getDocumentElement(); if (catalog == null || !CATALOG_ELEMENT.equals(catalog.getNodeName())) { throw new RegistratorException("Invalid service catalog found at '" + classpathResource + "'"); } final Catalog.Builder builder = Catalog.newCatalog(); if (catalog.hasAttribute(CATALOG_DELAY)) { builder.withDelay(catalog.getAttribute(CATALOG_DELAY)); } extractServices(catalog, builder); extractKeyValuePairs(catalog, builder); return builder.build(); } private void extractServices(Element catalog, Catalog.Builder builder) { final NodeList services = catalog.getElementsByTagName(SERVICE_ELEMENT); final int length = services.getLength(); for (int i = 0; i < length; i++) { extractService((Element) services.item(i), builder.newService()); } } private void extractService(Element service, Service.Builder builder) { if (service.hasAttribute(SERVICE_NAME)) { builder.withName(service.getAttribute(SERVICE_NAME)); } if (service.hasAttribute(SERVICE_ID)) { builder.withId(service.getAttribute(SERVICE_ID)); } if (service.hasAttribute(SERVICE_ADDRESS)) { builder.withAddress(service.getAttribute(SERVICE_ADDRESS)); } if (service.hasAttribute(SERVICE_PORT)) { builder.withPort(service.getAttribute(SERVICE_PORT)); } extractHealthCheck(service, builder); extractTags(service, builder); builder.build(); } private void extractHealthCheck(Element service, Service.Builder builder) { final NodeList checks = service.getElementsByTagName(HTTP_CHECK_ELEMENT); if (checks.getLength() == 0) { return; } final Element check = (Element) checks.item(0); if (check.hasAttribute(HTTP_CHECK_URL)) { builder.withHttpCheckUrl(check.getAttribute(HTTP_CHECK_URL)); } if (check.hasAttribute(HTTP_CHECK_INTERVAL)) { builder.withHttpCheckInterval(check.getAttribute(HTTP_CHECK_INTERVAL)); } } private void extractTags(Element service, Service.Builder builder) { final NodeList tags = service.getElementsByTagName(TAG_ELEMENT); final int length = tags.getLength(); for (int i = 0; i < length; i++) { final Element tag = (Element) tags.item(i); if (tag.hasAttribute(TAG_NAME)) { builder.withTag(tag.getAttribute(TAG_NAME)); } } } private void extractKeyValuePairs(Element catalog, Catalog.Builder builder) { final NodeList keyValuePairs = catalog.getElementsByTagName(KEY_ELEMENT); final int length = keyValuePairs.getLength(); for (int i = 0; i < length; i++) { extractKeyValuePair((Element) keyValuePairs.item(i), builder); } } private void extractKeyValuePair(Element keyValuePair, Catalog.Builder builder) { if (keyValuePair.hasAttribute(KEY_NAME) && keyValuePair.hasAttribute(KEY_VALUE)) { builder.withKeyValuePair( keyValuePair.getAttribute(KEY_NAME), keyValuePair.getAttribute(KEY_VALUE) ); } } }
mit
dvt32/cpp-journey
Java/TopCoder/KiloMan.java
527
// https://community.topcoder.com/stat?c=problem_statement&pm=2268 public class KiloMan { public static int hitsTaken(int[] pattern, String jumps) { int hitsCount = 0; for (int i = 0; i < pattern.length; ++i) { int currentHeight = pattern[i]; char currentKiloManAction = jumps.charAt(i); if (currentKiloManAction == 'S' && (currentHeight == 1 || currentHeight == 2)) { hitsCount++; } else if (currentKiloManAction == 'J' && currentHeight > 2) { hitsCount++; } } return hitsCount; } }
mit
ad-tech-group/openssp
data-sim-client/src/main/java/com/atg/openssp/dspSim/model/MessageStatus.java
299
package com.atg.openssp.dspSim.model; import java.awt.*; public enum MessageStatus { NOMINAL(Color.WHITE), FAULT(Color.RED), WARNING(Color.YELLOW); private final Color c; MessageStatus(Color c) { this.c = c; } public Color getColor() { return c; } }
mit
mmithril/XChange
xchange-cavirtex/src/main/java/org/knowm/xchange/virtex/v2/VirtEx.java
1161
package org.knowm.xchange.virtex.v2; import java.io.IOException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.knowm.xchange.virtex.v2.dto.marketdata.VirtExDepthWrapper; import org.knowm.xchange.virtex.v2.dto.marketdata.VirtExTickerWrapper; import org.knowm.xchange.virtex.v2.dto.marketdata.VirtExTradesWrapper; /** * @author veken0m */ @Path("api2") @Produces(MediaType.APPLICATION_JSON) public interface VirtEx { @GET @Path("ticker.json?currencypair={ident}{currency}") public VirtExTickerWrapper getTicker(@PathParam("ident") String tradableIdentifier, @PathParam("currency") String currency) throws IOException; @GET @Path("orderbook.json?currencypair={ident}{currency}") public VirtExDepthWrapper getFullDepth(@PathParam("ident") String tradableIdentifier, @PathParam("currency") String currency) throws IOException; @GET @Path("trades.json?currencypair={ident}{currency}") public VirtExTradesWrapper getTrades(@PathParam("ident") String tradableIdentifier, @PathParam("currency") String currency) throws IOException; }
mit
InfinityPhase/CARIS
lavaplayer/lavaplayer/track/playback/AudioFrameConsumer.java
448
package lavaplayer.track.playback; /** * A consumer for audio frames */ public interface AudioFrameConsumer { /** * Consumes the frame, may block * @param frame The frame to consume * @throws InterruptedException When interrupted */ void consume(AudioFrame frame) throws InterruptedException; /** * Rebuild all caches frames * @param rebuilder The rebuilder to use */ void rebuild(AudioFrameRebuilder rebuilder); }
mit
nimashoghi/LoLChatClient
src/main/java/JFrameEx.java
1010
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; public class JFrameEx extends JFrame { public JFrameEx(String title, Runnable onAction) { super(title); JRootPane rootPane = super.getRootPane(); rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), "f2-action"); Image image = Toolkit.getDefaultToolkit().getImage( this.getClass().getResource("icon.png")); ImageIcon icon = new ImageIcon(image); this.setIconImage(icon.getImage()); rootPane.getActionMap().put("f2-action", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { if (onAction != null) { onAction.run(); } } }); } public JFrameEx(String title) { this(title, null); } }
mit
MapsIndoors/MapsIndoorsAndroid
app/src/main/java/com/mapsindoors/stdapp/ui/activitymain/adapters/POIMarkerInfoWindowAdapter.java
2831
package com.mapsindoors.stdapp.ui.activitymain.adapters; /** * Created by amine on 25/01/2018. */ import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import androidx.core.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.Marker; import com.mapsindoors.mapssdk.MPLocation; import com.mapsindoors.mapssdk.MapControl; import com.mapsindoors.mapssdk.dbglog; import com.mapsindoors.stdapp.BuildConfig; import com.mapsindoors.stdapp.R; /** * Custom Info Window used in MI markers */ public class POIMarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter { public static final String TAG = POIMarkerInfoWindowAdapter.class.getSimpleName(); public static final int INFOWINDOW_TYPE_LINK = 0; public static final int INFOWINDOW_TYPE_NORMAL = 1; private int currentType; private Context mCtx; private View mInfoWindowView; private MapControl mMapControl; private TextView mTitleTextView; public POIMarkerInfoWindowAdapter(Context ctx, MapControl mapControl) { mCtx = ctx; View v = mInfoWindowView = LayoutInflater.from(mCtx).inflate(R.layout.control_poi_infowindow, null); int ScreenWidth = Resources.getSystem().getDisplayMetrics().widthPixels; mTitleTextView = v.findViewById(R.id.poi_info_title); mTitleTextView.setMaxWidth((ScreenWidth / 100) * 60); mMapControl = mapControl; } //region IMPLEMENTS GoogleMap.InfoWindowAdapter @Override public View getInfoWindow(Marker marker) { View view = mInfoWindowView; if (view != null) { renderView(marker); } return view; } @Override public View getInfoContents(Marker marker) { return null; } //endregion void renderView(Marker marker) { MPLocation location = mMapControl.getLocation(marker); if (location != null) { final String locationName = location.getName(); mTitleTextView.setText(locationName); } else { if (BuildConfig.DEBUG) { dbglog.LogW(TAG, "renderView: got no location (null) for the given marker (" + marker.getId() + marker.getTitle() + ")"); } } } public void setInfoWindowType(int type) { currentType = type; switch (currentType) { case INFOWINDOW_TYPE_LINK: mTitleTextView.setTextColor(ContextCompat.getColor(mCtx, R.color.info_window_text_color)); break; case INFOWINDOW_TYPE_NORMAL: mTitleTextView.setTextColor(Color.BLACK); break; } } }
mit
CS2103JAN2017-W13-B2/main
src/main/java/seedu/address/model/task/date/TimePeriod.java
2735
//@@author A0144885R package seedu.address.model.task.date; import java.util.Objects; import java.util.Optional; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.commons.util.DateUtil; import seedu.address.model.task.date.DateParser.PairResult; /** * Represents a Time Period with beginning and ending dates. */ public class TimePeriod implements TaskDate { public static final String MESSAGE_TIMEPERIOD_CONSTRAINTS = "Allowed format for TimePeriod obj: from [Valid Date] to [Valid Date]"; public static final String OUTPUT_FORMAT = "from %s to %s"; private final DateValue beginDate; private final DateValue endDate; public TimePeriod(String dateString) throws IllegalValueException { Optional<PairResult<DateValue, DateValue>> parseResult = DateParser.parseTimePeriodString(dateString); if (!parseResult.isPresent()) { throw new IllegalValueException(MESSAGE_TIMEPERIOD_CONSTRAINTS); } beginDate = parseResult.get().first; endDate = parseResult.get().second; if (beginDate.after(endDate)) { throw new IllegalValueException(MESSAGE_TIMEPERIOD_CONSTRAINTS); } } /* Floating taskDate contains no value */ public boolean isFloating() { return false; } public boolean hasPassed() { return endDate.before(DateUtil.getToday()); } public boolean isHappeningToday() { DateValue today = DateUtil.getToday(); return DateUtil.haveIntersection(beginDate.getBeginning(), endDate.getEnding(), DateUtil.getBeginOfDay(today), DateUtil.getEndOfDay(today)); } public boolean isHappeningTomorrow() { DateValue tmr = DateUtil.getTomorrow(); return DateUtil.haveIntersection(beginDate.getBeginning(), endDate.getEnding(), DateUtil.getBeginOfDay(tmr), DateUtil.getEndOfDay(tmr)); } public DateValue getBeginning() { return beginDate.getBeginning(); } public DateValue getEnding() { return endDate.getEnding(); } @Override public String toString() { return String.format(OUTPUT_FORMAT, beginDate.toString(), endDate.toString()); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof TimePeriod // instanceof handles nulls && this.beginDate.equals(((TimePeriod) other).beginDate) // state check && this.endDate.equals(((TimePeriod) other).endDate)); } @Override public int hashCode() { return Objects.hash(beginDate, endDate); } }
mit
plugadoeep/plugado
src/main/java/br/edu/fumep/converter/LocalDateAttributeConverter.java
630
package br.edu.fumep.converter; import javax.persistence.AttributeConverter; import javax.persistence.Converter; import java.time.LocalDate; import java.sql.Date; /** * Created by arabasso on 19/03/2017. * */ @Converter(autoApply = true) public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> { @Override public Date convertToDatabaseColumn(LocalDate locDate) { return (locDate == null ? null : Date.valueOf(locDate)); } @Override public LocalDate convertToEntityAttribute(Date sqlDate) { return (sqlDate == null ? null : sqlDate.toLocalDate()); } }
mit
matthias-dirickx/SoapUI-extensions
src/main/java/com/md/soapui/custom/support/html/simplebuilder/HtmlSimpleElement.java
775
package com.md.soapui.custom.support.html.simplebuilder; public class HtmlSimpleElement extends HtmlTag { private String content; public HtmlSimpleElement(String tag, String content) { super(tag); this.content = escapeLight(content); } public HtmlSimpleElement(String tag) { super(tag); this.content = null; } public String getHtmlString() { if(this.content != null) { return this.start()+content+this.end(); } else { return this.startWithoutContent(); } } private String escapeLight(String s) { return s.replace("&", "&amp;") .replace("<", "&lt;") .replace(">", "&gt;") .replace("\"", "&quot;") .replace("'", "&apos;") .replace("\n", "</br>"); } }
mit
ganthore/docker-workflow-plugin
api/src/main/java/org/jenkinsci/plugins/workflow/actions/LogAction.java
2178
/* * The MIT License * * Copyright (c) 2013-2014, 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 org.jenkinsci.plugins.workflow.actions; import hudson.console.AnnotatedLargeText; import hudson.model.Action; import hudson.model.TaskListener; import org.jenkinsci.plugins.workflow.flow.FlowExecution; import org.jenkinsci.plugins.workflow.graph.FlowNode; import org.jenkinsci.plugins.workflow.steps.StepContext; /** * Associated with a node which has some log text. * So if {@link StepContext} is asked for {@link TaskListener}, the {@link FlowExecution} should attach this action to the contextual {@link FlowNode}. */ public abstract class LogAction implements Action { /** * Access the log file and expose it to the UI with the progressive logging functionality */ public abstract AnnotatedLargeText<? extends FlowNode> getLogText(); @Override public String getIconFileName() { return "clipboard.png"; } @Override public String getDisplayName() { return "Console Output"; } @Override public String getUrlName() { return "log"; } }
mit
juckele/vivarium
vivarium-serialization/src/main/java/io/vivarium/serialization/FileIO.java
2933
package io.vivarium.serialization; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Scanner; import com.googlecode.gwtstreamer.client.Streamer; import io.vivarium.util.UserFacingError; public class FileIO { public static void saveSerializer(VivariumObject serializer, String fileName, Format f) { String data = null; if (f == Format.JSON) { data = JSONConverter.serializerToJSONString(serializer); } else { throw new UserFacingError("Writing format " + f + " is not supported."); } saveStringToFile(data, fileName); } public static void saveSerializerCollection(VivariumObjectCollection serializer, String fileName, Format f) { String data = null; if (f == Format.JSON) { data = JSONConverter.serializerToJSONString(serializer); } else if (f == Format.GWT) { data = Streamer.get().toString(serializer); } else { throw new UserFacingError("Writing format " + f + " is not supported."); } saveStringToFile(data, fileName); } public static void saveStringToFile(String dataString, String fileName) { try { saveStringToFile(dataString, new File(fileName)); } catch (IOException e) { throw new UserFacingError("Unable to write the file " + fileName); } } public static void saveStringToFile(String dataString, File file) throws IOException { try (FileOutputStream fos = new FileOutputStream(file)) { byte[] jsonByteData = dataString.getBytes("UTF-8"); fos.write(jsonByteData); fos.flush(); } } public static String loadFileToString(String fileName) { try { return loadFileToString(new File(fileName)); } catch (FileNotFoundException e) { throw new UserFacingError("Unable to read the file " + fileName); } } public static String loadFileToString(File file) throws FileNotFoundException { try (Scanner scanner = new Scanner(file, "UTF-8")) { return scanner.useDelimiter("\\Z").next(); } } public static VivariumObjectCollection loadObjectCollection(String fileName, Format f) { String data = loadFileToString(fileName); if (f == Format.JSON) { return JSONConverter.jsonStringToSerializerCollection(data); } else if (f == Format.GWT) { return (VivariumObjectCollection) Streamer.get().fromString(data); } else { throw new UserFacingError("Loading format " + f + " is not supported"); } } }
mit
mocha-android/collection-view
src/main/java/mocha/ui/collectionview/CollectionViewFlowLayout.java
7610
/** * @author Shaun * @date 4/17/14 * @copyright 2014 Mocha. All rights reserved. */ package mocha.ui.collectionview; import mocha.foundation.IndexPath; import mocha.foundation.OptionalInterfaceHelper; import mocha.graphics.Rect; import mocha.graphics.Size; import mocha.ui.EdgeInsets; import java.util.List; public class CollectionViewFlowLayout extends CollectionViewLayout { public static final String ELEMENT_KIND_SECTION_HEADER = "ELEMENT_KIND_SECTION_HEADER"; public static final String ELEMENT_KIND_SECTION_FOOTER = "ELEMENT_KIND_SECTION_FOOTER"; private CollectionViewFlowLayoutData data; private boolean prepared; private Size lastBoundsSize; float minimumLineSpacing; float minimumInteritemSpacing; Size itemSize; ScrollDirection scrollDirection; Size headerReferenceSize; Size footerReferenceSize; EdgeInsets sectionInset; boolean delegateSizeForItem; boolean delegateReferenceSizeForHeader; boolean delegateReferenceSizeForFooter; boolean delegateInsetForSection; boolean delegateInteritemSpacingForSection; boolean delegateLineSpacingForSection; public enum ScrollDirection { VERTICAL, HORIZONTAL } public interface Delegate extends CollectionView.Delegate { @Optional Size collectionViewLayoutSizeForItemAtIndexPath(CollectionView collectionView, CollectionViewLayout collectionViewLayout, IndexPath indexPath); @Optional mocha.ui.EdgeInsets collectionViewLayoutInsetForSectionAtIndex(CollectionView collectionView, CollectionViewLayout collectionViewLayout, int section); @Optional float collectionViewLayoutMinimumLineSpacingForSectionAtIndex(CollectionView collectionView, CollectionViewLayout collectionViewLayout, int section); @Optional float collectionViewLayoutMinimumInteritemSpacingForSectionAtIndex(CollectionView collectionView, CollectionViewLayout collectionViewLayout, int section); @Optional Size collectionViewLayoutReferenceSizeForHeaderInSection(CollectionView collectionView, CollectionViewLayout collectionViewLayout, int section); @Optional Size collectionViewLayoutReferenceSizeForFooterInSection(CollectionView collectionView, CollectionViewLayout collectionViewLayout, int section); } public CollectionViewFlowLayout() { this.minimumInteritemSpacing = 10.0f; this.minimumLineSpacing = 10.0f; this.itemSize = new Size(50.0f, 50.0f); this.scrollDirection = ScrollDirection.VERTICAL; this.headerReferenceSize = Size.zero(); this.footerReferenceSize = Size.zero(); this.sectionInset = EdgeInsets.zero(); this.data = new CollectionViewFlowLayoutData(this); } public void collectionViewDelegateDidChange() { super.collectionViewDelegateDidChange(); CollectionView.Delegate delegate = this.getCollectionView().getDelegate(); Delegate flowLayoutDelegate; if (delegate instanceof Delegate) { flowLayoutDelegate = (Delegate)delegate; } else { flowLayoutDelegate = null; } this.delegateSizeForItem = OptionalInterfaceHelper.hasImplemented(flowLayoutDelegate, Delegate.class, "collectionViewLayoutSizeForItemAtIndexPath", CollectionView.class, CollectionViewLayout.class, IndexPath.class); this.delegateInsetForSection = OptionalInterfaceHelper.hasImplemented(flowLayoutDelegate, Delegate.class, "collectionViewLayoutInsetForSectionAtIndex", CollectionView.class, CollectionViewLayout.class, int.class); this.delegateLineSpacingForSection = OptionalInterfaceHelper.hasImplemented(flowLayoutDelegate, Delegate.class, "collectionViewLayoutMinimumLineSpacingForSectionAtIndex", CollectionView.class, CollectionViewLayout.class, int.class); this.delegateInteritemSpacingForSection = OptionalInterfaceHelper.hasImplemented(flowLayoutDelegate, Delegate.class, "collectionViewLayoutMinimumInteritemSpacingForSectionAtIndex", CollectionView.class, CollectionViewLayout.class, int.class); this.delegateReferenceSizeForHeader = OptionalInterfaceHelper.hasImplemented(flowLayoutDelegate, Delegate.class, "collectionViewLayoutReferenceSizeForHeaderInSection", CollectionView.class, CollectionViewLayout.class, int.class); this.delegateReferenceSizeForFooter = OptionalInterfaceHelper.hasImplemented(flowLayoutDelegate, Delegate.class, "collectionViewLayoutReferenceSizeForFooterInSection", CollectionView.class, CollectionViewLayout.class, int.class); } public void prepareLayout() { if(!this.prepared) { this.data.reloadData(); this.prepared = true; } } public void invalidateLayout() { super.invalidateLayout(); this.prepared = false; } public List<CollectionViewLayoutAttributes> layoutAttributesForElementsInRect(Rect rect) { if(!this.prepared) { this.prepareLayout(); } return this.data.layoutAttributesForElementsInRect(rect); } public CollectionViewLayoutAttributes layoutAttributesForItemAtIndexPath(IndexPath indexPath) { if(!this.prepared) { this.prepareLayout(); } return this.data.layoutAttributesForItemAtIndexPath(indexPath); } public CollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKindAtIndexPath(String kind, IndexPath indexPath) { if(!this.prepared) { this.prepareLayout(); } return this.data.layoutAttributesForSupplementaryViewOfKindAtIndexPath(kind, indexPath); } public CollectionViewLayoutAttributes layoutAttributesForDecorationViewOfKindAtIndexPath(String kind, IndexPath indexPath) { return null; } public Size collectionViewContentSize() { return this.data.contentSize.copy(); } public CollectionReusableView decorationViewForCollectionViewWithReuseIdentifierIndexPath(CollectionView collectionView, String reuseIdentifier, IndexPath indexPath) { return null; } public boolean shouldInvalidateLayoutForBoundsChange(Rect newBounds) { boolean invalidate = false; if(this.lastBoundsSize == null) { invalidate = true; this.lastBoundsSize = new Size(); } else if(this.scrollDirection == ScrollDirection.VERTICAL) { invalidate = newBounds.size.width != this.lastBoundsSize.width; } else if(this.scrollDirection == ScrollDirection.HORIZONTAL) { invalidate = newBounds.size.height != this.lastBoundsSize.height; } if(invalidate) { this.lastBoundsSize.width = newBounds.size.width; this.lastBoundsSize.height = newBounds.size.height; return true; } else { return false; } } public float getMinimumLineSpacing() { return minimumLineSpacing; } public void setMinimumLineSpacing(float minimumLineSpacing) { this.minimumLineSpacing = minimumLineSpacing; } public float getMinimumInteritemSpacing() { return minimumInteritemSpacing; } public void setMinimumInteritemSpacing(float minimumInteritemSpacing) { this.minimumInteritemSpacing = minimumInteritemSpacing; } public Size getItemSize() { return this.itemSize.copy(); } public void setItemSize(Size itemSize) { this.itemSize.set(itemSize); } public ScrollDirection getScrollDirection() { return this.scrollDirection; } public void setScrollDirection(ScrollDirection scrollDirection) { this.scrollDirection = scrollDirection; } public Size getHeaderReferenceSize() { return this.headerReferenceSize.copy(); } public void setHeaderReferenceSize(Size headerReferenceSize) { this.headerReferenceSize.set(headerReferenceSize); } public Size getFooterReferenceSize() { return this.footerReferenceSize.copy(); } public void setFooterReferenceSize(Size footerReferenceSize) { this.footerReferenceSize.set(footerReferenceSize); } public EdgeInsets getSectionInset() { return this.sectionInset.copy(); } public void setSectionInset(EdgeInsets sectionInset) { this.sectionInset.set(sectionInset); } }
mit
zaqwes8811/micro-apps
buffer/jvm-tricks/intern/ant-tasks/src/FileSorter.java
2309
import java.io.*; import java.util.*; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import java.text.SimpleDateFormat; /** * Ïðîñòîå çàäàíèå äëÿ ñîðòèðîâêè ôàéëà */ public class FileSorter extends Task { private File file, tofile; private String sfile; // Ìåòîä, âûïîëíÿþùèé çàäàíèå public void execute() throws BuildException { // Íàïå÷àòàòü ñïèñîê ôàéëîâ â äèðåêòîðèè ListAllFiles fileList = new ListAllFiles(); fileList.printListFiles("."); // Òåñòè òèïà âõîäíûå ïàðàìåòðîâ System.out.println( sfile ); // Ïîëó÷èòü äàòó ïîñëåäíåãî èçìåíåíèÿ ôàéëà File f = new File( "./input.txt" ); long datetime = f.lastModified(); Date d = new Date(datetime); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); String dateString = sdf.format(d); System.out.println("The file was last modified on: " + dateString); // Ñîðòèðîâêà â ôàéëå System.out.println("Sorting file="+file); try { BufferedReader from = new BufferedReader(new FileReader(file)); BufferedWriter to = new BufferedWriter(new FileWriter(tofile)); List allLines = new ArrayList(); // ïðî÷èòàòü âõîäíîé ôàéë String line = from.readLine(); while (line != null) { allLines.add(line); line = from.readLine(); } from.close(); // îòñîðòèðîâàòü ñïèñîê Collections.sort(allLines); // çàïèñàòü îòñîðòèðîâàííûé ñïèñîê for (ListIterator i=allLines.listIterator(); i.hasNext(); ) { String s = (String)i.next(); to.write(s); to.newLine(); } to.close(); } catch (FileNotFoundException e) { throw new BuildException(e); } catch (IOException e) { throw new BuildException(e); } } // setter äëÿ àòðèáóòà "file" public void setFile(File file) { this.file = file; } // setter äëÿ àòðèáóòà "tofile" public void setTofile(File tofile) { this.tofile = tofile; } // setter äëÿ àòðèáóòà "file" public void setSFile(String sfile) { this.sfile = sfile; } }
mit
mrajian/xinyuan
xinyuan-parent/xinyuan-pub-parent/xinyuan-pub-dao/src/main/java/com/xinyuan/pub/business/bi/dao/BiHrPersonLeaveDao.java
674
package com.xinyuan.pub.business.bi.dao; import com.xinyuan.pub.model.business.bi.po.BiHrPersonLeave; import com.xinyuan.pub.model.business.bi.po.query.BiHrPersonLeaveQuery; import java.util.List; /** * @author liangyongjian * @desc 人员离职数据表 Dao层接口 * @create 2018-06-22 23:47 **/ public interface BiHrPersonLeaveDao { /** * 获取全部的人员学历结构数据 * @return */ List<BiHrPersonLeave> getAllBiHrPersonLeaveInfo(); /** * 根据检索条件获取人员学历结构数据 * @param query * @return */ List<BiHrPersonLeave> getBiHrPersonLeaveInfoByQuery(BiHrPersonLeaveQuery query); }
mit
wtghby/app
zxing-android/zxing-lib/src/com/google/zxing/client/android/CaptureActivity.java
11772
/* * Copyright (C) 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.client.android; import android.view.*; import com.google.zxing.BarcodeFormat; import com.google.zxing.DecodeHintType; import com.google.zxing.Result; import com.google.zxing.ResultMetadataType; import com.google.zxing.client.android.camera.CameraManager; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.TextView; import java.io.IOException; import java.util.Collection; import java.util.Map; /** * This activity opens the camera and does the actual scanning on a background thread. It draws a * viewfinder to help the user place the barcode correctly, shows feedback as the image processing * is happening, and then overlays the results when a scan is successful. * * @author dswitkin@google.com (Daniel Switkin) * @author Sean Owen */ @SuppressWarnings("unchecked") public final class CaptureActivity extends Activity implements SurfaceHolder.Callback { private static final String TAG = CaptureActivity.class.getSimpleName(); private CameraManager cameraManager; private CaptureActivityHandler handler; private ViewfinderView viewfinderView; private TextView statusView; private boolean hasSurface; private Collection<BarcodeFormat> decodeFormats; private Map<DecodeHintType, ?> decodeHints; private String characterSet; private InactivityTimer inactivityTimer; private BeepManager beepManager; private AmbientLightManager ambientLightManager; ViewfinderView getViewfinderView() { return viewfinderView; } public Handler getHandler() { return handler; } CameraManager getCameraManager() { return cameraManager; } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.activity_zxing_capture); hasSurface = false; inactivityTimer = new InactivityTimer(this); beepManager = new BeepManager(this); ambientLightManager = new AmbientLightManager(this); } @Override protected void onResume() { super.onResume(); // CameraManager must be initialized here, not in onCreate(). This is necessary because we don't // want to open the camera driver and measure the screen size if we're going to show the help on // first launch. That led to bugs where the scanning rectangle was the wrong size and partially // off screen. cameraManager = new CameraManager(getApplication()); viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view); viewfinderView.setCameraManager(cameraManager); statusView = (TextView) findViewById(R.id.status_view); handler = null; resetStatusView(); SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view); SurfaceHolder surfaceHolder = surfaceView.getHolder(); if (hasSurface) { // The activity was paused but not stopped, so the surface still exists. Therefore // surfaceCreated() won't be called, so init the camera here. initCamera(surfaceHolder); } else { // Install the callback and wait for surfaceCreated() to init the camera. surfaceHolder.addCallback(this); } beepManager.updatePrefs(); ambientLightManager.start(cameraManager); inactivityTimer.onResume(); Intent intent = getIntent(); decodeFormats = null; characterSet = null; if (intent != null) { String action = intent.getAction(); if (Intents.Scan.ACTION.equals(action)) { // Scan the formats the intent requested, and return the result to the calling activity. decodeFormats = DecodeFormatManager.parseDecodeFormats(intent); decodeHints = DecodeHintManager.parseDecodeHints(intent); if (intent.hasExtra(Intents.Scan.WIDTH) && intent.hasExtra(Intents.Scan.HEIGHT)) { int width = intent.getIntExtra(Intents.Scan.WIDTH, 0); int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0); if (width > 0 && height > 0) { cameraManager.setManualFramingRect(width, height); } } if (intent.hasExtra(Intents.Scan.CAMERA_ID)) { int cameraId = intent.getIntExtra(Intents.Scan.CAMERA_ID, -1); if (cameraId >= 0) { cameraManager.setManualCameraId(cameraId); } } String customPromptMessage = intent.getStringExtra(Intents.Scan.PROMPT_MESSAGE); if (customPromptMessage != null) { statusView.setText(customPromptMessage); } } characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET); } } @Override protected void onPause() { if (handler != null) { handler.quitSynchronously(); handler = null; } inactivityTimer.onPause(); ambientLightManager.stop(); beepManager.close(); cameraManager.closeDriver(); if (!hasSurface) { SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view); SurfaceHolder surfaceHolder = surfaceView.getHolder(); surfaceHolder.removeCallback(this); } super.onPause(); } @Override protected void onDestroy() { inactivityTimer.shutdown(); super.onDestroy(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: setResult(RESULT_CANCELED); finish(); return true; case KeyEvent.KEYCODE_FOCUS: case KeyEvent.KEYCODE_CAMERA: // Handle these events so they don't launch the Camera app return true; // Use volume up/down to turn on light case KeyEvent.KEYCODE_VOLUME_DOWN: cameraManager.setTorch(false); return true; case KeyEvent.KEYCODE_VOLUME_UP: cameraManager.setTorch(true); return true; } return super.onKeyDown(keyCode, event); } @Override public void surfaceCreated(SurfaceHolder holder) { if (holder == null) { Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!"); } if (!hasSurface) { hasSurface = true; initCamera(holder); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { hasSurface = false; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } /** * A valid barcode has been found, so give an indication of success and show the results. * * @param rawResult The contents of the barcode. */ public void handleDecode(Result rawResult) { inactivityTimer.onActivity(); // Then not from history, so beep/vibrate and we have an image to draw on beepManager.playBeepSoundAndVibrate(); handleDecodeExternally(rawResult); } // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner. private void handleDecodeExternally(Result rawResult) { // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when // the deprecated intent is retired. Intent intent = new Intent(getIntent().getAction()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); intent.putExtra(Intents.Scan.RESULT, rawResult.toString()); intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString()); byte[] rawBytes = rawResult.getRawBytes(); if (rawBytes != null && rawBytes.length > 0) { intent.putExtra(Intents.Scan.RESULT_BYTES, rawBytes); } Map<ResultMetadataType,?> metadata = rawResult.getResultMetadata(); if (metadata != null) { if (metadata.containsKey(ResultMetadataType.UPC_EAN_EXTENSION)) { intent.putExtra(Intents.Scan.RESULT_UPC_EAN_EXTENSION, metadata.get(ResultMetadataType.UPC_EAN_EXTENSION).toString()); } Number orientation = (Number) metadata.get(ResultMetadataType.ORIENTATION); if (orientation != null) { intent.putExtra(Intents.Scan.RESULT_ORIENTATION, orientation.intValue()); } String ecLevel = (String) metadata.get(ResultMetadataType.ERROR_CORRECTION_LEVEL); if (ecLevel != null) { intent.putExtra(Intents.Scan.RESULT_ERROR_CORRECTION_LEVEL, ecLevel); } Iterable<byte[]> byteSegments = (Iterable<byte[]>) metadata.get(ResultMetadataType.BYTE_SEGMENTS); if (byteSegments != null) { int i = 0; for (byte[] byteSegment : byteSegments) { intent.putExtra(Intents.Scan.RESULT_BYTE_SEGMENTS_PREFIX + i, byteSegment); i++; } } } sendReplyMessage(R.id.return_scan_result, intent); } private void sendReplyMessage(int id, Object arg) { if (handler != null) { Message message = Message.obtain(handler, id, arg); handler.sendMessage(message); } } private void initCamera(SurfaceHolder surfaceHolder) { if (surfaceHolder == null) { throw new IllegalStateException("No SurfaceHolder provided"); } if (cameraManager.isOpen()) { Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?"); return; } try { cameraManager.openDriver(surfaceHolder); // Creating the handler starts the preview, which can also throw a RuntimeException. if (handler == null) { handler = new CaptureActivityHandler(this, decodeFormats, decodeHints, characterSet, cameraManager); } } catch (IOException ioe) { Log.w(TAG, ioe); } catch (RuntimeException e) { // Barcode Scanner has seen crashes in the wild of this variety: // java.?lang.?RuntimeException: Fail to connect to camera service Log.w(TAG, "Unexpected error initializing camera", e); } } private void resetStatusView() { statusView.setText(R.string.zxing_msg_default_status); statusView.setVisibility(View.VISIBLE); viewfinderView.setVisibility(View.VISIBLE); } public void drawViewfinder() { viewfinderView.drawViewfinder(); } }
mit
egillespie/pegger
pegger-war/src/main/java/com/technicalrex/webapp/pegger/internal/JacksonObjectMapperConfig.java
831
package com.technicalrex.webapp.pegger.internal; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.guava.GuavaModule; import com.fasterxml.jackson.datatype.joda.JodaModule; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.Provider; @Provider public class JacksonObjectMapperConfig implements ContextResolver<ObjectMapper> { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper() .disable(MapperFeature.AUTO_DETECT_CREATORS) .disable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS) .registerModule(new GuavaModule()) .registerModule(new JodaModule()); @Override public ObjectMapper getContext(Class<?> aClass) { return OBJECT_MAPPER; } }
mit
selvasingh/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/implementation/ExpressRouteCircuitAuthorizationsClientImpl.java
56208
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.network.implementation; import com.azure.core.annotation.BodyParam; import com.azure.core.annotation.Delete; import com.azure.core.annotation.ExpectedResponses; import com.azure.core.annotation.Get; import com.azure.core.annotation.Headers; import com.azure.core.annotation.Host; import com.azure.core.annotation.HostParam; import com.azure.core.annotation.PathParam; import com.azure.core.annotation.Put; import com.azure.core.annotation.QueryParam; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.PagedResponseBase; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; import com.azure.core.management.exception.ManagementException; import com.azure.core.management.polling.PollResult; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.polling.PollerFlux; import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.network.fluent.ExpressRouteCircuitAuthorizationsClient; import com.azure.resourcemanager.network.fluent.models.ExpressRouteCircuitAuthorizationInner; import com.azure.resourcemanager.network.models.AuthorizationListResult; import java.nio.ByteBuffer; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** * An instance of this class provides access to all the operations defined in ExpressRouteCircuitAuthorizationsClient. */ public final class ExpressRouteCircuitAuthorizationsClientImpl implements ExpressRouteCircuitAuthorizationsClient { private final ClientLogger logger = new ClientLogger(ExpressRouteCircuitAuthorizationsClientImpl.class); /** The proxy service used to perform REST calls. */ private final ExpressRouteCircuitAuthorizationsService service; /** The service client containing this operation class. */ private final NetworkManagementClientImpl client; /** * Initializes an instance of ExpressRouteCircuitAuthorizationsClientImpl. * * @param client the instance of the service client containing this operation class. */ ExpressRouteCircuitAuthorizationsClientImpl(NetworkManagementClientImpl client) { this.service = RestProxy .create( ExpressRouteCircuitAuthorizationsService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** * The interface defining all the services for NetworkManagementClientExpressRouteCircuitAuthorizations to be used * by the proxy service to perform REST calls. */ @Host("{$host}") @ServiceInterface(name = "NetworkManagementCli") private interface ExpressRouteCircuitAuthorizationsService { @Headers({"Accept: application/json;q=0.9", "Content-Type: application/json"}) @Delete( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network" + "/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}") @ExpectedResponses({200, 202, 204}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<Flux<ByteBuffer>>> delete( @HostParam("$host") String endpoint, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("circuitName") String circuitName, @PathParam("authorizationName") String authorizationName, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, Context context); @Headers({"Accept: application/json", "Content-Type: application/json"}) @Get( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network" + "/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<ExpressRouteCircuitAuthorizationInner>> get( @HostParam("$host") String endpoint, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("circuitName") String circuitName, @PathParam("authorizationName") String authorizationName, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, Context context); @Headers({"Accept: application/json", "Content-Type: application/json"}) @Put( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network" + "/expressRouteCircuits/{circuitName}/authorizations/{authorizationName}") @ExpectedResponses({200, 201}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<Flux<ByteBuffer>>> createOrUpdate( @HostParam("$host") String endpoint, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("circuitName") String circuitName, @PathParam("authorizationName") String authorizationName, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @BodyParam("application/json") ExpressRouteCircuitAuthorizationInner authorizationParameters, Context context); @Headers({"Accept: application/json", "Content-Type: application/json"}) @Get( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network" + "/expressRouteCircuits/{circuitName}/authorizations") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<AuthorizationListResult>> list( @HostParam("$host") String endpoint, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("circuitName") String circuitName, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, Context context); @Headers({"Accept: application/json", "Content-Type: application/json"}) @Get("{nextLink}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<AuthorizationListResult>> listNext( @PathParam(value = "nextLink", encoded = true) String nextLink, Context context); } /** * Deletes the specified authorization from the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Flux<ByteBuffer>>> deleteWithResponseAsync( String resourceGroupName, String circuitName, String authorizationName) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (circuitName == null) { return Mono.error(new IllegalArgumentException("Parameter circuitName is required and cannot be null.")); } if (authorizationName == null) { return Mono .error(new IllegalArgumentException("Parameter authorizationName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String apiVersion = "2020-05-01"; return FluxUtil .withContext( context -> service .delete( this.client.getEndpoint(), resourceGroupName, circuitName, authorizationName, apiVersion, this.client.getSubscriptionId(), context)) .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()))); } /** * Deletes the specified authorization from the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Response<Flux<ByteBuffer>>> deleteWithResponseAsync( String resourceGroupName, String circuitName, String authorizationName, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (circuitName == null) { return Mono.error(new IllegalArgumentException("Parameter circuitName is required and cannot be null.")); } if (authorizationName == null) { return Mono .error(new IllegalArgumentException("Parameter authorizationName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String apiVersion = "2020-05-01"; context = this.client.mergeContext(context); return service .delete( this.client.getEndpoint(), resourceGroupName, circuitName, authorizationName, apiVersion, this.client.getSubscriptionId(), context); } /** * Deletes the specified authorization from the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<PollResult<Void>, Void> beginDeleteAsync( String resourceGroupName, String circuitName, String authorizationName) { Mono<Response<Flux<ByteBuffer>>> mono = deleteWithResponseAsync(resourceGroupName, circuitName, authorizationName); return this .client .<Void, Void>getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, Context.NONE); } /** * Deletes the specified authorization from the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) private PollerFlux<PollResult<Void>, Void> beginDeleteAsync( String resourceGroupName, String circuitName, String authorizationName, Context context) { context = this.client.mergeContext(context); Mono<Response<Flux<ByteBuffer>>> mono = deleteWithResponseAsync(resourceGroupName, circuitName, authorizationName, context); return this .client .<Void, Void>getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, context); } /** * Deletes the specified authorization from the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public SyncPoller<PollResult<Void>, Void> beginDelete( String resourceGroupName, String circuitName, String authorizationName) { return beginDeleteAsync(resourceGroupName, circuitName, authorizationName).getSyncPoller(); } /** * Deletes the specified authorization from the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public SyncPoller<PollResult<Void>, Void> beginDelete( String resourceGroupName, String circuitName, String authorizationName, Context context) { return beginDeleteAsync(resourceGroupName, circuitName, authorizationName, context).getSyncPoller(); } /** * Deletes the specified authorization from the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Void> deleteAsync(String resourceGroupName, String circuitName, String authorizationName) { return beginDeleteAsync(resourceGroupName, circuitName, authorizationName) .last() .flatMap(this.client::getLroFinalResultOrError); } /** * Deletes the specified authorization from the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the completion. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Void> deleteAsync( String resourceGroupName, String circuitName, String authorizationName, Context context) { return beginDeleteAsync(resourceGroupName, circuitName, authorizationName, context) .last() .flatMap(this.client::getLroFinalResultOrError); } /** * Deletes the specified authorization from the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public void delete(String resourceGroupName, String circuitName, String authorizationName) { deleteAsync(resourceGroupName, circuitName, authorizationName).block(); } /** * Deletes the specified authorization from the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) public void delete(String resourceGroupName, String circuitName, String authorizationName, Context context) { deleteAsync(resourceGroupName, circuitName, authorizationName, context).block(); } /** * Gets the specified authorization from the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the specified authorization from the specified express route circuit. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ExpressRouteCircuitAuthorizationInner>> getWithResponseAsync( String resourceGroupName, String circuitName, String authorizationName) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (circuitName == null) { return Mono.error(new IllegalArgumentException("Parameter circuitName is required and cannot be null.")); } if (authorizationName == null) { return Mono .error(new IllegalArgumentException("Parameter authorizationName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String apiVersion = "2020-05-01"; return FluxUtil .withContext( context -> service .get( this.client.getEndpoint(), resourceGroupName, circuitName, authorizationName, apiVersion, this.client.getSubscriptionId(), context)) .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()))); } /** * Gets the specified authorization from the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the specified authorization from the specified express route circuit. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Response<ExpressRouteCircuitAuthorizationInner>> getWithResponseAsync( String resourceGroupName, String circuitName, String authorizationName, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (circuitName == null) { return Mono.error(new IllegalArgumentException("Parameter circuitName is required and cannot be null.")); } if (authorizationName == null) { return Mono .error(new IllegalArgumentException("Parameter authorizationName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String apiVersion = "2020-05-01"; context = this.client.mergeContext(context); return service .get( this.client.getEndpoint(), resourceGroupName, circuitName, authorizationName, apiVersion, this.client.getSubscriptionId(), context); } /** * Gets the specified authorization from the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the specified authorization from the specified express route circuit. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ExpressRouteCircuitAuthorizationInner> getAsync( String resourceGroupName, String circuitName, String authorizationName) { return getWithResponseAsync(resourceGroupName, circuitName, authorizationName) .flatMap( (Response<ExpressRouteCircuitAuthorizationInner> res) -> { if (res.getValue() != null) { return Mono.just(res.getValue()); } else { return Mono.empty(); } }); } /** * Gets the specified authorization from the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the specified authorization from the specified express route circuit. */ @ServiceMethod(returns = ReturnType.SINGLE) public ExpressRouteCircuitAuthorizationInner get( String resourceGroupName, String circuitName, String authorizationName) { return getAsync(resourceGroupName, circuitName, authorizationName).block(); } /** * Gets the specified authorization from the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the specified authorization from the specified express route circuit. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<ExpressRouteCircuitAuthorizationInner> getWithResponse( String resourceGroupName, String circuitName, String authorizationName, Context context) { return getWithResponseAsync(resourceGroupName, circuitName, authorizationName, context).block(); } /** * Creates or updates an authorization in the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param authorizationParameters Authorization in an ExpressRouteCircuit resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return authorization in an ExpressRouteCircuit resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Flux<ByteBuffer>>> createOrUpdateWithResponseAsync( String resourceGroupName, String circuitName, String authorizationName, ExpressRouteCircuitAuthorizationInner authorizationParameters) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (circuitName == null) { return Mono.error(new IllegalArgumentException("Parameter circuitName is required and cannot be null.")); } if (authorizationName == null) { return Mono .error(new IllegalArgumentException("Parameter authorizationName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } if (authorizationParameters == null) { return Mono .error( new IllegalArgumentException("Parameter authorizationParameters is required and cannot be null.")); } else { authorizationParameters.validate(); } final String apiVersion = "2020-05-01"; return FluxUtil .withContext( context -> service .createOrUpdate( this.client.getEndpoint(), resourceGroupName, circuitName, authorizationName, apiVersion, this.client.getSubscriptionId(), authorizationParameters, context)) .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()))); } /** * Creates or updates an authorization in the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param authorizationParameters Authorization in an ExpressRouteCircuit resource. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return authorization in an ExpressRouteCircuit resource. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Response<Flux<ByteBuffer>>> createOrUpdateWithResponseAsync( String resourceGroupName, String circuitName, String authorizationName, ExpressRouteCircuitAuthorizationInner authorizationParameters, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (circuitName == null) { return Mono.error(new IllegalArgumentException("Parameter circuitName is required and cannot be null.")); } if (authorizationName == null) { return Mono .error(new IllegalArgumentException("Parameter authorizationName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } if (authorizationParameters == null) { return Mono .error( new IllegalArgumentException("Parameter authorizationParameters is required and cannot be null.")); } else { authorizationParameters.validate(); } final String apiVersion = "2020-05-01"; context = this.client.mergeContext(context); return service .createOrUpdate( this.client.getEndpoint(), resourceGroupName, circuitName, authorizationName, apiVersion, this.client.getSubscriptionId(), authorizationParameters, context); } /** * Creates or updates an authorization in the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param authorizationParameters Authorization in an ExpressRouteCircuit resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return authorization in an ExpressRouteCircuit resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public PollerFlux<PollResult<ExpressRouteCircuitAuthorizationInner>, ExpressRouteCircuitAuthorizationInner> beginCreateOrUpdateAsync( String resourceGroupName, String circuitName, String authorizationName, ExpressRouteCircuitAuthorizationInner authorizationParameters) { Mono<Response<Flux<ByteBuffer>>> mono = createOrUpdateWithResponseAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters); return this .client .<ExpressRouteCircuitAuthorizationInner, ExpressRouteCircuitAuthorizationInner>getLroResult( mono, this.client.getHttpPipeline(), ExpressRouteCircuitAuthorizationInner.class, ExpressRouteCircuitAuthorizationInner.class, Context.NONE); } /** * Creates or updates an authorization in the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param authorizationParameters Authorization in an ExpressRouteCircuit resource. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return authorization in an ExpressRouteCircuit resource. */ @ServiceMethod(returns = ReturnType.SINGLE) private PollerFlux<PollResult<ExpressRouteCircuitAuthorizationInner>, ExpressRouteCircuitAuthorizationInner> beginCreateOrUpdateAsync( String resourceGroupName, String circuitName, String authorizationName, ExpressRouteCircuitAuthorizationInner authorizationParameters, Context context) { context = this.client.mergeContext(context); Mono<Response<Flux<ByteBuffer>>> mono = createOrUpdateWithResponseAsync( resourceGroupName, circuitName, authorizationName, authorizationParameters, context); return this .client .<ExpressRouteCircuitAuthorizationInner, ExpressRouteCircuitAuthorizationInner>getLroResult( mono, this.client.getHttpPipeline(), ExpressRouteCircuitAuthorizationInner.class, ExpressRouteCircuitAuthorizationInner.class, context); } /** * Creates or updates an authorization in the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param authorizationParameters Authorization in an ExpressRouteCircuit resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return authorization in an ExpressRouteCircuit resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public SyncPoller<PollResult<ExpressRouteCircuitAuthorizationInner>, ExpressRouteCircuitAuthorizationInner> beginCreateOrUpdate( String resourceGroupName, String circuitName, String authorizationName, ExpressRouteCircuitAuthorizationInner authorizationParameters) { return beginCreateOrUpdateAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters) .getSyncPoller(); } /** * Creates or updates an authorization in the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param authorizationParameters Authorization in an ExpressRouteCircuit resource. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return authorization in an ExpressRouteCircuit resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public SyncPoller<PollResult<ExpressRouteCircuitAuthorizationInner>, ExpressRouteCircuitAuthorizationInner> beginCreateOrUpdate( String resourceGroupName, String circuitName, String authorizationName, ExpressRouteCircuitAuthorizationInner authorizationParameters, Context context) { return beginCreateOrUpdateAsync( resourceGroupName, circuitName, authorizationName, authorizationParameters, context) .getSyncPoller(); } /** * Creates or updates an authorization in the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param authorizationParameters Authorization in an ExpressRouteCircuit resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return authorization in an ExpressRouteCircuit resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ExpressRouteCircuitAuthorizationInner> createOrUpdateAsync( String resourceGroupName, String circuitName, String authorizationName, ExpressRouteCircuitAuthorizationInner authorizationParameters) { return beginCreateOrUpdateAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters) .last() .flatMap(this.client::getLroFinalResultOrError); } /** * Creates or updates an authorization in the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param authorizationParameters Authorization in an ExpressRouteCircuit resource. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return authorization in an ExpressRouteCircuit resource. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<ExpressRouteCircuitAuthorizationInner> createOrUpdateAsync( String resourceGroupName, String circuitName, String authorizationName, ExpressRouteCircuitAuthorizationInner authorizationParameters, Context context) { return beginCreateOrUpdateAsync( resourceGroupName, circuitName, authorizationName, authorizationParameters, context) .last() .flatMap(this.client::getLroFinalResultOrError); } /** * Creates or updates an authorization in the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param authorizationParameters Authorization in an ExpressRouteCircuit resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return authorization in an ExpressRouteCircuit resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public ExpressRouteCircuitAuthorizationInner createOrUpdate( String resourceGroupName, String circuitName, String authorizationName, ExpressRouteCircuitAuthorizationInner authorizationParameters) { return createOrUpdateAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters).block(); } /** * Creates or updates an authorization in the specified express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the express route circuit. * @param authorizationName The name of the authorization. * @param authorizationParameters Authorization in an ExpressRouteCircuit resource. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return authorization in an ExpressRouteCircuit resource. */ @ServiceMethod(returns = ReturnType.SINGLE) public ExpressRouteCircuitAuthorizationInner createOrUpdate( String resourceGroupName, String circuitName, String authorizationName, ExpressRouteCircuitAuthorizationInner authorizationParameters, Context context) { return createOrUpdateAsync(resourceGroupName, circuitName, authorizationName, authorizationParameters, context) .block(); } /** * Gets all authorizations in an express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the circuit. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all authorizations in an express route circuit. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<ExpressRouteCircuitAuthorizationInner>> listSinglePageAsync( String resourceGroupName, String circuitName) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (circuitName == null) { return Mono.error(new IllegalArgumentException("Parameter circuitName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String apiVersion = "2020-05-01"; return FluxUtil .withContext( context -> service .list( this.client.getEndpoint(), resourceGroupName, circuitName, apiVersion, this.client.getSubscriptionId(), context)) .<PagedResponse<ExpressRouteCircuitAuthorizationInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()))); } /** * Gets all authorizations in an express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the circuit. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all authorizations in an express route circuit. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<ExpressRouteCircuitAuthorizationInner>> listSinglePageAsync( String resourceGroupName, String circuitName, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (circuitName == null) { return Mono.error(new IllegalArgumentException("Parameter circuitName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String apiVersion = "2020-05-01"; context = this.client.mergeContext(context); return service .list( this.client.getEndpoint(), resourceGroupName, circuitName, apiVersion, this.client.getSubscriptionId(), context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } /** * Gets all authorizations in an express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the circuit. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all authorizations in an express route circuit. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ExpressRouteCircuitAuthorizationInner> listAsync(String resourceGroupName, String circuitName) { return new PagedFlux<>( () -> listSinglePageAsync(resourceGroupName, circuitName), nextLink -> listNextSinglePageAsync(nextLink)); } /** * Gets all authorizations in an express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the circuit. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all authorizations in an express route circuit. */ @ServiceMethod(returns = ReturnType.COLLECTION) private PagedFlux<ExpressRouteCircuitAuthorizationInner> listAsync( String resourceGroupName, String circuitName, Context context) { return new PagedFlux<>( () -> listSinglePageAsync(resourceGroupName, circuitName, context), nextLink -> listNextSinglePageAsync(nextLink, context)); } /** * Gets all authorizations in an express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the circuit. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all authorizations in an express route circuit. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<ExpressRouteCircuitAuthorizationInner> list(String resourceGroupName, String circuitName) { return new PagedIterable<>(listAsync(resourceGroupName, circuitName)); } /** * Gets all authorizations in an express route circuit. * * @param resourceGroupName The name of the resource group. * @param circuitName The name of the circuit. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return all authorizations in an express route circuit. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable<ExpressRouteCircuitAuthorizationInner> list( String resourceGroupName, String circuitName, Context context) { return new PagedIterable<>(listAsync(resourceGroupName, circuitName, context)); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ListAuthorizations API service call retrieves all authorizations that belongs to an * ExpressRouteCircuit. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<ExpressRouteCircuitAuthorizationInner>> listNextSinglePageAsync(String nextLink) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } return FluxUtil .withContext(context -> service.listNext(nextLink, context)) .<PagedResponse<ExpressRouteCircuitAuthorizationInner>>map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)) .subscriberContext(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()))); } /** * Get the next page of items. * * @param nextLink The nextLink parameter. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return response for ListAuthorizations API service call retrieves all authorizations that belongs to an * ExpressRouteCircuit. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<PagedResponse<ExpressRouteCircuitAuthorizationInner>> listNextSinglePageAsync( String nextLink, Context context) { if (nextLink == null) { return Mono.error(new IllegalArgumentException("Parameter nextLink is required and cannot be null.")); } context = this.client.mergeContext(context); return service .listNext(nextLink, context) .map( res -> new PagedResponseBase<>( res.getRequest(), res.getStatusCode(), res.getHeaders(), res.getValue().value(), res.getValue().nextLink(), null)); } }
mit
sebastienhouzet/nabaztag-source-code
server/OS/net/violet/platform/datamodel/factories/implementations/ContinentFactoryImpl.java
749
package net.violet.platform.datamodel.factories.implementations; import java.util.Arrays; import java.util.List; import net.violet.db.records.factories.RecordFactoryImpl; import net.violet.platform.datamodel.Continent; import net.violet.platform.datamodel.ContinentImpl; import net.violet.platform.datamodel.factories.ContinentFactory; public class ContinentFactoryImpl extends RecordFactoryImpl<Continent, ContinentImpl> implements ContinentFactory { ContinentFactoryImpl() { super(ContinentImpl.SPECIFICATION); } public List<Continent> findAllContinents() { return findAll(null, null, "name"); } public Continent findIdByName(String continentName) { return find("name = ?", Arrays.asList(new Object[] { continentName })); } }
mit
shaunmahony/seqcode
src/edu/psu/compbio/seqcode/gse/clustering/Clusterable.java
108
package edu.psu.compbio.seqcode.gse.clustering; public interface Clusterable { public String name(); }
mit
Spartahacks2016/Hack_Project
app/src/main/java/com/clarifai/androidstarter/MainActivity.java
9476
package com.clarifai.androidstarter; /** * Created by Navid on 2/28/2016. */ import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.StrictMode; import android.provider.MediaStore; import android.provider.Settings; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageView; import android.widget.Toast; import com.clarifai.api.ClarifaiClient; import com.clarifai.api.RecognitionRequest; import com.clarifai.api.RecognitionResult; import com.clarifai.api.Tag; public class MainActivity extends Activity { Button searchBtn; EditText searchString; ImageAdapter myImageAdapter; File[] files; HashMap<String, ArrayList<File>> map; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); searchString = (EditText) findViewById(R.id.search_string); //StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); //StrictMode.setThreadPolicy(policy); // picturesRef = myFirebaseRef.child("Pictures"); //picturesRef.addChildEventListener(new ChildEventListener(); ArrayList<String> taggingList = new ArrayList<>(); map = new HashMap<>(); String ExternalStorageDirectoryPath = Environment .getExternalStorageDirectory() .getAbsolutePath(); String targetPath = ExternalStorageDirectoryPath + "/DCIM/Camera/"; ArrayList<File> fileArrayList = new ArrayList<File>(); File targetDirector = new File(targetPath); files = targetDirector.listFiles(); ClarifaiClient clarifai = new ClarifaiClient("QwyVMelyYYyB57bUcmAj5pNJ8DFbF2vX_otHSwP1", "uTvXRCBEaenYGwAbae56BIcxavMduS6TtJHMnYCZ"); ImageAdapter imageAdapter = new ImageAdapter(getApplicationContext()); GridView gridview = (GridView) findViewById(R.id.gridview); myImageAdapter = new ImageAdapter(this); gridview.setAdapter(myImageAdapter); new AsyncTask<File, Void, Tag>() { RecognitionActivity recognitionActivity = new RecognitionActivity(); Bitmap bitmap = BitmapFactory.decodeFile(files[0].getAbsolutePath()); @Override protected RecognitionResult doInBackground(Bitmap... bitmaps) { return recognitionActivity.recognizeBitmap(bitmap); } @Override protected void onPostExecute(RecognitionResult result) { //updateUIForResult(result); } }.execute(); Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show(); searchBtn = (Button) findViewById(R.id.select_button); searchBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String search = searchString.getText() + ""; ArrayList<File> searchResults = new ArrayList<File>(); if (map.containsKey(search)) { searchResults = map.get(search); for (int i = 0; i < searchResults.size(); i++) { myImageAdapter.add(searchResults.get(i).getAbsolutePath()); } } else { System.out.println("No images found"); } } }); // for (Tag tag : results.get(0).getTags()) // results = clarifai.recognize(new RecognitionRequest(file)); // taggingList = updateUForResult(recognitionActivity.recognizeBitmap(imageAdapter.decodeSampledBitmapFromUri(targetPath+file.getName(), 8, 8))); // recognitionActivity.connection(); /* new AsyncTask<Bitmap, Void, RecognitionResult>() { RecognitionActivity recognitionActivity = new RecognitionActivity(); ImageAdapter imageAdapter = new ImageAdapter(getApplicationContext()); @Override protected RecognitionResult doInBackground(Bitmap... bitmaps) { return recognitionActivity.recognizeBitmap(bitmaps[0]); } @Override protected void onPostExecute(RecognitionResult result) { updateUForResult(result); } }.execute(); taggingList = updateUForResult(recognitionActivity.recognizeBitmap(imageAdapter.decodeSampledBitmapFromUri(targetPath+file.getName(), 8, 8))); } } /*public void postData(){ HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(https://api.clarifai.com/v1/tag/); try{ }*/ } public HashMap<Tag, ArrayList<File>> godMethod(File[] files, ClarifaiClient clarifai) { HashMap<Tag, ArrayList<File>> map = new HashMap<>(); for (File file : files) { //myImageAdapter.add(file.getAbsolutePath()); ArrayList<File> fileArrayList = new ArrayList<File>(); fileArrayList.add(file); try { List<RecognitionResult> results = clarifai.recognize(new RecognitionRequest(file)); for (Tag tag : results.get(0).getTags()) if (map.containsKey(tag.getName())) { map.get(tag.getName()).add(file); } else { ArrayList<File> temp = new ArrayList<>(); temp.add(file); map.put(tag, temp); } } catch (Exception e) { System.out.println(file.toString()); } } return map; } private ArrayList<String> updateUForResult(RecognitionResult result) { ArrayList<String> tagList = new ArrayList<>(); if (result != null) { if (result.getStatusCode() == RecognitionResult.StatusCode.OK) { // Display the list of tags in the UI. StringBuilder b = new StringBuilder(); for (Tag tag : result.getTags()) { tagList.add(tag.getName()); } } } return tagList; } public class ImageAdapter extends BaseAdapter { private Context mContext; ArrayList<String> itemList = new ArrayList<String>(); public ImageAdapter(Context c) { mContext = c; } void add(String path) { itemList.add(path); } @Override public int getCount() { return itemList.size(); } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(8, 8)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); } else { imageView = (ImageView) convertView; } Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 220); imageView.setImageBitmap(bm); return imageView; } public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) { Bitmap bm = null; // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; bm = BitmapFactory.decodeFile(path, options); return bm; } public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { if (width > height) { inSampleSize = Math.round((float) height / (float) reqHeight); } else { inSampleSize = Math.round((float) width / (float) reqWidth); } } return inSampleSize; } } }
mit
mixer/interactive-java
src/test/java/com/mixer/interactive/test/util/TestUtils.java
7291
package com.mixer.interactive.test.util; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.stream.JsonReader; import com.mixer.interactive.exception.InteractiveNoHostsFoundException; import com.mixer.interactive.util.EndpointUtil; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Constants used for testing in multiple test suites. Wherever possible constants are read from a properties file. * * @author Microsoft Corporation * * @since 1.0.0 */ public class TestUtils { /** * Property file name */ private static final String PROPERTY_FILE_NAME = "interactive-project.json"; /** * Property key for retrieving the <code>SERVICE_URI</code> property */ private static final String PROPERTY_KEY_INTERACTIVE_SERVICE = "SERVICE_URI"; /** * Property key for retrieving the <code>PROJECT_ID</code> property */ private static final String PROPERTY_KEY_PROJECT_ID = "PROJECT_ID"; /** * Property key for retrieving the <code>OAUTH_TOKEN</code> property */ private static final String PROPERTY_KEY_OAUTH_TOKEN = "OAUTH_TOKEN"; /** * Property key for retrieving the <code>CHANNEL_ID</code> property */ private static final String PROPERTY_KEY_CHANNEL_ID = "CHANNEL_ID"; /** * Property key for retrieving the <code>API_BASE_URL</code> property */ private static final String PROPERTY_KEY_API_BASE_URL = "API_BASE_URL"; /** * Property key for retrieving the <code>PARTICIPANT_TOKENS</code> property */ private static final String PROPERTY_PARTICIPANT_TOKENS = "PARTICIPANT_TOKENS"; /** * URI for localhost testing */ private static final URI INTERACTIVE_LOCALHOST = URI.create("ws://localhost:3000/gameClient"); /** * Test client id */ public static final String CLIENT_ID = "clientId"; /** * The URI of the Interactive service used for testing */ public static final URI INTERACTIVE_SERVICE_URI; /** * The URI that mock participants connect to */ static final URI INTERACTIVE_PARTICIPANT_URI; /** * Project version ID for the testing Interactive integration */ public static final int INTERACTIVE_PROJECT_ID; /** * OAuth Bearer token */ public static final String OAUTH_BEARER_TOKEN; /** * Channel Id that test participants will connect to */ public static final int CHANNEL_ID; /** * Which base url to use for API calls */ public static final String API_BASE_URL; /** * <code>List</code> of test participants */ public static final List<InteractiveTestParticipant> TEST_PARTICIPANTS = new ArrayList<>(); static { URL propertyFileURL = ClassLoader.getSystemClassLoader().getResource(PROPERTY_FILE_NAME); JsonElement jsonElement = null; if (propertyFileURL != null) { File propertyFile = new File(propertyFileURL.getFile()); try (JsonReader jsonReader = new JsonReader(new FileReader(propertyFile))) { jsonElement = new JsonParser().parse(jsonReader); } catch (IOException e) { e.printStackTrace(); } } if (System.getenv(PROPERTY_KEY_INTERACTIVE_SERVICE) != null) { INTERACTIVE_SERVICE_URI = URI.create(System.getenv(PROPERTY_KEY_INTERACTIVE_SERVICE)); } else { if (jsonElement != null && jsonElement instanceof JsonObject && ((JsonObject) jsonElement).get(PROPERTY_KEY_INTERACTIVE_SERVICE) != null) { INTERACTIVE_SERVICE_URI = URI.create(((JsonObject) jsonElement).get(PROPERTY_KEY_INTERACTIVE_SERVICE).getAsString()); } else { URI serviceHost; try { serviceHost = EndpointUtil.getInteractiveHost(CLIENT_ID).getAddress(); } catch (InteractiveNoHostsFoundException e) { serviceHost = INTERACTIVE_LOCALHOST; } INTERACTIVE_SERVICE_URI = serviceHost; } } OAUTH_BEARER_TOKEN = System.getenv(PROPERTY_KEY_OAUTH_TOKEN) != null ? System.getenv(PROPERTY_KEY_OAUTH_TOKEN) : (jsonElement != null && jsonElement instanceof JsonObject && ((JsonObject) jsonElement).get(PROPERTY_KEY_OAUTH_TOKEN) != null ? ((JsonObject) jsonElement).get(PROPERTY_KEY_OAUTH_TOKEN).getAsString() : "foo"); INTERACTIVE_PROJECT_ID = System.getenv(PROPERTY_KEY_PROJECT_ID) != null ? Integer.parseInt(System.getenv(PROPERTY_KEY_PROJECT_ID)) : (jsonElement != null && jsonElement instanceof JsonObject && ((JsonObject) jsonElement).get(PROPERTY_KEY_PROJECT_ID) != null ? ((JsonObject) jsonElement).get(PROPERTY_KEY_PROJECT_ID).getAsInt() : 1000); CHANNEL_ID = System.getenv(PROPERTY_KEY_CHANNEL_ID) != null ? Integer.parseInt(System.getenv(PROPERTY_KEY_CHANNEL_ID)) : (jsonElement != null && jsonElement instanceof JsonObject && ((JsonObject) jsonElement).get(PROPERTY_KEY_CHANNEL_ID) != null ? ((JsonObject) jsonElement).get(PROPERTY_KEY_CHANNEL_ID).getAsInt() : 0); API_BASE_URL = System.getenv(PROPERTY_KEY_API_BASE_URL) != null ? System.getenv(PROPERTY_KEY_API_BASE_URL) : (jsonElement != null && jsonElement instanceof JsonObject && ((JsonObject) jsonElement).get(PROPERTY_KEY_API_BASE_URL) != null ? ((JsonObject) jsonElement).get(PROPERTY_KEY_API_BASE_URL).getAsString() : "https://localhost/api/v1/"); INTERACTIVE_PARTICIPANT_URI = URI.create(String.format("%s://%s/participant?channel=%s", INTERACTIVE_SERVICE_URI.getScheme(), INTERACTIVE_SERVICE_URI.getAuthority(), CHANNEL_ID)); String encodedTokens = System.getenv(PROPERTY_PARTICIPANT_TOKENS) != null ? System.getenv(PROPERTY_PARTICIPANT_TOKENS) : (jsonElement != null && jsonElement instanceof JsonObject && ((JsonObject) jsonElement).get(PROPERTY_PARTICIPANT_TOKENS) != null ? ((JsonObject) jsonElement).get(PROPERTY_PARTICIPANT_TOKENS).getAsString() : "[\"foo\", \"foo\", \"foo\"]"); List<String> tokens = new Gson().fromJson(encodedTokens, new TypeToken<List<String>>(){}.getType()); tokens.forEach(token -> TEST_PARTICIPANTS.add(new InteractiveTestParticipant(token))); } /** * Waits a period of time to give the <code>InteractiveWebSocketClient</code> time to receive input * from the Interactive service prior to executing any assertions. * * @since 1.0.0 */ public static void waitForWebSocket() { try { Thread.sleep(250); } catch (InterruptedException e) { e.printStackTrace(); } } }
mit
lakshmi-nair/mozu-java
mozu-java-core/src/main/java/com/mozu/api/resources/commerce/catalog/admin/products/ProductOptionResource.java
10427
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.resources.commerce.catalog.admin.products; import com.mozu.api.ApiContext; import java.util.List; import java.util.ArrayList; import com.mozu.api.MozuClient; import com.mozu.api.MozuClientFactory; import com.mozu.api.MozuUrl; import com.mozu.api.Headers; import org.joda.time.DateTime; import com.mozu.api.security.AuthTicket; import org.apache.commons.lang.StringUtils; import com.mozu.api.DataViewMode; /** <summary> * Use the Options resource to configure the option attributes and vocabulary values for an individual product associated with the product type that uses the option attribute. Options are used to generate variations of a product. * </summary> */ public class ProductOptionResource { /// /// <see cref="Mozu.Api.ApiContext"/> /// private ApiContext _apiContext; private DataViewMode _dataViewMode; public ProductOptionResource(ApiContext apiContext) { _apiContext = apiContext; _dataViewMode = DataViewMode.Live; } public ProductOptionResource(ApiContext apiContext, DataViewMode dataViewMode) { _apiContext = apiContext; _dataViewMode = dataViewMode; } /** * Retrieves a list of all option attributes configured for the product specified in the request. * <p><pre><code> * ProductOption productoption = new ProductOption(); * ProductOption productOption = productoption.getOptions( productCode); * </code></pre></p> * @param productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only. * @return List<com.mozu.api.contracts.productadmin.ProductOption> * @see com.mozu.api.contracts.productadmin.ProductOption */ public List<com.mozu.api.contracts.productadmin.ProductOption> getOptions(String productCode) throws Exception { MozuClient<List<com.mozu.api.contracts.productadmin.ProductOption>> client = com.mozu.api.clients.commerce.catalog.admin.products.ProductOptionClient.getOptionsClient(_dataViewMode, productCode); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * Retrieves the details of an option attribute configuration for the specified product. * <p><pre><code> * ProductOption productoption = new ProductOption(); * ProductOption productOption = productoption.getOption( productCode, attributeFQN); * </code></pre></p> * @param attributeFQN The fully qualified name of the attribute, which is a user defined attribute identifier. * @param productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only. * @return com.mozu.api.contracts.productadmin.ProductOption * @see com.mozu.api.contracts.productadmin.ProductOption */ public com.mozu.api.contracts.productadmin.ProductOption getOption(String productCode, String attributeFQN) throws Exception { return getOption( productCode, attributeFQN, null); } /** * Retrieves the details of an option attribute configuration for the specified product. * <p><pre><code> * ProductOption productoption = new ProductOption(); * ProductOption productOption = productoption.getOption( productCode, attributeFQN, responseFields); * </code></pre></p> * @param attributeFQN The fully qualified name of the attribute, which is a user defined attribute identifier. * @param productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only. * @param responseFields Use this field to include those fields which are not included by default. * @return com.mozu.api.contracts.productadmin.ProductOption * @see com.mozu.api.contracts.productadmin.ProductOption */ public com.mozu.api.contracts.productadmin.ProductOption getOption(String productCode, String attributeFQN, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.productadmin.ProductOption> client = com.mozu.api.clients.commerce.catalog.admin.products.ProductOptionClient.getOptionClient(_dataViewMode, productCode, attributeFQN, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * Configures an option attribute for the product specified in the request. * <p><pre><code> * ProductOption productoption = new ProductOption(); * ProductOption productOption = productoption.addOption( productOption, productCode); * </code></pre></p> * @param productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only. * @param productOption Properties of the product option to create such as attribute detail, fully qualified name, and list of product option values. * @return com.mozu.api.contracts.productadmin.ProductOption * @see com.mozu.api.contracts.productadmin.ProductOption * @see com.mozu.api.contracts.productadmin.ProductOption */ public com.mozu.api.contracts.productadmin.ProductOption addOption(com.mozu.api.contracts.productadmin.ProductOption productOption, String productCode) throws Exception { return addOption( productOption, productCode, null); } /** * Configures an option attribute for the product specified in the request. * <p><pre><code> * ProductOption productoption = new ProductOption(); * ProductOption productOption = productoption.addOption( productOption, productCode, responseFields); * </code></pre></p> * @param productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only. * @param responseFields Use this field to include those fields which are not included by default. * @param productOption Properties of the product option to create such as attribute detail, fully qualified name, and list of product option values. * @return com.mozu.api.contracts.productadmin.ProductOption * @see com.mozu.api.contracts.productadmin.ProductOption * @see com.mozu.api.contracts.productadmin.ProductOption */ public com.mozu.api.contracts.productadmin.ProductOption addOption(com.mozu.api.contracts.productadmin.ProductOption productOption, String productCode, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.productadmin.ProductOption> client = com.mozu.api.clients.commerce.catalog.admin.products.ProductOptionClient.addOptionClient(_dataViewMode, productOption, productCode, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * Updates one or more properties of an option attribute configured for a product. * <p><pre><code> * ProductOption productoption = new ProductOption(); * ProductOption productOption = productoption.updateOption( productOption, productCode, attributeFQN); * </code></pre></p> * @param attributeFQN The fully qualified name of the attribute, which is a user defined attribute identifier. * @param productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only. * @param productOption Properties of the product option to create such as attribute detail, fully qualified name, and list of product option values. * @return com.mozu.api.contracts.productadmin.ProductOption * @see com.mozu.api.contracts.productadmin.ProductOption * @see com.mozu.api.contracts.productadmin.ProductOption */ public com.mozu.api.contracts.productadmin.ProductOption updateOption(com.mozu.api.contracts.productadmin.ProductOption productOption, String productCode, String attributeFQN) throws Exception { return updateOption( productOption, productCode, attributeFQN, null); } /** * Updates one or more properties of an option attribute configured for a product. * <p><pre><code> * ProductOption productoption = new ProductOption(); * ProductOption productOption = productoption.updateOption( productOption, productCode, attributeFQN, responseFields); * </code></pre></p> * @param attributeFQN The fully qualified name of the attribute, which is a user defined attribute identifier. * @param productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only. * @param responseFields Use this field to include those fields which are not included by default. * @param productOption Properties of the product option to create such as attribute detail, fully qualified name, and list of product option values. * @return com.mozu.api.contracts.productadmin.ProductOption * @see com.mozu.api.contracts.productadmin.ProductOption * @see com.mozu.api.contracts.productadmin.ProductOption */ public com.mozu.api.contracts.productadmin.ProductOption updateOption(com.mozu.api.contracts.productadmin.ProductOption productOption, String productCode, String attributeFQN, String responseFields) throws Exception { MozuClient<com.mozu.api.contracts.productadmin.ProductOption> client = com.mozu.api.clients.commerce.catalog.admin.products.ProductOptionClient.updateOptionClient(_dataViewMode, productOption, productCode, attributeFQN, responseFields); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * Deletes the configuration of an option attribute for the product specified in the request. * <p><pre><code> * ProductOption productoption = new ProductOption(); * productoption.deleteOption( productCode, attributeFQN); * </code></pre></p> * @param attributeFQN The fully qualified name of the attribute, which is a user defined attribute identifier. * @param productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only. * @return */ public void deleteOption(String productCode, String attributeFQN) throws Exception { MozuClient client = com.mozu.api.clients.commerce.catalog.admin.products.ProductOptionClient.deleteOptionClient(_dataViewMode, productCode, attributeFQN); client.setContext(_apiContext); client.executeRequest(); client.cleanupHttpConnection(); } }
mit
Azure/azure-sdk-for-java
sdk/eventhubs/azure-messaging-eventhubs/src/samples/java/com/azure/messaging/eventhubs/PublishIterableEvents.java
3399
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.messaging.eventhubs; import static java.nio.charset.StandardCharsets.UTF_8; import com.azure.core.amqp.AmqpRetryMode; import com.azure.core.amqp.AmqpRetryOptions; import com.azure.messaging.eventhubs.models.SendOptions; import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import reactor.core.publisher.Flux; /** * Sample demonstrates how to send an iterable of events to specific event hub partition by defining partition id using * {@link SendOptions#setPartitionId(String)}. */ public class PublishIterableEvents { /** * Main method to invoke this demo about how to send an iterable of events with partition id configured. * * @param args Unused arguments to the program. * @throws InterruptedException If the program was interrupted before completion. */ public static void main(String[] args) throws InterruptedException { // The connection string value can be obtained by: // 1. Going to your Event Hubs namespace in Azure Portal. // 2. Creating an Event Hub instance. // 3. Creating a "Shared access policy" for your Event Hub instance. // 4. Copying the connection string from the policy's properties. String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}"; // Set some custom retry options other than the default set. AmqpRetryOptions retryOptions = new AmqpRetryOptions() .setDelay(Duration.ofSeconds(30)) .setMaxRetries(2) .setMode(AmqpRetryMode.EXPONENTIAL); // Instantiate a client that will be used to call the service. EventHubProducerAsyncClient producer = new EventHubClientBuilder() .connectionString(connectionString) .retry(retryOptions) .buildAsyncProducerClient(); // Create an iterable of events to send. Note that the events in iterable should // fit in a single batch. If the events exceed the size of the batch, then send operation will fail. final Iterable<EventData> events = Flux.range(0, 100).map(number -> { final String contents = "event-data-" + number; return new EventData(contents.getBytes(UTF_8)); }).collectList().block(); // To send our events, we need to know what partition to send it to. For the sake of this example, we take the // first partition id. CountDownLatch countDownLatch = new CountDownLatch(1); producer.getPartitionIds() .take(1) // take the first partition id .flatMap(partitionId -> producer.send(events, new SendOptions().setPartitionId(partitionId))) .subscribe(unused -> { }, ex -> System.out.println("Failed to send events: " + ex.getMessage()), () -> { countDownLatch.countDown(); System.out.println("Sending events completed successfully"); }); // Wait for async operation to complete or timeout after 10 seconds. try { countDownLatch.await(10, TimeUnit.SECONDS); } finally { producer.close(); } } }
mit
Azure/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/fluent/models/SignaturesOverridesInner.java
4064
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.network.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.management.ProxyResource; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.network.models.SignaturesOverridesProperties; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** Contains all specific policy signatures overrides for the IDPS. */ @Fluent public final class SignaturesOverridesInner extends ProxyResource { @JsonIgnore private final ClientLogger logger = new ClientLogger(SignaturesOverridesInner.class); /* * Contains the name of the resource (default) */ @JsonProperty(value = "name") private String name; /* * Will contain the resource id of the signature override resource */ @JsonProperty(value = "id") private String id; /* * Will contain the type of the resource: * Microsoft.Network/firewallPolicies/intrusionDetectionSignaturesOverrides */ @JsonProperty(value = "type") private String type; /* * Will contain the properties of the resource (the actual signature * overrides) */ @JsonProperty(value = "properties") private SignaturesOverridesProperties properties; /** * Get the name property: Contains the name of the resource (default). * * @return the name value. */ public String name() { return this.name; } /** * Set the name property: Contains the name of the resource (default). * * @param name the name value to set. * @return the SignaturesOverridesInner object itself. */ public SignaturesOverridesInner withName(String name) { this.name = name; return this; } /** * Get the id property: Will contain the resource id of the signature override resource. * * @return the id value. */ public String id() { return this.id; } /** * Set the id property: Will contain the resource id of the signature override resource. * * @param id the id value to set. * @return the SignaturesOverridesInner object itself. */ public SignaturesOverridesInner withId(String id) { this.id = id; return this; } /** * Get the type property: Will contain the type of the resource: * Microsoft.Network/firewallPolicies/intrusionDetectionSignaturesOverrides. * * @return the type value. */ public String type() { return this.type; } /** * Set the type property: Will contain the type of the resource: * Microsoft.Network/firewallPolicies/intrusionDetectionSignaturesOverrides. * * @param type the type value to set. * @return the SignaturesOverridesInner object itself. */ public SignaturesOverridesInner withType(String type) { this.type = type; return this; } /** * Get the properties property: Will contain the properties of the resource (the actual signature overrides). * * @return the properties value. */ public SignaturesOverridesProperties properties() { return this.properties; } /** * Set the properties property: Will contain the properties of the resource (the actual signature overrides). * * @param properties the properties value to set. * @return the SignaturesOverridesInner object itself. */ public SignaturesOverridesInner withProperties(SignaturesOverridesProperties properties) { this.properties = properties; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (properties() != null) { properties().validate(); } } }
mit
EhWhoAmI/Monster-Quest
src/MonsterQuest/game/UI/PlayerDetails.java
2251
/* * The MIT License * * Copyright 2017 Zyun. * * 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 MonsterQuest.game.UI; import MonsterQuest.game.painter.Paintable; import MonsterQuest.util.GraphicsUnit; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.awt.Color; /** * This is the implementation for the player details. * @author Zyun */ @GraphicsUnit public class PlayerDetails implements Paintable{ // All the rectangles for the UI public static Rectangle2D.Float userAvatar = new Rectangle2D.Float(50, 50, 100, 100); public static Rectangle2D.Float hpBar = new Rectangle2D.Float(150, 60, 200, 25); public static Rectangle2D.Float energyBar = new Rectangle2D.Float(150, 100, 200, 25); @Override public void paint (Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.RED); g2d.fill(userAvatar); g2d.fill(hpBar); g2d.setColor(Color.BLUE); g2d.fill(energyBar); } public static boolean mouseInSelection (int x, int y) { return (userAvatar.intersects(x, y, 1, 1) | hpBar.intersects(x, y, 1, 1) | energyBar.intersects(x, y, 1, 1)); } }
mit
zenilt/kalah
src/com/zenilt/kalah/exception/KalahException.java
1322
/* * The MIT License * * Copyright 2015 Juan Francisco Rodríguez. * * 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.zenilt.kalah.exception; /** * * @author Juan Francisco Rodríguez */ public class KalahException extends Exception { public KalahException() { } }
mit
Azure/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/cosmos/generated/SqlResourcesListSqlTriggersSamples.java
997
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.cosmos.generated; import com.azure.core.util.Context; /** Samples for SqlResources ListSqlTriggers. */ public final class SqlResourcesListSqlTriggersSamples { /* * x-ms-original-file: specification/cosmos-db/resource-manager/Microsoft.DocumentDB/stable/2021-10-15/examples/CosmosDBSqlTriggerList.json */ /** * Sample code: CosmosDBSqlTriggerList. * * @param azure The entry point for accessing resource management APIs in Azure. */ public static void cosmosDBSqlTriggerList(com.azure.resourcemanager.AzureResourceManager azure) { azure .cosmosDBAccounts() .manager() .serviceClient() .getSqlResources() .listSqlTriggers("rgName", "ddb1", "databaseName", "containerName", Context.NONE); } }
mit
vincent-t/KinoCast
app/src/main/java/com/ov3rk1ll/kinocast/ui/helper/PaletteManager.java
1212
package com.ov3rk1ll.kinocast.ui.helper; import android.graphics.Bitmap; import android.support.v4.util.LruCache; import android.support.v7.graphics.Palette; public class PaletteManager { private LruCache<String, Palette> cache = new LruCache<String, Palette>(100); private static PaletteManager instance; public static PaletteManager getInstance(){ if(instance == null) instance = new PaletteManager(); return instance; } public interface Callback { void onPaletteReady(Palette palette); } public void getPalette(final String key, Bitmap bitmap, final Callback callback) { Palette palette = cache.get(key); if (palette != null) callback.onPaletteReady(palette); else if(bitmap == null){ callback.onPaletteReady(null); } else { Palette.generateAsync(bitmap, 24, new Palette.PaletteAsyncListener() { @Override public void onGenerated(Palette palette) { cache.put(key, palette); callback.onPaletteReady(palette); } }); } } }
mit
amazingyyc/ResistCloud
ResistCloud/src/com/resistcloud/constant/Eye.java
542
package com.resistcloud.constant; /* * ÉèÖÃÊӽǵÄλÖà °üº¬ÁËÊӽǵÄλÖà */ public class Eye { //ÑÛ¾¦ËùÔÚµÄλÖà public static float eyeX; public static float eyeY; public static float eyeZ; //ÖÐÐĵ㼴˵¿´µÃµã public static float centerX; public static float centerY; public static float centerZ; public static void set() { eyeX = GLConstant.GLWidth /2; eyeY = GLConstant.GLHeight/2; eyeZ = GLConstant.GLHeight/2; centerX = GLConstant.GLWidth /2; centerY = GLConstant.GLHeight/2; centerZ = 0; } }
mit
mylog00/search_csv
src/csv/search/SearchCSV.java
3101
package csv.search; import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.CSVWriter; import java.io.*; public class SearchCSV { private static final char DEFAULT_SEPARATOR = ';'; private static final char DEFAULT_QUOTE_CHAR = '"'; private static final String DEFAULT_LINE_END = "\r\n"; public static final String DEFAULT_CHARSET_NAME = "cp1251"; private String FILE_ENCODE; private String SEARCH_FILE_PATH; private String RESULT_FILE_PATH; /** * * @param inputFilePath */ public SearchCSV( String inputFilePath, String outputFilePath, String fileEncode) { SEARCH_FILE_PATH = inputFilePath; RESULT_FILE_PATH = outputFilePath; FILE_ENCODE = fileEncode; } /** * * @param searchValue * @param columnName * @throws ESearchException * @throws IOException * @throws UnsupportedEncodingException * @throws FileNotFoundException */ public void searchValue(String searchValue ,String columnName) throws ESearchException, IOException, FileNotFoundException, UnsupportedEncodingException { int columnIndex; String[] row; //FileReader inputFile = null; //FileWriter outputFile = null; InputStreamReader inputFile = null; OutputStreamWriter outputFile = null; CSVReader in = null; CSVWriter out = null; try { inputFile = new InputStreamReader (new FileInputStream(SEARCH_FILE_PATH), FILE_ENCODE); in = new CSVReader(inputFile, DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHAR, DEFAULT_QUOTE_CHAR); // read columns name and type row = in.readNext(); if( row == null) { throw new ESearchException("Invalid file format"); } columnIndex = getColumnIndex(columnName, row); outputFile = new OutputStreamWriter( new FileOutputStream(RESULT_FILE_PATH, false), FILE_ENCODE); out = new CSVWriter(outputFile, DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHAR, DEFAULT_LINE_END); out.writeNext(row); while ( (row = in.readNext()) != null ) { if ( searchValue.equals( row[columnIndex] ) ) { out.writeNext(row); } } } // catch (IOException e) { // e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. // // } finally { if( in != null) { // try { in.close(); // } catch (IOException e) { // e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. // } } if( inputFile != null) { // try { inputFile.close(); // } catch (IOException e) { // e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. // } } if( out != null) { out.close(); } if( outputFile != null) { outputFile.close(); } } } /** * * @param searchColumnName * @param colName * @return * @throws ESearchException */ private int getColumnIndex(String searchColumnName, String[] colName) throws ESearchException { for (int index = 0; index < colName.length; index++) { String name = colName[index].split(" ")[0]; if( name.equals(searchColumnName)) { return index; } } throw new ESearchException("Column name not found"); } }
mit