text
stringlengths
10
2.72M
package com.example.rahmanm2.list_grid_zigzag_view.Adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.rahmanm2.list_grid_zigzag_view.Data_Model.Animals; import com.example.rahmanm2.list_grid_zigzag_view.R; import java.util.List; public class diffrentViewAdapter extends RecyclerView.Adapter<diffrentViewAdapter.myViewHolder> { private static final String TAG = diffrentViewAdapter.class.getSimpleName(); private List<Animals>mAnimalsList; LayoutInflater mLayoutInflater; public diffrentViewAdapter(Context context, List<Animals>animalsList){ this.mAnimalsList = animalsList; this.mLayoutInflater = LayoutInflater.from(context); } @NonNull @Override public myViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = mLayoutInflater.inflate(R.layout.different_view, parent,false); myViewHolder viewHolder = new myViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(@NonNull myViewHolder holder, int position) { Animals currentObj = mAnimalsList.get(position); holder.setData(currentObj); } @Override public int getItemCount() { return mAnimalsList.size(); } class myViewHolder extends RecyclerView.ViewHolder{ ImageView mImageView; TextView mTextView; public myViewHolder(View itemView) { super(itemView); mImageView = (ImageView)itemView.findViewById(R.id.image_ID_differentView); mTextView = (TextView)itemView.findViewById(R.id.text_ID_differentview); } public void setData(Animals animals){ this.mTextView.setText(animals.getTitle()); this.mImageView.setImageResource(animals.getID()); } } }
package org.usfirst.frc.team3216.robot.commands; import org.usfirst.frc.team3216.lib.Logger; import org.usfirst.frc.team3216.robot.Robot; import org.usfirst.frc.team3216.robot.RobotMap; import org.usfirst.frc.team3216.robot.subsystems.ClimbArm; import edu.wpi.first.wpilibj.command.Command; public class ClimbArm_Rotate extends Command { private static final Logger.Level LOG_LEVEL = RobotMap.LOG_CLIMB_ARM; Logger log = new Logger(LOG_LEVEL, getName()); ClimbArm climbArm = Robot.climbArm; private double degrees; private double encoderValue; double motorSpeed = RobotMap.CLIMB_ARM_SPEED; public ClimbArm_Rotate(double degrees) { requires(climbArm); this.degrees = degrees; } // Called just before this Command runs the first time @Override protected void initialize() { } // Called repeatedly when this Command is scheduled to run @Override protected void execute() { encoderValue = 0; // Once we get the encoder for the arm working, we need to set this to the value // of the encoder rotation if (degrees > 0) { // checks if it is positive if (encoderValue < degrees) { // if the arm needs to continue rotating forwards climbArm.setPower(motorSpeed); } else { // stop arm when it reaches or passes goal climbArm.stop(); } } else if (degrees > 0) { // checks if it is negative if (encoderValue > degrees) { // if the arm needs to continue rotating backwards climbArm.setPower(-1 * motorSpeed); } else { // stop arm when it reaches or passes goal climbArm.stop(); } } else { // only called if degrees = 0 climbArm.stop(); } } // Make this return true when this Command no longer needs to run execute() @Override protected boolean isFinished() { return false; } // Called once after isFinished returns true @Override protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run @Override protected void interrupted() { } }
package com.cloudogu.smeagol.wiki.usecase; import com.cloudogu.smeagol.AccountService; import com.cloudogu.smeagol.wiki.domain.*; import de.triology.cb.CommandHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Component; import static com.cloudogu.smeagol.wiki.usecase.Commits.createNewCommit; /** * Handler for {@link MovePageCommand}. */ @Component public class MovePageCommandHandler implements CommandHandler<Page, MovePageCommand> { private final ApplicationEventPublisher publisher; private final PageRepository repository; private final AccountService accountService; @Autowired public MovePageCommandHandler(ApplicationEventPublisher publisher, PageRepository repository, AccountService accountService) { this.publisher = publisher; this.repository = repository; this.accountService = accountService; } @Override public Page handle(MovePageCommand command) { Path source = command.getSource(); Page page = repository.findByWikiIdAndPath(command.getWikiId(), source) .orElseThrow(() -> new PageNotFoundException(source)); Path target = command.getTarget(); if (repository.exists(command.getWikiId(), target)) { throw new PageAlreadyExistsException(target, "the page already exists"); } Commit commit = createNewCommit(accountService, command.getMessage()); page.move(commit, target); Page movedPage = repository.save(page); publisher.publishEvent(new PageDeletedEvent(command.getWikiId(), source)); publisher.publishEvent(new PageCreatedEvent(movedPage)); return movedPage; } }
package com.tencent.mm.plugin.luckymoney.sns.b; import com.tencent.mm.kernel.g; public final class a { public static int bbi() { g.Ek(); return ((Integer) g.Ei().DT().get(com.tencent.mm.storage.aa.a.sSG, Integer.valueOf(0))).intValue(); } public static void si(int i) { g.Ek(); g.Ei().DT().a(com.tencent.mm.storage.aa.a.sSG, Integer.valueOf(i)); g.Ek(); g.Ei().DT().lm(true); } public static String bbj() { g.Ek(); return (String) g.Ei().DT().get(com.tencent.mm.storage.aa.a.sSL, ""); } public static String bbk() { g.Ek(); return (String) g.Ei().DT().get(com.tencent.mm.storage.aa.a.sSM, ""); } }
package bootcamp.test.fileuploaddownload; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.firefox.FirefoxProfile; import io.github.bonigarcia.wdm.WebDriverManager; public class FileDownloadFIrefox { public static void main(String[] args) { WebDriverManager.firefoxdriver().setup(); FirefoxProfile profile = new FirefoxProfile(); profile.setPreference("browser.download.manager.showWhenStarting", false); profile.setPreference("browser.helperApps.alwaysAsk.force", false); profile.setPreference("browser.download.dir", "/Users/kunalashar"); profile.setPreference("browser.download.folderList", 2); // Set Preference to not show file download confirmation dialogue using MIME // types Of different file extension types. profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml"); FirefoxOptions options = new FirefoxOptions(); options.setProfile(profile); WebDriver driver = new FirefoxDriver(options); driver.get("https://demoqa.com/upload-download"); driver.findElement(By.id("downloadButton")).click(); } }
package kh.cocoa.statics; import java.sql.Date; public class DocumentConfigurator { public static int recordCountPerPage = 10; public static int naviCountPerPage = 10; //프로그램 시작일(일단 documentList쪽에서 사용) public static Date startDate= Date.valueOf("2020-01-01"); }
package org.dmonix; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; import junit.framework.Assert; /** * Base class for all testcases. The class will also force the JVM locale to be EN-US. * * @author Peter Nerg * @since 2.0 */ public abstract class AbstractTestCase extends Assert { /** The logger instance for this class */ protected final Logger logger = Logger.getLogger(getClass().getName()); /** * The time stamp for when the time measurement is started for test case. The time can either be set by directly accessing the variable or by executing * <code>startTimeMeasurement</code> The variable is automatically set in the constructor to the current system time. * * @see #startTimeMeasurement() * @see #assertExecutionTime() * @see #assertExecutionTime(long) */ protected long testStartTime; /** * The variable defines the maximum exution time for a test case. Set in the constructor. * * @see #assertExecutionTime() */ protected long maxExecutionTime; /** * Flag that states if an exception has been caught or not. */ protected boolean exceptionCaught = false; static { Locale.setDefault(Locale.US); System.setProperty("user.country", Locale.US.getCountry()); System.setProperty("user.language", Locale.US.getLanguage()); System.setProperty("user.variant", Locale.US.getVariant()); } /** * Sets the logging level. * * @param level * @see java.util.logging.Level */ protected void setLogLevel(Level level) { Enumeration<String> names = LogManager.getLogManager().getLoggerNames(); while (names.hasMoreElements()) { LogManager.getLogManager().getLogger(names.nextElement()).setLevel(level); } } /** * Set the flag that states if an exception has been caught or not. * * @see #exceptionCaught * @see #assertExceptionCaught() */ protected void setExceptionCaught() { this.exceptionCaught = true; } /** * Assert that the current time minus the start time is less than or equal to the maximum allowed execution time. * * <pre> * I.e.<code>System.currentTimeMillis() - startTime &lt;= maxExecutionTime</code> * This method will use the internal variable for measuring the start time. * This time stamp can be set by executing<code>startTimeMeasurement</code> * The maxumum allowed execution time has to be set in the constructor. * </pre> * * @see #startTimeMeasurement */ protected void assertExecutionTime() { assertExecutionTime(this.maxExecutionTime, this.testStartTime); } /** * Assert that the current time minus the start time is less than or equal to the maximum allowed execution time. * * <pre> * I.e. <code>System.currentTimeMillis() - startTime &lt;= maxExecutionTime</code> * This method will use the internal variable for measuring the start time. * This time stamp can be set by executing<code>startTimeMeasurement</code> * </pre> * * @param maxExecutionTime * The allowed execution time * @see #startTimeMeasurement */ protected void assertExecutionTime(long maxExecutionTime) { assertExecutionTime(maxExecutionTime, this.testStartTime); } /** * Assert that the current time minus the start time is less than or equal to the maximum allowed execution time. I.e. * <code>System.currentTimeMillis() - startTime <= maxExecutionTime</code> * * @param maxExecutionTime * The allowed execution time * @param startTime * The start time */ protected void assertExecutionTime(long maxExecutionTime, long startTime) { long elapsedTime = System.currentTimeMillis() - startTime; assertTrue("Execution time [" + elapsedTime + " millis] exceeded the maximum time [" + maxExecutionTime + " millis]", elapsedTime <= maxExecutionTime); logger.info("Time for executing the test : " + elapsedTime + " millis, maximum allowed time is " + maxExecutionTime + " millis"); } /** * Assert that the <code>exceptionCaught</code> attribute has been set. * * @see #exceptionCaught * @see #setExceptionCaught() */ protected void assertExceptionCaught() { this.assertExceptionCaught("Expected an exception."); } /** * Assert that the <code>exceptionCaught</code> attribute has been set. * * @param message * The message to use in case the assertion fails. * @see #exceptionCaught * @see #setExceptionCaught() */ protected void assertExceptionCaught(String message) { assertTrue(message, exceptionCaught); } /** * Assert that the content of the input collections are equal. * * @param expected * The expected collection * @param actual * The actual collection */ protected void assertCollections(Collection<?> expected, Collection<?> actual) { assertCollectionSize(actual, expected.size()); Object o1, o2; Iterator<?> iterator1 = expected.iterator(); Iterator<?> iterator2 = actual.iterator(); while (iterator1.hasNext()) { o1 = iterator1.next(); o2 = iterator2.next(); assertEquals("The objects don't match", o1, o2); } } /** * Assert that the input collection is not null and not empty. * * @param collection * The collection to assert */ protected void assertCollectionNotEmpty(Collection<?> collection) { assertNotNull("The collection was null", collection); if (collection.size() == 0) { fail("The collection was empty"); } } /** * Assert that the input collection is not null and has the expected size. * * @param collection * The collection to assert * @param expectedSize * The expected size of the collection */ protected void assertCollectionSize(Collection<?> collection, int expectedSize) { assertNotNull("The collection was null", collection); if (collection.size() != expectedSize) { fail("The size of the collection [" + collection.size() + "] does not match the expected size [" + expectedSize + "]"); } } /** * Assert that the input collection is not null and has the expected size. * * @param collection * The collection to assert * @param minSize * The minumum size of the collection * @param maxSize * The maximum size of the collection */ protected void assertCollectionSizeRange(Collection<?> collection, int minSize, int maxSize) { assertNotNull("The collection was null", collection); if (collection.size() < minSize || collection.size() > maxSize) { fail("The size of the collection [" + collection.size() + "] does not match the expected range [" + minSize + "-" + maxSize + "]"); } } /** * Assert that the input map is not null and not empty. * * @param map * The map to assert */ protected void assertMapNotEmpty(Map<?, ?> map) { assertNotNull("The collection was null", map); if (map.size() == 0) { fail("The collection was empty"); } } /** * Assert that the input map is not null and has the expected size. * * @param map * The map to assert * @param expectedSize * The expected size of the collection */ protected void assertMapSize(Map<?, ?> map, int expectedSize) { assertNotNull("The map was null", map); if (map.size() != expectedSize) { fail("The size of the map [" + map.size() + "] does not match the expected size [" + expectedSize + "]"); } } /** * Assert that the content of the input maps are equal. * * @param expected * The expected map * @param actual * The actual map */ protected void assertMaps(Map<?, ?> expected, Map<?, ?> actual) { assertMapSize(actual, expected.size()); Object o1, o2; for (Object key : expected.keySet()) { o1 = expected.get(key); o2 = actual.get(key); assertNotNull("Could not find the key [" + key + "]", o2); assertEquals("The objects don't match", o1, o2); } } /** * Put the current thread to sleep for the provided time. * * @param millis * The time in millis */ protected void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { } } /** * This method will set the start time stamp for when the testcase measured. * * @see #testStartTime */ protected void startTimeMeasurement() { this.testStartTime = System.currentTimeMillis(); } }
package com.tencent.mm.plugin.profile.ui; import android.content.Context; import com.tencent.mm.R; final class q implements HelperHeaderPreference$a { private Context context; public q(Context context) { this.context = context; } public final CharSequence getHint() { return this.context.getString(R.l.contact_info_feedsapp_tip); } public final void a(HelperHeaderPreference helperHeaderPreference) { helperHeaderPreference.hd((com.tencent.mm.model.q.GQ() & 32768) == 0); } }
package com.tencent.mm.plugin.sns.ui; import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView.LayoutParams; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.tencent.mm.ar.n; import com.tencent.mm.ar.r; import com.tencent.mm.plugin.sns.i.f; import com.tencent.mm.plugin.sns.model.af; import com.tencent.mm.protocal.c.ate; import com.tencent.mm.sdk.platformtools.ag; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.av; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public final class g extends BaseAdapter { private final Activity bOb; private final ag handler = new ag(); private String kCA = ""; final List<ate> list = new ArrayList(); final Map<Integer, Integer> nKG = new HashMap(); final Map<Integer, Integer> nKH = new HashMap(); int nKI = 0; int nKJ = 0; private final b nKK; private final h nKL; final a nKM; public g(Activity activity, String str, b bVar, a aVar) { this.bOb = activity; this.kCA = str; this.nKK = bVar; this.nKM = aVar; this.nKL = new h(new 1(this)); WT(); } public final void WT() { if (this.nKL != null) { r.Qp(); String Qm = n.Qm(); x.d("MicroMsg.ArtistAdapter", "packgePath: " + Qm); this.nKL.eO(this.kCA, Qm); } } public final int getCount() { return this.nKI; } public final Object getItem(int i) { return this.list.get(i); } public final long getItemId(int i) { return 0; } public final View getView(int i, View view, ViewGroup viewGroup) { c cVar; if (view == null) { cVar = new c(this); view = View.inflate(this.bOb, com.tencent.mm.plugin.sns.i.g.sns_artist_item, null); cVar.eGX = (TextView) view.findViewById(f.sns_title); cVar.nKT = (TextView) view.findViewById(f.sns_title_en); cVar.nKU = (ImageView) view.findViewById(f.img1); cVar.nKV = (ImageView) view.findViewById(f.img2); cVar.nKW = (ImageView) view.findViewById(f.img3); cVar.nKX = (LinearLayout) view.findViewById(f.listener_keeper); cVar.nKY = view.findViewById(f.line_add); cVar.nKU.setOnClickListener(this.nKK.nKO); cVar.nKV.setOnClickListener(this.nKK.nKP); cVar.nKW.setOnClickListener(this.nKK.nKQ); view.setTag(cVar); } else { cVar = (c) view.getTag(); } int intValue = this.nKG.get(Integer.valueOf(i)) != null ? ((Integer) this.nKG.get(Integer.valueOf(i))).intValue() : -1; cVar.nKU.setVisibility(8); cVar.nKV.setVisibility(8); cVar.nKW.setVisibility(8); cVar.nKY.setVisibility(8); if (cVar.nKN.kCA.equals("en")) { cVar.eGX.setVisibility(8); cVar.nKT.setVisibility(4); } else { cVar.eGX.setVisibility(4); cVar.nKT.setVisibility(8); } if (intValue >= this.nKJ || intValue == -1) { view.setLayoutParams(new LayoutParams(-1, 1)); view.setVisibility(8); } else { String str = ""; if (intValue - 1 >= 0) { Object obj = ((ate) getItem(intValue - 1)).jOS; } else { String obj2 = str; } view.setLayoutParams(new LayoutParams(-1, -2)); view.setVisibility(0); int intValue2 = this.nKH.get(Integer.valueOf(i)) != null ? ((Integer) this.nKH.get(Integer.valueOf(i))).intValue() : 1; ate ate = (ate) getItem(intValue); if (ate.jOS.equals("") || !ate.jOS.equals(obj2)) { if (this.kCA.equals("en")) { cVar.nKT.setVisibility(0); cVar.nKT.setText(ate.jOS); cVar.nKY.setVisibility(0); } else { cVar.eGX.setVisibility(0); cVar.eGX.setText(ate.jOS); cVar.nKY.setVisibility(0); } } if (intValue2 > 0) { a(intValue, cVar.nKU); } if (intValue2 >= 2) { a(intValue + 1, cVar.nKV); } if (intValue2 >= 3) { a(intValue + 2, cVar.nKW); } } return view; } private void a(int i, ImageView imageView) { ate ate = (ate) getItem(i); imageView.setVisibility(0); a aVar = new a(); aVar.bSZ = ""; aVar.position = i; imageView.setTag(aVar); af.byl().b(ate, imageView, this.bOb.hashCode(), av.tbu); } }
package se.gareth.swm; import android.graphics.BitmapFactory; public class ExtraLifeItem extends ItemBaseObject { private static Sprite mHeartItemSprite; public ExtraLifeItem(GameBase gameBase) { super(gameBase); if (mHeartItemSprite == null) { mHeartItemSprite = new Sprite(BitmapFactory.decodeResource(game.res, R.drawable.item_heart1), 1); } setAnimation(new Animation(mHeartItemSprite, 0, 0)); } protected void behaviorFinished(Behavior behavior) { game.health.addLifes(1); deleteMe(); } @Override protected void useItem() { } @Override public void picked() { double x = game.health.getX(); double y = game.health.getY(); addBehavior(new MoveToBehavior(game, x, y, 1500.0)); game.gameStage.addActiveObject(this); } }
package com.facebook.react.uimanager.events; import android.view.MotionEvent; import android.view.View; import com.facebook.react.uimanager.RootViewUtil; public class NativeGestureUtil { public static void notifyNativeGestureStarted(View paramView, MotionEvent paramMotionEvent) { RootViewUtil.getRootView(paramView).onChildStartedNativeGesture(paramMotionEvent); } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\reac\\uimanager\events\NativeGestureUtil.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package org.mess110.jrattrack.util.exceptions; public class JRatException extends Exception { /** * */ private static final long serialVersionUID = -4455941964111679946L; public JRatException(String string) { super(string); } }
package ua.khai.slynko.library.db.entity; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.Optional; /** * Status entity. * * @author O.Slynko * */ public enum Status { READING_ROOM("readingRoom", 0), LIBRARY_CARD("libraryCard", 1), CLOSED("closed", 2) , NOT_CONFIRMED("notConfirmed", 3); private final String key; private final int value; Status(String key, int value) { this.key = key; this.value = value; } public int getValue() { return value; } public String getKey() { return key; } public static Status getByKey(String key) { Optional<Status> status = Arrays.stream(values()) .filter(s -> s.getKey().equals(key)) .findFirst(); return status.orElseThrow(NoSuchElementException::new); } }
package it.ozimov.seldon.core.algorithms.forecast.seasonal; /** * @version 0.1.0 * @since 0.1.0 */ public interface SeasonalForecastAlgorithm { }
package com.spr.container; import SprESRepo.Message; import org.elasticsearch.common.collect.Tuple; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by saurav on 27/03/17. */ public class GraphHolder { private Map<Long, SprESRepo.ProfileUser> userProfileMap; private Map<Long, SprESRepo.Message> messages; private List<Tuple<Long, Long>> links; public GraphHolder() { this.userProfileMap = new HashMap<>(); this.messages = new HashMap<>(); this.links = new ArrayList<>(); } public GraphHolder(Map<Long, SprESRepo.ProfileUser> userProfileMap, Map<Long, SprESRepo.Message> messages, List<Tuple<Long, Long>> edges) { this.userProfileMap = userProfileMap; this.messages = messages; this.links = edges; } public void addLink(SprESRepo.Message message) { SprESRepo.ProfileUser user = message.getUser(); this.userProfileMap.put(user.getId(), user); this.messages.put(message.getId(), message); this.links.add(Tuple.tuple(user.getId(), message.getId())); } public Map<Long, SprESRepo.ProfileUser> getUserProfileMap() { return userProfileMap; } public void setUserProfileMap(Map<Long, SprESRepo.ProfileUser> userProfileMap) { this.userProfileMap = userProfileMap; } public Map<Long, SprESRepo.Message> getMessages() { return messages; } public void setMessages(Map<Long, Message> messages) { this.messages = messages; } public List<Tuple<Long, Long>> getLinks() { return links; } public void setLinks(List<Tuple<Long, Long>> links) { this.links = links; } }
package com.espendwise.manta.model.view; // Generated by Hibernate Tools import com.espendwise.manta.model.ValueObject; /** * AllStoreIdentificationView generated by hbm2java */ public class AllStoreIdentificationView extends ValueObject implements java.io.Serializable { private static final long serialVersionUID = -1; public static final String MAIN_STORE_ID = "mainStoreId"; public static final String STORE_ID = "storeId"; public static final String STORE_NAME = "storeName"; public static final String DS_NAME = "dsName"; public static final String ALIVE = "alive"; private Long mainStoreId; private Long storeId; private String storeName; private String dsName; private boolean alive; public AllStoreIdentificationView() { } public AllStoreIdentificationView(Long mainStoreId) { this.setMainStoreId(mainStoreId); } public AllStoreIdentificationView(Long mainStoreId, Long storeId, String storeName, String dsName, boolean alive) { this.setMainStoreId(mainStoreId); this.setStoreId(storeId); this.setStoreName(storeName); this.setDsName(dsName); this.setAlive(alive); } public Long getMainStoreId() { return this.mainStoreId; } public void setMainStoreId(Long mainStoreId) { this.mainStoreId = mainStoreId; setDirty(true); } public Long getStoreId() { return this.storeId; } public void setStoreId(Long storeId) { this.storeId = storeId; setDirty(true); } public String getStoreName() { return this.storeName; } public void setStoreName(String storeName) { this.storeName = storeName; setDirty(true); } public String getDsName() { return this.dsName; } public void setDsName(String dsName) { this.dsName = dsName; setDirty(true); } public boolean isAlive() { return this.alive; } public void setAlive(boolean alive) { this.alive = alive; setDirty(true); } }
package jpa.project.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import jpa.project.service.BrandService; import jpa.project.service.ResponseService; import jpa.project.model.dto.brand.BrandDto; import jpa.project.model.dto.brand.BrandRegisterDto; import jpa.project.model.dto.brand.BrandUpdateDto; import jpa.project.response.CommonResult; import jpa.project.response.SingleResult; import lombok.RequiredArgsConstructor; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RestController @RequiredArgsConstructor @Api(tags = {"4.brand"}) public class BrandApiController { private final BrandService brandService; private final ResponseService responseService; @ApiImplicitParams({ @ApiImplicitParam(name = "X-AUTH-TOKEN",value = "로그인 성공후 access-token",required = true,dataType = "String",paramType = "header") }) @ApiOperation(value ="브랜드 등록" ,notes = "브랜드를 등록한다") @PostMapping("/admin/brand") public SingleResult<BrandDto> save(@Valid @ModelAttribute BrandRegisterDto brandRegisterDto){ return responseService.getSingResult(brandService.save(brandRegisterDto)); } @ApiOperation(value="브랜드 단건조회",notes="브랜드를 단건 조회한다") @GetMapping("/brand/{id}") public SingleResult<BrandDto>findById(@PathVariable("id")Long id){ return responseService.getSingResult(brandService.findById(id)); } @ApiImplicitParams({ @ApiImplicitParam(name = "X-AUTH-TOKEN",value = "로그인 성공후 access-token",required = true,dataType = "String",paramType = "header") }) @ApiOperation(value="브랜드 삭제",notes="브랜드를 삭제한다") @DeleteMapping("/admin/brand/{id}") public CommonResult delete(@PathVariable("id")Long id){ Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String username = authentication.getName(); brandService.delete(id,username); return responseService.getSuccessResult(); } @ApiImplicitParams({ @ApiImplicitParam(name = "X-AUTH-TOKEN",value = "로그인 성공후 access-token",required = true,dataType = "String",paramType = "header") }) @ApiOperation(value="브랜드 수정",notes="브랜드를 수정한다") @PutMapping("/admin/brand/{id}") public CommonResult update(@PathVariable("id")Long id, @ModelAttribute BrandUpdateDto brandUpdateDto) { brandService.updateBrand(id, brandUpdateDto); return responseService.getSuccessResult(); } }
/* Quadratic contains a variety of methods that can find zeros and other properties given a quadratic function Author: Teddy R + Ian D Last Updated: 10/10/18 */ public class Quadratic{ public static void main(String [] args) { Poly1Test(); Poly2Test(); Poly3Test(); } //tests all funcitons for first polynomial, checks expected with calculated value using method public static void Poly1Test(){ System.out.println("Tests for polynomial 1\n"); if(quadYTest(2,-1,1,-1,-3)){ System.out.println("Quad Y test passed"); } else System.out.println("Quad Y test failed"); if(discriminantTest(-1,1,-1,-3)){ System.out.println("Discriminant test passed"); } else System.out.println("Discriminant test failed"); if(numRootsTest(-1,1,-1,0)){ System.out.println("numRoots test passed"); } else System.out.println("numRoots test failed"); if(Double.isNaN(plusRoot(-1,1,-1))){ System.out.println("plusRoot test passed"); } else System.out.println("plusRoot test failed"); if (Double.isNaN(minusRoot(-1,1,-1))){ System.out.println("minusRoot test passed"); } else System.out.println("minusRoot test failed"); if(findRootsTest(-1,1,-1,(""))){ System.out.println("findRoots test passed"); } else System.out.println("findRoots test failed"); if(xSymTest(-1,1,-1,0.5)){ System.out.println("X Sym test passed"); } else System.out.println("X Sym test failed"); if(yVertexTest(-1,1,-1,-0.75)){ System.out.println("Y Vertex test passed"); } else System.out.println("Y Vertex test failed"); } //tests for poly 2 public static void Poly2Test(){ System.out.println("\n\nTests for polynomial 2\n"); if(quadYTest(2,-2,-12,-18,-50)){ System.out.println("Quad Y test passed"); } else System.out.println("Quad Y test failed"); if(discriminantTest(-2,-12,-18,0)){ System.out.println("Discriminant test passed"); } else System.out.println("Discriminant test failed"); if(numRootsTest(-2,-12,-18,1)){ System.out.println("numRoots test passed"); } else System.out.println("numRoots test failed"); if(plusRootTest(-2,-12,-18,-3)){ System.out.println("plusRoot test passed"); } else System.out.println("plusRoot test failed"); if(minusRootTest(-2,-12,-18,-3)){ System.out.println("minusRoot test passed"); } else System.out.println("minusRoot test failed"); if(findRootsTest(-2,-12,-18,("-3.0,0"))){ System.out.println("findRoots test passed"); } else System.out.println("findRoots test failed"); if(xSymTest(-2,-12,-18,-3)){ System.out.println("X Sym test passed"); } else System.out.println("X Sym test failed"); if(yVertexTest(-2,-12,-18,0)){ System.out.println("Y Vertex test passed"); } else System.out.println("Y Vertex test failed"); } //tests for poly 3 public static void Poly3Test(){ System.out.println("\n\nTests for polynomial 3\n"); if(quadYTest(2,1,0,-2,2)){ System.out.println("Quad Y test passed"); } else System.out.println("Quad Y test failed"); if(discriminantTest(1,0,-2,8)){ System.out.println("Discriminant test passed"); } else System.out.println("Discriminant test failed"); if(numRootsTest(1,0,-2,2)){ System.out.println("numRoots test passed"); } else System.out.println("numRoots test failed"); if(plusRootTest(1,0,-2,1.4142135623730951)){ System.out.println("plusRoot test passed"); } else System.out.println("plusRoot test failed"); if(minusRootTest(1,0,-2,-1.4142135623730951)){ System.out.println("minusRoot test passed"); } else System.out.println("minusRoot test failed"); if(findRootsTest(1,0,-2,((minusRoot(1,0,-2))+",0 and "+plusRoot(1,0,-2)+",0"))){ System.out.println("findRoots test passed"); } else System.out.println("findRoots test failed"); if(xSymTest(1,0,-2,0)){ System.out.println("X Sym test passed"); } else System.out.println("X Sym test failed"); if(yVertexTest(1,0,-2,-2)){ System.out.println("Y Vertex test passed"); } else System.out.println("Y Vertex test failed\n\n"); } //find value of equation given x public static double quadY(double x, double a, double b, double c){ return x*x*a+x*b+c; } //tests above with a given expected value public static boolean quadYTest(double x, double a, double b, double c, double expected){ if(quadY(x,a,b,c) == expected) return true; else return false; } //finds the value of b^2-4ac (the number under the square root which determines number of roots) public static double discriminant(double a, double b, double c){ return b*b-4*a*c; } //tests above with a given expected value public static boolean discriminantTest(double a, double b, double c, double expected){ if(discriminant(a,b,c) == expected) return true; else return false; } //uses dicriminant to determine the number of real roots public static int numRoots(double a, double b, double c){ if(b*b-4*a*c > 0) return 2; else if (((a==0)&&(b==0))&&(c==0)) return 0; else if(b*b-4*a*c == 0) return 1; else return 0; } //tests above with a given expected value public static boolean numRootsTest(double a, double b, double c, double expected){ if(numRoots(a,b,c)==expected) return true; else return false; } //finds the root(if possible) when the numerator of the quadratic formula is -b+(...) public static double plusRoot(double a, double b, double c){ if (b*b-4*a*c<0) return (Double.NaN); else return ((-b+Math.sqrt(b*b-4*a*c))/(2*a)); } //tests above with a given expected value public static boolean plusRootTest(double a, double b, double c, double expected){ if(plusRoot(a,b,c)==expected) return true; else return false; } //finds the root(if possible) when the numerator of the quadratic formula is -b-(...) public static double minusRoot(double a, double b, double c){ if (b*b-4*a*c<0) return (Double.NaN); else return ((-b-Math.sqrt(b*b-4*a*c))/(2*a)); } //tests above with a given expected value public static boolean minusRootTest(double a, double b, double c, double expected){ if(minusRoot(a,b,c)==expected) return true; else return false; } //returns all the real roots in order of smallest to largest public static String findRoots(double a, double b, double c){ if(b*b-4*a*c > 0) { if ((-b-Math.sqrt(b*b-4*a*c))/(2*a)<((-b+Math.sqrt(b*b-4*a*c))/(2*a))) return Double.toString(((-b-Math.sqrt(b*b-4*a*c))/(2*a)))+",0 and "+ Double.toString(((-b+Math.sqrt(b*b-4*a*c))/(2*a))) + ",0"; else return Double.toString(((-b+Math.sqrt(b*b-4*a*c))/(2*a)))+",0 and "+ Double.toString(((-b-Math.sqrt(b*b-4*a*c))/(2*a))) + ",0"; } else if (((a==0)&&(b==0))&&(c==0)) return ""; else if(b*b-4*a*c == 0) return Double.toString(-b/(2*a)) + ",0"; else return ""; } //tests above with a given expected value public static boolean findRootsTest(double a, double b, double c, String expected){ if(findRoots(a,b,c).equals(expected)) return true; else return false; } //finds the x-value of the axis of symmetry for the parabola public static double xSym(double a, double b, double c){ return (-b/(2*a)); } //tests above with a given expected value public static boolean xSymTest(double a, double b, double c, double expected){ if(xSym(a,b,c)==expected) return true; else return false; } //finds the y-value of the vertex of the parabola public static double yVertex(double a, double b, double c){ double x = xSym(a,b,c); return a*x*x+b*x+c; } //tests above with a given expected value public static boolean yVertexTest(double a, double b, double c, double expected){ if(yVertex(a,b,c)==expected) return true; else return false; } }
package littleservantmod.util; import littleservantmod.entity.EntityLittleServant; import littleservantmod.entity.EntityLittleServantBase; import net.minecraft.world.World; public class OpenGuiEntityId { //X public int entityId; //Y public int dimensionId; public OpenGuiEntityId(EntityLittleServantBase servant) { this.entityId = servant.getEntityId(); this.dimensionId = servant.world.provider.getDimension(); } public static EntityLittleServant getEntityFromXYZ(World world, int x, int y, int z) { return (EntityLittleServant) world.getEntityByID(x); } public int getX() { return this.entityId; } }
package com.tencent.tinker.a.a; import com.tencent.tinker.a.a.b.c; import com.tencent.tinker.a.a.t.a.a; public final class r extends a<r> { public int vph; public int vpi; public int vpj; public final /* synthetic */ int compareTo(Object obj) { r rVar = (r) obj; int fI = c.fI(this.vph, rVar.vph); if (fI != 0) { return fI; } fI = c.fI(this.vpi, rVar.vpi); return fI == 0 ? c.fJ(this.vpj, rVar.vpj) : fI; } public r(int i, int i2, int i3, int i4) { super(i); this.vph = i2; this.vpi = i3; this.vpj = i4; } }
package com.agong.demo.ui; public abstract class WindowCallback<T> { abstract public void onSuccess(T param); public void onFailure(Throwable e, String errorMsg) { e.printStackTrace(); } public void onStart() { } public void onProgress(Object progress) { } public void onFinish() { } }
package Util; import Models.Artifact; import Models.MinHeap; /** * Created by Hance on 2016-12-23. */ public class Heap { private static Heap ourHeap = new Heap(); public MinHeap TheHeap = new MinHeap(64); public static Heap getInstance() { return ourHeap; } private Heap() { } }
package view; import Controllers.MainController; import client.Client; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.stage.StageStyle; import java.io.IOException; public class Window extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { FXMLLoader loader = new FXMLLoader(Window.class.getResource("/Main.fxml")); Parent parent = null; try { parent = loader.load(); } catch (IOException e) { e.printStackTrace(); } Scene scene = new Scene(parent); Client client = new Client(); // client.setKey("thisisakey"); // client.addPassword("hello","this","is","password"); // client.addPassword("google", "tings", "yee", "nout"); // client.addPassword("twitter", "oijoijo", "fan", "toid"); // client.addPassword("facebook", "bigtiddy", "youknowit", ""); MainController controller = loader.getController(); controller.setClient(client); controller.setPrimaryStage(primaryStage); primaryStage.setTitle("Toms cool password manager"); primaryStage.setScene(scene); primaryStage.show(); }; }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Stack; public class Listener extends ExprBaseListener{ Stack<ArrayList<Node>> nodes = new Stack<>(); NFA nfa = new NFA(); public Stack<ArrayList<Node>> getNodes() { return nodes; } @Override public void exitPlus(ExprParser.PlusContext ctx) { ArrayList<Node> last = nodes.pop(); List<Integer> path = new ArrayList<>(); path.add(last.get(0).getIdentifier()); last.get(last.size() - 1).getPaths().put('ñ', path); nodes.push(last); } @Override public void exitRange(ExprParser.RangeContext ctx) { ArrayList<Node> right = nodes.pop(); ArrayList<Node> left = nodes.pop(); int leftRange = left.get(0).getPaths().keySet().toArray(new Character[0])[0] + 0; int rightRange = right.get(0).getPaths().keySet().toArray(new Character[0])[0] + 0; HashMap<Character, List<Integer>> paths = new HashMap<>(); List<Integer> lst = new ArrayList<>(); lst.add(1); while (leftRange <= rightRange){ nfa.getAlphabet().add((char)leftRange); paths.put((char)leftRange++, lst); } Node start = new Node(0, paths); ArrayList<Node> lstNodes = new ArrayList<>(); lstNodes.add(start); lstNodes.add(new Node(1, new HashMap<>())); nodes.push(lstNodes); } @Override public void exitConcatenation(ExprParser.ConcatenationContext ctx) { ArrayList<Node> right = nodes.pop(); ArrayList<Node> left = nodes.pop(); int leftSize = left.size(); left.remove(left.size() - 1); for(Node n : right){ int id = n.getIdentifier() + leftSize - 1; n.setIdentifier(id); Character[] ar = n.getPaths().keySet().toArray(new Character[0]); for(Character c : ar){ List<Integer> newList = new ArrayList<>(); for(Integer i : n.getPaths().get(c)){ newList.add(i + leftSize - 1); } n.getPaths().put(c, newList); } left.add(n); } nodes.add(left); } @Override public void exitStar(ExprParser.StarContext ctx) { ArrayList<Node> block = new ArrayList<>(); ArrayList<Node> nodeList = nodes.pop(); int lastIdNode = nodeList.size() + 1; HashMap<Character, List<Integer>> startHashmap = new HashMap<>(); List<Integer> listStart = new ArrayList<>(); listStart.add(1); listStart.add(lastIdNode); startHashmap.put('ñ', listStart); Node start = new Node(0, startHashmap); block.add(start); for(Node n : nodeList){ n.setIdentifier(n.getIdentifier() + 1); Character[] ar = n.getPaths().keySet().toArray(new Character[0]); for(Character c : ar){ List<Integer> newList = new ArrayList<>(); for(Integer i : n.getPaths().get(c)){ newList.add(i + 1); } n.getPaths().put(c, newList); } block.add(n); } List<Integer> directionNode = new ArrayList<>(); directionNode.add(nodeList.get(0).getIdentifier()); directionNode.add(lastIdNode); block.get(block.size() - 1).getPaths().put('ñ', directionNode); Node last = new Node(nodeList.size() + 1, new HashMap<>()); block.add(last); nodes.push(block); } @Override public void exitChara(ExprParser.CharaContext ctx) { Character c = ctx.getText().charAt(0); nfa.getAlphabet().add(c); HashMap<Character, List<Integer>> hm = new HashMap<>(); List<Integer> destiny = new ArrayList<>(); destiny.add(1); hm.put(c, destiny); Node n = new Node(0, hm); Node d = new Node(1, new HashMap<>()); ArrayList<Node> newList = new ArrayList<>(); newList.add(n); newList.add(d); nodes.push(newList); } @Override public void exitUnion(ExprParser.UnionContext ctx) { ArrayList<Node> block = new ArrayList<>(); ArrayList<Node> rightUnion = nodes.pop(); ArrayList<Node> leftUnion = nodes.pop(); HashMap<Character, List<Integer>> hm = new HashMap<>(); List<Integer> l = new ArrayList<>(); l.add(leftUnion.get(0).getIdentifier()+1); l.add(leftUnion.size()+1); hm.put('ñ', l); Node start = new Node(0, hm); block.add(start); for(Node n : leftUnion){ n.setIdentifier(n.getIdentifier() + 1); Character[] ar = n.getPaths().keySet().toArray(new Character[0]); for(Character c : ar){ List<Integer> newList = new ArrayList<>(); for(Integer i : n.getPaths().get(c)){ newList.add(i + 1); } n.getPaths().put(c, newList); } block.add(n); } for(Node n : rightUnion){ int id = n.getIdentifier() + leftUnion.size() + 1; n.setIdentifier(id); Character[] ar = n.getPaths().keySet().toArray(new Character[0]); for(Character c : ar){ List<Integer> newList = new ArrayList<>(); for(Integer i : n.getPaths().get(c)){ newList.add(i + leftUnion.size() + 1); } n.getPaths().put(c, newList); } block.add(n); } int lastNodeId = leftUnion.size() + rightUnion.size() + 1; List<Integer> lastDirection = new ArrayList<>(); lastDirection.add(lastNodeId); block.get(leftUnion.size()).getPaths().put('ñ', lastDirection); block.get(leftUnion.size() + rightUnion.size()).getPaths().put('ñ', lastDirection); Node last = new Node(lastNodeId, new HashMap<>()); block.add(last); nodes.push(block); } public NFA getNfa() { return nfa; } }
package br.com.edu.fafic.release1.service; import br.com.edu.fafic.release1.domain.Aluno; import br.com.edu.fafic.release1.domain.Professor; import br.com.edu.fafic.release1.repositories.AlunoRepository; import br.com.edu.fafic.release1.repositories.ProfessorRepository; import org.springframework.stereotype.Service; @Service public class BibliotecarioService { private final ProfessorRepository professorRepository; private final AlunoRepository alunoRepository; public BibliotecarioService(ProfessorRepository professorRepository, AlunoRepository alunoRepository) { this.professorRepository = professorRepository; this.alunoRepository = alunoRepository; } public Professor saveProfessor(Professor professor){ return professorRepository.save(professor); } public Aluno saveAluno(Aluno aluno){ return alunoRepository.save(aluno); } }
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class p09 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int tot = 0; int count = 0; ArrayList<Integer> b = new ArrayList<Integer>(); for(int a_i=0; a_i < n; a_i++){ int temp = in.nextInt(); b.add(temp); tot += temp; } Collections.sort(b); int c = b.get(b.size()-1); while(c >= (tot - c)){ count++; b.remove(b.size()-1); if(c%2 == 1){ b.add(c/2); b.add((c/2) +1); } else{ b.add(c/2); b.add(c/2); } Collections.sort(b); c = b.get(b.size()-1); } System.out.println(count); } }
package 手撕; import nowcoder.剑指offer.TreeNode; /** * @Author: Mr.M * @Date: 2019-05-28 21:10 * @Description: **/ public class 二叉树序列化与反序列化 { public int index = -1; String Serialize(TreeNode root) { StringBuilder s = new StringBuilder(); if (root == null) { s.append("#,"); return s.toString(); } s.append(root.val + ","); s.append(Serialize(root.left)); s.append(Serialize(root.right)); return s.toString(); } TreeNode Deserialize(String str) { index++; String[] DLRseq = str.split(","); TreeNode leave = null; if (!DLRseq[index].equals("#")) { leave = new TreeNode(Integer.valueOf(DLRseq[index])); leave.left = Deserialize(str); leave.right = Deserialize(str); } return leave; } }
package com.tencent.mm.plugin.appbrand.jsapi; import android.content.Intent; import com.tencent.mm.bg.d; import com.tencent.mm.plugin.appbrand.l; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.MMActivity; import org.json.JSONArray; import org.json.JSONObject; public final class at extends a { public static final int CTRL_INDEX = 434; public static final String NAME = "openQRCode"; private static volatile boolean fGq = false; public final void a(l lVar, JSONObject jSONObject, int i) { if (fGq) { lVar.E(i, f("cancel", null)); return; } fGq = true; x.i("MicroMsg.JsApiOpenQRCode", "openQRCode data::%s", new Object[]{jSONObject}); MMActivity c = c(lVar); if (c == null) { fGq = false; x.e("MicroMsg.JsApiOpenQRCode", "pageContext is null, err"); lVar.E(i, f("fail:context is err", null)); return; } boolean z; boolean z2; int i2; jSONObject.optString("desc"); int i3 = bi.getInt(jSONObject.optString("needResult"), 1); String optString = jSONObject.optString("scanType"); if (bi.oW(optString)) { z = true; z2 = true; } else { z = false; z2 = false; } if (optString != null) { try { JSONArray jSONArray = new JSONArray(optString); int i4 = 0; while (i4 < jSONArray.length()) { boolean z3; optString = (String) jSONArray.get(i4); if (optString.equalsIgnoreCase("qrCode")) { z3 = z; z2 = true; } else if (optString.equalsIgnoreCase("barCode")) { z3 = true; } else { z3 = z; } i4++; z = z3; } } catch (Exception e) { x.e("MicroMsg.JsApiOpenQRCode", "doScanQRCode, ex in scanType"); } } if (z2 && !r2) { i2 = 8; } else if (z2 || !r2) { i2 = 1; } else { i2 = 4; } c.geJ = new 1(this, lVar, i); if (i3 == 0) { x.i("MicroMsg.JsApiOpenQRCode", "doScanQRCode, startActivity"); Intent intent = new Intent(); intent.putExtra("BaseScanUI_select_scan_mode", i2); d.c(c, "scanner", ".ui.SingleTopScanUI", intent); fGq = false; lVar.E(i, f("ok", null)); } else if (i3 == 1) { x.d("MicroMsg.JsApiOpenQRCode", "doScanQRCode, startActivityForResult requestCode:%d", new Object[]{Integer.valueOf(hashCode())}); Intent intent2 = new Intent(); intent2.putExtra("BaseScanUI_select_scan_mode", i2); intent2.putExtra("BaseScanUI_only_scan_qrcode_with_zbar", true); intent2.putExtra("key_is_finish_on_scanned", true); intent2.putExtra("GetFriendQRCodeUI.INTENT_FROM_ACTIVITY", 3); d.a(c, "scanner", ".ui.SingleTopScanUI", intent2, hashCode() & 65535, false); } else { x.e("MicroMsg.JsApiOpenQRCode", "needResult is err"); lVar.E(i, f("fail:invalid data", null)); } } }
package com.santander.bi.DAO; import java.util.List; import org.springframework.stereotype.Repository; import com.santander.bi.model.Modulo; @Repository @SuppressWarnings({ "unchecked" }) public class ModuloDAOImpl extends AbstractBaseDAO implements ModuloDAO{ /* (non-Javadoc) * @see com.santander.bi.DAO.ModuloDAO#get(int) */ @Override public Modulo get(int id){ session = getCurrenSessionFactory(); Modulo p = (Modulo) session.load(Modulo.class, new Integer(id)); logger.info("Person loaded successfully, Person details="+p); return p; } /* (non-Javadoc) * @see com.santander.bi.DAO.ModuloDAO#getAll() */ @Override public List<Modulo> getAll() { List<Modulo> moduloList = null; try { session = getCurrenSessionFactory(); moduloList = session.createQuery("from Modulo mod order by mod.modulo").list(); }catch(Exception ex) { ex.printStackTrace(); } return moduloList; } /* (non-Javadoc) * @see com.santander.bi.DAO.ModuloDAO#save(com.santander.bi.model.Modulo) */ @Override public Modulo save(Modulo t) { try { session = getCurrenSessionFactory(); try { session.beginTransaction(); t = (Modulo)session.merge(t); session.persist(t); session.getTransaction().commit(); //session.close(); logger.info("Modulo saved successfully, Person Details="+t); }catch(Exception ex) { ex.printStackTrace(); session.getTransaction().rollback(); } }catch(Exception ex) { ex.printStackTrace(); return null; } return t; } /* (non-Javadoc) * @see com.santander.bi.DAO.ModuloDAO#update(com.santander.bi.model.Modulo) */ @Override public Modulo update(Modulo t) { try { session = getCurrenSessionFactory(); try { session.beginTransaction(); t = (Modulo)session.merge(t); session.saveOrUpdate(t); session.getTransaction().commit(); //session.close(); logger.info("Modulo updated successfully, Person Details="+t); }catch(Exception ex) { ex.printStackTrace(); session.getTransaction().rollback(); } }catch(Exception ex) { ex.printStackTrace(); return null; } return t; } /* (non-Javadoc) * @see com.santander.bi.DAO.ModuloDAO#delete(int) */ @Override public Modulo delete(int id) { Modulo p= null; try { session = getCurrenSessionFactory(); p = (Modulo) session.load(Modulo.class, new Integer(id)); if(null != p){ try { session.beginTransaction(); session.delete(p); session.getTransaction().commit(); //session.close(); logger.info("Modulo updated successfully, Person Details="+p); }catch(Exception ex) { ex.printStackTrace(); session.getTransaction().rollback(); } } }catch(Exception ex) { ex.printStackTrace(); return null; } logger.info("Person deleted successfully, person details="+p); return p; } /* (non-Javadoc) * @see com.santander.bi.DAO.ModuloDAO#delete(com.santander.bi.model.Modulo) */ @Override public Modulo delete(Modulo p) { // TODO Auto-generated method stub try { session = getCurrenSessionFactory(); if(null != p){ try { p = (Modulo)session.merge(p); session.beginTransaction(); session.delete(p); session.getTransaction().commit(); //session.close(); logger.info("Modulo updated successfully, Person Details="+p); }catch(Exception ex) { ex.printStackTrace(); session.getTransaction().rollback(); } } }catch(Exception ex) { ex.printStackTrace(); return null; } logger.info("Person deleted successfully, person details="+p); return p; } }
/*import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession;*/ import com.alibaba.fastjson.JSON; import com.asn1c.core.Bool; import com.sun.tools.attach.AttachNotSupportedException; import com.sun.tools.attach.VirtualMachine; import com.sun.tools.attach.VirtualMachineDescriptor; import java.io.IOException; import java.text.DateFormat; import java.util.*; public class TraceHelper { private String name; private StringBuilder sb; private String $agentId(){ return "1"; } private String $pid(){ return "1"; } private String $host(){ return "127.0.0.1"; } private static native void send(String data); private static native void traceServlet(long t1,long t2,Object src,Object err,Object request,Object response); public TraceHelper(String name){ this.name = name; sb = new StringBuilder().append("{\"").append(name). append("\":[{\"agentId\":\"").append($agentId()).append("\""). append(",\"pid\":\"").append($pid()).append("\""); } public void send(){ sb.append("}]}"); try{ send(sb.toString()); }catch(UnsatisfiedLinkError e){} } public TraceHelper append(String key,int value){ sb = sb.append(",\"").append(key).append("\":").append(value); return this; } public TraceHelper append(String key,long value){ sb = sb.append(",\"").append(key).append("\":").append(value); return this; } public TraceHelper append(String key,float value){ sb = sb.append(",\"").append(key).append("\":").append(value); return this; } public TraceHelper append(String key,double value){ sb = sb.append(",\"").append(key).append("\":").append(value); return this; } public TraceHelper append(String key,boolean value){ sb = sb.append(",\"").append(key).append("\":").append(value); return this; } public TraceHelper append(String key,String value){ if ("".equals(value))return this; sb = sb.append(",\"").append(key).append("\":\"").append(value.replaceAll("\\\\","\\\\\\\\")).append("\""); return this; } public String host(String host) { if ("0:0:0:0:0:0:0:1".equals(host)|| "127.0.0.1".equals(host)|| "localhost".equals(host)){ return $host( ); }else{ return host; } } public static void main(String[] args) throws IOException, AttachNotSupportedException { List<VirtualMachineDescriptor> vms =com.sun.tools.attach.VirtualMachine.list();; for (VirtualMachineDescriptor vmd : vms) { if(vmd.displayName().equals("weblogic.Server")){ VirtualMachine vm = VirtualMachine.attach(vmd); vm.getSystemProperties().forEach((k,v)->System.out.println(k +":"+v)); vm.detach(); } } } }
import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; class Result { /* * Complete the 'diagonalDifference' function below. * * The function is expected to return an INTEGER. The function accepts * 2D_INTEGER_ARRAY arr as parameter. */ public static int diagonalDifference(List<List<Integer>> arr) { int leftSum = 0; int rightSum = 0; int leftIndex = 0; int rightIndex = arr.size() - 1; while (leftIndex < arr.size()) { leftSum += arr.get(leftIndex).get(leftIndex); System.out.println(leftSum); rightSum += arr.get(leftIndex).get(rightIndex); System.out.println(rightSum); leftIndex++; rightIndex--; } return Math.abs(leftSum - rightSum); } }
package com.yan.checkpolygon; import android.app.ProgressDialog; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Point; import android.location.Location; import android.os.Bundle; import android.os.Environment; import android.support.v4.app.FragmentActivity; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.*; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mGoogleMap; private Polygon drawenPolygon; private Polyline distanceLine; private boolean loading = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); try { importfile("test_polygon.kml"); } catch (IOException e) { e.printStackTrace(); } SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(final GoogleMap googleMap) { mGoogleMap = googleMap; //kml layer works but cant click inside thats why better draw polygon myself // KmlLayer layer = null; // try { // layer = new KmlLayer(mGoogleMap, R.raw.allowed_area, getApplicationContext()); // } catch (XmlPullParserException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // try { // layer.addLayerToMap(); // } catch (IOException e) { // e.printStackTrace(); // } catch (XmlPullParserException e) { // e.printStackTrace(); // } try { drawPoligonFromKmlFile(getStringFromFile(Environment.getExternalStorageDirectory() + "/test_polygon.kml")); } catch (Exception e) { e.printStackTrace(); } mGoogleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() { @Override public void onMapLoaded() { mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { Marker marker; public void onMapClick(final LatLng clickedPosition) { if (!loading) {//ignore clicks while loading loading = true; //create and lunch load dialog final ProgressDialog loadingProgressDialog; loadingProgressDialog = ProgressDialog.show(MapsActivity.this, "Loading", "Please Wait", true); if (marker != null) { marker.remove(); } if (distanceLine != null) { distanceLine.remove(); } final int tempFill = drawenPolygon.getFillColor(); final int polyInlineColor = Color.GRAY; drawenPolygon.setFillColor(polyInlineColor); GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() { @Override public void onSnapshotReady(Bitmap snapshot) { Point clickedPositionPixels = mGoogleMap.getProjection().toScreenLocation(clickedPosition); marker = mGoogleMap.addMarker(new MarkerOptions().position(clickedPosition)); //check inside or not if (snapshot.getPixel(clickedPositionPixels.x, clickedPositionPixels.y) == polyInlineColor) { //inside case when taking a snapshot and checking if color i set temp for polygon area is equal to colr of clicked point marker.setTitle("Inside"); } else { //check which of the outline points have the closest distance float minDistancePoint = Float.MAX_VALUE; LatLng closestLatLngPoint = clickedPosition; for (int i = 0; i < drawenPolygon.getPoints().size() - 1; i++) {//for each point in polygon List<LatLng> linePoints = getAllPointsWithDistance(20, drawenPolygon.getPoints().get(i), drawenPolygon.getPoints().get(i + 1));//maximum distance for (LatLng linePoint : linePoints) {//check each point distance float distanceInMeters = getDistanceBetween(clickedPosition, linePoint); if (minDistancePoint > distanceInMeters) { minDistancePoint = distanceInMeters; closestLatLngPoint = linePoint; } } } //draw the line from clicked point to closest // Instantiates a new Polyline object and adds points to define a rectangle PolylineOptions rectOptions = new PolylineOptions().add(clickedPosition).add(closestLatLngPoint).color(Color.BLUE); // Get back the mutable Polyline distanceLine = mGoogleMap.addPolyline(rectOptions); marker.setTitle("Outside, closest is: " + (getDistanceBetween(clickedPosition, closestLatLngPoint) / 1000) + " Km"); } //show marker info marker.showInfoWindow(); //remove loading loadingProgressDialog.dismiss(); loading = false; //return prev filled color drawenPolygon.setFillColor(tempFill); } }; mGoogleMap.snapshot(callback); } } }); //init camera tel aviv mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(32.109333, 34.855499), 12.0f)); } }); } //add more points to each line to get more accurate closest length to click outside polygon private List<LatLng> getAllPointsWithDistance(float distance, LatLng point1, LatLng point2) { List<LatLng> filledPoints = new ArrayList<LatLng>(); filledPoints.add(point1); filledPoints.add(point2); while (getDistanceBetween(filledPoints.get(0), filledPoints.get(1)) > distance) { for (int i = 0; i < filledPoints.size() - 1; i = i + 2) {//add center points filledPoints.add(i + 1, new LatLng((filledPoints.get(i).latitude + filledPoints.get(i + 1).latitude) / 2, (filledPoints.get(i).longitude + filledPoints.get(i + 1).longitude) / 2)); } } return filledPoints; } //get distance between 2 points private float getDistanceBetween(LatLng point1, LatLng point2) { float[] results = new float[1]; Location.distanceBetween(point1.latitude, point1.longitude, point2.latitude, point2.longitude, results); return results[0]; } //since kml layer disabling ability to click on the layer added i instead read file coordinates and draw it myself with google maps api private void drawPoligonFromKmlFile(String kmlFile) { //get only coordinates String pattern = "<coordinates>(.|\\r\\n|\\r|\\n)*<\\/coordinates>"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(kmlFile); String inverseKmlCordString; if (m.find()) { inverseKmlCordString = m.group(0).replaceAll("<coordinates>|\\r\\n|\\r|\\n|\\t|<\\/coordinates>|0 ", ""); String[] inverseKmlCordParts = inverseKmlCordString.split(","); PolygonOptions rectOptions = new PolygonOptions(); for (int i = inverseKmlCordParts.length - 1; i >= 0; i = i - 2) { rectOptions.add(new LatLng(Double.parseDouble(inverseKmlCordParts[i]), Double.parseDouble(inverseKmlCordParts[i - 1]))); } rectOptions.strokeColor(Color.rgb(1, 1, 1)).fillColor(Color.argb(90, 0, 0, 0)); drawenPolygon = mGoogleMap.addPolygon(rectOptions); } else { System.out.println("NO MATCH"); } } private String convertStreamToString(InputStream is) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } reader.close(); return sb.toString(); } private String getStringFromFile(String filePath) throws Exception { File fl = new File(filePath); FileInputStream fin = new FileInputStream(fl); String ret = convertStreamToString(fin); //Make sure you close all streams. fin.close(); return ret; } private void importfile(String name) throws IOException { //create empty file with right name to write to File new_file = new File(Environment.getExternalStorageDirectory() + File.separator + name); try { new_file.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //copy data from file in proj AssetManager am = getAssets(); InputStream inputstream = am.open(name); try { if (new_file.length() == 0) copyfiles(inputstream, new_file); } catch (IOException e) { e.printStackTrace(); } } private void copyfiles(InputStream in, File dst) throws IOException { OutputStream out = new FileOutputStream(dst); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } }
package com.tencent.mm.plugin.backup.g; import com.tencent.mm.ak.g; import com.tencent.mm.bt.h; import com.tencent.mm.model.af; import com.tencent.mm.modelvideo.s; import com.tencent.mm.plugin.messenger.foundation.a.a.f; import com.tencent.mm.plugin.messenger.foundation.a.a.i; import com.tencent.mm.pluginsdk.model.app.c; import com.tencent.mm.pluginsdk.model.app.k; import com.tencent.mm.storage.ay; import com.tencent.mm.storage.az; import com.tencent.mm.storage.emotion.d; import com.tencent.mm.storage.x; public final class b { String dqp; public h dqq = null; x gYC; ay gYD; f gYE; az gYF; g gYG; d gYH; public i gYI; s gYJ; af gYK; public k gYL; public com.tencent.mm.pluginsdk.model.app.i gYM; c gYN; public int uin = 0; public final x DT() { if (this.uin != 0) { return this.gYC; } throw new com.tencent.mm.model.b(); } public final ay FR() { if (this.uin != 0) { return this.gYD; } throw new com.tencent.mm.model.b(); } public final f FT() { if (this.uin != 0) { return this.gYE; } throw new com.tencent.mm.model.b(); } public final az FW() { if (this.uin != 0) { return this.gYF; } throw new com.tencent.mm.model.b(); } public final g asD() { if (this.uin != 0) { return this.gYG; } throw new com.tencent.mm.model.b(); } public final d asE() { if (this.uin != 0) { return this.gYH; } throw new com.tencent.mm.model.b(); } public final s Ta() { if (this.uin != 0) { return this.gYJ; } throw new com.tencent.mm.model.b(); } public final String Gg() { if (this.uin != 0) { return this.dqp + "emoji/"; } throw new com.tencent.mm.model.b(); } public final c asF() { if (this.uin != 0) { return this.gYN; } throw new com.tencent.mm.model.b(); } }
package ru.sg_studio.escapegame.primitives.topclass; import net.raydeejay.escapegame.GameRegistry; import net.raydeejay.escapegame.Room; import ru.sg_studio.escapegame.primitives.GraphicalEntity; public class Overlay extends GraphicalEntity { //DUMMY CLASS AS COMMON POINT FOR ALL OVERLAYS public Overlay addToRoom(Room aRoom) { aRoom.addGraphicalEntity(this); return this; } public Overlay addToRoomNamed(String aRoomName) { Room aRoom = GameRegistry.instance().getRoom(aRoomName.toString()); return this.addToRoom(aRoom); } }
package com.smxknife.java2.aio; import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.channels.AsynchronousFileChannel; import java.nio.channels.FileLock; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.time.LocalTime; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * @author smxknife * 2020/11/3 */ public class _02_AsynchronousFileChannel_region_lock { /** * 获取文件的区域独占锁public final Future<FileLock> lock(position, size, shared); * Future的get方法在成功完成时返回FileLock */ @Test public void testLockA() { Path path = Paths.get(this.getClass().getClassLoader().getResource("aio/_01_lock").getPath()); try(AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE)) { Future<FileLock> lockFuture = channel.lock(0, 3, false); FileLock fileLock = lockFuture.get(); System.out.println("A get lock time " + LocalTime.now()); TimeUnit.SECONDS.sleep(30); fileLock.release(); System.out.println("A release lock time " + LocalTime.now()); } catch (IOException | InterruptedException | ExecutionException e) { e.printStackTrace(); } } @Test public void testLockB() { Path path = Paths.get(this.getClass().getClassLoader().getResource("aio/_01_lock").getPath()); try(AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE)) { System.out.println("B get lock begin " + LocalTime.now()); Future<FileLock> lockFuture = channel.lock(0, 3, false); // 下面的输出紧接着begin输出,说明调用lock方法立刻返回,不会产生阻塞 System.out.println("B get lock end " + LocalTime.now()); FileLock fileLock = lockFuture.get(); // 这里的get lock time 会一直阻塞,等待testLockA中的释放锁之后才会继续执行 System.out.println("B get lock time " + LocalTime.now()); fileLock.release(); System.out.println("B release lock time " + LocalTime.now()); } catch (IOException | InterruptedException | ExecutionException e) { e.printStackTrace(); } } @Test public void testLockC() { Path path = Paths.get(this.getClass().getClassLoader().getResource("aio/_01_lock").getPath()); try(AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE)) { System.out.println("C get lock begin " + LocalTime.now()); Future<FileLock> lockFuture = channel.lock(4, 8, false); // 下面的输出紧接着begin输出,说明调用lock方法立刻返回,不会产生阻塞 System.out.println("C get lock end " + LocalTime.now()); FileLock fileLock = lockFuture.get(); // 这里的get lock time 会一直阻塞,等待testLockA中的释放锁之后才会继续执行 System.out.println("C get lock time " + LocalTime.now()); fileLock.release(); System.out.println("C release lock time " + LocalTime.now()); } catch (IOException | InterruptedException | ExecutionException e) { e.printStackTrace(); } } }
package compression; /** * This class models the state and behavior of a Linked List Stack * @author Matthew F. Leader */ public class LinkedList { /** the first element in the collection */ private Node front; /** size of the list */ private int size; /** * Construct a Linked List */ public LinkedList() { front = null; size = 0; } public boolean isEmpty() { return front == null; } public int size() { return size; } /** * Add an item to the front, or if it is already on the list, then move * element the containing data equal to the parameter to the front. * @param data * the data to add to the list */ public void add(String data) { if (front == null) { front = new Node(data, null); } else { remove(data); front = new Node(data, front); } size++; } /** * Find a String on the list. * @param data * the String to look for on the list * @return if the String is on the list, then return the index, * otherwise return -1 * */ public int find(String data) { int index = -1; for (Node k = front; k != null; k = k.next) { index++; if (k.data.equals(data)) { return index; } } return -1; } /** * Remove a Node with the given data, if it exists * @param data * the data to remove from the list * @return the Node removed from the list */ private String remove(String data) { Node current = front; Node previous = null; while (current != null && !current.data.equals(data)) { previous = current; current = current.next; } if (current != null) { if (current == front) { front = front.next; } else { previous.next = current.next; } size--; return current.data; } return null; } /** * Convert the Linked List to an array * @return an array of the objects on the List */ public String[] toArray() { String[] array = null; if (!isEmpty()) { array = new String[size]; int k = 0; Node current = front; while (k < size && current != null) { array[k] = current.data; k++; current = current.next; } } return array; } public String get(int index) { Node current = front; for (int k = 0; k < index; k++) { current = current.next; } if (current != null) { return current.data; } return null; } /** * Remove a Node at a given index * @param index * the index of the element to remove from the list * @return the Node removed from the list */ private Node remove(int index) { return null; } /** * This class models the state and behavior of a Node in the * LinkedList. */ private class Node { /** the data within the element */ private String data; /** a reference to the next element in the list */ private Node next; /** * Constructs a Node given data and a pointer to the next element. * @param data * the data in this element * @param next * the pointer to the next element */ public Node(String data, Node next) { this.data = data; this.next = next; } /** * Constructs a Node with null pointers * @param data * the data in this element */ public Node(String data) { this(data, null); } } }
package com.smxknife.network.demo07; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.TimeUnit; /** * @author smxknife * 2020/10/18 */ public class MockServer { public static void main(String[] args) { try(ServerSocket serverSocket = new ServerSocket(6666)) { Socket socket = serverSocket.accept(); TimeUnit.HOURS.sleep(1); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
/** * Just an image class. * Can either be filled or not filled. */ package com.neet.entity; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import com.neet.handlers.ImageLoader; public class Star { private BufferedImage star; private int tick; private int x; private int y; private int width; private int height; public Star(int x, int y, boolean full) { this.x = x; this.y = y; tick = 0; if(full) star = ImageLoader.STAR; else star = ImageLoader.STAROUTLINE; width = 32; height = 32; } public void update() { tick++; if(tick == 120) { tick = 0; } if(tick < 60) { width = (int) 32.0 * tick / 60; } else { width = (int) 32.0 * (120 - tick) / 60; } } public void draw(Graphics2D g) { g.drawImage(star, x - width / 2, y, width, height, null); } }
package com.espendwise.tools.gencode.util; import com.espendwise.tools.gencode.hbmxml.persistence.HbmPersistenceXmlAssist; import com.espendwise.tools.gencode.spring.dbaccessxml.SpringDatabaseAccessXmlAssist; import java.io.PrintWriter; import java.io.StringWriter; import java.util.List; import java.util.Map; public class DataAccessJavaClassGenerator { private static final String TEMPLATE = "package com.espendwise.manta.service;\n" + "\n" + "//Generated by DataAccessJavaClassGenerator.java" + "\n" + "import javax.persistence.EntityManager;\n" + "import javax.persistence.PersistenceContext;\n" + "\n" + "public abstract class DatabaseAccess {\n" + "%1$s" + "%2$s" + "%3$s" + "\n" + "%4$s" + "%5$s" + "%6$s" + "\n" + "}"; public String generate(List<Map.Entry<String, Map<String, ProjectDbProperty>>> entries) { String persistenceUnitNames = generateDeclarationPersistenceUnitNames(entries); String persistenceUnits = generateDeclarationPersistenceUnits(entries); String entityManagerGetterMethod = generateEntityManagetGetterMethod(entries); String mainUnitGetterMethod = generateMainUnitGetterMethod(entries); String constantsMethods = generateConstantsMethods(); String workUnitsArray = generateWorkUnitsArray(entries); return String.format( TEMPLATE, persistenceUnitNames, workUnitsArray, persistenceUnits, entityManagerGetterMethod, mainUnitGetterMethod, constantsMethods ); } private String generateMainUnitGetterMethod(List<Map.Entry<String, Map<String, ProjectDbProperty>>> entries) { StringWriter buffer = new StringWriter(); PrintWriter writer = new PrintWriter(buffer); writer.println(); boolean mainUniExist = false; for (Map.Entry<String, Map<String, ProjectDbProperty>> e : entries) { if (e.getKey().equalsIgnoreCase(ProjectDbProperty.MAIN_UNIT_ID)) { mainUniExist = true; } } writer.println(tab(1) + "public static String getMainUnit() {"); writer.print(tab(2) + "return " + (mainUniExist ? "PERSISTENCE_UNIT_" + ProjectDbProperty.MAIN_UNIT_ID.toUpperCase() : "null")); writer.println(";"); writer.println(tab(1) +"}"); return buffer.getBuffer().toString(); } private String generateConstantsMethods() { StringWriter buffer = new StringWriter(); PrintWriter writer = new PrintWriter(buffer); writer.println(); writer.println(tab(1) + "public static String[] availableUnits() {"); writer.println(tab(2) + "return AVAILABLE_UNITS;"); writer.println(tab(1) + "}"); return buffer.getBuffer().toString(); } private String generateEntityManagetGetterMethod(List<Map.Entry<String, Map<String, ProjectDbProperty>>> entries) { StringWriter buffer = new StringWriter(); PrintWriter writer = new PrintWriter(buffer); writer.println(); writer.println(tab(1) + "public EntityManager getEntityManager(String unit) {"); int i = 0; for (Map.Entry<String, Map<String, ProjectDbProperty>> e : entries) { writer.print((i == 0 ? tab(2) + "if(" : " else if(")); writer.print("PERSISTENCE_UNIT_" + e.getKey().toUpperCase() + ".equals(unit)"); writer.println(") {"); writer.println(tab(3) + "return " + SpringDatabaseAccessXmlAssist.getName(SpringDatabaseAccessXmlAssist.ENTITY_MANAGER_PROPERTY_ID_PREFIX, e.getKey()) + ";"); writer.print(tab(2) + "}"); i++; } writer.println(); writer.println(); writer.println(tab(2) + "return null;"); writer.println(); writer.println(tab(1) + "}"); return buffer.getBuffer().toString(); } private String tab(int i) { String s = ""; for (int j = 0; j < i; j++) { s += " "; } return s; } private String generateDeclarationPersistenceUnitNames(List<Map.Entry<String, Map<String, ProjectDbProperty>>> entries) { StringWriter buffer = new StringWriter(); PrintWriter writer = new PrintWriter(buffer); writer.println(); String s = ""; for (Map.Entry<String, Map<String, ProjectDbProperty>> e : entries) { writer.print(tab(1) + "private static final String PERSISTENCE_UNIT_" + e.getKey().toUpperCase() + " = "); writer.println("\"" + HbmPersistenceXmlAssist.PERSISTENCE_UNIT_PREFIX + e.getKey() + "\";"); } return buffer.getBuffer().toString(); } private String generateDeclarationPersistenceUnits(List<Map.Entry<String, Map<String, ProjectDbProperty>>> entries) { StringWriter buffer = new StringWriter(); PrintWriter writer = new PrintWriter(buffer); writer.println(); for (Map.Entry<String, Map<String, ProjectDbProperty>> e : entries) { writer.println(); writer.println(tab(1) + "@PersistenceContext(unitName = PERSISTENCE_UNIT_" + e.getKey().toUpperCase() + ")"); writer.println(tab(1) + "private transient EntityManager "+SpringDatabaseAccessXmlAssist.getName(SpringDatabaseAccessXmlAssist.ENTITY_MANAGER_PROPERTY_ID_PREFIX, e.getKey())+";"); } return buffer.getBuffer().toString(); } private String generateWorkUnitsArray(List<Map.Entry<String, Map<String, ProjectDbProperty>>> entries) { StringWriter buffer = new StringWriter(); PrintWriter writer = new PrintWriter(buffer); writer.println(); writer.println(tab(1) + "private static final String[] AVAILABLE_UNITS = new String[] {"); int i = 0; for (Map.Entry<String, Map<String, ProjectDbProperty>> e : entries) { if (!e.getKey().equalsIgnoreCase(ProjectDbProperty.MAIN_UNIT_ID)) { writer.println(tab(2) + "PERSISTENCE_UNIT_" + e.getKey().toUpperCase() + ((i < entries.size() - 1) ? "," : "")); } i++; } writer.println(tab(1) + "};"); return buffer.getBuffer().toString(); } }
package com.tencent.mm.model; import com.tencent.mm.compatible.util.e; import com.tencent.mm.compatible.util.f; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.j; import com.tencent.mm.sdk.platformtools.x; class c$b implements Runnable { String bXS; String dAl; public c$b(String str, String str2) { this.bXS = str; this.dAl = str2; } public final void run() { if (!bi.oW(this.bXS) && !bi.oW(this.dAl)) { x.d("MicroMsg.AccountStorage", "MoveDataFiles :" + this.bXS + " to :" + this.dAl); if (f.zZ() && this.dAl.substring(0, e.bnE.length()).equals(e.bnE)) { j.q(this.bXS + "image/", this.dAl + "image/", true); j.q(this.bXS + "image2/", this.dAl + "image2/", true); j.q(this.bXS + "video/", this.dAl + "video/", true); j.q(this.bXS + "voice/", this.dAl + "voice/", true); j.q(this.bXS + "voice2/", this.dAl + "voice2/", true); j.q(this.bXS + "package/", this.dAl + "package/", true); j.q(this.bXS + "emoji/", this.dAl + "emoji/", true); j.q(this.bXS + "mailapp/", this.dAl + "mailapp/", true); j.q(this.bXS + "brandicon/", this.dAl + "brandicon/", true); } } } }
package net.optifine; import java.util.Comparator; import net.minecraft.src.Config; public class CustomItemsComparator implements Comparator { @Override public int compare(final Object o1, final Object o2) { final CustomItemProperties customitemproperties = (CustomItemProperties) o1; final CustomItemProperties customitemproperties1 = (CustomItemProperties) o2; return customitemproperties.weight != customitemproperties1.weight ? customitemproperties1.weight - customitemproperties.weight : !Config.equals(customitemproperties.basePath, customitemproperties1.basePath) ? customitemproperties.basePath.compareTo(customitemproperties1.basePath) : customitemproperties.name.compareTo(customitemproperties1.name); } }
package com.espendwise.manta.web.forms; import com.espendwise.manta.model.view.AccountListView; import com.espendwise.manta.util.SelectableObjects; import java.util.List; public class LocateAccountFilterResultForm extends AbstractFilterResult<SelectableObjects.SelectableObject<AccountListView>> { private SelectableObjects<AccountListView> selectedAccounts; private boolean multiSelected; public SelectableObjects<AccountListView> getSelectedAccounts() { return selectedAccounts; } public void setSelectedAccounts(SelectableObjects<AccountListView> selectedAccounts) { this.selectedAccounts = selectedAccounts; } @Override public List<SelectableObjects.SelectableObject<AccountListView>> getResult() { return selectedAccounts != null ? selectedAccounts.getSelectableObjects() : null; } @Override public void reset() { super.reset(); selectedAccounts = null; } public void setMultiSelected(boolean multiSelected) { this.multiSelected = multiSelected; } public boolean getMultiSelected() { return multiSelected; } }
package com.rowland.qrdecoder.camera; import android.hardware.Camera; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import com.rowland.qrdecoder.ui.fragments.ScanFragment; import java.lang.ref.WeakReference; /** * Created by Oti Rowland on 1/8/2016. */ public class CameraHandlerThread extends HandlerThread implements Camera.AutoFocusCallback, Camera.PreviewCallback { // The threading identifier private static String THREAD_TAG = "CameraHandlerThread"; // Class logging Identifier private final String LOG_TAG = CameraHandlerThread.class.getSimpleName(); // The thread handler private Handler mHandler = null; // Soft reference private WeakReference<ScanFragment> mWeakReferenceCameraPreviewFragment = null; // The Barcode scanner thread private CameraBarcodeScanThread mCameraBarCodeScannerThread = null; // Default constructor public CameraHandlerThread(ScanFragment scanFragment) { super(THREAD_TAG); // This is a call to begin the thread start(); mHandler = new Handler(getLooper()); mWeakReferenceCameraPreviewFragment = new WeakReference<>(scanFragment); mWeakReferenceCameraPreviewFragment.get().getPreviewSurface().setPreviewCallback(this); mWeakReferenceCameraPreviewFragment.get().getPreviewSurface().setAutoFocusCallback(this); } @Override public void onAutoFocus(boolean success, Camera camera) { } @Override public void onPreviewFrame(byte[] data, Camera camera) { // if (mWeakReferenceCameraPreviewFragment.get() != null) { // We might need a scanner thread if (mCameraBarCodeScannerThread == null) { mCameraBarCodeScannerThread = new CameraBarcodeScanThread(mWeakReferenceCameraPreviewFragment.get()); // Begin the scanning mCameraBarCodeScannerThread.initializeScan(); } mCameraBarCodeScannerThread.queueCreateScanResult(data, camera); } Log.d(LOG_TAG, "onPreviewFrame Called"); } synchronized void notifyCameraOpened() { notify(); } public void openCamera() { mHandler.post(new Runnable() { @Override public void run() { if (mWeakReferenceCameraPreviewFragment.get() != null) { mWeakReferenceCameraPreviewFragment.get().openCameraOld(); notifyCameraOpened(); } } }); try { wait(); } catch (InterruptedException e) { Log.w(LOG_TAG, "wait was interrupted"); } } @Override public boolean quitSafely() { if (mCameraBarCodeScannerThread != null) { mCameraBarCodeScannerThread.quitSafely(); mCameraBarCodeScannerThread = null; } return super.quitSafely(); } }
package java1; public class withoutpredefined { public static void main(String[] args) { int a[] = {11,55,88}; int len=0; for(int t:a) { len++; } System.out.println(len); } }
package gerenciador.funcionario; import gerenciador.administrador.Usuario; import gerenciador.pessoa.Pessoa; /* * @author Evolute Jackson */ public class Funcionario extends Pessoa { private int id, situacao; private Usuario usario; private Funcao funcao; private Turno turno; private String cnt, observacao, dataEntrada; private float salario; private boolean usuarioAutorizado; /** * * * @param cpf * @param rg * @param nome * @param dataNascimento * @param email * @param sexo * @param cnt * @param salario */ public Funcionario(String cpf, String rg, String nome, String dataNascimento, String email, char sexo, String cnt, float salario) { super(cpf, rg, nome, dataNascimento, email, sexo); usario = new Usuario(); this.turno = new Turno(); this.funcao = new Funcao(); this.cnt = cnt; this.salario = salario; } public String getObservacao() { return observacao; } public void setObservacao(String observacao) { this.observacao = observacao; } public void setId(int Id) { this.id = Id; // Altera a variavel Id da classe Funcao para o parametro passado } //Declaração do método Id public int getId() { return id; //retorna o Valor da Variavel Id } public Usuario getUsario() { return usario; } public void setUsario(Usuario usario) { this.usario = usario; } public void setUsuarioAutorizado(boolean usuario) { this.usuarioAutorizado = usuario; } public boolean isUsuarioAutorizado() { return usuarioAutorizado; } //Declaração do método setcnt public void setCnt(String cnt) { this.cnt = cnt; // Altera a variavel cnt da classe Funcao para o parametro passado } //Declaração do método cnt public String getCnt() { return cnt; //retorna o Valor da Variavel cnt } //Declaração do método salario public void setSalario(float salario) { this.salario = salario; // Altera a variavel salario da classe Funcao para o parametro passado } //Declaração do método cnt public float getSalario() { return salario; //retorna o Valor da Variavel salario } public Funcao getFuncao() { return funcao; } public void setTurno(Turno turno) { this.turno = turno; } public void setFuncao(Funcao funcao) { this.funcao = funcao; } public Turno getTurno() { return turno; } public String getDataEntrada() { return dataEntrada; } public void setDataEntrada(String dataEntrada) { this.dataEntrada = dataEntrada; } public int getSituacao() { return situacao; } public void setSituacao(int situacao) { this.situacao = situacao; } }
package br.edu.ifpb.consultalistview; import android.app.Activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; import java.util.ArrayList; import java.util.List; public class MainActivity extends Activity { private ListView lista; private List<String> listBase; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listBase = new ArrayList<>(); listBase.add("Henrique"); listBase.add("Renato"); listBase.add("José"); listBase.add("Jaum"); listBase.add("Jaum II"); listBase.add("Pedro"); lista = (ListView) findViewById(R.id.lista); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listBase); lista.setAdapter(adapter); EditText edtNome = (EditText) findViewById(R.id.edtNome); edtNome.addTextChangedListener(new ConsultaTextWatcher(this)); } public ListView getLista (){ return this.lista; } public void setLista (List<String> listPesquisa){ ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listPesquisa); this.lista.setAdapter(adapter); } public List<String> getListBase (){ return this.listBase; } }
package com.revature.producerconsumer; public class Holder { int contents = 0; private boolean isAvailable = false; /** * This class will hold all of the values generated by another thread * * And it will contain synchronized methods for getting and setting values */ public synchronized int getVal() { // this weill return the value of the holder to the consumer while(!isAvailable) { try { wait(); // this method forces the current thread to wait until some other thread // invokes notify() or notifyuAll() on the same object } catch (InterruptedException e) { e.printStackTrace(); } } isAvailable = false; notifyAll(); return contents; } public synchronized void setVal(int val) { // this method will be invoked by the producer while(isAvailable) { try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } contents = val; isAvailable = true; notifyAll(); } } }
package quiz; import java.util.Scanner; public class Quiz23 { public static void main(String[] args) { /* * 두 정수를 입력받습니다 * 단 두 수의 크기는 정해지지 않았습니다 * 두 수 사이의 합을 구하는 코드를 최대한 간략하게 작성해보세요 * */ Scanner scan = new Scanner(System.in); System.out.print("정수 입력 1> "); int a =scan.nextInt(); System.out.print("정수 입력 2> "); int b =scan.nextInt(); int sum =0; // if (a == b) { // sum = 0; // }else if (a > b) { // for (int i = b; i <= a; i++) { // sum +=i; // } // }else // for (int i = a; i <= b; i++) { // sum +=i; // } for (int i = a==b?0:(a > b? b : a);i<=(a==b?0:( a > b ? a : b)); i++) { sum +=i; } System.out.println(a+" ~ "+b+" 사이 합 = "+sum); scan.close(); } }
package com.example.androidtest; import java.io.IOException; import android.app.Activity; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class SensorTestActivity extends Activity implements OnClickListener, SensorEventListener {// 这里实现传感器监听 /** Called when the activity is first created. */ Button btn_start = null; Button btn_stop = null; Button btn_close = null; Button btn_open = null; // /mediaplaer MediaPlayer _mediaPlayer = null; // 音乐播放管理器 AudioManager audioManager = null; // 声音管理器 SensorManager _sensorManager = null; // 传感器管理器 Sensor mProximiny = null; // 传感器实例 float f_proximiny; // 当前传感器距离 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sensor_test); btn_start = (Button) findViewById(R.id.btn_start); btn_start.setOnClickListener(this); btn_stop = (Button) findViewById(R.id.btn_stop); btn_stop.setOnClickListener(this); btn_close = (Button) findViewById(R.id.btn_close); btn_close.setOnClickListener(this); btn_open = (Button) findViewById(R.id.btn_open); btn_open.setOnClickListener(this); _mediaPlayer = new MediaPlayer(); audioManager = (AudioManager) this .getSystemService(Context.AUDIO_SERVICE); _sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mProximiny = _sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); } @Override protected void onResume() { super.onResume(); // 注册传感器 _sensorManager.registerListener(this, mProximiny, SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onPause() { super.onPause(); // 取消注册传感器 _sensorManager.unregisterListener(this); } private void playerMusic(String path) { // 重置播放器 _mediaPlayer.reset(); try { // 设置播放路径 _mediaPlayer.setDataSource(path); // 准备播放 _mediaPlayer.prepare(); // 开始播放 _mediaPlayer.start(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void stopPlayerMusic() { // 停止播放 if (_mediaPlayer.isPlaying()) { _mediaPlayer.reset(); } } /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_close: audioManager.setMode(AudioManager.MODE_NORMAL); break; case R.id.btn_open: audioManager.setMode(AudioManager.MODE_IN_CALL); break; case R.id.btn_start:// 音乐取自于Sd卡上的音乐 String path = Environment.getExternalStorageDirectory() + "/MIUI/music/mp3/主旋律_陈奕迅.mp3"; playerMusic(path); break; case R.id.btn_stop: stopPlayerMusic(); break; } } /* * 实现SensorEventListener需要实现的两个方法。 */ @Override public void onSensorChanged(SensorEvent event) { f_proximiny = event.values[0]; Log.v("tag", "--> " + f_proximiny + " | " + mProximiny.getMaximumRange()); if (f_proximiny < mProximiny.getMaximumRange()) { audioManager.setMode(AudioManager.MODE_NORMAL); } else { audioManager.setMode(AudioManager.MODE_IN_CALL); } } /* */ @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }
package com.geekbrains.server.exceptions; public class AlreadyExistsException extends RestResourceException { public AlreadyExistsException(String message) { super(message); } }
package br.com.giorgetti.games.squareplatform.tiles; import br.com.giorgetti.games.squareplatform.main.GamePanel; import java.awt.*; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; /** * Represents a background in the map. A background moves in a different speed * than the player is moving to provide a feeling of distance. The slowest it moves * the more distant it is. * * Created by fgiorgetti on 5/9/15. */ public class Background { private String bgPath; private BufferedImage image; private int speedPct; public Background(String bgPath, String speedPct) { try { this.bgPath = bgPath; this.image = ImageIO.read(getClass().getResourceAsStream(bgPath)); } catch (Exception e) { e.printStackTrace(); } this.speedPct = Integer.parseInt(speedPct); } public void draw(Graphics2D g, int mapX, int mapY) { int bgWidth = getImage().getWidth(); int bgHeigth = GamePanel.HEIGHT - getImage().getHeight(); int bgX = (int) (- mapX / 100.00 * getSpeedPct() % bgWidth); int bgY = (int) ( mapY / 100.00 * (getSpeedPct()/2) % bgHeigth); //System.out.printf("bgX = %d - bgY = %d\n", bgX, bgY); // Consider X offset as map.x / 100 * bg.speed g.drawImage(getImage(), null, bgX, bgY); g.drawImage(getImage(), null, bgX + bgWidth, bgY); g.drawImage(getImage(), null, bgX, bgY + bgHeigth); g.drawImage(getImage(), null, bgX + bgWidth, bgY + bgHeigth); } public BufferedImage getImage() { return image; } public void setImage(BufferedImage image) { this.image = image; } public int getSpeedPct() { return speedPct; } public void setSpeedPct(int speedPct) { this.speedPct = speedPct; } public String toString() { return speedPct + TileMap.PROP_SEPARATOR + bgPath; } }
package com.doomcrow.toadgod.components; import com.artemis.Component; import com.badlogic.gdx.utils.ObjectMap; import com.doomcrow.toadgod.Pair; public class PairMap extends Component { public ObjectMap<Pair, Boolean> map = new ObjectMap<Pair, Boolean>(); }
package edu.northeastern.cs5200.repositories; import edu.northeastern.cs5200.models.Course; import edu.northeastern.cs5200.models.Section; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import java.util.List; public interface SectionRepository extends CrudRepository<Section,Integer> { @Query("SELECT s FROM Section s WHERE s.course=:course") public List<Section> findSectionforCourse(@Param("course") Course course); }
package net.client; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; public class Client implements Runnable { private Socket socket; private DataInputStream in; private DataOutputStream out; private Thread clientThread; private static int id = 2; private List<String> outputList = new ArrayList<>(); private String ip; private int port; public Input input; private boolean canSend; public Client(int id, String ip, int port) throws IOException { this.id = id; this.ip = ip; this.port = port; } public void start() throws UnknownHostException, IOException { this.clientThread = new Thread(this, "Client Thread" + id); this.clientThread.start(); canSend = true; } public void addMessage(String key, String message) { outputList.add(key + ":" + message); } public void addMessage(String key, int x) { addMessage(key, String.valueOf(x)); } public void addMessage(String key, int[] array) { addMessage(key, array[0] + "," + array[1]); } public void sendMessages() { for (String output : new ArrayList<>(outputList)) { try { if (canSend) { out.writeUTF((id * this.hashCode() + ":" + output).trim()); outputList.remove(output); } } catch (IOException e) { canSend = false; } } } public boolean isConnected() { if (socket == null) { return false; } if (socket.isConnected()) { return true; } return false; } @Override public void run() { System.out.println("Connection..."); try { socket = new Socket(ip, port); System.out.println("Connection succesful"); System.err.println("ID: " + id); in = new DataInputStream(socket.getInputStream()); out = new DataOutputStream(socket.getOutputStream()); input = new Input(in, id * this.hashCode()); Thread thread = new Thread(input); thread.start(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.example.demo.config; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import com.example.demo.entity.UserEntity; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.Date; import java.util.List; /** * * * * 接下来通过实现WebMvcConfigurer接口来配置FastJsonHttpMessageConverter,springboot2.0版本以后推荐使用这种方式 * * 来进行web配置,这样不会覆盖掉springboot的一些默认配置。配置类如下: * */ @Configuration public class MyWebmvcConfiguration implements WebMvcConfigurer { @Override public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); /** * fastJson配置实体调用setSerializerFeatures方法可以配置多个过滤方式,常用的如下: * *   1、WriteNullListAsEmpty : List字段如果为null,输出为[],而非null *   2、WriteNullStringAsEmpty : 字符类型字段如果为null,输出为"",而非null *   3、DisableCircularReferenceDetect :消除对同一对象循环引用的问题, * 默认为false(如果不配置有可能会进入死循环) *   4、WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,而非null *   5、WriteMapNullValue:是否输出值为null的字段,默认为false。 * */ FastJsonConfig fastJsonConfig = new FastJsonConfig(); //将字符串null转换为"" [{"address":"changsha","date":"2019-13-19 00:13:05","name":""}] //fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteNullStringAsEmpty); //pretty format [ { "address":"changsha", "date":"2019-14-19 00:14:00" } ] fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); //日期格式化 fastJsonConfig.setDateFormat("yyyy-mm-dd HH:mm:ss"); fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); converters.add(fastJsonHttpMessageConverter); } }
/** * shopmobile for tpshop * ============================================================================ * 版权所有 2015-2099 深圳搜豹网络科技有限公司,并保留所有权利。 * 网站地址: http://www.tp-shop.cn * —————————————————————————————————————— * 这不是一个自由软件!您只能在不用于商业目的的前提下对程序代码进行修改和使用 . * 不允许对程序代码以任何形式任何目的的再发布。 * ============================================================================ * Author: 飞龙 wangqh01292@163.com * Date: @date 2015年10月28日 下午8:13:39 * Description:所有URL请求的基类 * @version V1.0 */ package com.tpshop.mallc.http.base; import android.content.Context; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.BinaryHttpResponseHandler; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.tpshop.mallc.activity.common.SPIViewController; import com.tpshop.mallc.global.SPMobileApplication; import com.tpshop.mallc.common.SPMobileConstants; import com.tpshop.mallc.model.person.SPUser; import com.tpshop.mallc.utils.SMobileLog; import com.soubao.tpshop.utils.SPCommonUtils; import com.soubao.tpshop.utils.SPStringUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import cz.msebera.android.httpclient.Header; /** * 网络请求基类, 实现GET , POS方法 * 网络请求已经是异步实现, 调用时不需要额外开辟新线程调用 * @author 飞龙 * */ public class SPMobileHttptRequest { private static String TAG = "SouLeopardHttptRequest"; public static void init(Context context){ } private SPMobileHttptRequest(){ } /** * @Description: 回调 * @param url GET 请求URL * @param params 请求参数 * @return void 返回类型 * @throws */ public static void get(String url , RequestParams params ,JsonHttpResponseHandler responseHandler) { if (params == null){ params = new RequestParams(); } if (SPMobileApplication.getInstance().isLogined){ SPUser user = SPMobileApplication.getInstance().getLoginUser(); params.put("user_id" , user.getUserID()); if(!SPStringUtils.isEmpty(user.getToken()))params.put("token" , user.getToken()); } if (SPMobileApplication.getInstance().getDeviceId() !=null){ String imei = SPMobileApplication.getInstance().getDeviceId(); params.put("unique_id" , imei); } try { configSign(params , url); AsyncHttpClient client = new AsyncHttpClient(); client.get(url, params, responseHandler); } catch (Exception e) { e.printStackTrace(); responseHandler.onFailure(-1 , new Header[]{},new Throwable(e.getMessage()) , new JSONObject()); } } /** * @Description: POST回调 * @param url 请求URL * @param params 请求参数 * @return void 返回类型 * @throws */ public static void post(String url , RequestParams params , JsonHttpResponseHandler responseHandler){ AsyncHttpClient client = new AsyncHttpClient(); if (params == null){ params = new RequestParams(); } if (SPMobileApplication.getInstance().isLogined){ SPUser user = SPMobileApplication.getInstance().getLoginUser(); params.put("user_id" , user.getUserID()); if(!SPStringUtils.isEmpty(user.getToken()))params.put("token" , user.getToken()); } if (SPMobileApplication.getInstance().getDeviceId() != null){ String imei = SPMobileApplication.getInstance().getDeviceId(); params.put("unique_id" , imei); } try { configSign(params, url); client.post(url, params, responseHandler); } catch (Exception e) { e.printStackTrace(); responseHandler.onFailure(-1 , new Header[]{},new Throwable(e.getMessage()) , new JSONObject()); } } /** * @Description: 下载文件 * @param url 请求URL * @param params 请求参数 * @return void 返回类型 * @throws */ public static void downloadFile(String url , RequestParams params , BinaryHttpResponseHandler responseHandler){ AsyncHttpClient client = new AsyncHttpClient(); if (params == null){ params = new RequestParams(); } if (SPMobileApplication.getInstance().isLogined){ SPUser user = SPMobileApplication.getInstance().getLoginUser(); params.put("user_id" , user.getUserID()); if(!SPStringUtils.isEmpty(user.getToken()))params.put("token" , user.getToken()); } if (SPMobileApplication.getInstance().getDeviceId() != null){ String imei = SPMobileApplication.getInstance().getDeviceId(); params.put("unique_id" , imei); } // 获取二进制数据如图片和其他文件 client.get(url, params, responseHandler); } /** * 根据控制器和action组装请求URL * @param c * @param action * @return */ public static String getRequestUrl(String c , String action){ return SPMobileConstants.BASE_URL +"&c="+c+"&a="+action; } /*public interface SuccessListener{ public void onRespone(String msg , Object response); } public interface FailuredListener{ public void onRespone(String msg , int errorCode); }*/ /** * 每一个访问接口都要调用改函数进行签名 * 具体签名方法, 参考: tpshop 开发手册 -> 手机api接口 -> 公共接口 * * @param params */ public static void configSign(RequestParams params , String url){ long locaTime = SPCommonUtils.getCurrentTime();//本地时间 long cutTime = SPMobileApplication.getInstance().getCutServiceTime(); String time = String.valueOf(locaTime + cutTime); Map<String ,String> paramsMap = convertRequestParamsToMap(params); String signFmt = SPCommonUtils.signParameter(paramsMap , time , SPMobileConstants.SP_SIGN_PRIVATGE_KEY , url); params.put("sign" , signFmt); params.put("time" , time); } public static Map<String ,String> convertRequestParamsToMap(RequestParams params){ Map<String ,String> paramsMap = new HashMap<String ,String>(); if(params!=null){ try { String[] items = params.toString().split("&"); if (items!=null){ for(String keyValue : items ){ String[] keyValues = keyValue.split("="); if (keyValues!=null && keyValues.length == 2){ paramsMap.put(keyValues[0] , keyValues[1]); } } } } catch (Exception e) { e.printStackTrace(); } } return paramsMap; } public static List<String> convertJsonArrayToList(JSONArray jsonArray) throws JSONException { List<String> itemList = new ArrayList<String>(); for(int i=0; i<jsonArray.length() ; i++){ String item = jsonArray.getString(i); itemList.add(item); } return itemList; } }
package dev.soapy.worldheightbooster.mixin.worldgen; import dev.soapy.worldheightbooster.WorldHeightBooster; import net.minecraft.world.level.levelgen.carver.WorldCarver; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.Constant; import org.spongepowered.asm.mixin.injection.ModifyConstant; @Mixin(WorldCarver.class) public class MixinCarver { @ModifyConstant(method = "<clinit>()V", constant = @Constant(intValue = 256)) private static int actualCaveHeight(int oldValue) { return WorldHeightBooster.WORLD_HEIGHT; } }
package edu.jalc.everydaythings.liquid; public class Liquid { }
package com.bingo.code.example.design.facade.facadeexample; public class BModuleImpl implements BModuleApi{ public void testB() { System.out.println("Module B"); } }
package com.xiudun.service; import com.xiudun.beans.Person; public interface PersonService { /* * 添加 */ void save(Person person); /* * 修改 */ /* * 删除 */ /* * 显示 */ /* * 获取对象 */ /* * 获取文件 */ }
package voting; public interface VotingObservable { void register(VotingObserver o); void unregister(VotingObserver o); void notifyObservers(); }
package co.usa.recursohumanog35.recursohumanog35.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import co.usa.recursohumanog35.recursohumanog35.model.Empleado; import co.usa.recursohumanog35.recursohumanog35.repository.Empleadorepositorio; @Service public class EmpleadoServicio { @Autowired private Empleadorepositorio empleadorepositorio; public List<Empleado>getAll(){ return empleadorepositorio.getAll(); } public Optional<Empleado>getEmpleado(int id){ return empleadorepositorio.getEmpleado(id); } public Empleado save(Empleado empleado){ if (empleado.getNumId()==null) { return empleadorepositorio.save(empleado); } else { Optional<Empleado> consulta=empleadorepositorio.getEmpleado(empleado.getNumId()); if (consulta.isEmpty()) { return empleadorepositorio.save(empleado); } else { return empleado; } } } }
package com.drzewo97.ballotbox.core.model.poll; import com.drzewo97.ballotbox.core.model.country.Country; import com.drzewo97.ballotbox.core.model.district.District; import com.drzewo97.ballotbox.core.model.ward.Ward; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import java.util.Optional; import java.util.Set; public interface PollRepository extends CrudRepository<Poll, Integer> { Boolean existsByName(String name); Set<Poll> findByCountryOrDistrictOrWard(Country country, District district, Ward ward); @Query("select p from Poll p where p.id=?1 and (p.country=?2 or p.district=?3 or p.ward=?4)") Optional<Poll> findByIdAndCountryOrDistrictOrWard(Integer Id, Country country, District district, Ward ward); }
package com.user188245.util.rsort; class DoubleBitExtractor implements BitExtractor<Double>{ @Override public int bitSize() { return 64; } @Override public boolean getSignificantBit(Double elem, int exp) { long b = Double.doubleToRawLongBits(elem); if(b<0)b=b^9223372036854775807L; return (((b + -9223372036854775808L) >>> exp) & 1) == 1; } }
package com.flutterwave.raveandroid.di.components; import com.flutterwave.raveandroid.barter.BarterFragment; import com.flutterwave.raveandroid.di.modules.BarterModule; import com.flutterwave.raveandroid.di.scopes.BarterScope; import dagger.Subcomponent; @BarterScope @Subcomponent(modules = {BarterModule.class}) public interface BarterComponent { void inject(BarterFragment barterFragment); }
package pe.gob.sunarp.incidenciasapp.service.contrato; import java.util.List; import pe.gob.sunarp.incidenciasapp.dto.IncidenciaDto; public interface IncidenciaService { /** * Retornar un arreglo con la lista de los nombres de los incidentes * @return */ String[] getListaNombre(); /** * Registrar la incidencia * @param dto objeto de la clase IncedienciaDto * @return OK:1 ERROR:-1 */ void registrarIncidencia(IncidenciaDto dto); /** * Muestra los incidentes segun el tipo de incidencia * @param tipo * @return */ List<IncidenciaDto> getIncidente(String tipo); }
/* * Copyright (C) 2018 Ilya Lebedev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.ilya_lebedev.worldmeal.data.network; import android.content.Context; import android.content.Intent; import io.github.ilya_lebedev.worldmeal.utilities.WorldMealInjectorUtils; /** * WorldMealFetchUtils */ public class WorldMealFetchUtils { public static final String TAG = "WorldMealFetchUtils"; public static final String ACTION_FETCH_AREA_LIST = "fetch_area_list"; public static final String ACTION_FETCH_CATEGORY_LIST = "fetch_category_list"; public static final String ACTION_FETCH_INGREDIENT_LIST = "fetch_ingredient_list"; public static final String ACTION_FETCH_AREA_MEAL_LIST = "fetch_area_meal_list"; public static final String ACTION_FETCH_CATEGORY_MEAL_LIST = "fetch_category_meal_list"; public static final String ACTION_FETCH_INGREDIENT_MEAL_LIST = "fetch_ingredient_meal_list"; public static final String ACTION_FETCH_MEAL = "fetch_meal"; public static final String ACTION_FETCH_MEAL_OF_DAY = "fetch_meal_of_day"; private static final String EXTRA_AREA_NAME = "area_name"; private static final String EXTRA_CATEGORY_NAME = "category_name"; private static final String EXTRA_INGREDIENT_NAME = "ingredient_name"; private static final String EXTRA_MEAL_ID = "meal_id"; public static void fetch(Context context, Intent fetchIntent) { WorldMealNetworkDataSource networkDataSource = WorldMealInjectorUtils.provideNetworkDataSource(context.getApplicationContext()); String action = fetchIntent.getAction(); if (ACTION_FETCH_AREA_LIST.equals(action)) { networkDataSource.fetchAreaList(); } else if (ACTION_FETCH_CATEGORY_LIST.equals(action)) { networkDataSource.fetchCategoryList(); } else if (ACTION_FETCH_INGREDIENT_LIST.equals(action)) { networkDataSource.fetchIngredientList(); } else if (ACTION_FETCH_AREA_MEAL_LIST.equals(action)) { String areaName = fetchIntent.getStringExtra(EXTRA_AREA_NAME); networkDataSource.fetchAreaMealList(areaName); } else if (ACTION_FETCH_CATEGORY_MEAL_LIST.equals(action)) { String categoryName = fetchIntent.getStringExtra(EXTRA_CATEGORY_NAME); networkDataSource.fetchCategoryMealList(categoryName); } else if (ACTION_FETCH_INGREDIENT_MEAL_LIST.equals(action)) { String ingredientName = fetchIntent.getStringExtra(EXTRA_INGREDIENT_NAME); networkDataSource.fetchIngredientMealList(ingredientName); } else if(ACTION_FETCH_MEAL.equals(action)) { long mealId = fetchIntent.getLongExtra(EXTRA_MEAL_ID, -1); networkDataSource.fetchMeal(mealId); } else if(ACTION_FETCH_MEAL_OF_DAY.equals(action)) { networkDataSource.fetchMealOfDay(); } else { throw new IllegalArgumentException("Unsupported action: " + action); } } public static void startFetchAreaList(Context context) { Intent fetchIntent = new Intent(context.getApplicationContext(), WorldMealSyncIntentService.class); fetchIntent.setAction(ACTION_FETCH_AREA_LIST); context.startService(fetchIntent); } public static void startFetchCategoryList(Context context) { Intent fetchIntent = new Intent(context.getApplicationContext(), WorldMealSyncIntentService.class); fetchIntent.setAction(ACTION_FETCH_CATEGORY_LIST); context.startService(fetchIntent); } public static void startFetchIngredientList(Context context) { Intent fetchIntent = new Intent(context.getApplicationContext(), WorldMealSyncIntentService.class); fetchIntent.setAction(ACTION_FETCH_INGREDIENT_LIST); context.startService(fetchIntent); } public static void startFetchAreaMealList(Context context, String areaName) { Intent fetchIntent = new Intent(context.getApplicationContext(), WorldMealSyncIntentService.class); fetchIntent.setAction(ACTION_FETCH_AREA_MEAL_LIST); fetchIntent.putExtra(EXTRA_AREA_NAME, areaName); context.startService(fetchIntent); } public static void startFetchCategoryMealList(Context context, String categoryName) { Intent fetchIntent = new Intent(context.getApplicationContext(), WorldMealSyncIntentService.class); fetchIntent.setAction(ACTION_FETCH_CATEGORY_MEAL_LIST); fetchIntent.putExtra(EXTRA_CATEGORY_NAME, categoryName); context.startService(fetchIntent); } public static void startFetchIngredientMealList(Context context, String ingredientName) { Intent fetchIntent = new Intent(context.getApplicationContext(), WorldMealSyncIntentService.class); fetchIntent.setAction(ACTION_FETCH_INGREDIENT_MEAL_LIST); fetchIntent.putExtra(EXTRA_INGREDIENT_NAME, ingredientName); context.startService(fetchIntent); } public static void startFetchMeal(Context context, long mealId) { Intent fetchIntent = new Intent(context.getApplicationContext(), WorldMealSyncIntentService.class); fetchIntent.setAction(ACTION_FETCH_MEAL); fetchIntent.putExtra(EXTRA_MEAL_ID, mealId); context.startService(fetchIntent); } public static void startFetchMealOfDay(Context context) { Intent fetchIntent = new Intent(context.getApplicationContext(), WorldMealSyncIntentService.class); fetchIntent.setAction(ACTION_FETCH_MEAL_OF_DAY); context.startService(fetchIntent); } }
/* * 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 TFD.Presentation; import TFD.DomainModel.Categoria; import TFD.DomainModel.CategoriaRepositorio; import java.io.Serializable; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.component.UIInput; import javax.faces.context.FacesContext; import javax.inject.Named; /** * * @author Rosy */ @Named(value = "categoriaController") @SessionScoped public class CategoriaController implements Serializable{ Categoria entidade; Categoria filtro; List<Categoria> lista; @EJB CategoriaRepositorio dao; public CategoriaController() { entidade = new Categoria(); filtro = new Categoria(); } public void validarEspacoEmBranco(FacesContext contexto, UIComponent componente, Object valor) { String valorString = (String) valor; if (valorString.trim().equals("")) { ((UIInput) componente).setValid(false); String mensagem = componente.getAttributes().get("label") + ":Não é permitido espaço em branco. "; FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, mensagem, mensagem); contexto.addMessage(componente.getClientId(contexto), facesMessage); } } public void exibirMensagem(String msg) { FacesContext context = FacesContext.getCurrentInstance(); context.addMessage(null, new FacesMessage(msg)); } /** * Criando o Metodo de salvar */ public void salvar() { dao.Salvar(entidade); lista = null; exibirMensagem("Salvo!"); } public String editar() { return "CategoriaEditar.xhtml"; } public String novo(){ return "CategoriaEditar.xhtml"; } public String criar() { entidade = new Categoria(); return "CategoriaEditar.xhtml"; } public String apagar() { dao.Apagar(entidade); lista = null; exibirMensagem("Apagado com sucesso!"); return "CategoriaListagem.xhtml"; } public String filtrar() { lista = dao.Buscar(filtro); return "CategoriaListagem.xhtml"; } public String voltar() { lista = null; return "CategoriaListagem.xhtml"; } public Categoria getEntidade() { return entidade; } public void setEntidade(Categoria entidade) { this.entidade = entidade; } public List<Categoria> getLista() { if (lista == null) { Categoria filtro = new Categoria(); lista = dao.Buscar(filtro); } return lista; } public void setLista(List<Categoria> lista) { this.lista = lista; } public Categoria getFiltro() { return filtro; } public void setFiltro(Categoria filtro) { this.filtro = filtro; } }
/**************************************************** * $Project: DinoAge $ * $Date:: Jan 27, 2008 2:14:06 AM $ * $Revision: $ * $Author:: khoanguyen $ * $Comment:: $ **************************************************/ package org.ddth.blogging; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class Entry { private long entryId; private BlogPost post; private List<Comment> comments = new CopyOnWriteArrayList<Comment>(); private String url; public Entry(BlogPost post) { this.post = post; } public void setUrl(String url) { this.url = url; } public String getUrl() { return url; } public BlogPost getPost() { return post; } public long getEntryId() { return entryId; } public void setEntryId(long entryId) { this.entryId = entryId; } public List<Comment> getComments() { return comments; } public void addComment(Comment comment) { comments.add(comment); } public void removeComment(Comment comment) { comments.remove(comment); } }
package de.korten.wicket.examples.webcomponents.tasks; import org.apache.wicket.ajax.AjaxRequestTarget; public class TaskListChangedPayload { private AjaxRequestTarget target; public TaskListChangedPayload(AjaxRequestTarget target) { this.target = target; } public AjaxRequestTarget getTarget() { return target; } }
package step._02_IfStatement; import java.util.Scanner; /* date : 2021-06-25 (금) * author : develiberta * number : 02884 * * [단계] * 02. If문 * if문을 사용해 봅시다. * [제목] * 05. 알람 시계 (02884) * 시간 뺄셈 문제 * [문제] * 상근이는 매일 아침 알람을 듣고 일어난다. 알람을 듣고 바로 일어나면 다행이겠지만, 항상 조금만 더 자려는 마음 때문에 매일 학교를 지각하고 있다. * 상근이는 모든 방법을 동원해보았지만, 조금만 더 자려는 마음은 그 어떤 것도 없앨 수가 없었다. * 이런 상근이를 불쌍하게 보던, 창영이는 자신이 사용하는 방법을 추천해 주었다. * 바로 "45분 일찍 알람 설정하기"이다. * 이 방법은 단순하다. 원래 설정되어 있는 알람을 45분 앞서는 시간으로 바꾸는 것이다. 어차피 알람 소리를 들으면, 알람을 끄고 조금 더 잘 것이기 때문이다. * 이 방법을 사용하면, 매일 아침 더 잤다는 기분을 느낄 수 있고, 학교도 지각하지 않게 된다. * 현재 상근이가 설정한 알람 시각이 주어졌을 때, 창영이의 방법을 사용한다면, 이를 언제로 고쳐야 하는지 구하는 프로그램을 작성하시오. * [입력] * 첫째 줄에 두 정수 H와 M이 주어진다. (0 ≤ H ≤ 23, 0 ≤ M ≤ 59) 그리고 이것은 현재 상근이가 설정한 놓은 알람 시간 H시 M분을 의미한다. * 입력 시간은 24시간 표현을 사용한다. 24시간 표현에서 하루의 시작은 0:0(자정)이고, 끝은 23:59(다음날 자정 1분 전)이다. 시간을 나타낼 때, 불필요한 0은 사용하지 않는다. * [출력] * 첫째 줄에 상근이가 창영이의 방법을 사용할 때, 설정해야 하는 알람 시간을 출력한다. (입력과 같은 형태로 출력하면 된다.) * (예제 입력 1) * 10 10 * (예제 출력 1) * 9 25 * (예제 입력 2) * 0 30 * (예제 출력 2) * 23 45 * (예제 입력 3) * 23 40 * (예제 출력 3) * 22 55 */ public class _05_02884_AlarmClock { public static void main(String[] args) { Scanner in = new Scanner(System.in); int hour = in.nextInt(); int minute = in.nextInt(); if (minute >= 45) { minute = minute - 45; } else { minute = (minute - 45) + 60; if (hour > 0) { hour = hour - 1; } else { hour = (hour - 1) + 24; } } System.out.print(hour + " " + minute); in.close(); } }
package com.spower.basesystem.common.service.dao.hibernate; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.util.EmptyIterator; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.spower.basesystem.common.command.Page; import com.spower.basesystem.common.service.dao.ICommonDao; //import com.spower.basesystem.common.systemdata.SystemData; /** * The <code>HibernateCommonDao</code> class 基于Hibernate的ICommonDao实现. * * @author Qsj * @version 1.0, 2005-3-10 */ public class HibernateCommonDao extends HibernateDaoSupport implements ICommonDao { /** * @see com.spower.basesystem.common.service.dao.ICommonDao#insert(java.lang.Object) */ public void insert(Object entity) { super.getHibernateTemplate().save(entity); } /** * @see com.spower.basesystem.common.service.dao.ICommonDao#update(java.lang.Object) */ public void update(Object entity) { super.getHibernateTemplate().update(entity); } /** * @see com.spower.basesystem.common.service.dao.ICommonDao#save(java.lang.Object) */ public void save(Object entity) { super.getHibernateTemplate().saveOrUpdate(entity); //super.getHibernateTemplate().flush(); } /** (non Javadoc) * @see com.spower.basesystem.common.service.dao.ICommonDao#saveAndRefresh(java.lang.Object) */ public void saveAndRefresh(Object entity) { super.getHibernateTemplate().saveOrUpdate(entity); super.getHibernateTemplate().flush(); super.getHibernateTemplate().refresh(entity); } /** * @see com.spower.basesystem.common.service.dao.ICommonDao#saveAll(java.util.Collection) */ public void saveAll(Collection entities) { super.getHibernateTemplate().saveOrUpdateAll(entities); } /** * @see com.spower.basesystem.common.service.dao.ICommonDao#delete(java.lang.Object) */ public void delete(Object entity) { super.getHibernateTemplate().delete(entity); super.getHibernateTemplate().flush(); } /** * @see com.spower.basesystem.common.service.dao.ICommonDao#deleteAll(java.util.Collection) */ public void deleteAll(Collection entities) { super.getHibernateTemplate().deleteAll(entities); super.getHibernateTemplate().flush(); } /** * @see com.spower.basesystem.common.service.dao.ICommonDao#load(java.lang.Class, java.io.Serializable) */ public Object load(Class entityClass, Serializable id) { return super.getHibernateTemplate().get(entityClass, id); } /** (non Javadoc) * @see com.spower.basesystem.common.service.dao.ICommonDao#loadAll(java.lang.Class) */ public List loadAll(Class entityClass) { return super.getHibernateTemplate().loadAll(entityClass); } /** * @see com.spower.basesystem.common.service.dao.ICommonDao#initialize(java.lang.Object) */ public void initialize(Object proxy) { super.getHibernateTemplate().initialize(proxy); } /** (non Javadoc) * @see com.spower.basesystem.common.service.dao.ICommonDao#executeSql(java.lang.String) */ public List executeSql(String queryString) { return super.getHibernateTemplate().find(queryString); } /** (non Javadoc) * @see com.spower.basesystem.common.service.dao.ICommonDao#executeSql(java.lang.String, java.lang.Object[]) */ public List executeSql(String queryString, Object[] values) { return super.getHibernateTemplate().find(queryString, values); } //////////分页查询 private static String sqlFromToken = " from "; private static String sqlSelectToken = "select "; private static String sqlDistinctToken = "distinct"; private static String sqlGroupByToken = "group by "; private static String sqlOrderByToken = "order by "; //private static int NULL_DEFAULTSIZE = -1; /** 缺省每页显示行数. */ private int DEFAUT_PAGESIZE = 20; public int getDefaultSize() { return this.DEFAUT_PAGESIZE; } /** private int defaultSize = NULL_DEFAULTSIZE; public int getDefaultSize() { if (NULL_DEFAULTSIZE == defaultSize) { initDefaultSize(); } return this.defaultSize; } private void initDefaultSize() { String size = (String) SystemData.getInstance().getSystemData("分页", "每页行数"); if (null != size) { this.defaultSize = Integer.parseInt(size); } else { this.defaultSize = NULL_DEFAULTSIZE; } } */ /** * 缺省构造方法. */ public HibernateCommonDao() { //在Spring上下文初始化对象的时候,数据库实现的SystemData中还没有初始化完“分页”数据,所以修改初始化defaultSize的机制。 } /** * 取得查询计划总记录数的HSQL. * @param queryString 查询数据的HSQL * @return 查询总记录数的HSQL */ protected String getCountString(final String queryString) { String countTokenString = "*"; String targetString = queryString.toLowerCase(); int fromPos = targetString.indexOf(sqlFromToken); String fromTokenString = queryString.substring((fromPos < 0) ? 0 : fromPos); int orderPos = fromTokenString.indexOf(sqlOrderByToken); if (orderPos > 0) { fromTokenString = fromTokenString.substring(0, orderPos); } if (fromPos > 0) { int selectPos = targetString.indexOf(sqlSelectToken); int distinctPos = targetString.indexOf(sqlDistinctToken); if (selectPos >= 0 && distinctPos >= 0) { countTokenString = queryString.substring(selectPos + sqlSelectToken.length(), fromPos); String[] tokenArray = countTokenString.split(","); if (tokenArray.length > 0) { countTokenString = tokenArray[0]; } } } return new StringBuffer().append("select count(").append(countTokenString).append(") ") .append(fromTokenString).toString(); } /** 获取总记录数,在兼容以往处理机制的基础上,增加对分组数据的处理 * @param queryString 查询语句 * @param iterator 执行getCountString后返回的迭代器 * @return 总记录数 */ protected long getRecordNumber(final String queryString, Iterator iterator) { long recordNumber = 0; if (queryString.indexOf(sqlGroupByToken) > 0) { while (iterator.hasNext()) { recordNumber++; iterator.next(); } } else if (iterator.hasNext()) { recordNumber = ((Long) iterator.next()).longValue(); } if (!(iterator instanceof EmptyIterator)) { super.getHibernateTemplate().closeIterator(iterator); } return recordNumber; } /** * @see com.spower.basesystem.common.service.dao.ICommonDao#find(java.lang.String, int) */ public Page find(String queryString, int pageNumber) { return this.find(queryString, pageNumber, 5); } /** * @see com.spower.basesystem.common.service.dao.ICommonDao#find(java.lang.String, int, int) */ public Page find(final String queryString, final int pageNumber, final int pageSize) { Iterator iterator = super.getHibernateTemplate().iterate(this.getCountString(queryString)); long recordNumber = this.getRecordNumber(queryString, iterator); if (recordNumber == 0) { return new HibernatePage(); } final HibernatePage page = new HibernatePage(pageSize, pageNumber, recordNumber); List data = (List) super.getHibernateTemplate().execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query queryObject = session.createQuery(queryString); queryObject.setFirstResult((page.getPageNumber() - 1) * pageSize); queryObject.setMaxResults(pageSize); return queryObject.list(); } }, true); page.setData(data); return page; } /** * @see com.spower.basesystem.common.service.dao.ICommonDao#find(java.lang.String, java.lang.Object, int) */ public Page find(String queryString, Object value, int pageNumber) { return this.find(queryString, value, pageNumber, getDefaultSize()); } /** * @see com.spower.basesystem.common.service.dao.ICommonDao#find(java.lang.String, java.lang.Object, int, int) */ public Page find(final String queryString, final Object value, final int pageNumber, final int pageSize) { Iterator iterator = super.getHibernateTemplate().iterate(this.getCountString(queryString), value); // int recordNumber = 0; // if (iterator.hasNext()) { // recordNumber = ((Integer) iterator.next()).intValue(); // } // super.getHibernateTemplate().closeIterator(iterator); long recordNumber = this.getRecordNumber(queryString, iterator); if (recordNumber == 0) { return new HibernatePage(); } final HibernatePage page = new HibernatePage(pageSize, pageNumber, recordNumber); List data = (List) super.getHibernateTemplate().execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query queryObject = session.createQuery(queryString); queryObject.setParameter(0, value); queryObject.setFirstResult((page.getPageNumber() - 1) * pageSize); queryObject.setMaxResults(pageSize); return queryObject.list(); } }, true); page.setData(data); return page; } /** * @see com.spower.basesystem.common.service.dao.ICommonDao#find(java.lang.String, java.lang.Object[], int) */ public Page find(String queryString, Object[] values, int pageNumber) { return this.find(queryString, values, pageNumber, getDefaultSize()); } /** * @see com.spower.basesystem.common.service.dao.ICommonDao#find(java.lang.String, java.lang.Object[], int, int) */ public Page find(final String queryString, final Object[] values, final int pageNumber, final int pageSize) { Iterator iterator = super.getHibernateTemplate().iterate(this.getCountString(queryString), values); // int recordNumber = 0; // if (iterator.hasNext()) { // recordNumber = ((Integer) iterator.next()).intValue(); // } // super.getHibernateTemplate().closeIterator(iterator); long recordNumber = this.getRecordNumber(queryString, iterator); if (recordNumber == 0) { return new HibernatePage(); } final HibernatePage page = new HibernatePage(pageSize, pageNumber, recordNumber); List data = (List) super.getHibernateTemplate().execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query queryObject = session.createQuery(queryString); for (int i = 0; i < values.length; ++i) { queryObject.setParameter(i, values[i]); } queryObject.setFirstResult((page.getPageNumber() - 1) * pageSize); queryObject.setMaxResults(pageSize); // queryObject.setMaxResults(pageSize + 1); return queryObject.list(); } }, true); page.setData(data); return page; } /** * @see com.spower.basesystem.common.multipage.dao.ICommonDao#find(java.lang.String, java.lang.String, java.lang.Object[], int) */ public Page find(final String queryString, final String fieldString, final Object[] values, final int pageNumber) { Iterator iterator = super.getHibernateTemplate().iterate(this.getCountString(queryString), values); // int recordNumber = 0; // if (iterator.hasNext()) { // recordNumber = ((Integer) iterator.next()).intValue(); // } // super.getHibernateTemplate().closeIterator(iterator); long recordNumber = this.getRecordNumber(queryString, iterator); if (recordNumber == 0) { return new HibernatePage(); } final HibernatePage page = new HibernatePage(getDefaultSize(), pageNumber, recordNumber); List data = (List) super.getHibernateTemplate().execute( new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException { Query queryObject = session.createQuery("select " + fieldString + queryString); for (int i = 0; i < values.length; ++i) { queryObject.setParameter(i, values[i]); } queryObject.setFirstResult((page.getPageNumber() - 1) * getDefaultSize()); queryObject.setMaxResults(getDefaultSize()); return queryObject.list(); } }, true); page.setData(data); return page; } /** (non Javadoc) * @see com.spower.basesystem.common.service.dao.ICommonDao#putDataToPage(List) */ public Page putDataToPage(List data) { Page result = new HibernatePage(100000, 0, 0); result.setData(data); return result; } /** (non Javadoc) * @see com.spower.basesystem.common.service.dao.ICommonDao#pureCacheObject() */ public void pureCacheObject() { super.getHibernateTemplate().flush(); super.getHibernateTemplate().clear(); } /** * The <code>HibernatePage</code> class represents an adapter object. * * @author Qsj * @version 1.0, 2005-3-10 */ class HibernatePage implements Page { /** 本页包含的数据. */ private List data; private int pageSize; /** 总行数. */ private int totalPage; /** 当前页码. */ private int pageNumber; /** 令牌. */ private Long token; /** 总记录数 */ private Long recordNumber; /** 记录扩展的model数据. */ private Map model; /** * 构造方法. * @param pageSize 每页显示的记录数 * @param pageNumber 当前页码 * @param recordNumber 记录总数 */ HibernatePage(int pageSize, int pageNumber, long recordNumber) { this.pageSize = pageSize; this.pageNumber = pageNumber; this.recordNumber = recordNumber; this.totalPage = (int) Math.ceil((double) recordNumber / (double) pageSize); //确定当前页 if (this.pageNumber < 1) { this.pageNumber = 1; } if (this.pageNumber > this.totalPage) { this.pageNumber = this.totalPage; } } /** * 构造方法:构造一个空的分页对象. */ HibernatePage() { this.data = Collections.EMPTY_LIST; this.totalPage = 0; this.pageNumber = 0; // this.pageSize = pageSize; } /** * @see com.spower.basesystem.common.command.Page#setData(java.util.List) */ public void setData(List data) { this.data = data; } /** * @return Returns the token. */ public Long getToken() { return this.token; } /** * @param token The token to set. */ public void setToken(Long token) { this.token = token; } /** * @see com.spower.basesystem.common.command.Page#getTotalPage() */ public int getTotalPage() { return this.totalPage; } /** * @see com.spower.basesystem.common.command.Page#getPageNumber() */ public int getPageNumber() { return this.pageNumber; } /** * @see com.spower.basesystem.common.command.Page#hasPreviousPage() */ public boolean hasPreviousPage() { return this.pageNumber > 1; } /** * @see com.spower.basesystem.common.command.Page#hasNextPage() */ public boolean hasNextPage() { return this.pageNumber < this.totalPage; } /** * @see com.spower.basesystem.common.command.Page#getData() */ public List getData() { return this.data; // return hasNextPage() ? data.subList(0, pageSize) : data; } /** * @return Returns the pageSize. */ public int getPageSize() { return pageSize; } /** (non Javadoc) * @see com.spower.basesystem.common.command.Page#getModelData(java.lang.Object) */ public Object getModelData(Object key) { if (model != null) { return model.get(key); } return null; } /** (non Javadoc) * @see com.spower.basesystem.common.command.Page#setModelData(java.lang.Object, java.lang.Object) */ public void setModelData(Object key, Object value) { if (model == null) { model = new HashMap(); } model.put(key, value); } public Long getRecordNumber() { return recordNumber; } } }
package com.semantyca.nb.modules.administrator.model; import com.semantyca.nb.core.dataengine.jpa.model.SimpleReferenceEntity; import com.semantyca.nb.modules.administrator.init.ModuleConst; import javax.persistence.*; @Entity @Table(name = ModuleConst.CODE + "__modules", uniqueConstraints = @UniqueConstraint(columnNames = {"identifier"})) @NamedQuery(name = "Module.findAll", query = "SELECT m FROM Module AS m ORDER BY m.regDate") public class Module extends SimpleReferenceEntity { @Column(name = "is_on") private boolean isOn; @Column(name = "icon_url") private String iconUrl; public boolean isOn() { return isOn; } public void setOn(boolean isOn) { this.isOn = isOn; } public String getIconUrl() { return iconUrl; } public void setIconUrl(String iconUrl) { boolean isValid = iconUrl != null && !iconUrl.trim().isEmpty() && !iconUrl.contains("/api/"); if (isValid) { this.iconUrl = iconUrl.trim(); } else { this.iconUrl = null; } } }
package Pro.Homework.Lesson2.Task1; /** * Created by andrey on 25.01.17. */ public class XML_Parser { public static String pars(String xml, String tag) { String res = xml.substring(xml.indexOf(sTag(tag)) + sTag(tag).length(), xml.indexOf(eTag(tag))); return res; } private static String sTag(String tag) { return "<" + tag + ">"; } private static String eTag(String tag) { return "</" + tag + ">"; } }
package models; import org.junit.Test; import static org.junit.Assert.*; public class CommentTest { @Test public void getRateTest(){ Comment comment = new Comment(); assertTrue(comment.getRate()==0); comment.upvotes.add(new User()); comment.upvotes.add(new User()); comment.upvotes.add(new User()); assertTrue(comment.getRate() == 3); comment.upvotes.remove(2); assertTrue(comment.getRate() == 2); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mvirtual.catalog.authority; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ActionContext; import org.mvirtual.persistence.entity.Authority; import java.util.Map; import mvirtual.catalog.SessionNames; import org.hibernate.Session; import org.hibernate.Transaction; /** * * @author Fabricio */ public class SaveAuthorityPage extends ActionSupport { private String name; private String nickname; private String birthdate; private String deathdate; public void setBirthdate(String birthdate) { this.birthdate = birthdate; } public void setDeathdate(String deathdate) { this.deathdate = deathdate; } public void setName(String name) { this.name = name; } public void setNickname(String nickname) { this.nickname = nickname; } @Override public String execute () { Map <String, Object> httpSession = ActionContext.getContext().getSession (); Authority authority = (Authority) httpSession.get (SessionNames.AUTHORITY); Session dbSession = (Session) httpSession.get (SessionNames.AUTHORITY_DB_SESSION); Transaction dbTransaction = (Transaction) httpSession.get (SessionNames.AUTHORITY_DB_TRANSACTION); String authorityOperation = (String) httpSession.get (SessionNames.AUTHORITY_OPERATION); if (authorityOperation.equalsIgnoreCase("new")) { authority.setName(this.name); authority.setNickname(this.nickname); authority.setBirthDate(this.birthdate); authority.setDeathDate(this.deathdate); dbTransaction.commit (); dbSession.close(); } if (authorityOperation.equalsIgnoreCase("edit")) { authority.setName(this.name); authority.setNickname(this.nickname); authority.setBirthDate(this.birthdate); authority.setDeathDate(this.deathdate); dbTransaction.commit (); dbSession.close(); } httpSession.put (SessionNames.AUTHORITY, null); httpSession.put (SessionNames.AUTHORITY_DB_SESSION, null); httpSession.put (SessionNames.AUTHORITY_DB_TRANSACTION, null); httpSession.put (SessionNames.AUTHORITY_OPERATION, null); return SUCCESS; } }
/* * Copyright (C) 2023 Hedera Hashgraph, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hedera.mirror.graphql.mapper; import static org.assertj.core.api.Assertions.assertThat; import com.google.protobuf.ByteString; import com.hedera.mirror.common.domain.DomainBuilder; import com.hedera.mirror.common.domain.entity.Entity; import com.hedera.mirror.graphql.viewmodel.Account; import com.hedera.mirror.graphql.viewmodel.EntityId; import com.hedera.mirror.graphql.viewmodel.EntityType; import com.hedera.mirror.graphql.viewmodel.TimestampRange; import com.hederahashgraph.api.proto.java.Key; import java.time.Duration; import java.time.Instant; import java.util.Map; import org.apache.commons.codec.binary.Hex; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class AccountMapperTest { private AccountMapper accountMapper; private DomainBuilder domainBuilder; @BeforeEach void setup() { accountMapper = new AccountMapperImpl(new CommonMapperImpl()); domainBuilder = new DomainBuilder(); } @Test void map() { var bytes = ByteString.copyFrom(new byte[] {0, 1, 2}); var key = Key.newBuilder().setECDSASecp256K1(bytes).build().toByteArray(); var entity = domainBuilder.entity().customize(e -> e.key(key)).get(); assertThat(accountMapper.map(entity)) .returns(Hex.encodeHexString(entity.getAlias()), Account::getAlias) .returns(Duration.ofSeconds(entity.getAutoRenewPeriod()), Account::getAutoRenewPeriod) .returns(entity.getBalance(), Account::getBalance) .returns(Instant.ofEpochSecond(0L, entity.getCreatedTimestamp()), Account::getCreatedTimestamp) .returns(entity.getDeclineReward(), Account::getDeclineReward) .returns(entity.getDeleted(), Account::getDeleted) .returns(Instant.ofEpochSecond(0L, entity.getExpirationTimestamp()), Account::getExpirationTimestamp) .returns(Map.of("ECDSA_SECP256K1", "AAEC"), Account::getKey) .returns(entity.getMaxAutomaticTokenAssociations(), Account::getMaxAutomaticTokenAssociations) .returns(entity.getMemo(), Account::getMemo) .returns(entity.getEthereumNonce(), Account::getNonce) .returns(entity.getReceiverSigRequired(), Account::getReceiverSigRequired) .returns(Instant.ofEpochSecond(0L, entity.getStakePeriodStart()), Account::getStakePeriodStart) .returns(EntityType.valueOf(entity.getType().toString()), Account::getType) .satisfies(a -> assertThat(a.getEntityId()) .returns(entity.getShard(), EntityId::getShard) .returns(entity.getRealm(), EntityId::getRealm) .returns(entity.getNum(), EntityId::getNum)) .satisfies(a -> assertThat(a.getTimestamp()) .returns(Instant.ofEpochSecond(0L, entity.getTimestampLower()), TimestampRange::getFrom) .returns(null, TimestampRange::getTo)); } @Test void mapNulls() { var entity = new Entity(); assertThat(accountMapper.map(entity)) .returns(null, Account::getAlias) .returns(null, Account::getAutoRenewPeriod) .returns(null, Account::getBalance) .returns(null, Account::getCreatedTimestamp) .returns(null, Account::getDeclineReward) .returns(null, Account::getDeleted) .returns(null, Account::getEntityId) .returns(null, Account::getExpirationTimestamp) .returns(null, Account::getId) .returns(null, Account::getKey) .returns(null, Account::getMaxAutomaticTokenAssociations) .returns(null, Account::getMemo) .returns(null, Account::getNonce) .returns(null, Account::getPendingReward) .returns(null, Account::getReceiverSigRequired) .returns(null, Account::getStakePeriodStart) .returns(null, Account::getTimestamp) .returns(null, Account::getType); } }
package controles; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class AvisoServlet */ @WebServlet("/aviso") public class AvisoServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public AvisoServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String mensagem, cor, voltar; mensagem = request.getParameter("msg"); cor = request.getParameter("cor"); voltar = "/Modular/MenuPrincipal"; PrintWriter html = response.getWriter(); html.print("<HTML>"); html.print("<HEAD><TITLE> Estacionamento Web</TITLE></HEAD>"); html.print("<BODY bgcolor='" + cor + "' align='center'>"); html.print("<HR>"); html.print("<font color='white'>"); html.print("<H1>" + mensagem + "</H1>"); html.print("</font>"); html.print("<a href='" + voltar + "'>Voltar</a>"); html.print("<HR>"); html.print("</BODY>"); html.print("</HTML>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
package com.bingo.code.example.design.adapter.adapterlog; import java.util.*; public interface LogDbOperateApi { public void createLog(LogModel lm); public void updateLog(LogModel lm); public void removeLog(LogModel lm); public List<LogModel> getAllLog(); }
package app.davecstillo.com.schoolapp; import android.graphics.Bitmap; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.animation.LinearInterpolator; import android.widget.ImageView; import android.widget.RelativeLayout; import com.google.gson.JsonElement; /** * A simple {@link Fragment} subclass. */ public class cafeteria extends BaseFragment { ImageView cartel; float scalediff; private static final int NONE = 0; private static final int DRAG = 1; private static final int ZOOM = 2; private int mode = NONE; private float oldDist = 1f; private float d = 0f; private float newRot = 0f; private FloatingActionButton cafeteriaMenuFAB; public cafeteria() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view; view = inflater.inflate(R.layout.fragment_cafeteria, container, false); cartel = (ImageView) view.findViewById(R.id.cafeteriaMenu); // view.setMinimumHeight(screenHeight); // view.setMinimumWidth(screenWidth); cafeteriaMenuFAB = (FloatingActionButton) view.findViewById(R.id.cafeteriaFAB); cafeteriaMenuFAB.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { // Log.e("FAB","OnTouchListener 1"); RelativeLayout.LayoutParams parametros = (RelativeLayout.LayoutParams) cartel.getLayoutParams(); // Log.i("Imagen LMargin",String.valueOf(parametros.leftMargin)); // Log.i("Imagen RMargin", String.valueOf(parametros.rightMargin)); // Log.i("Imagen TMargin",String.valueOf(parametros.topMargin)); // Log.i("Imagen BMargin",String.valueOf(parametros.bottomMargin)); cartel.setLayoutParams(setMenuPosition()); cartel.setScaleY(1f); cartel.setScaleX(1f); Log.e("FAB","OnTouchListener 2"); // // Log.i("Imagen LMargin",String.valueOf(parametros.leftMargin)); // Log.i("Imagen RMargin", String.valueOf(parametros.rightMargin)); // Log.i("Imagen TMargin",String.valueOf(parametros.topMargin)); // Log.i("Imagen BMargin",String.valueOf(parametros.bottomMargin)); return true; } }); callList("getMenu.php"); return view; } public void callList(String path){ new BackgroundTask<JsonElement>(()-> httpHandler.instance.getJson(path), (json, ex)->{ if(ex!=null){ } if(json!=null){ for(JsonElement res : json.getAsJsonObject().get("Menu").getAsJsonArray()){ JsonElement elm; elm = res.getAsJsonObject().get("Imagen"); putImg(elm.getAsString()); } } }).execute(); } public void putImg(String imgName){ new BackgroundTask<Bitmap>(()->Imagenes.get(imgName), (b, ex)->{ if(ex!=null){ } if(b!=null) { cartel.setImageBitmap(b); cartel.setLayoutParams(setMenuPosition()); cartel.setOnTouchListener(touchListener()); } }).execute(); } public RelativeLayout.LayoutParams setMenuPosition(){ RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(250, 250); layoutParams.leftMargin = 0; layoutParams.topMargin = 0; layoutParams.bottomMargin = 0; layoutParams.rightMargin = 0; layoutParams.width= getScreenWidth(); layoutParams.height = getScreenHeight(); return layoutParams; } public int getScreenWidth(){ return this.getResources().getDisplayMetrics().widthPixels; } public int getScreenHeight(){ return this.getResources().getDisplayMetrics().heightPixels; } public OnTouchListener touchListener(){ return new OnTouchListener() { RelativeLayout.LayoutParams parms; int startwidth; int startheight; float dx = 0, dy = 0, x = 0, y = 0; float angle = 0; int screenWidth = getResources().getDisplayMetrics().widthPixels; int screenHeight = getResources().getDisplayMetrics().heightPixels; @Override public boolean onTouch(View v, MotionEvent event) { // Log.d("Widths: ", "screenWidth: " + String.valueOf(screenWidth)); // Log.d("Heights: ", "screenHeight: " + String.valueOf(screenHeight)); final ImageView view = (ImageView) v; switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: parms = (RelativeLayout.LayoutParams) view.getLayoutParams(); startwidth = parms.width; startheight = parms.height; dx = event.getRawX() - parms.leftMargin; dy = event.getRawY() - parms.topMargin; mode = DRAG; break; case MotionEvent.ACTION_POINTER_DOWN: oldDist = spacing(event); if (oldDist > 10f) { mode = ZOOM; } //d = rotation(event); break; case MotionEvent.ACTION_UP: // parms = (RelativeLayout.LayoutParams) view.getLayoutParams(); // // parms.leftMargin = 0; // parms.topMargin = 0; // parms.bottomMargin = 0; // parms.rightMargin = 0; //// parms.width= screenWidth; //// parms.height = screenHeight; // view.setAdjustViewBounds(true); // view.setLayoutParams(parms); break; case MotionEvent.ACTION_POINTER_UP: mode = NONE; break; case MotionEvent.ACTION_MOVE: if (mode == DRAG) { x = event.getRawX(); y = event.getRawY(); parms.leftMargin = (int) (x - dx); parms.topMargin = (int) (y - dy); parms.rightMargin = 0; parms.bottomMargin = 0; parms.rightMargin = parms.leftMargin + (5 * parms.width); parms.bottomMargin = parms.topMargin + (10 * parms.height); view.setLayoutParams(parms); } else if (mode == ZOOM) { if (event.getPointerCount() == 2) { //newRot = rotation(event); float r = newRot - d; angle = r; x = event.getRawX(); y = event.getRawY(); float newDist = spacing(event); if (newDist > 10f) { float scale = newDist / oldDist * view.getScaleX(); if (scale > 0.6) { scalediff = scale; view.setScaleX(scale); view.setScaleY(scale); } } view.animate().rotationBy(angle).setDuration(0).setInterpolator(new LinearInterpolator()).start(); x = event.getRawX(); y = event.getRawY(); parms.leftMargin = (int) ((x - dx) + scalediff); parms.topMargin = (int) ((y - dy) + scalediff); parms.rightMargin = 0; parms.bottomMargin = 0; parms.rightMargin = parms.leftMargin + (5 * parms.width); parms.bottomMargin = parms.topMargin + (10 * parms.height); view.setLayoutParams(parms); } } break; } return true; } }; } private float spacing(MotionEvent event) { float x = event.getX(0) - event.getX(1); float y = event.getY(0) - event.getY(1); return (float) Math.sqrt(x * x + y * y); } // private float rotation(MotionEvent event) { // double delta_x = (event.getX(0) - event.getX(1)); // double delta_y = (event.getY(0) - event.getY(1)); // double radians = Math.atan2(delta_y, delta_x); // return (float) Math.toDegrees(radians); // } }
package pt.up.fe.socialcrowd.activities; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import pt.up.fe.socialcrowd.R; import pt.up.fe.socialcrowd.API.Request; import pt.up.fe.socialcrowd.API.RequestException; import pt.up.fe.socialcrowd.logic.BaseEvent; import pt.up.fe.socialcrowd.logic.GPSCoords; import pt.up.fe.socialcrowd.managers.DataHolder; import android.annotation.SuppressLint; import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.widget.TextView.OnEditorActionListener; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks; import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener; import com.google.android.gms.location.LocationClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.LatLngBounds.Builder; import com.google.android.gms.maps.model.MarkerOptions; public class MarkerActivity extends FragmentActivity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener{ /** * Note that this may be null if the Google Play services APK is not available. */ private GoogleMap mMap; private Geocoder geo; private LatLng loc; private LocationClient mLocationClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_choose_location); geo = new Geocoder(getApplicationContext()); if(!Geocoder.isPresent()){ Log.d("GEO", "NOT PRESENT!"); } final Builder bounds = new LatLngBounds.Builder(); try { ArrayList<BaseEvent> events = Request.getEvents(); for(int i = 0; i < events.size(); i++){ GPSCoords gps = events.get(i).getLocation().getGps(); if(gps != null){ mMap.addMarker(new MarkerOptions() .position(new LatLng(gps.getLatitude(),gps.getLongitude())) .title(events.get(i).getLocation().getText())); bounds.include(new LatLng(gps.getLatitude(),gps.getLongitude())); } } final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView(); if (mapView.getViewTreeObserver().isAlive()) { mapView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @SuppressWarnings("deprecation") // We use the new method when supported @SuppressLint("NewApi") // We check which build version we are using. @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } LatLngBounds bound = bounds.build(); mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bound, 50)); } }); } } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RequestException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); setUpLocationClientIfNeeded(); mLocationClient.connect(); } /** * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly * installed) and the map has not already been instantiated.. This will ensure that we only ever * call {@link #setUpMap()} once when {@link #mMap} is not null. * <p> * If it isn't installed {@link SupportMapFragment} (and * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to * install/update the Google Play services APK on their device. * <p> * A user can return to this FragmentActivity after following the prompt and correctly * installing/updating/enabling the Google Play services. Since the FragmentActivity may not have been * completely destroyed during this process (it is likely that it would only be stopped or * paused), {@link #onCreate(Bundle)} may not be called again so we should call this method in * {@link #onResume()} to guarantee that it will be called. */ private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } /** * This is where we can add markers or lines, add listeners or move the camera. In this case, we * just add a marker near Africa. * <p> * This should only be called once and when we are sure that {@link #mMap} is not null. */ private void setUpMap() { setUpLocationClientIfNeeded(); // Pan to see all markers in view. // Cannot zoom to bounds until the map has a size. mMap.setMyLocationEnabled(true); //mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc,12)); } private void setUpLocationClientIfNeeded() { if (mLocationClient == null) { mLocationClient = new LocationClient(getApplicationContext(), this, this); } } @Override public void onConnected(Bundle arg0) { LatLng myLoc = new LatLng(mLocationClient.getLastLocation().getLatitude(), mLocationClient.getLastLocation().getLongitude()); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLoc,11)); } @Override public void onDisconnected() { // TODO Auto-generated method stub } @Override public void onConnectionFailed(ConnectionResult arg0) { // TODO Auto-generated method stub } @Override public void onLocationChanged(Location arg0) { } }
package cybersoft.java12.crmapp.servlet; import java.io.IOException; import java.sql.SQLException; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cybersoft.java12.crmapp.DTO.UserCreateDTO; import cybersoft.java12.crmapp.model.User; import cybersoft.java12.crmapp.service.UserService; import cybersoft.java12.crmapp.util.JspUtils; import cybersoft.java12.crmapp.util.UrlUtils; @WebServlet (name = "userServlet", urlPatterns = { UrlUtils.USER_DASHBOARD, UrlUtils.USER_PROFILE, UrlUtils.USER_ADD, UrlUtils.USER_UPDATE, UrlUtils.USER_DELETE }) public class UserServlet extends HttpServlet { private UserService service; @Override public void init() throws ServletException { super.init(); service = new UserService(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String servletPath = req.getServletPath(); switch(servletPath) { case UrlUtils.USER_DASHBOARD:{ getUserDashBoard(req,resp); break; } case UrlUtils.USER_PROFILE: { getUserProfile(req,resp); break; } case UrlUtils.USER_ADD: { getUserAdd(req, resp); break; } case UrlUtils.USER_UPDATE:{ getUserUpdate(req,resp); break; } case UrlUtils.USER_DELETE:{ getUserDelete(req,resp); break; } } } private void getUserUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int id = Integer.parseInt(req.getParameter("id")); UserCreateDTO userDTO = null; try { userDTO = service.findUserById(id); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("UserDTO: " +userDTO.getRoleId()); req.setAttribute("userDTO", userDTO); req.getRequestDispatcher(JspUtils.USER_UPDATE).forward(req, resp); } private void getUserDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { int id = Integer.parseInt(req.getParameter("id")); service.deleteById(id); resp.sendRedirect(req.getContextPath() + UrlUtils.USER_DASHBOARD); } private void getUserAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher(JspUtils.USER_ADD).forward(req, resp); } private void getUserProfile(HttpServletRequest req, HttpServletResponse resp) { // TODO Auto-generated method stub } private void getUserDashBoard(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<User> users = service.findAll(); if(users != null && !users.isEmpty()) { req.setAttribute("users", users); } req.getRequestDispatcher(JspUtils.USER_DASHBOARD).forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String servletPath = req.getServletPath(); switch(servletPath) { case UrlUtils.USER_DASHBOARD:{ break; } case UrlUtils.USER_PROFILE: { break; } case UrlUtils.USER_UPDATE:{ postUserUpdate(req,resp); break; } case UrlUtils.USER_ADD: { postUserAdd(req, resp); break; } case UrlUtils.USER_DELETE:{ break; } } } private void postUserUpdate(HttpServletRequest req, HttpServletResponse resp) throws IOException { UserCreateDTO dto = extractDTOFromReq(req); int id = Integer.parseInt(req.getParameter("id")); service.updateByID(dto, id); resp.sendRedirect(req.getContextPath() + UrlUtils.USER_DASHBOARD); } private void postUserAdd(HttpServletRequest req, HttpServletResponse resp) throws IOException { UserCreateDTO dto = extractDTOFromReq(req); service.add(dto); resp.sendRedirect(req.getContextPath() + UrlUtils.USER_DASHBOARD); } private UserCreateDTO extractDTOFromReq(HttpServletRequest req) { String email = req.getParameter("email"); String password = req.getParameter("password"); String name = req.getParameter("name"); String phone = req.getParameter("phone"); String address = req.getParameter("address"); int roleId = Integer.parseInt(req.getParameter("role")); return new UserCreateDTO(email, password, name, address, phone, roleId); } }
/** * */ package com.cnk.travelogix.common.facades.product.sort.impl; import java.util.ArrayList; import java.util.List; import com.cnk.travelogix.common.facades.product.provider.CnkFacetValueProvider; /** * @author i313890 * */ public class HotelSortedToModelMapper extends SortedToModelMapper { private CnkFacetValueProvider defaultCnkFacetValueProvider; @Override protected List<SortedToModelEntry> buildMockupEntries() { final List<SortedToModelEntry> entrys = new ArrayList(); entrys.add(createEntry("Price", "Price(from low to high)", "hotelPriceValueProvider")); entrys.add(createEntry("hotelRating", "Star Rating(from low to high)", "hotelStarRatingValueProvider")); entrys.add(createEntry("Recommended", "Recommended(from low to high)", "hotelRecommendedValueProvider")); entrys.add(createEntry("Popularity", "Popularity(from low to high)", "hotelPopularityValueProvider")); return entrys; } private SortedToModelEntry createEntry(final String code, final String name, final String providerName) { final SortedToModelEntry entry = new SortedToModelEntry(); entry.setCode(code); entry.setName(name); entry.setDesc(false); entry.setSortedValueProvider(getProviderByName(providerName)); return entry; } /** * @return the defaultCnkFacetValueProvider */ public CnkFacetValueProvider getDefaultCnkFacetValueProvider() { return defaultCnkFacetValueProvider; } /** * @param defaultCnkFacetValueProvider * the defaultCnkFacetValueProvider to set */ public void setDefaultCnkFacetValueProvider(final CnkFacetValueProvider defaultCnkFacetValueProvider) { this.defaultCnkFacetValueProvider = defaultCnkFacetValueProvider; } }
package divers; import java.io.BufferedReader; import java.io.InputStreamReader; public class LectureClavier { private BufferedReader br; public LectureClavier() { //constructeur par defaut this.br = new BufferedReader (new InputStreamReader (System.in)); } public float lireEntreeFloat(int min, float max) { float montant; while (true) { try { montant = Float.parseFloat(br.readLine()); if (montant >= min && montant <= max) { break; } } catch (Exception e) { e.printStackTrace(); System.out.println("Mauvaise valeur, veuillez saisir un reel !"); } } return montant; } }
package sarong; import java.util.ArrayList; /** * Created by Tommy Ettinger on 3/21/2016. */ public class EditRNGTest { public static void d20Graph(EditRNG rng, double expected, String description) { System.out.println("Testing " + description + ", expecting average of " + expected + ", centrality of " + rng.getCentrality()); rng.setExpected(expected); rng.setState(-3036294613074652313L); ArrayList<StringBuilder> rolls = new ArrayList<StringBuilder>(20); for (int i = 0; i < 20; i++) { rolls.add(new StringBuilder(200)); } for (int i = 0; i < 500; i++) { rolls.get(rng.nextInt(20)).append(rng.rawLatest < 0.05 ? '~' : rng.rawLatest >= 0.95 ? '!' : '*'); } double avg = 0; for (int i = 0; i < 20; i++) { StringBuilder sb = rolls.get(i); int len = sb.length(); avg += len * i; System.out.print(i + (i < 10 ? " : " : ": ")); System.out.print(sb); System.out.print(" Count: "); System.out.println(len); } System.out.println("Total: " + avg + ", Real Average: " + avg / 500.0); System.out.println(); } public static void main(String[] args) { EditRNG lr = new EditRNG(new LightRNG(0xDADA157), 0.5, 0.0), lpr = new EditRNG(new LongPeriodRNG(0xDADA157), 0.5, 0.0); for (double d = 0.1; d < 0.9; d+= 0.05) { d20Graph(lr, d, "LightRNG"); d20Graph(lpr, d, "LongPeriodRNG"); } lr.setCentrality(-25); lpr.setCentrality(-25); for (double d = 0.1; d < 0.9; d+= 0.05) { d20Graph(lr, d, "LightRNG"); d20Graph(lpr, d, "LongPeriodRNG"); } lr.setCentrality(-50); lpr.setCentrality(-50); for (double d = 0.1; d < 0.9; d+= 0.05) { d20Graph(lr, d, "LightRNG"); d20Graph(lpr, d, "LongPeriodRNG"); } lr.setCentrality(150); lpr.setCentrality(150); for (double d = 0.1; d < 0.9; d+= 0.05) { d20Graph(lr, d, "LightRNG"); d20Graph(lpr, d, "LongPeriodRNG"); } lr.setCentrality(200); lpr.setCentrality(200); for (double d = 0.1; d < 0.9; d+= 0.05) { d20Graph(lr, d, "LightRNG"); d20Graph(lpr, d, "LongPeriodRNG"); } lr.setCentrality(-25); lpr.setCentrality(-25); for (double d = 0.1; d < 0.9; d+= 0.05) { d20Graph(lr, d, "LightRNG"); d20Graph(lpr, d, "LongPeriodRNG"); } lr.setCentrality(-50); lpr.setCentrality(-50); for (double d = 0.1; d < 0.9; d+= 0.05) { d20Graph(lr, d, "LightRNG"); d20Graph(lpr, d, "LongPeriodRNG"); } lr.setCentrality(-150); lpr.setCentrality(-150); for (double d = 0.1; d < 0.9; d+= 0.05) { d20Graph(lr, d, "LightRNG"); d20Graph(lpr, d, "LongPeriodRNG"); } lr.setCentrality(-200); lpr.setCentrality(-200); for (double d = 0.1; d < 0.9; d+= 0.05) { d20Graph(lr, d, "LightRNG"); d20Graph(lpr, d, "LongPeriodRNG"); } } }
package com.tencent.mm.plugin.appbrand.g; import android.webkit.ValueCallback; import com.tencent.xweb.g; import java.net.URL; class i$2 implements Runnable { final /* synthetic */ String fwG; final /* synthetic */ ValueCallback fwH; final /* synthetic */ i gdS; final /* synthetic */ URL gdT; i$2(i iVar, URL url, String str, ValueCallback valueCallback) { this.gdS = iVar; this.gdT = url; this.fwG = str; this.fwH = valueCallback; } public final void run() { g a = i.a(this.gdS); URL url = this.gdT; String str = this.fwG; ValueCallback valueCallback = this.fwH; if (!a.fwD) { a.vzZ.evaluateJavascript(str, valueCallback, url); } } }
package com.timmy.framework.annotationCompile; /** * Created by admin on 2017/9/20. */ //public class MyProcessor extends AbstractProcessor { public class MyProcessor { }
package com.wtu.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @Author menglanyingfei * @Created on 2018.01.11 9:00 */ public class ServletDemo1 extends HttpServlet{ @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().print(req.getHeader("User-Agent")); //Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); } }
package se.magmag.oauth.endpoint; import lombok.Data; import java.net.URI; /** * EndpointResponse contains the response from an endpoint with unparsed data. */ @Data public class EndpointResponse { private int statusCode; private String message; private URI location; }
package ua.project.protester.service.library; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ua.project.protester.exception.LibraryAlreadyExistsException; import ua.project.protester.exception.LibraryNotFoundException; import ua.project.protester.model.Library; import ua.project.protester.model.executable.Step; import ua.project.protester.repository.library.LibraryRepository; import ua.project.protester.request.LibraryRequestModel; import ua.project.protester.utils.Page; import ua.project.protester.utils.PaginationLibrary; import java.util.stream.Collectors; @Slf4j @Service @RequiredArgsConstructor public class LibraryServiceImpl implements LibraryService { private final LibraryRepository libraryRepository; @Override @Transactional public void createLibrary(LibraryRequestModel libraryRequest) throws LibraryAlreadyExistsException { Library newLibrary = new Library(); newLibrary.setName(libraryRequest.getName()); newLibrary.setDescription(libraryRequest.getDescription()); newLibrary.setComponents( libraryRequest.getComponents() .stream() .map(componentRepresentation -> new Step( componentRepresentation.getId(), componentRepresentation.isAction(), null, componentRepresentation.getParameters() )).collect(Collectors.toList()) ); try { libraryRepository.createLibrary(newLibrary); } catch (Exception e) { throw new LibraryAlreadyExistsException("Library already exists", e); } } @Override @Transactional public void updateLibrary(LibraryRequestModel libraryRequest, int id) throws LibraryAlreadyExistsException { Library updateLibrary = new Library(); updateLibrary.setName(libraryRequest.getName()); updateLibrary.setDescription(libraryRequest.getDescription()); updateLibrary.setComponents( libraryRequest.getComponents() .stream() .map(componentRepresentation -> new Step( componentRepresentation.getId(), componentRepresentation.isAction(), null, componentRepresentation.getParameters() )).collect(Collectors.toList()) ); try { libraryRepository.updateLibrary(updateLibrary, id); } catch (Exception e) { throw new LibraryAlreadyExistsException("Library already exists", e); } } @Override @Transactional public Page<Library> findAll(PaginationLibrary paginationLibrary) { return new Page<>( libraryRepository.findAll(paginationLibrary), libraryRepository.getCountLibraries(paginationLibrary) ); } @Override @Transactional public Library getLibraryById(int id) throws LibraryNotFoundException { return libraryRepository.findLibraryById(id).orElseThrow(() -> new LibraryNotFoundException("Can`t find library by id=" + id)); } @Override @Transactional public void deleteLibraryById(int id) throws LibraryNotFoundException { if (libraryRepository.findLibraryById(id).isPresent()) { libraryRepository.deleteLibraryById(id); } else { throw new LibraryNotFoundException("Can`t find library by id=" + id); } } }
package advisor; public class Config { public static String SERVER_PATH = "https://accounts.spotify.com"; public static String RESOURCE = "https://api.spotify.com"; public static int RESULTS_PER_PAGE = 5; public static String REDIRECT_URI = "http://localhost:8050/authorization"; public static String CLIENT_ID = "d6dcedba1c5e43328fa43bc1873b2b84"; public static String CLIENT_SECRET = "4ecb3c8cefd24940925f6296a1542b04"; public static String ACCESS_TOKEN = ""; public static String AUTH_CODE = ""; }
package graphana.script.bindings.basicops; import graphana.MainControl; import graphana.script.bindings.GraphanaScriptScope; import graphana.script.bindings.treeelems.GraphanaScriptOperationLazy; import scriptinterface.defaulttypes.GInteger; import scriptinterface.execution.returnvalues.ExecutionReturn; public class GrOpMeasureAlgorithmTime extends GraphanaScriptOperationLazy { @Override public ExecutionReturn derivExecute(GraphanaScriptScope scope) { MainControl mainControl = scope.getMainControl(); mainControl.startAlgorithmTimer(); ExecutionReturn exec = super.children[0].execute(scope); if (exec.isStopExecution()) return exec; else return new GInteger(mainControl.getAlgorithmTime()); } @Override public String getName() { return "measureAlgorithmTime"; } }
package test.main; import java.util.Random; /* * 프로그래머가 직접 예외 클래스를 정의하고 * 필요한 시점에 예외를 발생 시킬수도 있을까? * * Exception or RuntimeException 클래스를 상속 받으면 가능하다! */ public class MainClass07 { public static void main(String[] args) { System.out.println("main 메소드가 시작 되었습니다."); Random ran=new Random(); int ranNum=ran.nextInt(3); if(ranNum==0) {//우연히 0 이 나오면 //throw 예약어를 이용해서 HeadacheException 발생 시키기 throw new HeadacheException("으악 머리아퍼 ㄷ ㄷ ㄷ"); } System.out.println("main 메소드가 종료 됩니다."); } //머리 아픈 Exception static class HeadacheException extends RuntimeException{ //예외 메세지를 String type 으로 전달 받는 생성자 public HeadacheException(String msg) { //부모 생성자에 전달해야 한다. super(msg); } } }
import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; public class CounterTest { @Before public void setUp() throws Exception { Counter x = new Counter("Shane"); } @After public void tearDown() throws Exception { } @Test public void testIncrement() { Counter x = new Counter("Shane"); x.increment(); assertEquals(x.toString(), "1 Shane"); } }
/* * Copyright 2008 University of California at Berkeley * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.rebioma.server.services; import java.util.List; import java.util.Set; import org.hibernate.Session; import org.rebioma.client.UserQuery; import org.rebioma.client.bean.Role; import org.rebioma.client.bean.User; /** * Service interface for data object access of {@link User}. * */ // @ImplementedBy(UserDbImpl.class) public interface UserDb { /** * Gives a user a Role * * @param user the user to be assigned with the given role * @param role */ public void addRole(User user, Role role); /** * Attaches a clean instance of {@link User} to the database. * * @param instance an User */ public void attachClean(User instance); /** * Attaches a dirty set of {@link User} objects to the database. * * @param instances the set of Users */ public void attachDirty(Set<User> instances); /** * Attaches a dirty instance of {@link User} to the database. * * @param instance the User */ public void attachDirty(User instance); /** * Deletes a persistent instance of {@link User} from the database. * * @param persistentInstances the User */ public void delete(User persistentInstance); public List<User> findByEmail(Set<String> userEmails); public User findByEmail(String userEmails); /** * Finds a list of {@link User} by using instances of {@link User} in the * database. * * @param instances the example Users * @return a list of Users */ public List<User> findByExample(Set<User> instances); /** * Finds an {@link User} by using an instance of {@link User} in the database. * * @param instance the example User * @return an User */ public List<User> findByExample(User instance); /** * Finds an {@link User} by id. * * @param id the User id * @return an User */ public User findById(java.lang.Integer id); public User findById(Session session,java.lang.Integer id); /** * Finds all {@link User} by id. * * @param ids the User ids * @return a list of Users */ public List<User> findById(Set<Integer> ids); public UserQuery findByQuery(UserQuery query, Integer loggedInUserId) throws Exception; /** * Merges changes in a detached instance of {@link User}. * * @param detachedInstance the User * @return the merged User */ public User merge(User detachedInstance); /** * Persists a transient instance of {@link User}. * * @param transientInstance the User */ public void persist(User transientInstance); /** * Removes the given role form the user * * @param user * @param role */ public void removeRole(User user, Role role); /** * Remove a user along with all its associated roles * * @param user * @return */ public boolean removeUser(User user); }
package game; public class Player { private Account account; private String name; private int position; private boolean alive; private boolean jailed; private int timeJailed; public Player(String x, int a) { name = x; account = new Account(a); position = 0; alive = true; jailed = false; timeJailed = 0; } public String getName() { return name; } public Account getAccount() { return account; } public int getPosition() { return position; } public void setPosition(int x) { position = x; } public boolean isAlive() { return alive; } public void setAlive(boolean alive) { this.alive = alive; } public boolean getJailed() { return jailed; } public void setJailed(boolean jailed) { this.jailed = jailed; } public int getTimeJailed(){ return timeJailed; } public void setTimeJailed(int timeJailed){ this.timeJailed = timeJailed; } }
package contactmanagementsoftware; //import java.util.ArrayList; public class ContactManagementSoftware{ private static MUI mg; private static AcquaintancesSystem ac = new AcquaintancesList("master"); private static AcquaintancesSystem perF1 = new AcquaintancesList("Personal Friends"); private static AcquaintancesSystem rel1 = new AcquaintancesList("Relatives"); private static AcquaintancesSystem proF1 = new AcquaintancesList("Professional Friends"); private static AcquaintancesSystem ca1 = new AcquaintancesList("Casual Acquaintance"); public static void main(String[] args) { mg = new MUI(); mg.setMg(mg); ac.addAcquaintances(perF1); ac.addAcquaintances(rel1); ac.addAcquaintances(proF1); ac.addAcquaintances(ca1); mg.setAc(ac); mg.setVisible(true); } }
package nb.controller; import nb.additional.SignerBank; import nb.domain.*; import nb.queryDomain.AcceptPriceHistory; import nb.queryDomain.CreditAccPriceHistory; import nb.queryDomain.FondDecisionsByLotHistory; import nb.service.*; import nb.util.CustomDateFormats; import nb.util.Excel; import nb.util.MathCalculationUtil; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.DataFormatter; import org.apache.poi.ss.util.DateFormatConverter; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xwpf.usermodel.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.*; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; @Controller @SessionAttributes({"userId", "lotRid", "objIdToDownload", "docName", "docType", "reportPath", "assetPortionNum"}) public class AssetController { @Autowired private CreditService creditService; @Autowired private LotService lotService; @Autowired private UserService userService; @Autowired private ExchangeService exchangeService; @Autowired private BidService bidService; @Autowired private AssetService assetService; @Autowired private PayService payService; @Autowired private CustomerService customerService; @Autowired private ReportService reportService; private static final String documentsPath = "C:\\SCAN\\DocumentsByLots\\"; private static final String bidDocumentsPath = "C:\\SCAN\\DocumentsByBid\\"; private String replaceRunText(String text, String kd, String year, String fio, String address, String inn, String prn, String prd, String pmb, String fpr, String knd, String subscr) { text = text.replace("kd", kd); text = text.replace("year", year); text = text.replace("fio", fio); text = text.replace("address", address); text = text.replace("inn", inn); text = text.replace("prn", prn); text = text.replace("prd", prd); text = text.replace("pmb", pmb); text = text.replace("fpr", fpr); text = text.replace("knd", knd); if (subscr.equals("null")) text = text.replace("sub", fio); else text = text.replace("sub", subscr); return text; } private String replaceRunTextAssets(String text, String bidDAte, int count, String kd, String year, String fio, String address, String inn, String prn, String prd, String pmb, String fpr, String subscr, String pass_seria, String pass_num, String pass_vidano, String pass_vidano_date, String operates_basis, String account_bank, String bid_enter, String bid_client, String signer_bank, String signer_bank_text, String property_fp, String property_fp_pdv, String elseAssets_fp, String elseAssets_pdv) { String factPrice_pdv; try { factPrice_pdv = String.valueOf(BigDecimal.valueOf(Double.parseDouble(fpr) / 6).setScale(2, RoundingMode.UP)); } catch (Exception e) { factPrice_pdv = ""; } text = text.replace("audat", bidDAte); text = text.replace("count", String.valueOf(count)); text = text.replace("kd", kd); text = text.replace("year", year); text = text.replace("fio", fio); text = text.replace("address", address); text = text.replace("inn", inn); text = text.replace("prn", prn); text = text.replace("prd", prd); text = text.replace("pmb", pmb); text = text.replace("fpr", fpr); text = text.replace("pdv", factPrice_pdv); text = text.replace("ps", pass_seria); text = text.replace("pn", pass_num); text = text.replace("pv", pass_vidano); text = text.replace("pdat", pass_vidano_date); text = text.replace("ob", operates_basis); text = text.replace("bank", account_bank); text = text.replace("bide", bid_enter); text = text.replace("bidc", bid_client); text = text.replace("sbf", signer_bank); text = text.replace("sbt", signer_bank_text); text = text.replace("nfp", property_fp); text = text.replace("npd", property_fp_pdv); text = text.replace("nefp", elseAssets_fp); text = text.replace("nepd", elseAssets_pdv); if (subscr.equals("null")) text = text.replace("sub", fio); else text = text.replace("sub", subscr); return text; } private String makeHistoryReportByAssets(List<Asset> assetList) throws IOException { InputStream ExcelFileToRead = new FileInputStream("C:\\projectFiles\\History.xlsx"); XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead); XSSFSheet sheet1 = wb.getSheetAt(0); XSSFSheet sheet2 = wb.getSheetAt(1); XSSFSheet sheet3 = wb.getSheetAt(2); //задаем формат даты String excelFormatter = DateFormatConverter.convert(Locale.ENGLISH, "yyyy-MM-dd"); CellStyle cellStyle = wb.createCellStyle(); CellStyle numStyle = wb.createCellStyle(); DataFormat poiFormat = wb.createDataFormat(); cellStyle.setDataFormat(poiFormat.getFormat(excelFormatter)); numStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("$#,##0.00")); //end int numRow1 = 0; int numRow2 = 0; int numRow3 = 0; // int i = 0; for (Asset asset : assetList) { List<Long> lotIdList = assetService.getLotIdHistoryByAsset(asset.getId()); for (Long lotId : lotIdList) { List<FondDecisionsByLotHistory> fondDecisionsByLotHistory = lotService.getFondDecisionsByLotHistory(lotId); for (FondDecisionsByLotHistory fondDecision : fondDecisionsByLotHistory) { numRow3++; XSSFRow row = sheet3.createRow(numRow3); row.createCell(0).setCellValue(lotId); try { row.createCell(1).setCellValue(CustomDateFormats.sdfshort.format(fondDecision.getFondDecisionDate())); } catch (Exception e) { } row.createCell(2).setCellValue(fondDecision.getDecisionNumber()); row.createCell(3).setCellValue(fondDecision.getFondDecision()); } List<Bid> bidList = lotService.getLotHistoryAggregatedByBid(lotId); Collections.sort(bidList); for (Bid bid : bidList) { numRow1++; XSSFRow row = sheet1.createRow(numRow1); row.createCell(0).setCellValue(asset.getInn()); row.createCell(1).setCellValue(lotId); row.createCell(2).setCellValue(bid.getExchange().getCompanyName()); row.createCell(3).setCellValue(CustomDateFormats.sdfshort.format(bid.getBidDate())); try { row.createCell(4).setCellValue(assetService.getAccPriceByLotIdHistory(asset.getId(), lotId).doubleValue()); } catch (NullPointerException e) { } } } List<AcceptPriceHistory> acceptPriceHistoryList = assetService.getDateAndAccPriceHistoryByAsset(asset.getId()); for (AcceptPriceHistory acceptPriceHistory : acceptPriceHistoryList) { numRow2++; XSSFRow row2 = sheet2.createRow(numRow2); row2.createCell(0).setCellValue(asset.getInn()); row2.createCell(1).setCellValue(CustomDateFormats.sdfshort.format(acceptPriceHistory.getDate())); row2.createCell(2).setCellValue(acceptPriceHistory.getAcceptedPrice().doubleValue()); } } String fileName = "C:\\projectFiles\\" + ("History " + CustomDateFormats.sdfshort.format(new Date()) + ".xlsx"); try (OutputStream fileOut = new FileOutputStream(fileName)) { wb.write(fileOut); } return fileName; } private String creditContract(Lot lot, String contract_year, String contract_address, String contract_protokol_num, String contract_protokol_date, String protocol_made_by, String subscriber) throws IOException { List<Credit> creditList = lotService.getCRDTSByLot(lot); InputStream fs = new FileInputStream("C:\\projectFiles\\Lot_Credits_Docs\\Dogovir.docx"); XWPFDocument docx = new XWPFDocument(fs); for (XWPFParagraph p : docx.getParagraphs()) { List<XWPFRun> runs = p.getRuns(); if (runs != null) { for (XWPFRun r : runs) { String text = r.getText(0); if (text != null) { StringBuilder tempText = new StringBuilder(); if (!creditList.isEmpty() && text.contains("knd")) { for (Credit credit : creditList) { tempText.append("№") .append(credit.getContractNum()) .append(" від ") .append(CustomDateFormats.sdfpoints.format(credit.getContractStart())) .append("року,"); } } r.setText(replaceRunText(text, String.valueOf(creditList.get(0).getContractNum()), contract_year, String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().shortDescription()), String.valueOf(contract_address), String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().getCustomerInn()), String.valueOf(contract_protokol_num), String.valueOf(contract_protokol_date), String.valueOf(protocol_made_by), String.valueOf(lot.getFactPrice()), tempText.toString(), subscriber), 0); } } } } for (XWPFTable tbl : docx.getTables()) { for (XWPFTableRow row : tbl.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { for (XWPFParagraph p : cell.getParagraphs()) { List<XWPFRun> runs = p.getRuns(); if (runs != null) { for (XWPFRun r : runs) { String text = r.getText(0); if (text != null) { StringBuilder tempText = new StringBuilder(); if (!creditList.isEmpty() && text.contains("knd")) { for (Credit credit : creditList) { tempText .append("№") .append(credit.getContractNum()) .append(" від ") .append(CustomDateFormats.sdfpoints.format(credit.getContractStart())) .append("року,"); } } r.setText(replaceRunText(text, String.valueOf(creditList.get(0).getContractNum()), contract_year, String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().shortDescription()), String.valueOf(contract_address), String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().getCustomerInn()), String.valueOf(contract_protokol_num), String.valueOf(contract_protokol_date), String.valueOf(protocol_made_by), String.valueOf(lot.getFactPrice()), tempText.toString(), subscriber), 0); } } } } } } } String fileName = "C:\\projectFiles\\Lot_Credits_Docs\\Dogovir_" + lot.getId() + ".docx"; OutputStream fileOut = new FileOutputStream(fileName); docx.write(fileOut); fileOut.close(); return fileName; } private String assetContract(Lot lot, String contract_year, String contract_address, String contract_protokol_num, String contract_protokol_date, String protocol_made_by, String subscriber, String pass_seria, String pass_num, String pass_vidano, String pass_vidano_date, String operates_basis, String account_bank, String bid_enter, String bid_client, String signer_bank_fio, String signer_bank_text) throws IOException { List<Asset> assetList = lotService.getAssetsByLot(lot); String bidDate; try { bidDate = CustomDateFormats.sdfpoints.format(lot.getBid().getBidDate()); } catch (NullPointerException e) { bidDate = "дата торгів"; } InputStream fs = new FileInputStream("C:\\projectFiles\\Lot_Assets_Docs\\Dogovir.docx"); XWPFDocument docx = new XWPFDocument(fs); List<XWPFTable> tableList = docx.getTables(); XWPFTable objTable = tableList.get(0); int i = assetList.size(); BigDecimal propertyPrice = new BigDecimal(0); XWPFTableRow totalRow = objTable.getRow(1); totalRow.getCell(0).setText("Основні засоби в кількості " + i + " одиниць загальною вартістю"); try { totalRow.getCell(1).setText(String.valueOf(lot.getFactPrice())); } catch (NullPointerException npl) { totalRow.getCell(1).setText("0"); } for (Asset asset : assetList) { if (asset.getFactPrice() != null && (asset.getAssetGroupCode().equals("101") || asset.getAssetGroupCode().equals("102"))) propertyPrice = propertyPrice.add(asset.getFactPrice()); XWPFTableRow newRow = objTable.insertNewTableRow(1); newRow.createCell().setText(i + "."); newRow.createCell().setText(asset.getInn()); newRow.createCell().setText(asset.getAsset_name()); newRow.createCell().setText(asset.getAsset_descr()); newRow.createCell().setText(asset.getAddress()); if (asset.getFactPrice() != null) newRow.createCell().setText(String.valueOf(asset.getFactPrice())); i--; } BigDecimal propertyPDV = propertyPrice.divide(new BigDecimal(6), 2, BigDecimal.ROUND_HALF_UP); BigDecimal notPropertyPrice; BigDecimal notPropertyPDV; try { notPropertyPrice = lot.getFactPrice().subtract(propertyPrice); notPropertyPDV = (lot.getFactPrice().divide(new BigDecimal(6), 2, BigDecimal.ROUND_HALF_UP)).subtract(propertyPDV); } catch (Exception npe) { notPropertyPrice = new BigDecimal(0); notPropertyPDV = new BigDecimal(0); } objTable.setInsideVBorder(XWPFTable.XWPFBorderType.SINGLE, 2, 0, "000000"); objTable.setInsideHBorder(XWPFTable.XWPFBorderType.SINGLE, 2, 0, "000000"); //objTable.removeRow(1); for (XWPFParagraph p : docx.getParagraphs()) { List<XWPFRun> runs = p.getRuns(); if (runs != null) { for (XWPFRun r : runs) { String text = r.getText(0); if (text != null) { r.setText(replaceRunTextAssets(text, bidDate, assetList.size(), lot.getLotNum(), contract_year, String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().shortDescription()), String.valueOf(contract_address), String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().getCustomerInn()), String.valueOf(contract_protokol_num), String.valueOf(contract_protokol_date), String.valueOf(protocol_made_by), String.valueOf(lot.getFactPrice()), subscriber, pass_seria, pass_num, pass_vidano, pass_vidano_date, operates_basis, account_bank, bid_enter, bid_client, signer_bank_fio, signer_bank_text, String.valueOf(propertyPrice), String.valueOf(propertyPDV), String.valueOf(notPropertyPrice), String.valueOf(notPropertyPDV)), 0); } } } } for (XWPFTable tbl : tableList) { for (XWPFTableRow row : tbl.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { for (XWPFParagraph p : cell.getParagraphs()) { List<XWPFRun> runs = p.getRuns(); if (runs != null) { for (XWPFRun r : runs) { String text = r.getText(0); if (text != null) { r.setText(replaceRunTextAssets(text, bidDate, assetList.size(), lot.getLotNum(), contract_year, String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().shortDescription()), String.valueOf(contract_address), String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().getCustomerInn()), String.valueOf(contract_protokol_num), String.valueOf(contract_protokol_date), String.valueOf(protocol_made_by), String.valueOf(lot.getFactPrice()), subscriber, pass_seria, pass_num, pass_vidano, pass_vidano_date, operates_basis, account_bank, bid_enter, bid_client, signer_bank_fio, signer_bank_text, String.valueOf(propertyPrice), String.valueOf(propertyPDV), String.valueOf(notPropertyPrice), String.valueOf(notPropertyPDV)), 0); } } } } } } } String fileName = "C:\\projectFiles\\Lot_Assets_Docs\\Dogovir_" + lot.getLotNum() + " (" + lot.getId() + ").docx"; OutputStream fileOut = new FileOutputStream(fileName); docx.write(fileOut); fileOut.close(); return fileName; } private String creditContract_Akt(Lot lot, String contract_year, String contract_address, String contract_protokol_num, String contract_protokol_date, String protocol_made_by, String subscriber) throws IOException { List<Credit> creditList = lotService.getCRDTSByLot(lot); InputStream fs = new FileInputStream("C:\\projectFiles\\Lot_Credits_Docs\\Dogovir_Akt.docx"); XWPFDocument docx = new XWPFDocument(fs); for (XWPFParagraph p : docx.getParagraphs()) { List<XWPFRun> runs = p.getRuns(); if (runs != null) { for (XWPFRun r : runs) { String text = r.getText(0); if (text != null) { String tempText = ""; if (!creditList.isEmpty() && text.contains("knd")) { for (Credit credit : creditList) { tempText += "№" + credit.getContractNum() + " від " + CustomDateFormats.sdfpoints.format(credit.getContractStart()) + "року,"; } } r.setText(replaceRunText(text, String.valueOf(creditList.get(0).getContractNum()), contract_year, String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().shortDescription()), String.valueOf(contract_address), String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().getCustomerInn()), String.valueOf(contract_protokol_num), String.valueOf(contract_protokol_date), String.valueOf(protocol_made_by), String.valueOf(lot.getFactPrice()), tempText, subscriber), 0); } } } } List<XWPFTable> tableList = docx.getTables(); for (XWPFTable tbl : tableList) { for (XWPFTableRow row : tbl.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { for (XWPFParagraph p : cell.getParagraphs()) { List<XWPFRun> runs = p.getRuns(); if (runs != null) { for (XWPFRun r : runs) { String text = r.getText(0); if (text != null) { String tempText = ""; if (!creditList.isEmpty() && text.contains("knd")) { for (Credit credit : creditList) { tempText += "№" + credit.getContractNum() + " від " + CustomDateFormats.sdfpoints.format(credit.getContractStart()) + "року,"; } } r.setText(replaceRunText(text, String.valueOf(creditList.get(0).getContractNum()), contract_year, String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().shortDescription()), String.valueOf(contract_address), String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().getCustomerInn()), String.valueOf(contract_protokol_num), String.valueOf(contract_protokol_date), String.valueOf(protocol_made_by), String.valueOf(lot.getFactPrice()), tempText, subscriber), 0); } } } } } } } XWPFTable objTable = tableList.get(0); int i = 0; for (Credit credit : creditList) { i++; String creditStartDate = ""; try { creditStartDate = CustomDateFormats.sdfpoints.format(credit.getContractStart()); } catch (NullPointerException e) { } XWPFTableRow newRow = objTable.createRow(); newRow.getCell(0).setText(i + "."); newRow.getCell(1).setText("Кредитний договір №" + credit.getContractNum() + " від " + creditStartDate + " року"); } objTable.setInsideVBorder(XWPFTable.XWPFBorderType.SINGLE, 2, 0, "000000"); objTable.setInsideHBorder(XWPFTable.XWPFBorderType.SINGLE, 2, 0, "000000"); objTable.removeRow(1); String fileName = "C:\\projectFiles\\Lot_Credits_Docs\\Dogovir_Akt_" + lot.getId() + ".docx"; OutputStream fileOut = new FileOutputStream(fileName); docx.write(fileOut); fileOut.close(); return fileName; } private String assetContract_Akt(Lot lot, String contract_year, String contract_address, String contract_protokol_num, String contract_protokol_date, String protocol_made_by, String subscriber, String pass_seria, String pass_num, String pass_vidano, String pass_vidano_date, String operates_basis, String account_bank, String bid_enter, String bid_client, String signer_bank_fio, String signer_bank_text) throws IOException { List<Asset> assetList = lotService.getAssetsByLot(lot); String bidDate; try { bidDate = CustomDateFormats.sdfpoints.format(lot.getBid().getBidDate()); } catch (NullPointerException e) { bidDate = "дата торгів"; } InputStream fs = new FileInputStream("C:\\projectFiles\\Lot_Assets_Docs\\Dogovir_Akt.docx"); XWPFDocument docx = new XWPFDocument(fs); List<XWPFTable> tableList = docx.getTables(); XWPFTable objTable = tableList.get(0); int i = assetList.size(); XWPFTableRow totalRow = objTable.getRow(1); totalRow.getCell(0).setText("Основні засоби в кількості " + i + " одиниць загальною вартістю"); try { totalRow.getCell(1).setText(String.valueOf(lot.getFactPrice())); } catch (NullPointerException npl) { totalRow.getCell(1).setText("0"); } for (Asset asset : assetList) { XWPFTableRow newRow = objTable.insertNewTableRow(1); newRow.createCell().setText(i + "."); newRow.createCell().setText(asset.getInn()); newRow.createCell().setText(asset.getAsset_name()); newRow.createCell().setText(asset.getAsset_descr()); newRow.createCell().setText(asset.getAddress()); if (asset.getFactPrice() != null) newRow.createCell().setText(String.valueOf(asset.getFactPrice())); i--; } // objTable.setInsideVBorder(XWPFTable.XWPFBorderType.SINGLE, 2, 0, "000000"); objTable.setInsideHBorder(XWPFTable.XWPFBorderType.SINGLE, 2, 0, "000000"); //objTable.removeRow(1); for (XWPFParagraph p : docx.getParagraphs()) { List<XWPFRun> runs = p.getRuns(); if (runs != null) { for (XWPFRun r : runs) { String text = r.getText(0); if (text != null) { r.setText(replaceRunTextAssets(text, bidDate, assetList.size(), lot.getLotNum(), contract_year, String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().shortDescription()), String.valueOf(contract_address), String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().getCustomerInn()), String.valueOf(contract_protokol_num), String.valueOf(contract_protokol_date), String.valueOf(protocol_made_by), String.valueOf(lot.getFactPrice()), subscriber, pass_seria, pass_num, pass_vidano, pass_vidano_date, operates_basis, account_bank, bid_enter, bid_client, signer_bank_fio, signer_bank_text, "0", "0", "0", "0"), 0); } } } } for (XWPFTable tbl : tableList) { for (XWPFTableRow row : tbl.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { for (XWPFParagraph p : cell.getParagraphs()) { List<XWPFRun> runs = p.getRuns(); if (runs != null) { for (XWPFRun r : runs) { String text = r.getText(0); if (text != null) { r.setText(replaceRunTextAssets(text, bidDate, assetList.size(), lot.getLotNum(), contract_year, String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().shortDescription()), String.valueOf(contract_address), String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().getCustomerInn()), String.valueOf(contract_protokol_num), String.valueOf(contract_protokol_date), String.valueOf(protocol_made_by), String.valueOf(lot.getFactPrice()), subscriber, pass_seria, pass_num, pass_vidano, pass_vidano_date, operates_basis, account_bank, bid_enter, bid_client, signer_bank_fio, signer_bank_text, "0", "0", "0", "0"), 0); } } } } } } } String fileName = "C:\\projectFiles\\Lot_Assets_Docs\\Dogovir_Akt_" + lot.getLotNum() + " (" + lot.getId() + ").docx"; OutputStream fileOut = new FileOutputStream(fileName); docx.write(fileOut); fileOut.close(); return fileName; } private String creditContract_Dodatok1(Lot lot, String contract_year, String contract_address, String contract_protokol_num, String contract_protokol_date, String protocol_made_by, String subscriber) throws IOException { List<Credit> creditList = lotService.getCRDTSByLot(lot); InputStream fs = new FileInputStream("C:\\projectFiles\\Lot_Credits_Docs\\Dogovir_Dodatok1.docx"); XWPFDocument docx = new XWPFDocument(fs); for (XWPFParagraph p : docx.getParagraphs()) { List<XWPFRun> runs = p.getRuns(); if (runs != null) { for (XWPFRun r : runs) { String text = r.getText(0); if (text != null) { String tempText = ""; if (!creditList.isEmpty() && text.contains("knd")) { for (Credit credit : creditList) { tempText += "№" + credit.getContractNum() + " від " + CustomDateFormats.sdfpoints.format(credit.getContractStart()) + "року,"; } } r.setText(replaceRunText(text, String.valueOf(creditList.get(0).getContractNum()), contract_year, String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().shortDescription()), String.valueOf(contract_address), String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().getCustomerInn()), String.valueOf(contract_protokol_num), String.valueOf(contract_protokol_date), String.valueOf(protocol_made_by), String.valueOf(lot.getFactPrice()), tempText, subscriber), 0); } } } } List<XWPFTable> tableList = docx.getTables(); for (XWPFTable tbl : tableList) { for (XWPFTableRow row : tbl.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { for (XWPFParagraph p : cell.getParagraphs()) { List<XWPFRun> runs = p.getRuns(); if (runs != null) { for (XWPFRun r : runs) { String text = r.getText(0); if (text != null) { String tempText = ""; if (!creditList.isEmpty() && text.contains("knd")) { for (Credit credit : creditList) { tempText += "№" + credit.getContractNum() + " від " + CustomDateFormats.sdfpoints.format(credit.getContractStart()) + "року,"; } } r.setText(replaceRunText(text, String.valueOf(creditList.get(0).getContractNum()), contract_year, String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().shortDescription()), String.valueOf(contract_address), String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().getCustomerInn()), String.valueOf(contract_protokol_num), String.valueOf(contract_protokol_date), String.valueOf(protocol_made_by), String.valueOf(lot.getFactPrice()), tempText, subscriber), 0); } } } } } } } XWPFTable objTable = tableList.get(0); int i = creditList.size(); for (Credit credit : creditList) { XWPFTableRow newRow = objTable.insertNewTableRow(2); newRow.createCell().setText(i + "."); newRow.createCell().setText("Позичальник – " + credit.getFio() + ", РНОКПП " + credit.getInn()); String creditStartDate = ""; try { creditStartDate = CustomDateFormats.sdfpoints.format(credit.getContractStart()); } catch (NullPointerException e) { } newRow.createCell().setText("Кредитний договір " + credit.getContractNum() + " від " + creditStartDate); i--; } objTable.removeRow(1); String fileName = "C:\\projectFiles\\Lot_Credits_Docs\\Dogovir_Dodatok1_" + lot.getId() + ".docx"; try (OutputStream fileOut = new FileOutputStream(fileName)) { docx.write(fileOut); } return fileName; } private String creditContract_Dodatok2(Lot lot, String contract_year, String contract_address, String contract_protokol_num, String contract_protokol_date, String protocol_made_by, String subscriber) throws IOException { List<Credit> creditList = lotService.getCRDTSByLot(lot); InputStream fs = new FileInputStream("C:\\projectFiles\\Lot_Credits_Docs\\Dogovir_Dodatok2.docx"); XWPFDocument docx = new XWPFDocument(fs); for (XWPFParagraph p : docx.getParagraphs()) { List<XWPFRun> runs = p.getRuns(); if (runs != null) { for (XWPFRun r : runs) { String text = r.getText(0); if (text != null) { StringBuilder tempText = new StringBuilder(); if (!creditList.isEmpty() && text.contains("knd")) { for (Credit credit : creditList) { tempText .append("№") .append(credit.getContractNum()) .append(" від ") .append(CustomDateFormats.sdfpoints.format(credit.getContractStart())) .append("року,"); } } r.setText(replaceRunText(text, String.valueOf(creditList.get(0).getContractNum()), contract_year, String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().shortDescription()), String.valueOf(contract_address), String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().getCustomerInn()), String.valueOf(contract_protokol_num), String.valueOf(contract_protokol_date), String.valueOf(protocol_made_by), String.valueOf(lot.getFactPrice()), tempText.toString(), subscriber), 0); } } } } List<XWPFTable> tableList = docx.getTables(); for (XWPFTable tbl : tableList) { for (XWPFTableRow row : tbl.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { for (XWPFParagraph p : cell.getParagraphs()) { List<XWPFRun> runs = p.getRuns(); if (runs != null) { for (XWPFRun r : runs) { String text = r.getText(0); if (text != null) { String tempText = ""; if (!creditList.isEmpty() && text.contains("knd")) { for (Credit credit : creditList) { tempText += "№" + credit.getContractNum() + " від " + CustomDateFormats.sdfpoints.format(credit.getContractStart()) + "року,"; } } r.setText(replaceRunText(text, String.valueOf(creditList.get(0).getContractNum()), contract_year, String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().shortDescription()), String.valueOf(contract_address), String.valueOf((lot.getCustomer() == null) ? "" : lot.getCustomer().getCustomerInn()), String.valueOf(contract_protokol_num), String.valueOf(contract_protokol_date), String.valueOf(protocol_made_by), String.valueOf(lot.getFactPrice()), tempText, subscriber), 0); } } } } } } } String fileName = "C:\\projectFiles\\Lot_Credits_Docs\\Dogovir_Dodatok2_" + lot.getId() + ".docx"; try (OutputStream fileOut = new FileOutputStream(fileName)) { docx.write(fileOut); } return fileName; } private String makeContract(Long lotId, String contract_year, String contract_address, String contract_protokol_num, String contract_protokol_date, String protocol_made_by, String subscriber) throws Exception { Lot lot = lotService.getLot(lotId); return creditContract(lot, contract_year, contract_address, contract_protokol_num, contract_protokol_date, protocol_made_by, subscriber); } private String makeAssetContract(Long lotId, String contract_year, String contract_address, String contract_protokol_num, String contract_protokol_date, String protocol_made_by, String subscriber, String pass_seria, String pass_num, String pass_vidano, String pass_vidano_date, String operates_basis, String account_bank, String bid_enter, String bid_client, String signer_bank) throws Exception { Lot lot = lotService.getLot(lotId); SignerBank signerBank; switch (signer_bank) { case "1": signerBank = SignerBank.Kulibaba; break; case "2": signerBank = SignerBank.Glushchenko; break; case "3": signerBank = SignerBank.Strukova; break; default: signerBank = SignerBank.Glushchenko; break; } return assetContract(lot, contract_year, contract_address, contract_protokol_num, contract_protokol_date, protocol_made_by, subscriber, pass_seria, pass_num, pass_vidano, pass_vidano_date, operates_basis, account_bank, bid_enter, bid_client, signerBank.getFio(), signerBank.getText());// assetContract(); } private String makeContract_Akt(Long lotId, String contract_year, String contract_address, String contract_protokol_num, String contract_protokol_date, String protocol_made_by, String subscriber) throws Exception { Lot lot = lotService.getLot(lotId); return creditContract_Akt(lot, contract_year, contract_address, contract_protokol_num, contract_protokol_date, protocol_made_by, subscriber); } private String makeAssetContract_Akt(Long lotId, String contract_year, String contract_address, String contract_protokol_num, String contract_protokol_date, String protocol_made_by, String subscriber, String pass_seria, String pass_num, String pass_vidano, String pass_vidano_date, String operates_basis, String account_bank, String bid_enter, String bid_client, String signer_bank) throws Exception { Lot lot = lotService.getLot(lotId); SignerBank signerBank; switch (signer_bank) { case "1": signerBank = SignerBank.Kulibaba; break; case "2": signerBank = SignerBank.Glushchenko; break; case "3": signerBank = SignerBank.Strukova; break; default: signerBank = SignerBank.Glushchenko; break; } return assetContract_Akt(lot, contract_year, contract_address, contract_protokol_num, contract_protokol_date, protocol_made_by, subscriber, pass_seria, pass_num, pass_vidano, pass_vidano_date, operates_basis, account_bank, bid_enter, bid_client, signerBank.getFio(), signerBank.getText()); } private String makeContract_Dodatok1(Long lotId, String contract_year, String contract_address, String contract_protokol_num, String contract_protokol_date, String protocol_made_by, String subscriber) throws Exception { Lot lot = lotService.getLot(lotId); return creditContract_Dodatok1(lot, contract_year, contract_address, contract_protokol_num, contract_protokol_date, protocol_made_by, subscriber); } private String makeContract_Dodatok2(Long lotId, String contract_year, String contract_address, String contract_protokol_num, String contract_protokol_date, String protocol_made_by, String subscriber) throws Exception { Lot lot = lotService.getLot(lotId); return creditContract_Dodatok2(lot, contract_year, contract_address, contract_protokol_num, contract_protokol_date, protocol_made_by, subscriber); } @RequestMapping(value = "/lotList", method = RequestMethod.GET) private @ResponseBody List<Lot> getLots() { return lotService.getLots(); } @RequestMapping(value = "/exchanges", method = RequestMethod.GET) private @ResponseBody List<Exchange> jsonGetExchanges() { return exchangeService.getAllExchanges(); } @RequestMapping(value = "/lotDel", method = RequestMethod.POST) private @ResponseBody int deleteLot(@RequestParam("lotId") String lotId) { boolean isitDel = lotService.delLot(Long.parseLong(lotId)); if (isitDel) return 1; else return 0; } @RequestMapping(value = "/setLotSold", method = RequestMethod.POST) private @ResponseBody String setLotSold(HttpSession session, @RequestParam("lotID") String lotId) { String login = (String) session.getAttribute("userId"); Lot lot = lotService.getLot(Long.parseLong(lotId)); lot.setItSold(true); boolean isitUpdated = lotService.updateLot(login, lot); if (isitUpdated) return "1"; else return "0"; } @RequestMapping(value = "/statusChanger", method = RequestMethod.POST) private @ResponseBody String changeStatus (HttpSession session, @RequestParam("lotID") String lotId, @RequestParam("status") String status) { String login = (String) session.getAttribute("userId"); Lot lot = lotService.getLot(Long.parseLong(lotId)); lot.setWorkStage(status); lotService.updateLot(login, lot); return "1"; } @RequestMapping(value = "/regions", method = RequestMethod.POST) private @ResponseBody List<String> getAllRegs() { List<String> regList; regList = creditService.getRegions(); return regList; } @RequestMapping(value = "/crType", method = RequestMethod.POST) private @ResponseBody List<String> getAllTypes() { List<String> typesList; typesList = creditService.getTypes(); return typesList; } @RequestMapping(value = "/getCurs", method = RequestMethod.POST) private @ResponseBody List<String> getAllCurr() { List<String> currList; currList = creditService.getCurrencys(); return currList; } @RequestMapping(value = "/countSumByLot", method = RequestMethod.POST) private @ResponseBody List<String> countSumByLot(@RequestParam("lotId") Long idLot) { List<String> countSumList = new ArrayList<>(); Lot lot = lotService.getLot(idLot); Long count = lotService.lotCount(lot); BigDecimal sum = lotService.lotSum(lot); if (count != null) countSumList.add(count.toString()); if (sum != null) countSumList.add(sum.toString()); return countSumList; } @RequestMapping(value = "/paymentsSumByLot", method = RequestMethod.POST) private @ResponseBody BigDecimal paymentsSum(@RequestParam("lotId") Long idLot) { return lotService.paymentsSumByLot(lotService.getLot(idLot)); } @RequestMapping(value = "/paymentsByLot", method = RequestMethod.POST) private @ResponseBody List<Pay> paymentsByLot(@RequestParam("lotId") Long idLot) { Lot lot = lotService.getLot(idLot); return lotService.paymentsByLot(lot); } @RequestMapping(value = "/addPayToLot/{lotId}", method = RequestMethod.POST) private @ResponseBody String addPayToLot(HttpSession session, @PathVariable("lotId") Long idLot, @RequestParam("payDate") String payDate, @RequestParam("pay") BigDecimal pay, @RequestParam("paySource") String paySource) { String login = (String) session.getAttribute("userId"); Date date; try { date = CustomDateFormats.sdfshort.parse(payDate); } catch (ParseException e) { return "0"; } Lot lot = lotService.getLot(idLot); Pay payment = new Pay(lot, date, pay, paySource); payService.createPay(payment); BigDecimal totalLotSum = paySource.equals("Біржа") ? payService.sumByLotFromBid(idLot) : payService.sumByLotFromCustomer(idLot); if (lot.getLotType() == 1) { List<Asset> assetsByLot = lotService.getAssetsByLot(idLot); BigDecimal lotFactPrice = lot.getFactPrice(); BigDecimal assetsTotalPays = new BigDecimal(0.00); for (int i = 0; i < assetsByLot.size(); i++) { Asset asset = assetsByLot.get(i); BigDecimal coeff = MathCalculationUtil.getCoefficient(asset.getFactPrice(), lotFactPrice); //виправити!!!! BigDecimal payByAsset = (i == assetsByLot.size() - 1) ? totalLotSum.subtract(assetsTotalPays) : totalLotSum.multiply(coeff).setScale(2, BigDecimal.ROUND_HALF_UP); if (paySource.equals("Біржа")) { asset.setPaysBid(payByAsset); asset.setBidPayDate(date); } else { asset.setPaysCustomer(payByAsset); asset.setCustomerPayDate(date); } assetsTotalPays = assetsTotalPays.add(payByAsset); assetService.updateAsset(login, asset); } return "1"; } else if (lot.getLotType() == 0) { List<Credit> creditsByLot = lotService.getCRDTSByLot(lot); BigDecimal lotFactPrice = lot.getFactPrice(); BigDecimal assetsTotalPays = new BigDecimal(0.00); for (int i = 0; i < creditsByLot.size(); i++) { Credit credit = creditsByLot.get(i); BigDecimal coeff = MathCalculationUtil.getCoefficient(credit.getFactPrice(), lotFactPrice); BigDecimal payByAsset = (i == creditsByLot.size() - 1) ? totalLotSum.subtract(assetsTotalPays) : totalLotSum.multiply(coeff).setScale(2, BigDecimal.ROUND_HALF_UP); if (paySource.equals("Біржа")) { credit.setPaysBid(payByAsset); credit.setBidPayDate(date); } else { credit.setPaysCustomer(payByAsset); credit.setCustomerPayDate(date); } assetsTotalPays = assetsTotalPays.add(payByAsset); creditService.updateCredit(login, credit); } return "1"; } else return "0"; } @RequestMapping(value = "/delPay/{lotId}/{payId}", method = RequestMethod.POST) private @ResponseBody String delPay(HttpSession session, @PathVariable("payId") Long payId, @PathVariable("lotId") Long lotId) { String login = (String) session.getAttribute("userId"); Pay pay = payService.getPay(payId); Lot lot = lotService.getLot(lotId); pay.setHistoryLotId(pay.getLotId()); pay.setLotId(null); payService.updatePay(pay); BigDecimal totalLotSum = pay.getPaySource().equals("Біржа") ? payService.sumByLotFromBid(lotId) : payService.sumByLotFromCustomer(lotId); if (totalLotSum == null) totalLotSum = new BigDecimal(0); if (lot.getLotType() == 1) { List<Asset> assetsByLot = lotService.getAssetsByLot(lot); BigDecimal lotFactPrice = lot.getFactPrice(); BigDecimal assetsTotalPays = new BigDecimal(0.00); for (int i = 0; i < assetsByLot.size(); i++) { Asset asset = assetsByLot.get(i); BigDecimal coeff = MathCalculationUtil.getCoefficient(asset.getFactPrice(), lotFactPrice); //виправити!!!! BigDecimal payByAsset = (i == assetsByLot.size() - 1) ? totalLotSum.subtract(assetsTotalPays) : totalLotSum.multiply(coeff).setScale(2, BigDecimal.ROUND_HALF_UP); if (pay.getPaySource().equals("Біржа")) { asset.setPaysBid(payByAsset); } else { asset.setPaysCustomer(payByAsset); } assetsTotalPays = assetsTotalPays.add(payByAsset); assetService.updateAsset(login, asset); } return "1"; } else if (lot.getLotType() == 0) { List<Credit> creditsByLot = lotService.getCRDTSByLot(lot); BigDecimal lotFactPrice = lot.getFactPrice(); BigDecimal assetsTotalPays = new BigDecimal(0.00); for (int i = 0; i < creditsByLot.size(); i++) { Credit credit = creditsByLot.get(i); BigDecimal coeff = MathCalculationUtil.getCoefficient(credit.getFactPrice(), lotFactPrice); BigDecimal payByAsset = (i == creditsByLot.size() - 1) ? totalLotSum.subtract(assetsTotalPays) : totalLotSum.multiply(coeff).setScale(2, BigDecimal.ROUND_HALF_UP); if (pay.getPaySource().equals("Біржа")) { credit.setPaysBid(payByAsset); } else { credit.setPaysCustomer(payByAsset); } assetsTotalPays = assetsTotalPays.add(payByAsset); creditService.updateCredit(login, credit); } return "1"; } else return "0"; } @RequestMapping(value = "/setLotToPrint", method = RequestMethod.GET) private @ResponseBody String setLotsToPrint(@RequestParam("objId") String lotId, Model model) { model.addAttribute("objIdToDownload", lotId); return "1"; } @RequestMapping(value = "/setDocToDownload", method = RequestMethod.GET) private @ResponseBody String setDocToDownload(@RequestParam("objType") String objType, @RequestParam("objId") String objId, @RequestParam("docName") String docName, Model model) { model.addAttribute("objIdToDownload", objId); model.addAttribute("docName", docName); model.addAttribute("docType", objType); return "1"; } @RequestMapping(value = "/getReport/{reportNum}/{start}/{end}", method = RequestMethod.GET) public void getReport(HttpServletResponse response, @PathVariable String start, @PathVariable String end, @PathVariable int reportNum) throws IOException { File file = null; if (reportNum == 4) { file = reportService.fillAssTab(); } Date startDate = null; Date endDate = null; try { startDate = CustomDateFormats.sdfshort.parse(start); } catch (ParseException e) { } try { endDate = CustomDateFormats.sdfshort.parse(end); } catch (ParseException e) { } List<Credit> crList = creditService.getCredits_SuccessBids(startDate, endDate); if (reportNum == 3) { file = reportService.fillSoldedCrdTab(crList); } else if (reportNum == 1) { file = reportService.makeDodatok(assetService.findAllSuccessBids(startDate, endDate), crList, start, end); } else if (reportNum == 2) { file = new File("C:\\projectFiles\\Dodatok 2_14.xls"); } else if (reportNum == 5) { file = reportService.makePaymentsReport(payService.getPaysByDates(startDate, endDate), start, end); } else if (reportNum == 6) { file = reportService.makeBidsSumReport(lotService.getLotsHistoryByBidDates(startDate, endDate), lotService.getLotsHistoryAggregatedByBid(startDate, endDate)); } else if (reportNum == 7) { } else if (reportNum == 8) { file = reportService.fillCreditsReestr(lotService.getSoldedWithoutDealLots(0, startDate, endDate)); } response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); try (InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } } finally { file.delete(); } } /*@RequestMapping(value = "/getReport/{reportNum}/{start}/{end}", method = RequestMethod.GET) public void getReport(HttpServletResponse response, @PathVariable String start, @PathVariable String end, @PathVariable int reportNum) throws IOException { String reportPath = ""; if (reportNum == 4) { try { reportPath = fillAssTab(); } catch (IOException e) { e.printStackTrace(); } } *//*if(reportNum==3){ try { reportPath=fillCrdTab(creditService.getCreditsByPortion(1)); } catch (IOException e) { e.printStackTrace(); } }*//* Date startDate = null; Date endDate = null; try { startDate = CustomDateFormats.sdfshort.parse(start); } catch (ParseException e) { } try { endDate = CustomDateFormats.sdfshort.parse(end); } catch (ParseException e) { } List<Asset> assetList = assetService.findAllSuccessBids(startDate, endDate); List<Credit> crList = creditService.getCredits_SuccessBids(startDate, endDate); if (reportNum == 3) { try { reportPath = fillSoldedCrdTab(crList); } catch (IOException e) { e.printStackTrace(); } } else if (reportNum == 1) { try { reportPath = reportService.makeDodatok(assetList, crList, start, end); } catch (IOException e) { e.printStackTrace(); } } else if (reportNum == 2) { reportPath = "C:\\projectFiles\\Dodatok 2_14.xls"; } else if (reportNum == 5) { reportPath = makePaymentsReport(payService.getPaysByDates(startDate, endDate), start, end); } else if (reportNum == 6) { try { reportPath = makeBidsSumReport(lotService.getLotsHistoryByBidDates(startDate, endDate), lotService.getLotsHistoryAggregatedByBid(startDate, endDate)); } catch (IOException e) { e.printStackTrace(); } } else if (reportNum == 7) { *//*try { reportPath = makeBidsSumReport(lotService.getLotsHistoryByBidDates(startDate, endDate), lotService.getLotsHistoryAggregatedByBid(startDate, endDate)); } catch (IOException e) { e.printStackTrace(); }*//* } else if (reportNum == 8) { reportPath = fillCreditsReestr(lotService.getSoldedWithoutDealLots(0, startDate, endDate)); } File file = new File(reportPath); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); try(InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()){ byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } } finally { file.delete(); } }*/ @RequestMapping(value = "/getSalesReport/{portion}/{start}/{end}", method = RequestMethod.GET) public void getSalesReport(HttpServletResponse response, @PathVariable String start, @PathVariable String end, @PathVariable int portion) throws IOException { String reportPath = ""; Date startDate = null; Date endDate = null; try { startDate = CustomDateFormats.sdfshort.parse(start); } catch (ParseException e) { } try { endDate = CustomDateFormats.sdfshort.parse(end); } catch (ParseException e) { } List<Asset> assetList = assetService.findAllSuccessBids(startDate, endDate, portion); List<Credit> crList = creditService.getCredits_SuccessBids(startDate, endDate); File file = reportService.makeDodatok(assetList, crList, start, end); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); try (InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } } finally { file.delete(); } } @RequestMapping(value = "/getFileNames", method = RequestMethod.POST) private @ResponseBody List<String> getFileNames(@RequestParam("objId") String objId, @RequestParam("objType") String objType) { List<String> fileList = new ArrayList<>(); File[] fList; File F = null; if (objType.equals("lot")) F = new File(documentsPath + objId); if (objType.equals("bid")) F = new File(bidDocumentsPath + objId); try { fList = F.listFiles(); for (File aFList : fList) { if (aFList.isFile()) fileList.add(aFList.getName()); } } catch (NullPointerException e) { return fileList; } return fileList; } @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) private @ResponseBody String uploadLotFile(@RequestParam("file") MultipartFile file, @RequestParam("objId") Long objId, @RequestParam("objType") String objType, HttpServletResponse response, HttpServletRequest request) { response.setCharacterEncoding("UTF-8"); try { request.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { } String name = null; if (!file.isEmpty()) try { byte[] bytes = file.getBytes(); name = file.getOriginalFilename(); String rootPath = null; if (objType.equals("lot")) rootPath = documentsPath; if (objType.equals("bid")) rootPath = bidDocumentsPath; File dir = new File(rootPath + File.separator + objId); if (!dir.exists()) { dir.mkdirs(); } File uploadedFile = new File(dir.getAbsolutePath() + File.separator + name); try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(uploadedFile))) { stream.write(bytes); } return "File " + name + " zavantajeno"; } catch (Exception e) { return "Download error " + name + " => " + e.getMessage(); } else { return "Error. File not choosen."; } } @RequestMapping(value = "/uploadIdFileForHistory", method = RequestMethod.POST) private @ResponseBody String uploadIdFileForHistory(@RequestParam("file") MultipartFile multipartFile, Model model) throws IOException { List<Asset> assetList = new ArrayList<>(); if (!multipartFile.isEmpty()) { File file = reportService.getTempFile(multipartFile); XSSFWorkbook wb; try { wb = new XSSFWorkbook(file); XSSFSheet sheet = wb.getSheetAt(0); Iterator rows = sheet.rowIterator(); while (rows.hasNext()) { XSSFRow row = (XSSFRow) rows.next(); XSSFCell cell = row.getCell(0); DataFormatter formatter = new DataFormatter(); String inn = formatter.formatCellValue(cell); assetList.addAll(assetService.getAllAssetsByInNum(inn)); } } catch (Exception e) { return "4"; } String reportPath = makeHistoryReportByAssets(assetList); model.addAttribute("reportPath", reportPath); return "1"; } else return "0"; } @RequestMapping(value = "/uploadIdFile", method = RequestMethod.POST) private @ResponseBody List uploadIdFile(@RequestParam("file") MultipartFile multipartFile, @RequestParam("idType") int idType) throws IOException { File file = reportService.getTempFile(multipartFile); if (idType == 1) { List<Asset> assetList = new ArrayList<>(); if (!multipartFile.isEmpty()) { XSSFWorkbook wb; try { wb = new XSSFWorkbook(file); } catch (Exception e) { return null; } XSSFSheet sheet = wb.getSheetAt(0); Iterator rows = sheet.rowIterator(); while (rows.hasNext()) { XSSFRow row = (XSSFRow) rows.next(); XSSFCell cell = row.getCell(0); DataFormatter formatter = new DataFormatter(); String inn = formatter.formatCellValue(cell); assetList.addAll(assetService.getAllAssetsByInNum(inn)); } return assetList; } else return null; } if (idType == 0) { List<Credit> creditList = new ArrayList<>(); if (!multipartFile.isEmpty()) { XSSFWorkbook wb = null; try { wb = new XSSFWorkbook(file); } catch (InvalidFormatException e) { System.out.println("invalid Format"); } XSSFSheet sheet = wb.getSheetAt(0); Iterator rows = sheet.rowIterator(); while (rows.hasNext()) { XSSFRow row = (XSSFRow) rows.next(); Double idBars = row.getCell(0).getNumericCellValue(); creditList.addAll(creditService.getCreditsByIdBars(idBars.longValue())); } return creditList; } else return null; } else return null; } @RequestMapping(value = "/createLotsByFile", method = RequestMethod.POST) private @ResponseBody String creteLotsByFile(HttpSession session, @RequestParam("file") MultipartFile multipartFile, @RequestParam("idType") int idType) throws IOException { String login = (String) session.getAttribute("userId"); File file = reportService.getTempFile(multipartFile); if (idType == 1) { Map<String, List<String>> lotMap = new HashMap<>(); if (!multipartFile.isEmpty()) { XSSFWorkbook wb; try { wb = new XSSFWorkbook(file); } catch (Exception e) { return null; } XSSFSheet sheet = wb.getSheetAt(0); Iterator rows = sheet.rowIterator(); while (rows.hasNext()) { XSSFRow row = (XSSFRow) rows.next(); String inn = row.getCell(0).getStringCellValue(); String idLot = String.valueOf(row.getCell(1).getNumericCellValue()); if (lotMap.containsKey(idLot)) { lotMap.get(idLot).add(inn); } else { List<String> idList = new ArrayList<>(); idList.add(inn); lotMap.put(idLot, idList); } } for(List<String> assetsInn: lotMap.values()){ lotService.createAssetLot(login, assetsInn); } return "Successfully Created "+lotMap.size()+" lots!"; } else return "File is empty"; } if (idType == 0) { Map<String, List<Long>> lotMap = new HashMap<>(); if (!multipartFile.isEmpty()) { XSSFWorkbook wb = null; try { wb = new XSSFWorkbook(file); } catch (InvalidFormatException e) { System.out.println("invalid Format"); } XSSFSheet sheet = wb.getSheetAt(0); Iterator rows = sheet.rowIterator(); while (rows.hasNext()) { XSSFRow row = (XSSFRow) rows.next(); Double nd = row.getCell(0).getNumericCellValue(); String idLot = String.valueOf(row.getCell(1).getNumericCellValue()); Long idBars = nd.longValue(); if (lotMap.containsKey(idLot)) { lotMap.get(idLot).add(idBars); } else { List<Long> idList = new ArrayList<>(); idList.add(idBars); lotMap.put(idLot, idList); } } for(List<Long> creditsId: lotMap.values()){ lotService.createCreditLot(login, creditsId); } return "Successfully Created "+lotMap.size()+" lots!"; } else return "Error"; } else return "Error type"; } @RequestMapping(value = "/setAccPriceByFile", method = RequestMethod.POST) private @ResponseBody String setAccPriceByFile(HttpSession session, @RequestParam("file") MultipartFile multipartFile, @RequestParam("idType") int idType) throws IOException { String login = (String) session.getAttribute("userId"); File file = reportService.getTempFile(multipartFile); if (idType == 1) { List<Asset> assetList; if (!multipartFile.isEmpty()) { XSSFWorkbook wb; try { wb = new XSSFWorkbook(file); } catch (Exception e) { return null; } XSSFSheet sheet = wb.getSheetAt(0); Iterator rows = sheet.rowIterator(); while (rows.hasNext()) { XSSFRow row = (XSSFRow) rows.next(); XSSFCell cell = row.getCell(0); DataFormatter formatter = new DataFormatter(); String inn = formatter.formatCellValue(cell); Double accPrice = row.getCell(1).getNumericCellValue(); assetList = assetService.getAllAssetsByInNum(inn); assetList.forEach(asset -> asset.setAcceptPrice(BigDecimal.valueOf(accPrice))); assetList.forEach(asset -> assetService.updateAsset(login, asset)); } return "1"; } else return "0"; } if (idType == 0) { if (!multipartFile.isEmpty()) { XSSFWorkbook wb; try { wb = new XSSFWorkbook(file); XSSFSheet sheet = wb.getSheetAt(0); Iterator rows = sheet.rowIterator(); while (rows.hasNext()) { XSSFRow row = (XSSFRow) rows.next(); XSSFCell cell = row.getCell(0); DataFormatter formatter = new DataFormatter(); String inn = formatter.formatCellValue(cell); Double accPrice = row.getCell(1).getNumericCellValue(); List<Credit> creditList = creditService.getCreditsByIdBars(Long.parseLong(inn)); creditList.forEach(credit -> credit.setAcceptPrice(BigDecimal.valueOf(accPrice))); creditList.forEach(credit -> creditService.updateCredit(login, credit)); } return "1"; } catch (FileNotFoundException fnfe) { return "0"; } catch (IOException ioe) { return "0"; } catch (Exception e) { return "0"; } } else return "0"; } else return "0"; } @RequestMapping(value = "/{bidN}/setLotsToBid", method = RequestMethod.POST) private @ResponseBody String setLotsToBid(HttpSession session, @RequestParam("file_lots") MultipartFile multipartFile, @PathVariable("bidN") long bidId) /*@RequestParam("bidN") long bidId)*/ throws IOException { Bid bid = bidService.getBid(bidId); System.out.println(bid); String login = (String) session.getAttribute("userId"); File file = reportService.getTempFile(multipartFile); if (!multipartFile.isEmpty()) { XSSFWorkbook wb; try { wb = new XSSFWorkbook(file); } catch (Exception e) { return "-1"; } XSSFSheet sheet = wb.getSheetAt(0); Iterator rows = sheet.rowIterator(); int i = 0; while (rows.hasNext()) { XSSFRow row = (XSSFRow) rows.next(); String lotNum = row.getCell(0).getStringCellValue(); Lot lot = lotService.getLotByLotNum(lotNum); lot.setBid(bid); lotService.updateLot(login, lot); i++; } return String.valueOf(i); } else return "0"; } @RequestMapping(value = "/download", method = RequestMethod.GET) public void download(HttpServletResponse response, HttpSession session) throws IOException { String objIdToDownload = (String) session.getAttribute("objIdToDownload"); List<Lot> lotList = new ArrayList<>(); List<Asset> assetList = new ArrayList<>(); String[] idMass = objIdToDownload.split(","); for (String id : idMass) { Lot lot = lotService.getLot(Long.parseLong(id)); lotList.add(lot); assetList.addAll(lotService.getAssetsByLot(lot)); } String filePath = Excel.loadCreditsByList(lotList, assetList); File file = new File(filePath); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); try ( InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream() ) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } } finally { file.delete(); } } @RequestMapping(value = "/unitsByLot/{id}", method = RequestMethod.GET) public void getCreditsByLot(HttpServletResponse response, @PathVariable Long id) throws IOException { Lot lot = lotService.getLot(id); File file = null; if (lot.getLotType() == 0) { file = Excel.loadCreditsByLot(lot, creditService.getCrditsByLotId(id)); } else if (lot.getLotType() == 1) { file = Excel.loadAssetsByList(lot, lotService.getAssetsByLot(lot)); } response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); try (InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } } finally { file.delete(); } } @RequestMapping(value = "/downloadT/{id}", method = RequestMethod.GET) public void downloadT(HttpServletResponse response, @PathVariable Long id) throws IOException { Bid bid = bidService.getBid(id); List<Lot> lotList; List<Asset> assetList; lotList = lotService.getLotsByBid(bid); assetList = bidService.getAssetsByBid(bid); String filePath = Excel.loadCreditsByList(lotList, assetList); File file = new File(filePath); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); try (InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } } finally { file.delete(); } } @RequestMapping(value = "/reportDownload", method = RequestMethod.GET) public void reportDownload(HttpServletResponse response, HttpSession session) throws IOException { String reportPath = (String) session.getAttribute("reportPath"); File file = new File(reportPath); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); try (InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } } finally { file.delete(); } } @RequestMapping(value = "/downloadDocument", method = RequestMethod.GET) public void downloadDocument(HttpServletResponse response, HttpSession session) throws IOException { String objId = (String) session.getAttribute("objIdToDownload"); String docName = (String) session.getAttribute("docName"); String docType = (String) session.getAttribute("docType"); File file = null; if (docType.equals("lot")) file = new File(documentsPath + objId + File.separator + docName); if (docType.equals("bid")) file = new File(bidDocumentsPath + objId + File.separator + docName); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); try (InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } } finally { file.delete(); } } @RequestMapping(value = "/downloadOgolosh/{id}", method = RequestMethod.GET) public void downloadOgoloshennya(HttpServletResponse response, @PathVariable Long id) throws IOException { File file; String docName = reportService.makeOgoloshennya(id); file = new File(docName); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); try (InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } } finally { file.delete(); } } @RequestMapping(value = "/downloadCreditContract/{lotId}/{contract_year}/{contract_address}/{contract_protokol_num}/{contract_protokol_date}/{protocol_made_by}/{subscriber}", method = RequestMethod.GET) public void downloadCreditContract(HttpServletResponse response, @PathVariable Long lotId, @PathVariable String contract_year, @PathVariable String contract_address, @PathVariable String contract_protokol_num, @PathVariable String contract_protokol_date, @PathVariable String protocol_made_by, @PathVariable String subscriber) throws Exception { File file; file = new File(makeContract(lotId, contract_year, contract_address, contract_protokol_num, contract_protokol_date, protocol_made_by, subscriber)); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); try (InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } } finally { file.delete(); } } @RequestMapping(value = "/downloadAssetContract/{lotId}/{contract_year}/{contract_address}/{contract_protokol_num}/{contract_protokol_date}/{protocol_made_by}/{subscriber}/{pass_seria}/{pass_num}/{pass_vidano}/{pass_vidano_date}/{operates_basis}/{account_bank}/{bid_enter}/{bid_client}/{signer_bank}", method = RequestMethod.GET) public void downloadAssetContract(HttpServletResponse response, @PathVariable Long lotId, @PathVariable String contract_year, @PathVariable String contract_address, @PathVariable String contract_protokol_num, @PathVariable String contract_protokol_date, @PathVariable String protocol_made_by, @PathVariable String subscriber, @PathVariable String pass_seria, @PathVariable String pass_num, @PathVariable String pass_vidano, @PathVariable String pass_vidano_date, @PathVariable String operates_basis, @PathVariable String account_bank, @PathVariable String bid_enter, @PathVariable String bid_client, @PathVariable String signer_bank) throws Exception { File file; file = new File(makeAssetContract(lotId, contract_year, contract_address, contract_protokol_num, contract_protokol_date, protocol_made_by, subscriber, pass_seria, pass_num, pass_vidano, pass_vidano_date, operates_basis, account_bank, bid_enter, bid_client, signer_bank )); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); try (InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } } finally { file.delete(); } } @RequestMapping(value = "/downloadContract_Akt/{lotId}/{contract_year}/{contract_address}/{contract_protokol_num}/{contract_protokol_date}/{protocol_made_by}/{subscriber}", method = RequestMethod.GET) public void downloadContract_Akt(HttpServletResponse response, @PathVariable Long lotId, @PathVariable String contract_year, @PathVariable String contract_address, @PathVariable String contract_protokol_num, @PathVariable String contract_protokol_date, @PathVariable String protocol_made_by, @PathVariable String subscriber) throws Exception { File file; file = new File(makeContract_Akt(lotId, contract_year, contract_address, contract_protokol_num, contract_protokol_date, protocol_made_by, subscriber)); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); try (InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } } finally { file.delete(); } } @RequestMapping(value = "/downloadAssetContract_Akt/{lotId}/{contract_year}/{contract_address}/{contract_protokol_num}/{contract_protokol_date}/{protocol_made_by}/{subscriber}/{pass_seria}/{pass_num}/{pass_vidano}/{pass_vidano_date}/{operates_basis}/{account_bank}/{bid_enter}/{bid_client}/{signer_bank}", method = RequestMethod.GET) public void downloadAssetContract_Akt(HttpServletResponse response, @PathVariable Long lotId, @PathVariable String contract_year, @PathVariable String contract_address, @PathVariable String contract_protokol_num, @PathVariable String contract_protokol_date, @PathVariable String protocol_made_by, @PathVariable String subscriber, @PathVariable String pass_seria, @PathVariable String pass_num, @PathVariable String pass_vidano, @PathVariable String pass_vidano_date, @PathVariable String operates_basis, @PathVariable String account_bank, @PathVariable String bid_enter, @PathVariable String bid_client, @PathVariable String signer_bank ) throws Exception { File file; file = new File(makeAssetContract_Akt(lotId, contract_year, contract_address, contract_protokol_num, contract_protokol_date, protocol_made_by, subscriber, pass_seria, pass_num, pass_vidano, pass_vidano_date, operates_basis, account_bank, bid_enter, bid_client, signer_bank)); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); try (InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } } finally { file.delete(); } } @RequestMapping(value = "/downloadContract_Dodatok/{dodatok_num}/{lotId}/{contract_year}/{contract_address}/{contract_protokol_num}/{contract_protokol_date}/{protocol_made_by}/{subscriber}", method = RequestMethod.GET) public void downloadContractDodatok(HttpServletResponse response, @PathVariable Long dodatok_num, @PathVariable Long lotId, @PathVariable String contract_year, @PathVariable String contract_address, @PathVariable String contract_protokol_num, @PathVariable String contract_protokol_date, @PathVariable String protocol_made_by, @PathVariable String subscriber) throws Exception { File file; if (dodatok_num == 1) file = new File(makeContract_Dodatok1(lotId, contract_year, contract_address, contract_protokol_num, contract_protokol_date, protocol_made_by, subscriber)); else if (dodatok_num == 2) file = new File(makeContract_Dodatok2(lotId, contract_year, contract_address, contract_protokol_num, contract_protokol_date, protocol_made_by, subscriber)); else return; response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); try (InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } } finally { file.delete(); } } @RequestMapping(value = "/downLotIdListForm", method = RequestMethod.GET) public void downLotIdListForm(HttpServletResponse response) throws IOException { File file = new File("C:\\projectFiles\\LOT_ID_LIST.xlsx"); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); try (InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } } } //LOT_ID_LIST.xlsx public void setFactPriceFromLotToCredits(Lot lot, BigDecimal factLotPrice, String login) { List<Credit> credits = lotService.getCRDTSByLot(lot); if (lot.getFactPrice() != null && lot.getFactPrice().equals(factLotPrice)) { return; } if (factLotPrice == null) { for (Credit credit : credits) { credit.setFactPrice(null); creditService.updateCredit(login, credit); } } else if (!factLotPrice.equals(BigDecimal.valueOf(0.00))) { BigDecimal lotAcceptedSum = lotService.lotAcceptedSum(lot); BigDecimal creditsTotalFact = new BigDecimal(0.00); for (int i = 0; i < credits.size(); i++) { Credit credit = credits.get(i); BigDecimal factPrice; if (i == credits.size() - 1) { factPrice = factLotPrice.subtract(creditsTotalFact); } else { factPrice = (credit.getAcceptPrice().divide(lotAcceptedSum, 10, BigDecimal.ROUND_HALF_UP)).multiply(factLotPrice).setScale(2, BigDecimal.ROUND_HALF_UP); creditsTotalFact = creditsTotalFact.add(factPrice); } credit.setFactPrice(factPrice); creditService.updateCredit(login, credit); } } } public void setFactPriceFromLotToAssets(Lot lot, BigDecimal factLotPrice, String login) { List<Asset> assets = lotService.getAssetsByLot(lot); if (factLotPrice == null) { for (Asset asset : assets) { asset.setFactPrice(null); assetService.updateAsset(login, asset); } } else if (!factLotPrice.equals(new BigDecimal(0.00))) { BigDecimal lotAcceptedSum = lotService.lotAcceptedSum(lot); BigDecimal assetsTotalFact = new BigDecimal(0.00); for (int i = 0; i < assets.size(); i++) { Asset asset = assets.get(i); BigDecimal factPrice; if (i == assets.size() - 1) { factPrice = factLotPrice.subtract(assetsTotalFact); } else { factPrice = (asset.getAcceptPrice().divide(lotAcceptedSum, 10, BigDecimal.ROUND_HALF_UP)).multiply(factLotPrice).setScale(2, BigDecimal.ROUND_HALF_UP); assetsTotalFact = assetsTotalFact.add(factPrice); } asset.setFactPrice(factPrice); assetService.updateAsset(login, asset); } } } public void setFirstStartPriceFromLotToCredits(Lot lot, BigDecimal firstStartLotPrice, String login) { List<Credit> credits = lotService.getCRDTSByLot(lot); if (firstStartLotPrice != null && lot.getFirstStartPrice() != null && lot.getFirstStartPrice().equals(firstStartLotPrice)) { return; } if (firstStartLotPrice == null || firstStartLotPrice.equals(new BigDecimal(0.00))) { for (Credit credit : credits) { credit.setFirstStartPrice(firstStartLotPrice); creditService.updateCredit(login, credit); } } else { BigDecimal lotSum = lotService.lotSum(lot); BigDecimal crTotalFirstPrice = new BigDecimal(0.00); for (int i = 0; i < credits.size(); i++) { Credit credit = credits.get(i); BigDecimal firstPrice; if (i == credits.size() - 1) { firstPrice = firstStartLotPrice.subtract(crTotalFirstPrice); } else { firstPrice = (credit.getRv().divide(lotSum, 10, BigDecimal.ROUND_HALF_UP)).multiply(firstStartLotPrice).setScale(2, BigDecimal.ROUND_HALF_UP); crTotalFirstPrice = crTotalFirstPrice.add(firstPrice); } credit.setFirstStartPrice(firstPrice); creditService.updateCredit(login, credit); } } } //можно улучшить public void setStartPriceFromLotToCredits(Lot lot, BigDecimal startLotPrice, String login) { List<Credit> credits = lotService.getCRDTSByLot(lot); if (lot.getStartPrice() != null && lot.getStartPrice().equals(startLotPrice)) { return; } if (startLotPrice == null || startLotPrice.equals(new BigDecimal(0.00))) { for (Credit credit : credits) { credit.setStartPrice(startLotPrice); creditService.updateCredit(login, credit); } } else { BigDecimal lotSum = lotService.lotSum(lot); BigDecimal crTotalStartPrice = new BigDecimal(0.00); for (int i = 0; i < credits.size(); i++) { Credit credit = credits.get(i); BigDecimal startPrice; if (i == credits.size() - 1) { startPrice = startLotPrice.subtract(crTotalStartPrice); } else { startPrice = (credit.getRv().divide(lotSum, 10, BigDecimal.ROUND_HALF_UP)).multiply(startLotPrice).setScale(2, BigDecimal.ROUND_HALF_UP); crTotalStartPrice = crTotalStartPrice.add(startPrice); } credit.setStartPrice(startPrice); creditService.updateCredit(login, credit); } } } @RequestMapping(value = "/changeLotParams", method = RequestMethod.POST) private @ResponseBody String changeLotParams(HttpSession session, @RequestParam("lotId") String lotId, @RequestParam("lotNum") String lotNum, @RequestParam("workStage") String status, @RequestParam("comment") String comment, @RequestParam("bidStage") String bidStage, @RequestParam("resultStatus") String resultStatus, /*@RequestParam("customer") String customer, @RequestParam("customerInn") String customerInn,*/ @RequestParam("firstPrice") BigDecimal firstPrice, @RequestParam("startPrice") BigDecimal startPrice, @RequestParam("factPrice") BigDecimal factLotPrice, @RequestParam("isSold") String isSold, @RequestParam("selectedBidId") Long selectedBidId, @RequestParam("countOfParticipants") int countOfParticipants, @RequestParam("bidScenario") short bidScenario) { String login = (String) session.getAttribute("userId"); Lot lot = lotService.getLot(Long.parseLong(lotId)); lot.setLotNum(lotNum); lot.setWorkStage(status); lot.setComment(comment); lot.setBidStage(bidStage); lot.setStatus(resultStatus); /* lot.setCustomerName(customer); if (customerInn.equals("")) lot.setCustomerInn(0L); else lot.setCustomerInn(Long.parseLong(customerInn));*/ lot.setCountOfParticipants(countOfParticipants); lot.setBidScenario(bidScenario); if (selectedBidId == 0L) { lot.setBid(null); } else lot.setBid(bidService.getBid(selectedBidId)); if (lot.getLotType() == 1 /*&& lot.getFactPrice()!=null && !lot.getFactPrice().equals(factLotPrice)*/) { setFactPriceFromLotToAssets(lot, factLotPrice, login); } if (lot.getLotType() == 0) { // if(lot.getFirstStartPrice()!=null && !lot.getFirstStartPrice().equals(firstPrice)) setFirstStartPriceFromLotToCredits(lot, firstPrice, login); // if(lot.getStartPrice()!=null && !lot.getStartPrice().equals(startPrice)) setStartPriceFromLotToCredits(lot, startPrice, login); // if(lot.getFactPrice()!=null && !lot.getFactPrice().equals(factLotPrice)) setFactPriceFromLotToCredits(lot, factLotPrice, login); } lot.setFirstStartPrice(firstPrice); lot.setStartPrice(startPrice); lot.setFactPrice(factLotPrice); if (lot.getFirstStartPrice() == null) { setFirstStartPriceFromLotToCredits(lot, startPrice, login); lot.setFirstStartPrice(startPrice); } if (isSold.equals("1")) { List<Credit> credits = lotService.getCRDTSByLot(lot); List<Asset> assetList = lotService.getAssetsByLot(lot); lot.setActSignedDate(new Date()); lot.setItSold(true); for (Credit credit : credits) { credit.setSold(true); creditService.updateCredit(login, credit); } for (Asset asset : assetList) { asset.setSold(true); assetService.updateAsset(login, asset); } } boolean isitChanged = lotService.updateLot(login, lot); if (isitChanged) return "1"; else return "0"; } @RequestMapping(value = "/reBidByLot", method = RequestMethod.GET) private @ResponseBody String reBidByLot(HttpSession session, @RequestParam("lotId") String lotId, @RequestParam("reqType") int requestType) { String login = (String) session.getAttribute("userId"); Lot lot = lotService.getLot(Long.parseLong(lotId)); if (lot.getLotType() == 0) { if (lot.getFirstStartPrice() == null) { setFirstStartPriceFromLotToCredits(lot, lot.getStartPrice(), login); } setFactPriceFromLotToCredits(lot, null, login); } if (lot.getLotType() == 1) { setFactPriceFromLotToAssets(lot, null, login); } if (lot.getFirstStartPrice() == null) { lot.setFirstStartPrice(lot.getStartPrice()); } //Исправить говнокод if (requestType == 1) { if (lot.getBidStage().equals(StaticStatus.bidStatusList.get(0))) { lot.setBidStage(StaticStatus.bidStatusList.get(1)); } else if (lot.getBidStage().equals(StaticStatus.bidStatusList.get(1))) { lot.setBidStage(StaticStatus.bidStatusList.get(2)); } else if (lot.getBidStage().equals(StaticStatus.bidStatusList.get(2))) { lot.setBidStage(StaticStatus.bidStatusList.get(3)); } else if (lot.getBidStage().equals(StaticStatus.bidStatusList.get(3))) { lot.setBidStage(StaticStatus.bidStatusList.get(4)); } else if (lot.getBidStage().equals(StaticStatus.bidStatusList.get(4))) { lot.setBidStage(StaticStatus.bidStatusList.get(5)); } else if (lot.getBidStage().equals(StaticStatus.bidStatusList.get(5))) { lot.setBidStage(StaticStatus.bidStatusList.get(6)); } else if (lot.getBidStage().equals(StaticStatus.bidStatusList.get(6))) { lot.setBidStage(StaticStatus.bidStatusList.get(7)); } else if (lot.getBidStage().equals(StaticStatus.bidStatusList.get(7))) { lot.setBidStage(StaticStatus.bidStatusList.get(8)); } } else if (requestType == 2) { //lot.setFirstStartPrice(null); lot.setStartPrice(null); lot.setBidStage(StaticStatus.bidStatusList.get(0)); lot.setNeedNewFondDec(true); } lot.setFactPrice(null); lot.setBid(null); //lot.setLotNum(null); lot.setCountOfParticipants(0); lot.setWorkStage("Новий лот"); lot.setStatus(null); // lot.setCustomerName(null); lotService.updateLot(login, lot); return "1"; } @RequestMapping(value = "/changeBidParams", method = RequestMethod.POST) private @ResponseBody String changeBidParams(@RequestParam("bidId") String bidId, @RequestParam("bidDate") String bidDate, @RequestParam("exId") String exId, @RequestParam("newNP") String newNP, @RequestParam("newND1") String newND1, // @RequestParam("newND2") String coment, @RequestParam("newRED") String newRED) { Date bDate = null, ND1 = null, ND2 = null, RED = null; Bid bid = bidService.getBid(Long.parseLong(bidId)); Exchange exchange = exchangeService.getExchange(Long.parseLong(exId)); try { bDate = CustomDateFormats.sdfshort.parse(bidDate); } catch (ParseException e) { System.out.println("Неверный формат даты"); } try { ND1 = CustomDateFormats.sdfshort.parse(newND1); } catch (ParseException e) { System.out.println("Неверный формат даты"); } try { RED = CustomDateFormats.sdfshort.parse(newRED); } catch (ParseException e) { System.out.println("Неверный формат даты"); } bid.setExchange(exchange); bid.setBidDate(bDate); bid.setNewspaper(newNP); bid.setNews1Date(ND1); // bid.setComent(coment); bid.setRegistrEndDate(RED); bidService.updateBid(bid); return "1"; } @RequestMapping(value = "/deleteBid", method = RequestMethod.POST) private @ResponseBody String deleteBid(HttpSession session, @RequestParam("idBid") String bidId) { String login = (String) session.getAttribute("userId"); Bid bid = bidService.getBid(Long.parseLong(bidId)); List<Lot> lotList = lotService.getLotsByBid(bid); for (Lot lot : lotList) { lot.setBid(null); lotService.updateLot(login, lot); } bidService.delete(bid); return "1"; } @RequestMapping(value = "/setAssetPortionNum", method = RequestMethod.POST) private @ResponseBody String setAssetPortionNum(HttpSession session, @RequestParam("portion") String portion, Model model) { model.addAttribute("assetPortionNum", portion); return "1"; } @RequestMapping(value = "/createLotByCheckedAssets", method = RequestMethod.POST) private @ResponseBody String createLotByAssets(@RequestParam("idList") String idList, HttpSession session) { if (idList.equals("")) { return "0"; } String[] idMass = idList.split(","); session.setAttribute("assetsListToLot", idMass); return "1"; } @RequestMapping(value = "/createLotByCheckedCredits", method = RequestMethod.POST) private @ResponseBody String createLotByCheckedCredits(@RequestParam("idList") String idList, HttpSession session) { if (idList.equals("")) { return "0"; } String[] idMass = idList.split(","); session.setAttribute("creditsListToLot", idMass); return "1"; } @RequestMapping(value = "/creditsByClient", method = RequestMethod.POST) private @ResponseBody List<Credit> getCreditsByEx( @RequestParam("inn") String inn, @RequestParam("idBars") Long idBars) { return creditService.getCreditsByClient(inn, idBars); } @RequestMapping(value = "/allCreditsByClient", method = RequestMethod.POST) private @ResponseBody List<Credit> getAllCreditsByClient( @RequestParam("inn") String inn, @RequestParam("idBars") Long idBars) { return creditService.getAllCreditsByClient(inn, idBars); } @RequestMapping(value = "/objectsByInNum", method = RequestMethod.POST) private @ResponseBody List<Asset> getAssetsByInNum(@RequestParam("inn") String inn) { return assetService.getAssetsByInNum(inn); } @RequestMapping(value = "/allObjectsByInNum", method = RequestMethod.POST) private @ResponseBody List<Asset> getAllAssetsByInNum(@RequestParam("inn") String inn) { return assetService.getAllAssetsByInNum(inn); } @RequestMapping(value = "/getLastAccPriceByInNum", method = RequestMethod.POST) private @ResponseBody BigDecimal getLastAccPriceByInNum(@RequestParam("id") Long id) { return assetService.getLastAccPrice(id); } @RequestMapping(value = "/sumById", method = RequestMethod.POST) private @ResponseBody String sumById(@RequestParam("idMass") String ids) { Formatter f = new Formatter(); BigDecimal sum = new BigDecimal(0); String[] idm; try { idm = ids.substring(1).split(","); } catch (IndexOutOfBoundsException e) { return "0"; } for (String id : idm) { sum = sum.multiply(creditService.getCredit(Long.parseLong(id)).getRv()); } return f.format("%,.0f", sum).toString(); } @RequestMapping(value = "/sumByInvs", method = RequestMethod.POST) private @ResponseBody String sumByInvs(@RequestParam("idMass") String ids) { BigDecimal sum = new BigDecimal(0.00); String[] idm; try { idm = ids.substring(1).split(","); } catch (IndexOutOfBoundsException e) { return "0"; } for (String id : idm) { sum = sum.add(assetService.getAsset(Long.parseLong(id)).getRv()); } return sum.toString(); } @RequestMapping(value = "/sumByIDBars", method = RequestMethod.POST) private @ResponseBody String sumByIDBars(@RequestParam("idMass") String ids) { BigDecimal sum = new BigDecimal(0.00); String[] idm; try { idm = ids.substring(1).split(","); } catch (IndexOutOfBoundsException e) { return "0"; } for (String id : idm) { sum = sum.add(creditService.getCredit(Long.parseLong(id)).getRv()); } return sum.toString(); } @RequestMapping(value = "/lotsByBid", method = RequestMethod.POST) private @ResponseBody List<Lot> lotsByBid(@RequestParam("bidId") String bidId) { Bid bid = bidService.getBid(Long.parseLong(bidId)); return bidService.lotsByBid(bid); } @RequestMapping(value = "/comentsByLotsFromBid", method = RequestMethod.GET) private @ResponseBody List<String> getComments(@RequestParam("bidId") String bidId) { String aggregatedComment = ""; List<String> resList = new ArrayList<>(); Bid bid = bidService.getBid(Long.parseLong(bidId)); for (Lot l : (List<Lot>) bidService.lotsByBid(bid)) { aggregatedComment += l.getComment() + " ||"; } resList.add(aggregatedComment); return resList; } @RequestMapping(value = "/getPaySum_Residual", method = RequestMethod.GET) private @ResponseBody List<BigDecimal> getPaySumResidual(@RequestParam("id") String id) { List<BigDecimal> list = new ArrayList<>(); Asset asset = assetService.getAsset(Long.parseLong(id)); if (asset.getLot() == null) { return list; } else { Lot lot = asset.getLot(); BigDecimal coeff = MathCalculationUtil.getCoefficient(asset.getFactPrice(), lot.getFactPrice());// asset.getFactPrice().divide(lot.getFactPrice(), 10, BigDecimal.ROUND_HALF_UP); BigDecimal paySumByAsset; try { paySumByAsset = lotService.paymentsSumByLot(lot).multiply(coeff).setScale(2, BigDecimal.ROUND_HALF_UP); } catch (NullPointerException npe) { paySumByAsset = BigDecimal.valueOf(0); } BigDecimal residualToPay; try { residualToPay = asset.getFactPrice().subtract(paySumByAsset); } catch (NullPointerException npe) { residualToPay = null; } list.add(paySumByAsset); list.add(residualToPay); return list; } } @RequestMapping(value = "/getTotalCountOfObjects", method = RequestMethod.GET) private @ResponseBody Long getTotalCountOfObjects() { return assetService.getTotalCountOfAssets(); } @RequestMapping(value = "/objectsByPortions", method = RequestMethod.POST) private @ResponseBody List<Asset> objectsByPortions(@RequestParam("num") String portionNumber) { return assetService.getAssetsByPortion(Integer.parseInt(portionNumber)); } @RequestMapping(value = "/countCreditsByFilter", method = RequestMethod.POST) private @ResponseBody Long countCreditsByFilter(@RequestParam("isSold") int isSold, @RequestParam("isInLot") int isInLot, @RequestParam("clientType") int clientType, @RequestParam("isNbu") int isNbu, @RequestParam("isFondDec") int isFondDec, @RequestParam("inIDBarses") String inIDBarses, @RequestParam("inINNs") String inINNs, @RequestParam("inIDLots") String inIDLots) { String[] idBarsMass; String[] innMass; String[] idLotMass; if (inIDBarses.equals("")) { idBarsMass = new String[0]; } else idBarsMass = inIDBarses.split(","); if (inINNs.equals("")) { innMass = new String[0]; } else innMass = inINNs.split(","); if (inIDLots.equals("")) { idLotMass = new String[0]; } else idLotMass = inIDLots.split(","); return creditService.countOfFilteredCredits(isSold, isInLot, clientType, isNbu, isFondDec, idBarsMass, innMass, idLotMass); } @RequestMapping(value = "/creditsByPortions", method = RequestMethod.POST) private @ResponseBody List<String> creditsByPortions(@RequestParam("num") int portionNumber, @RequestParam("isSold") int isSold, @RequestParam("isInLot") int isInLot, @RequestParam("clientType") int clientType, @RequestParam("isNbu") int isNbu, @RequestParam("isFondDec") int isFondDec, @RequestParam("inIDBarses") String inIDBarses, @RequestParam("inINNs") String inINNs, @RequestParam("inIDLots") String inIDLots ) { String[] idBarsMass; String[] innMass; String[] idLotMass; if (inIDBarses.equals("")) { idBarsMass = new String[0]; } else idBarsMass = inIDBarses.split(","); if (inINNs.equals("")) { innMass = new String[0]; } else innMass = inINNs.split(","); if (inIDLots.equals("")) { idLotMass = new String[0]; } else idLotMass = inIDLots.split(","); List<Credit> crList = creditService.getCreditsByPortion(portionNumber, isSold, isInLot, clientType, isNbu, isFondDec, idBarsMass, innMass, idLotMass); List<String> rezList = new ArrayList<>(); for (Credit cr : crList) { String lotId = ""; String bidDate = ""; String exchangeName = ""; /*String nbuPledge = "Ні"; if (cr.getNbuPladge()) nbuPledge = "Так";*/ String factPrice = ""; if (cr.getFactPrice() != null) factPrice = String.valueOf(cr.getFactPrice()); String bidStage = ""; String bidResult = ""; String payStatus = ""; String paySum = ""; String residualToPay = ""; String customerName = ""; String workStage = ""; String fondDecisionDate = ""; String fondDecision = ""; String fondDecisionNumber = ""; String nbuDecisionDate = ""; String nbuDecision = ""; String nbuDecisionNumber = ""; String acceptedPrice = ""; String acceptedExchange = ""; if (cr.getAcceptPrice() != null) acceptedPrice = String.valueOf(cr.getAcceptPrice()); String actSignedDate = ""; if (cr.getLot() != null) { lotId = String.valueOf(cr.getLot()); Lot lot = lotService.getLot(cr.getLot()); if (lot.getBid() != null) { bidDate = String.valueOf(CustomDateFormats.sdfpoints.format(lot.getBid().getBidDate())); exchangeName = lot.getBid().getExchange().getCompanyName(); } bidStage = lot.getBidStage(); bidResult = lot.getStatus(); if (lotService.paymentsSumByLot(lot) != null) { BigDecimal paysSum = lotService.paymentsSumByLot(lot); paySum = String.valueOf(paysSum); if (lot.getFactPrice().compareTo(paysSum) < 0) payStatus = "100% сплата"; else if (!paysSum.equals(new BigDecimal(0))) payStatus = "Часткова оплата"; residualToPay = String.valueOf(lot.getFactPrice().subtract(paysSum)); } customerName = (lot.getCustomer() == null) ? "" : lot.getCustomer().shortDescription(); workStage = lot.getWorkStage(); if (lot.getFondDecisionDate() != null) fondDecisionDate = String.valueOf(CustomDateFormats.sdfpoints.format(lot.getFondDecisionDate())); fondDecision = lot.getFondDecision(); fondDecisionNumber = lot.getDecisionNumber(); if (lot.getNbuDecisionDate() != null) nbuDecisionDate = String.valueOf(CustomDateFormats.sdfpoints.format(lot.getNbuDecisionDate())); nbuDecision = lot.getNbuDecision(); nbuDecisionNumber = lot.getNbuDecisionNumber(); acceptedExchange = lot.getAcceptExchange(); if (lot.getActSignedDate() != null) actSignedDate = CustomDateFormats.sdfpoints.format(lot.getActSignedDate()); } String planSaleDate = ""; if (cr.getPlanSaleDate() != null) planSaleDate = CustomDateFormats.yearMonthFormat.format(cr.getPlanSaleDate()); rezList.add(lotId + "||" + cr.getNd() + "||" + cr.getInn() + "||" + cr.getContractNum() + "||" + bidDate + "||" + exchangeName + "||" + cr.getClientType() + "||" + cr.getFio() + "||" + cr.getProduct() + "||" + cr.getNbuPladge() + "||" + cr.getRegion() + "||" + cr.getCurr() + "||" + cr.getZb() + "||" + cr.getDpd() + "||" + cr.getRv() + "||" + bidStage + "||" + factPrice + "||" + bidResult + "||" + payStatus + "||" + paySum + "||" + residualToPay + "||" + customerName + "||" + workStage + "||" + fondDecisionDate + "||" + fondDecision + "||" + fondDecisionNumber + "||" + acceptedPrice + "||" + acceptedExchange + "||" + actSignedDate + "||" + planSaleDate + "||" + nbuDecisionDate + "||" + nbuDecision + "||" + nbuDecisionNumber ); } return rezList; } @RequestMapping(value = "/countSumLotsByBid", method = RequestMethod.POST) private @ResponseBody List<String> countSumLotsByBid(@RequestParam("bidId") String bidId) { Long id = Long.parseLong(bidId); Bid bid = bidService.getBid(id); List<String> list = new ArrayList<>(); Long count = bidService.countOfLots(bid); BigDecimal sum = bidService.sumByBid(bid); list.add(count.toString()); list.add(sum.toString()); return list; } @RequestMapping(value = "/countSumLotsByExchange", method = RequestMethod.POST) private @ResponseBody List<String> countSumLotsByExchange(@RequestParam("exId") Long exId) { Exchange exchange = exchangeService.getExchange(exId); List<Lot> lotsList = lotService.getLotsByExchange(exchange); List<String> list = new ArrayList<>(); BigDecimal lotRV = new BigDecimal(0.00); for (Lot lot : lotsList) { lotRV = lotRV.add(lotService.lotSum(lot)); } list.add(String.valueOf(lotsList.size())); list.add(String.valueOf(lotRV)); return list; } @RequestMapping(value = "/countBidsByExchange", method = RequestMethod.GET) private @ResponseBody int countBidsByExchange(@RequestParam("exId") Long exId) { Exchange exchange = exchangeService.getExchange(exId); return bidService.getBidsByExchange(exchange).size(); } @RequestMapping(value = "/selectedCRD", method = RequestMethod.POST) private @ResponseBody List<String> selectCrd( @RequestParam("types") String types, @RequestParam("regions") String regs, @RequestParam("curs") String curs, @RequestParam("dpdmin") int dpdmin, @RequestParam("dpdmax") int dpdmax, @RequestParam("zbmin") double zbmin, @RequestParam("zbmax") double zbmax) { String[] typesMass = types.split(","); String[] regsMass = regs.split(","); String[] curMass = curs.split(","); List<Credit> crList = creditService.selectCredits(typesMass, regsMass, curMass, dpdmin, dpdmax, zbmin, zbmax); List<String> rezList = new ArrayList<>(); rezList.add("ID" + '|' + "ІНН" + '|' + "Номер договору" + '|' + "ФІО" + '|' + "Регіон" + '|' + "Код типу активу" + '|' + "Код групи активу" + '|' + "Тип клієнта" + '|' + "Дата видачі" + '|' + "Дата закінчення" + '|' + "Валюта" + '|' + "Продукт" + '|' + "Загальний борг, грн." + '|' + "dpd" + '|' + "Вартість об'єкту, грн."); for (Credit cr : crList) { rezList.add(cr.getNd() + cr.toShotString()); } return rezList; } @RequestMapping(value = "/selectAssetsbyLot", method = RequestMethod.POST) private @ResponseBody List<Asset> selectAssetsbyLot(@RequestParam("lotId") Long lotId) { return lotService.getAssetsByLot(lotId); } @RequestMapping(value = "/selectCreditsLot", method = RequestMethod.POST) private @ResponseBody List<Credit> selectCreditsLot(@RequestParam("lotId") Long lotId) { return creditService.getCrditsByLotId(lotId); } @RequestMapping(value = "/delObjectFromLot", method = RequestMethod.POST) private @ResponseBody String delObjectFromLot(HttpSession session, @RequestParam("objId") Long objId, @RequestParam("lotId") Long lotId) { Lot lot = lotService.getLot(lotId); String login = (String) session.getAttribute("userId"); boolean isitUpdated = true; if (lot.getLotType() == 0) { Credit credit = creditService.getCredit(objId); credit.setLot(null); isitUpdated = creditService.updateCredit(login, credit); } else if (lot.getLotType() == 1) { Asset asset = assetService.getAsset(objId); asset.setLot(null); isitUpdated = assetService.updateAsset(login, asset); } if (isitUpdated) return "1"; else return "0"; } @RequestMapping(value = "/changeObjAccPrice", method = RequestMethod.POST) private @ResponseBody String changeObjAccPrice(HttpSession session, @RequestParam("objId") Long objId, @RequestParam("objAccPrice") BigDecimal accPrice, @RequestParam("lotId") Long lotId) { Lot lot = lotService.getLot(lotId); String login = (String) session.getAttribute("userId"); boolean isitUpdated = false; if (lot.getLotType() == 0) { Credit credit = creditService.getCredit(objId); credit.setAcceptPrice(accPrice); isitUpdated = creditService.updateCredit(login, credit); } else if (lot.getLotType() == 1) { Asset asset = assetService.getAsset(objId); asset.setAcceptPrice(accPrice); isitUpdated = assetService.updateAsset(login, asset); } if (isitUpdated) return "1"; else return "0"; } @RequestMapping(value = "/setAcceptedPrice", method = RequestMethod.POST) private @ResponseBody String setAcceptedPrice(HttpSession session, @RequestParam("assetId") String assetId, @RequestParam("acceptPrice") BigDecimal acceptPrice) { String login = (String) session.getAttribute("userId"); Asset asset = assetService.getAsset(Long.parseLong(assetId)); asset.setAcceptPrice(acceptPrice); assetService.updateAsset(login, asset); return "1"; } @RequestMapping(value = "/setAcceptEx", method = RequestMethod.POST) private @ResponseBody String setAcceptEx(HttpSession session, @RequestParam("lotId") String lotId, @RequestParam("acceptEx") Long exId) { String login = (String) session.getAttribute("userId"); Lot lot = lotService.getLot(Long.parseLong(lotId)); try { lot.setAcceptExchange(exchangeService.getExchange(exId).getCompanyName()); } catch (NullPointerException e) { lot.setAcceptExchange(null); } lotService.updateLot(login, lot); return "1"; } @RequestMapping(value = "/changeFondDec", method = RequestMethod.POST) private @ResponseBody String changeFondDec(HttpSession session, @RequestParam("lotId") Long lotId, @RequestParam("fondDecDate") String fondDecDate, @RequestParam("fondDec") String fondDec, @RequestParam("decNum") String decNum) { String login = (String) session.getAttribute("userId"); Date date = null; try { date = CustomDateFormats.sdfshort.parse(fondDecDate); } catch (ParseException e) { System.out.println("Халепа!"); } Lot lot = lotService.getLot(lotId); lot.setFondDecisionDate(date); lot.setFondDecision(fondDec); lot.setDecisionNumber(decNum); lot.setNeedNewFondDec(false); //убираем необходимость пересогласования lotService.updateLot(login, lot); return "1"; } @RequestMapping(value = "/changeNBUDec", method = RequestMethod.POST) private @ResponseBody String changeNBUDec(HttpSession session, @RequestParam("lotId") Long lotId, @RequestParam("NBUDecDate") String nbuDecDate, @RequestParam("NBUDec") String nbuDec, @RequestParam("decNum") String decNum) { String login = (String) session.getAttribute("userId"); Date date = null; try { date = CustomDateFormats.sdfshort.parse(nbuDecDate); } catch (ParseException e) { System.out.println("Халепа!"); } Lot lot = lotService.getLot(lotId); lot.setNbuDecisionDate(date); lot.setNbuDecision(nbuDec); lot.setNbuDecisionNumber(decNum); lotService.updateLot(login, lot); return "1"; } @RequestMapping(value = "/updateCreditsInLot", method = RequestMethod.POST) private @ResponseBody String updateCreditsInLot(HttpSession session, @RequestParam("newPricesId") String newPricesId, @RequestParam("newPrice") String newPrices, @RequestParam("factPricesId") String factPricesId, @RequestParam("factPrice") String factPrices, @RequestParam("soldId") String soldId) { String login = (String) session.getAttribute("userId"); if (!newPricesId.equals("")) { String[] newPricesIdMass = newPricesId.split(","); String[] newPricesMass = newPrices.split(","); for (int i = 0; i < newPricesIdMass.length; i++) { Credit credit = creditService.getCredit(Long.parseLong(newPricesIdMass[i])); credit.setDiscountPrice(BigDecimal.valueOf(Double.valueOf(newPricesMass[i]))); creditService.updateCredit(login, credit); } } if (!factPricesId.equals("")) { String[] factPricesIdMass = factPricesId.split(","); String[] factPricesMass = factPrices.split(","); for (int i = 0; i < factPricesIdMass.length; i++) { Credit credit = creditService.getCredit(Long.parseLong(factPricesIdMass[i])); credit.setFactPrice(BigDecimal.valueOf(Double.parseDouble(factPricesMass[i]))); creditService.updateCredit(login, credit); } } if (!soldId.equals("")) { String[] soldIdMass = soldId.split(","); for (String sId : soldIdMass) { Credit credit = creditService.getCredit(Long.parseLong(sId)); credit.setSold(true); creditService.updateCredit(login, credit); } } return "1"; } @RequestMapping(value = "/selectedParam", method = RequestMethod.POST) private @ResponseBody List<String> getParam(@RequestParam("types") String types, @RequestParam("regions") String regs, @RequestParam("curs") String curs, @RequestParam("dpdmin") int dpdmin, @RequestParam("dpdmax") int dpdmax, @RequestParam("zbmin") double zbmin, @RequestParam("zbmax") double zbmax) { String[] typesMass = types.split(","); String[] regsMass = regs.split(","); String[] curMass = curs.split(","); List<String> paramList = creditService.getCreditsResults(typesMass, regsMass, curMass, dpdmin, dpdmax, zbmin, zbmax); return paramList; } @RequestMapping(value = "/createSLot", method = RequestMethod.POST) private @ResponseBody String createLot(HttpSession session, Model model, @RequestParam("idMass") String ids, @RequestParam("comment") String comment) { String[] idm; try { idm = ids.substring(1).split(","); } catch (IndexOutOfBoundsException e) { return "0"; } String userLogin = (String) session.getAttribute("userId"); User user = userService.getByLogin(userLogin); BigDecimal startPrice = new BigDecimal(0); Lot newlot = new Lot("" + comment, user, new Date(), 1); Long lotRid = lotService.createLot(userLogin, newlot); for (String id : idm) { Asset asset = assetService.getAsset(Long.parseLong(id)); if (asset.getAcceptPrice() != null) startPrice = startPrice.add(asset.getAcceptPrice()); else startPrice = startPrice.add(asset.getRv()); if (asset.getLot() == null) asset.setLot(newlot); assetService.updateAsset(userLogin, asset); } newlot.setStartPrice(startPrice); newlot.setFirstStartPrice(startPrice); lotService.updateLot(newlot); return lotRid.toString(); } @RequestMapping(value = "/createCreditLot", method = RequestMethod.POST) private @ResponseBody String createCreditLot(HttpSession session, Model model, @RequestParam("idMass") String ids, @RequestParam("comment") String comment) { String[] idm; try { idm = ids.substring(1).split(","); } catch (IndexOutOfBoundsException e) { return "0"; } String userLogin = (String) session.getAttribute("userId"); User user = userService.getByLogin(userLogin); BigDecimal startPrice = new BigDecimal(0); Lot newlot = new Lot("" + comment, user, new Date(), 0); Long lotRid = lotService.createLot(userLogin, newlot); for (String id : idm) { Credit crdt = creditService.getCredit(Long.parseLong(id)); BigDecimal acceptedPr = crdt.getAcceptPrice(); BigDecimal rv = crdt.getRv(); if (acceptedPr != null) { startPrice = startPrice.add(acceptedPr); crdt.setFirstStartPrice(acceptedPr); crdt.setStartPrice(acceptedPr); // creditService.updateCredit(crdt); } else { startPrice = startPrice.add(rv); crdt.setFirstStartPrice(rv); crdt.setStartPrice(rv); // creditService.updateCredit(crdt); } if (crdt.getLot() == null) crdt.setLot(lotRid); creditService.updateCredit(userLogin, crdt); } newlot.setStartPrice(startPrice); newlot.setFirstStartPrice(startPrice); lotService.updateLot(newlot); return lotRid.toString(); } @RequestMapping(value = "/createBid", method = RequestMethod.GET) private @ResponseBody String createBid(@RequestParam("exId") String exId, @RequestParam("bidDate") String bidD, @RequestParam("newspaper") String newspaper, @RequestParam("newsDate1") String newsD1, @RequestParam("registrEnd") String regEnd) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); Date bidDate, newsDate1, registrEnd; try { bidDate = bidD.equals("") ? null : format.parse(bidD); newsDate1 = newsD1.equals("") ? null : format.parse(newsD1); registrEnd = regEnd.equals("") ? null : format.parse(regEnd); } catch (ParseException e) { e.printStackTrace(); return "0"; } Exchange exchange = exchangeService.getExchange(Long.parseLong(exId)); Bid bid = new Bid(bidDate, exchange, newspaper, newsDate1, registrEnd); bidService.createBid(bid); return "1"; } @RequestMapping(value = "/getAssetHistory", method = RequestMethod.POST) private @ResponseBody List assetHistory(@RequestParam("inn") String inn) { return assetService.getAssetHistory(inn); } @RequestMapping(value = "/getAccPriceHistory", method = RequestMethod.POST) private @ResponseBody List getDateAndAccPriceHistoryByAsset(@RequestParam("inn") String inn) { Asset asset = (Asset) assetService.getAllAssetsByInNum(inn).get(0); List<AcceptPriceHistory> acceptPriceHistoryList = assetService.getDateAndAccPriceHistoryByAsset(asset.getId()); return acceptPriceHistoryList; } @RequestMapping(value = "/getCreditsHistory", method = RequestMethod.POST) private @ResponseBody List creditHistory(@RequestParam("inn") String inn, @RequestParam("idBars") Long idBars) { List<String> rezList = new ArrayList<>(); String temp; Credit credit = (Credit) creditService.getAllCreditsByClient(inn, idBars).get(0); List<Long> lotIdList = creditService.getLotIdHistoryByCredit(credit.getNd()); for (Long lotId : lotIdList) { List<Bid> bidList = lotService.getLotHistoryAggregatedByBid(lotId); Collections.sort(bidList); for (Bid bid : bidList) { temp = credit.getInn() + "||" + lotId + "||" + bid.getExchange().getCompanyName() + "||" + CustomDateFormats.sdfshort.format(bid.getBidDate()) + "||" + creditService.getPriceByLotIdHistory(credit.getId(), lotId); rezList.add(temp); } } return rezList; } @RequestMapping(value = "/getCrPriceHistory", method = RequestMethod.POST) private @ResponseBody List getCrPriceHistory(@RequestParam("inn") String inn, @RequestParam("idBars") Long idBars) { Credit credit = (Credit) creditService.getAllCreditsByClient(inn, idBars).get(0); List<CreditAccPriceHistory> creditPriceHistoryList = creditService.getDateAndAccPriceHistoryByCredit(credit.getId()); return creditPriceHistoryList; } @RequestMapping(value = "/{lotId}/customer/update", method = RequestMethod.POST) private @ResponseBody Customer updateCustomer(HttpSession session, @PathVariable Long lotId, @RequestParam("inn") Long inn, @RequestParam("name") String name, @RequestParam("middleName") String middleName, @RequestParam("lastName") String lastName, @RequestParam("isMerried") boolean isMerried, @RequestParam("type") String type, @RequestParam("legalType") String legalType ) { String login = (String) session.getAttribute("userId"); Lot lot = lotService.getLot(lotId); Customer customer = customerService.getCustomerByInn(inn); if (customer == null) { customer = new Customer(); customer.setCustomerInn(inn); customer.setCustomerName(name); customer.setMiddleName(middleName); customer.setLastName(lastName); customer.setMerried(isMerried); customer.setType(Customer.SubscriberType.valueOf(type)); customer.setLegalType(Customer.LegalType.valueOf(legalType)); customerService.createCustomer(customer); lot.setCustomer(customer); lotService.updateLot(login, lot); } else { customer.setCustomerInn(inn); customer.setCustomerName(name); customer.setMiddleName(middleName); customer.setLastName(lastName); customer.setMerried(isMerried); customer.setType(Customer.SubscriberType.valueOf(type)); customer.setLegalType(Customer.LegalType.valueOf(legalType)); customerService.updateCustomer(customer); if (lot.getCustomer() == null || !lot.getCustomer().equals(customer)) { lot.setCustomer(customer); lotService.updateLot(login, lot); } } return customer; } @RequestMapping(value = "/customer/{id}", method = RequestMethod.POST) private @ResponseBody Customer getCustomerFromLot(@PathVariable Long id) { return customerService.getCustomerByInn(id); } @RequestMapping(value = "/{lotId}/customer/delete", method = RequestMethod.POST) private @ResponseBody String updateCustomer(@PathVariable Long lotId) { Lot lot = lotService.getLot(lotId); lot.setCustomer(null); lotService.updateLot(lot); return "успішно видалено!"; } @RequestMapping(value = "/{lotId}/setDates", method = RequestMethod.POST) private @ResponseBody String setDates(HttpSession session, @PathVariable Long lotId, @RequestParam("dateProzoro") String dateProzoro, @RequestParam("dateDeadline") String dateDeadline) { Lot lot = lotService.getLot(lotId); Date datePro; Date dateDead; try { datePro = CustomDateFormats.sdfshort.parse(dateProzoro); } catch (NullPointerException | ParseException e) { datePro = null; } try { dateDead = CustomDateFormats.sdfshort.parse(dateDeadline); } catch (NullPointerException | ParseException e) { dateDead = null; } lot.setProzoroDate(datePro); lot.setDeadlineDate(dateDead); lotService.updateLot(lot); return "ok"; } }
package com.vicky7230.sunny.activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.vicky7230.sunny.R; import com.vicky7230.sunny.utils.Util; import org.sufficientlysecure.htmltextview.HtmlTextView; public class AboutActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Util.night()) setTheme(R.style.AppThemeNight); setContentView(R.layout.activity_about); init(); } private void init() { Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); HtmlTextView iconAttribution = findViewById(R.id.icon_attribution); iconAttribution.setHtml("<div>App Icon made by <a href=\"https://www.flaticon.com/authors/kiranshastry\" title=\"Kiranshastry\">Kiranshastry</a> from <a href=\"https://www.flaticon.com/\" title=\"Flaticon\">www.flaticon.com</a> is licensed by <a href=\"http://creativecommons.org/licenses/by/3.0/\" title=\"Creative Commons BY 3.0\" target=\"_blank\">CC 3.0 BY</a></div>"); HtmlTextView apiAttribution = findViewById(R.id.api_attribution); apiAttribution.setHtml("Powered By <a href=\"https://openweathermap.org\" title=\"openWeatherMap\">OpenWeatherMap</a>"); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } }
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.AggregateprogrammType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ReceiveAggregateprogrammType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ReceiveHeaderType; import java.io.StringWriter; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; public class ReceiveAggregateprogrammTypeBuilder { public static String marshal(ReceiveAggregateprogrammType receiveAggregateprogrammType) throws JAXBException { JAXBElement<ReceiveAggregateprogrammType> jaxbElement = new JAXBElement<>(new QName("TESTING"), ReceiveAggregateprogrammType.class , receiveAggregateprogrammType); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } private AggregateprogrammType aggregateprogramm; private ReceiveHeaderType header; public ReceiveAggregateprogrammTypeBuilder setAggregateprogramm(AggregateprogrammType value) { this.aggregateprogramm = value; return this; } public ReceiveAggregateprogrammTypeBuilder setHeader(ReceiveHeaderType value) { this.header = value; return this; } public ReceiveAggregateprogrammType build() { ReceiveAggregateprogrammType result = new ReceiveAggregateprogrammType(); result.setAggregateprogramm(aggregateprogramm); result.setHeader(header); return result; } }