Datasets:
repo_name
stringlengths 7
104
| file_path
stringlengths 11
238
| context
list | import_statement
stringlengths 103
6.85k
| code
stringlengths 60
38.4k
| next_line
stringlengths 10
824
| gold_snippet_index
int32 0
8
|
---|---|---|---|---|---|---|
sastix/cms | server/src/main/java/com/sastix/cms/server/services/content/impl/ZipHandlerServiceImpl.java | [
"@Getter @Setter @NoArgsConstructor @ToString\npublic class CreateResourceDTO {\n\n /**\n * The media-type of this new resource.\n */\n @NotNull\n private String resourceMediaType;\n\n /**\n * The author creating this resource.\n */\n @NotNull\n private String resourceAuthor;\n\n /**\n * The byte[] array of this resource.\n */\n private byte[] resourceBinary;\n\n /**\n * The URI holding this resource.\n */\n private String resourceExternalURI;\n\n /**\n * The name of the resource with optional relative path.\n */\n @NotNull\n private String resourceName;\n\n /**\n * A system-specific tenant identifier for multi-tenancy reasons.\n */\n @NotNull\n private String resourceTenantId;\n \n // TODO: Should we add a parentResourceUID?\n \n /**\n * Constructor with mandatory fields.\n *\n * @param resourceMediaType a String with the media type\n * @param resourceAuthor a String with the author\n * @param resourceName a String with resource name\n * @param resourceTenantId a String with the tenant id\n */\n public CreateResourceDTO(final String resourceMediaType,\n final String resourceAuthor,\n final String resourceName,\n final String resourceTenantId) {\n this.resourceMediaType = resourceMediaType;\n this.resourceAuthor = resourceAuthor;\n this.resourceName = resourceName;\n this.resourceTenantId = resourceTenantId;\n }\n\n}",
"@Getter @Setter @NoArgsConstructor @ToString\npublic class ResourceDTO {\n\n /**\n * The UID of the object to lock.\n */\n @NotNull\n private String resourceUID;\n\n /**\n * The author requesting the lock.\n */\n @NotNull\n private String author;\n\n /**\n * If available, this URI can fetch this resource on a subsequent request, as R/O content.\n */\n private String resourceURI;\n\n /**\n * A list of all linked resources for this UID, valid only if this UID is a \"package\" containing several other resources that have been inserted.\n */\n private List<ResourceDTO> resourcesList;\n\n /**\n * Constructor with the mandatory fields.\n *\n * @param resourceUID a String with the resource UID\n * @param author a String with the author\n */\n public ResourceDTO(final String resourceUID, final String author) {\n this.resourceUID = resourceUID;\n this.author = author;\n }\n\n}",
"@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = Constants.RESOURCE_ACCESS_ERROR)\npublic class ResourceAccessError extends GeneralResourceException {\n\n /**\n * Serial Version UID.\n */\n private static final long serialVersionUID = 7739893346328334895L;\n\n /**\n * Constructor that allows a specific error message to be specified.\n *\n * @param message detail message.\n */\n public ResourceAccessError(String message) {\n super(message);\n }\n}",
"@Entity\n@Table(name = \"resource\")\n@NamedQueries({\n @NamedQuery(name = \"Resource.findAll\", query = \"SELECT resource FROM Resource resource\")\n , @NamedQuery(name = \"Resource.findByAuthor\", query = \"SELECT resource FROM Resource resource WHERE resource.author = :author\")\n , @NamedQuery(name = \"Resource.findByAuthorContaining\", query = \"SELECT resource FROM Resource resource WHERE resource.author like :author\")\n , @NamedQuery(name = \"Resource.findByName\", query = \"SELECT resource FROM Resource resource WHERE resource.name = :name\")\n , @NamedQuery(name = \"Resource.findByNameContaining\", query = \"SELECT resource FROM Resource resource WHERE resource.name like :name\")\n , @NamedQuery(name = \"Resource.findByMediaType\", query = \"SELECT resource FROM Resource resource WHERE resource.mediaType = :mediaType\")\n , @NamedQuery(name = \"Resource.findByMediaTypeContaining\", query = \"SELECT resource FROM Resource resource WHERE resource.mediaType like :mediaType\")\n , @NamedQuery(name = \"Resource.findByPath\", query = \"SELECT resource FROM Resource resource WHERE resource.path = :path\")\n , @NamedQuery(name = \"Resource.findByPathContaining\", query = \"SELECT resource FROM Resource resource WHERE resource.path like :path\")\n , @NamedQuery(name = \"Resource.findByUid\", query = \"SELECT resource FROM Resource resource WHERE resource.uid = :uid\")\n , @NamedQuery(name = \"Resource.findByUidContaining\", query = \"SELECT resource FROM Resource resource WHERE resource.uid like :uid\")\n})\n@Getter @Setter @NoArgsConstructor\npublic class Resource implements Serializable {\n\n public static final String FIND_ALL = \"Resource.findAll\";\n public static final String FIND_BY_AUTHOR = \"Resource.findByAuthor\";\n public static final String FIND_BY_AUTHOR_CONTAINING = \"Resource.findByAuthorContaining\";\n public static final String FIND_BY_NAME = \"Resource.findByName\";\n public static final String FIND_BY_NAME_CONTAINING = \"Resource.findByNameContaining\";\n public static final String FIND_BY_MEDIATYPE = \"Resource.findByMediaType\";\n public static final String FIND_BY_MEDIATYPE_CONTAINING = \"Resource.findByMediaTypeContaining\";\n public static final String FIND_BY_PATH = \"Resource.findByPath\";\n public static final String FIND_BY_PATH_CONTAINING = \"Resource.findByPathContaining\";\n public static final String FIND_BY_UID = \"Resource.findByUid\";\n public static final String FIND_BY_UID_CONTAINING = \"Resource.findByUidContaining\";\n private static final long serialVersionUID = -7222707205353947820L;\n\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Integer id;\n\n @Column(name = \"author\", nullable = false, unique = false)\n private String author;\n\n @Column(name = \"name\", nullable = false, unique = false)\n private String name;\n\n @Column(name = \"media_type\", nullable = false, unique = false)\n private String mediaType;\n\n @Column(name = \"path\", length = 512, nullable = false, unique = false)\n private String path;\n\n @Column(name = \"uid\", length = 255, nullable = false, unique = false)\n private String uid;\n\n @Column(name = \"uri\", length = 255, nullable = false, unique = false)\n private String uri;\n\n @Column(name = \"resource_tenant_id\", nullable = false)\n private String resourceTenantId;\n \n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"resource_id\")\n private Resource resource;\n\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"resource\")\n private Set<Resource> resources = new HashSet<Resource>(0);\n\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = \"resource\")\n private Set<Revision> revisions = new HashSet<Revision>(0);\n\n}",
"public interface DistributedCacheService {\n\n void cacheIt(String uri, String tenantId);\n\n void updateCache(String uri, String tenantId);\n}",
"public interface HashedDirectoryService {\n\n String storeFile(final String UURI, final String tenantID, final byte[] resourceBinary) throws IOException;\n\n String replaceFile(final String UURI, final String tenantID, final byte[] resourceBinary) throws IOException;\n\n String storeFile(final String UURI, final String tenantID, final URI resourceURI) throws IOException;\n\n String replaceFile(final String UURI, final String tenantID, final URI resourceURI) throws IOException;\n\n String storeFile(final String UURI, final String tenantID, final String resourceURI) throws IOException, URISyntaxException;\n\n String replaceFile(final String UURI, final String tenantID, final String resourceURI) throws IOException, URISyntaxException;\n\n Path getDataByUID(final String UID, final String tenantID) throws IOException;\n\n byte[] getBytesByUID(final String UID, final String tenantID) throws IOException;\n\n Path getDataByURI(final String resourceURI, final String tenantID) throws IOException, URISyntaxException;\n\n byte[] getBytesByURI(final String resourceURI, final String tenantID) throws IOException;\n\n long getFileSize(final String resourceURI, final String tenantID) throws IOException;\n\n String hashText(String text);\n\n String getAbsolutePath(String resourceURI, final String tenantID);\n\n String createTenantDirectory(final String tenantID) throws IOException;\n\n String getVolume();\n\n void setVolume(String value);\n\n void storeChecksum(final String tenantID, final String checksum) throws IOException;\n\n String getChecksum(final String tenantID) throws IOException;\n}",
"public interface ResourceService extends ContentApi {\n\n Path getDataPath(DataDTO dataDTO) throws ResourceAccessError;\n\n ResponseEntity<InputStreamResource> getResponseInputStream(String uuid) throws ResourceAccessError, IOException;\n\n MultipartFileSender getMultipartFileSender(String uuid) throws ResourceAccessError, IOException;\n\n Resource insertResource(final CreateResourceDTO createResourceDTO);\n\n Resource insertChildResource(final CreateResourceDTO createResourceDTO, final String parentUid, final Resource parentResource);\n\n\n}",
"public interface ZipHandlerService {\n\n ResourceDTO handleZip(Resource zipResource);\n\n boolean isZip(Resource zipResource);\n}"
] | import com.sastix.cms.common.content.CreateResourceDTO;
import com.sastix.cms.common.content.ResourceDTO;
import com.sastix.cms.common.content.exceptions.ResourceAccessError;
import com.sastix.cms.server.domain.entities.Resource;
import com.sastix.cms.server.services.content.DistributedCacheService;
import com.sastix.cms.server.services.content.HashedDirectoryService;
import com.sastix.cms.server.services.content.ResourceService;
import com.sastix.cms.server.services.content.ZipHandlerService;
import org.apache.tika.Tika;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.GsonJsonParser;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; | /*
* Copyright(c) 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sastix.cms.server.services.content.impl;
@Slf4j
@Service
public class ZipHandlerServiceImpl implements ZipHandlerService {
public static final String METADATA_XML_FILE = "imsmanifest.xml";
public static final String METADATA_JSON_FILE = "info.json";
public static final String METADATA_STARTPAGE = "startpage";
public static final String METADATA_STARTPAGE_CAMEL = "startPage";
private final GsonJsonParser gsonJsonParser = new GsonJsonParser();
@Autowired
DistributedCacheService distributedCacheService;
@Autowired | HashedDirectoryService hashedDirectoryService; | 5 |
melloc/roguelike | game/src/main/java/edu/brown/cs/roguelike/game/GUIApp.java | [
"public final class Vec2i implements Serializable {\r\n\tprivate static final long serialVersionUID = 5659632794862666943L;\r\n\t\r\n\t/**\r\n\t * Since {@link Vec2i} instances are immutable, their x and y fields may be accessed without getters.\r\n\t */\r\n\tpublic final int x, y;\r\n\t\r\n\t/**\r\n\t * Creates a new vector from an x and y component.\r\n\t * @param x the x-component of the vector\r\n\t * @param y the y-component of the vector\r\n\t */\r\n\tpublic Vec2i(int x, int y) {\r\n\t\tthis.x = x;\r\n\t\tthis.y = y;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Factory method that creates a {@code Vec2i} by {@linkplain Math#round(float) rounding} the components of a {@link Vec2f} to the nearest integer.\r\n\t * @param v the Vec2f to round\r\n\t * @return a Vec2i created by rounding the components of {@code v}\r\n\t */\r\n\tpublic final static Vec2i fromRounded(Vec2f v) {\r\n\t\treturn new Vec2i(round(v.x), round(v.y));\r\n\t}\r\n\t\r\n\t/**\r\n\t * Factory method that creates a {@code Vec2i} by taking the {@linkplain Math#floor(double) floor} of the components of a {@link Vec2f}.\r\n\t * @param v the {@code Vec2f} to floor\r\n\t * @return a {@code Vec2i} created by taking the floor of the components of {@code v}\r\n\t */\r\n\tpublic final static Vec2i fromFloored(Vec2f v) {\r\n\t\treturn new Vec2i((int)floor(v.x), (int)floor(v.y));\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * Factory method that creates a {@code Vec2i} by taking the {@linkplain Math#ceil(double) ceiling} of the components of a {@link Vec2f}.\r\n\t * @param v the {@code Vec2f} to ceil\r\n\t * @return a {@code Vec2i} created by taking the ceiling of the components of {@code v}\r\n\t */\r\n\tpublic final static Vec2i fromCeiled(Vec2f v) {\r\n\t\treturn new Vec2i((int)ceil(v.x), (int)ceil(v.y));\r\n\t}\r\n\t\r\n\t/*\r\n\t * Vector ops\r\n\t */\r\n\t\r\n\t/**\r\n\t * Multiplies the vector by a scalar.\r\n\t * @param s the scalar by which to multiply this vector\r\n\t * @return a new {@link Vec2i} instance where each component has been multiplied by {@code s}\r\n\t */\r\n\tpublic final Vec2i smult(int s) {\r\n\t\treturn new Vec2i(x*s, y*s);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Divides the vector by a scalar. Note that this is integer division.\r\n\t * @param s\t\tthe scalar by which to divide this vector\r\n\t * @return\t\ta new {@link Vec2i} instance where each component has been divided by\r\n\t * \t\t\t\t{@code s}\r\n\t */\r\n\tpublic final Vec2i sdiv(int s) {\r\n\t\treturn new Vec2i(x/s, y/s);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Multiplies the vector piecewise by another vector. NOT A DOT PRODUCT.\r\n\t * @param v the vector by which to multiply this vector\r\n\t * @return a new {@link Vec2i} instance where each component has been multiplied by the corresponding component in {@code v}\r\n\t */\r\n\tpublic final Vec2i pmult(Vec2i v) {\r\n\t\treturn new Vec2i(x*v.x, y*v.y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Primitive version of {@link #pmult(Vec2i)}.\r\n\t */\r\n\tpublic final Vec2i pmult(int x, int y) {\r\n\t\treturn new Vec2i(this.x * x, this.y * y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Divides the vector piecewise by another vector.\r\n\t * @param v the vector by which to divide this vector\r\n\t * @return a new {@link Vec2i} instance where each component has been divided by the corresponding component in {@code v}\r\n\t */\r\n\tpublic final Vec2i pdiv(Vec2i v) {\r\n\t\treturn new Vec2i(x/v.x, y/v.y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Primitive version of {@link #pdiv(Vec2i)}.\r\n\t */\r\n\tpublic final Vec2i pdiv(int x, int y) {\r\n\t\treturn new Vec2i(this.x/x, this.y/y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Adds another vector to this vector.\r\n\t * @param v the vector to add to this vector\r\n\t * @return a new {@link Vec2i} instance where each component has added the corresponding component in {@code v}\r\n\t */\r\n\tpublic final Vec2i plus(Vec2i v) {\r\n\t\treturn new Vec2i(x + v.x, y + v.y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Primitive version of {@link #plus(Vec2i)}.\r\n\t */\r\n\tpublic final Vec2i plus(int x, int y) {\r\n\t\treturn new Vec2i(this.x + x, this.y + y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Subtracts another vector from this vector.\r\n\t * @param v the vector to subtract from this vector\r\n\t * @return a new {@link Vec2i} instance where each component has added the corresponding component in {@code v}\r\n\t */\r\n\tpublic final Vec2i minus(Vec2i v) {\r\n\t\treturn new Vec2i(x - v.x, y - v.y);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Primitive version of {@link #minus(Vec2i)}.\r\n\t */\r\n\tpublic final Vec2i minus(int x, int y) {\r\n\t\treturn new Vec2i(this.x - x, this.y - y);\r\n\t}\r\n\t\r\n\tpublic Dimension toDimension() {\r\n\t\treturn new Dimension(this.x, this.y);\r\n\t}\r\n\t\r\n\t/*\r\n\t * Object overrides\r\n\t */\r\n\r\n\t@Override\r\n\tpublic final int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + x;\r\n\t\tresult = prime * result + y;\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic final boolean equals(Object obj) {\r\n\t\tif (obj == null || obj.getClass() != Vec2i.class)\r\n\t\t\treturn false;\r\n\t\tVec2i other = (Vec2i) obj;\r\n\t\treturn x == other.x && y == other.y;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic final String toString() {\r\n\t\treturn new StringBuilder(\"(\").append(x).append(\", \").append(y).append(\")\").toString();\r\n\t}\r\n\r\n\tpublic static Vec2i fromPoint(Point pt) {\r\n\t\treturn new Vec2i(pt.x, pt.y);\r\n\t}\r\n\r\n\tpublic Point toPoint() {\r\n\t\treturn new Point(this.x, this.y);\r\n\t}\r\n}\r",
"public class ConfigurationException extends Exception {\n\t\n\t/**\n\t * Generated \n\t */\n\tprivate static final long serialVersionUID = 5399497813931843528L;\n\n\tpublic ConfigurationException(String msg) {\n\t\tsuper(msg);\n\t}\n\t\n\tpublic ConfigurationException(Throwable cause) {\n\t\tsuper(cause);\n\t}\n\n}",
"public class CumulativeTurnManager extends TurnManager {\n\t\n\t/**\n\t * Generated\n\t */\n\tprivate static final long serialVersionUID = 2226734907191258919L;\n\t\n\tprivate final int pointsPerTurn;\n\t\n\t// If the player has less than minPtsPerTurn, they won't be given the\n\t// chance to go again during that turn. This helps to alleviate \n\t// player action lag. There may be a better way to do this\n\tprivate final int minPtsPerTurn;\n\t\n\n\tpublic CumulativeTurnManager(Application app, Game game, int pointsPerTurn) {\n\t\tsuper(app, game, pointsPerTurn);\n\t\tthis.pointsPerTurn = pointsPerTurn;\n\t\tthis.minPtsPerTurn = pointsPerTurn/2;\n\t}\n\t\n\t@Override\n\tpublic void takeTurnWithoutAnnounce(Action playerAction) {\n\t\t\n\t\tAction nextAction = null;\n\t\tint cost;\n\t\t\n\t\tEntityManager em = game.getCurrentLevel().getManager();\n\t\t\n\t\tEntityActionManager mainMgr = em.getEntity(\"main\").get(0);\n\t\t\n\t\t// if the player doesn't have an Action queued, then set one\n\t\tif (!mainMgr.hasNextAction()) { \n\t\t\tmainMgr.setNextAction(playerAction);\n\t\t} // otherwise try to do the action that has been queued\n\t\t\n\t\t// Player's turn:\n\t\tnextAction = mainMgr.getNextAction();\n\t\tcost = (nextAction instanceof Wait) ? \n\t\t\t\tpointsPerTurn : nextAction.getCost();\n\t\t\n\t\t// if the Player can take the action, then take it\n\t\tif (cost <= mainMgr.getActionPoints()) {\n\t\t\tmainMgr.takeNextAction();\n\t\t\tmainMgr.useActionPoints(cost);\n\t\t}\n\t\t\n\t\t// if there are more than minPtsPerTurn remaining, then return \n\t\t// and wait for player's next input\n\t\tif (mainMgr.getActionPoints() > minPtsPerTurn) return;\n\t\telse { // continue and grant APs for this turn\n\t\t\tmainMgr.addActionPoints(pointsPerTurn);\n\t\t}\n\n\t\t// take care of monsters:\n\t\t\n\t\tList<EntityActionManager> monsterMgrs = em.getEntity(\"monster\");\n\n\t\tfor (EntityActionManager mgr: monsterMgrs) {\n\n\t\t\tdo { // actions\n\t\t\t\t// check to make sure this monster still exists and hasn't been\n\t\t\t\t// concurrently removed\n\t\t\t\tif (em.reallyExists(mgr)) { \n\n\t\t\t\t\tnextAction = mgr.getNextAction();\n\t\t\t\t\tcost = (nextAction instanceof Wait) ? \n\t\t\t\t\t\t\tpointsPerTurn : nextAction.getCost();\n\n\t\t\t\t\t// if the monster can afford it, take the action\n\t\t\t\t\tif (cost <= mgr.getActionPoints()) {\n\t\t\t\t\t\tmgr.takeNextAction();\n\t\t\t\t\t\tmgr.useActionPoints(cost);\n\t\t\t\t\t} else { break; }\n\t\t\t\t} \n\t\t\t} \n\t\t\t// until we have too few points to try again\n\t\t\t// TODO: consider making the lower bound minPtsPerTurn? \n\t\t\twhile (mgr.getActionPoints() > 0);\n\t\t\t\n\t\t\t// finally, grant points for this turn\n\t\t\tmgr.addActionPoints(pointsPerTurn);\n\t\t}\n\t}\n}",
"public abstract class Game implements Saveable {\n\t\n\t/**\n\t * Generated\n\t */\n\tprivate static final long serialVersionUID = 4193150732888666463L;\n\n\tprotected GameState gameState;\n\t\n\tprotected Hashtable<Integer,Level> levels = new Hashtable<Integer,Level>();\n;\n\tprotected Level currentLevel;\n\tprotected Vec2i levelSize;\n\tprotected final Vec2i MAP_SIZE;\n \n public Game(Vec2i mapSize) {\n \tthis.MAP_SIZE = mapSize;\n \tthis.init();\n }\n \n /**Initalizes the first level\n * @throws ConfigurationException **/\n\tpublic void createInitalLevel(BSPLevelGenerator lg) throws ConfigurationException {\n\t\tthis.currentLevel = lg.generateLevel(MAP_SIZE, 1);\n\t\tlevels.put(1, currentLevel);\n\t\t\n\t\t//TODO: Get character name\n\t\tMainCharacter mc = new MainCharacter(\"Robert the Rogue\");\n\t\t\n\t\tcurrentLevel.placeCharacter(mc, true);\n\t}\n \n /**\n * Moves the player to the level indicated by depth\n * @param depth - The depth the player is moving to\n * @param levelGen - The level generator to use if new levels are needed\n * @throws ConfigurationException - A configuration problem exists\n */\n public void gotoLevel(int depth, LevelGenerator levelGen) throws ConfigurationException {\n \tif(levels.get(depth) == null) {\n \t\tLevel newLevel = levelGen.generateLevel(MAP_SIZE, depth);\n \t\t\n \t\tMainCharacter mc = currentLevel.removePlayer();\n \t\tnewLevel.placeCharacter(mc, currentLevel.getDepth() < depth);\n \t\tlevels.put(depth,newLevel);\n \t\tcurrentLevel = newLevel;\n \t}\n \telse {\n \t\tMainCharacter mc = currentLevel.removePlayer();\n \t\tlevels.get(depth).placeCharacter(mc, currentLevel.getDepth() < depth);\n \t\tcurrentLevel = levels.get(depth);\n \t}\n }\n \n private void init() {\n \tthis.gameState = GameState.INIT;\n }\n \n public void start() {\n \tthis.gameState = GameState.RUNNING;\n }\n \n public void win() { \n \tthis.gameState = GameState.WIN;\n }\n \n public void loss() { \n \tthis.gameState = GameState.LOSS;\n }\n \n public GameState getState() { \n \treturn this.gameState;\n }\n \n public Level getCurrentLevel() { return this.currentLevel; }\n\n \n /**\n * Takes a LevelGenerator to prevent the need to serialize a local copy\n * \n * @deprecated Use gotoLevel\n * \n * @param lg\n * @return\n * @throws ConfigurationException\n */\n public Level generateNewLevel(LevelGenerator lg) throws ConfigurationException {\n \tthis.currentLevel = lg.generateLevel(MAP_SIZE, 3);\n \treturn currentLevel;\n }\n \n \n \n\t/*** BEGIN Saveable ***/\n\n\tprivate UUID id;\n\t\n\t/** initialize id **/\n\t{\n\t\tthis.id = UUID.randomUUID();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\n\t\treturn result;\n\t}\n\t\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tGame other = (Game) obj;\n\t\tif (id == null) {\n\t\t\tif (other.id != null)\n\t\t\t\treturn false;\n\t\t} else if (id.equals(other.id))\n\t\t\t// return true if ids are the same\n\t\t\treturn true;\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic UUID getId() {\n\t\treturn this.id;\n\t}\n\t\n\t/*** END Saveable ***/\n\n}",
"public abstract class Application extends LanternaFrontend {\n\n /**\n * This stack contains all elements in the game that should be drawn.\n * The element on top of the stack is considered the `active` element,\n * and receives all key presses.\n */\n\tprotected Stack<Layer> layers = new Stack<Layer>();\n\t\n\tpublic Stack<Layer> getLayers() {return layers;}\n\t\n\tpublic Application(String title) {\n\t\tsuper(title);\n\t}\n\n\t@Override\n\tprotected void onTick(long nanosSincePreviousTick) {\n\t\tfor (Layer layer : layers)\n\t\t\tlayer.tick(nanosSincePreviousTick);\n\t}\n\n\t@Override\n\tprotected void onDraw(Section s) {\n\t\tfor (Layer layer : layers)\n\t\t\tlayer.doDraw(s);\n\t}\n\t\n /**\n * Takes care of any initialization that is necessary for the game. For \n * example, any {@link Layer}'s that need to be added to the stack should\n * be added here. Any other preparation that is necessary should also be \n * done here.\n *\n * @param screenSize The initial size of the screen. This is provided in \n * case there is a need to determine where things should initially be drawn\n * until the next resize (which may never happen, so passing this in is \n * sort of important).\n *\n * @return Boolean indicating whether initialization was sucessful.\n */\n\tprotected abstract boolean initialize(Vec2i screenSize);\n\n\t@Override\n\tprotected void onKeyPressed(Key k) {\n\t\tif (!layers.isEmpty()) {\n\t\t\tLayer active = layers.peek();\n\t\t\tactive.propagateAction(active.getActionForKey(k));\n\t\t}\n\t}\n\t\n\tpublic abstract void deleteSaveFile();\n\t\n\t\n\tprivate boolean initialized = false;\n\n\t@Override\n\tprotected void onResize(Vec2i newSize) {\n\t\tif (!initialized)\n\t\t\tinitialized = initialize(newSize);\n\t\t\t\n\t\tfor (Layer layer : layers)\n\t\t\tlayer.updateSize(newSize);\n\t}\n\n}",
"public class BSPLevelGenerator implements LevelGenerator{\r\n\tprivate final int depthMax = 3;\r\n\r\n\r\n\t//-----------------------------------------------------------------------CONSTANTS-----------------------------------------------------------------------------------------------------------------\r\n\t/*\r\n\tprivate float roomMin; //min % the room occupies of sublevel\r\n\tprivate float roomMax; //max % the room occupies of sublevel\r\n\tprivate float roomBuffer; //% on each side of room must be from edge\r\n\t */\r\n\r\n\tprivate final float splitMin = 0.1f; // min % to split at\r\n\tprivate final float splitMax = 0.9f; // max % to split at\r\n\r\n\tprivate final int minWallThickness = 2; //Should be >= 2\r\n\r\n\tprivate int minRoomDim = 5;\r\n\r\n\tprivate int splitTries = 7;\r\n\r\n\r\n\t//---------------------------------------------------------------------END CONSTANTS------------------------------------------------------------------------------------------------------\r\n\r\n\tTile[][] tiles;\r\n\tRandomGen rand;\r\n\r\n\tprivate String configDir;\r\n\r\n\tpublic BSPLevelGenerator(String configDir) {\r\n\t\tthis.configDir = configDir;\r\n\t}\r\n\r\n\t/**\r\n\t * Generates a full level whose size is levelSize\r\n\t * @throws ConfigurationException \r\n\t */\r\n\tpublic Level generateLevel(Vec2i levelSize, int depth) throws ConfigurationException {\r\n\t\trand = new RandomGen(System.nanoTime());\r\n\t\ttiles = new Tile[levelSize.x][levelSize.y];\r\n\r\n\t\t//Init with solid map\r\n\t\tfillWithSolids(tiles);\r\n\r\n\t\tSubLevel fullLevel = new SubLevel(new Vec2i(0,0), levelSize,0);\r\n\t\tsplitAndBuild(fullLevel);\r\n\r\n\t\tLevel level = new Level(tiles,fullLevel.rooms,fullLevel.hallways);\r\n\r\n\t\tcreateStairs(level);\r\n\r\n\t\tlevel.setDepth(depth); \r\n\t\tMonsterGenerator mg = new ProgressiveMonsterGenerator(configDir);\r\n\t\tmg.populateLevel(level);\r\n\r\n\t\tItemGenerator ig = new ProgressiveItemGenerator(configDir); \r\n\t\tig.populateLevel(level);\r\n\r\n\t\treturn level;\r\n\t}\r\n\r\n\r\n\r\n\t/**Creates the up and down stairs**/\r\n\tprivate void createStairs(Level level) {\r\n\r\n\t\tRoom r = level.getRooms().get(rand.getRandom(level.getRooms().size()));\r\n\t\tint mX = rand.getRandom(r.min.x, r.max.x);\r\n\t\tint mY = rand.getRandom(r.min.y, r.max.y);\r\n\t\tTile t = level.getTiles()[mX][mY];\t\r\n\t\tlevel.upStairs = t;\r\n\t\tt.setType(TileType.UP_STAIRS);\r\n\r\n\t\tRoom r2;\r\n\t\tTile t2;\r\n\r\n\t\tif(level.getRooms().size() == 1) {\r\n\t\t\tr2 = r;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tdo {\r\n\t\t\t\tr2 = level.getRooms().get(rand.getRandom(level.getRooms().size()));\r\n\t\t\t}\r\n\t\t\twhile (r2 == r);\r\n\t\t}\r\n\r\n\t\tint x = rand.getRandom(r2.min.x, r2.max.x);\r\n\t\tint y = rand.getRandom(r2.min.y, r2.max.y);\r\n\t\tt2 = level.getTiles()[x][y];\t\r\n\r\n\t\tlevel.downStairs = t2;\r\n\t\tt2.setType(TileType.DOWN_STAIRS);\r\n\t}\r\n\r\n\r\n\r\n\r\n\t/**\r\n\t * Splits the sublevel recursively until it builds rooms, then connects the rooms together\r\n\t * In the end, curr is populated with the current hallways and rooms\r\n\t */\r\n\r\n\tprivate void splitAndBuild(SubLevel curr) {\r\n\t\tboolean makeRoom = false;\r\n\t\tint splitAttempts = 0;\r\n\r\n\t\tif(curr.depth == depthMax) //Check to see if you should make a room\r\n\t\t{\r\n\t\t\tmakeRoom = true;\r\n\t\t}\r\n\t\tif(makeRoom) {\r\n\t\t\tmakeRoom(curr);\r\n\t\t}\r\n\t\telse{ \r\n\r\n\t\t\t//Split into two more sub-levels, recur, then connect\r\n\t\t\tSplit s = (rand.getRandom(2) == 0) ? Split.VER : Split.HOR;\r\n\r\n\t\t\tif(s == Split.HOR) {\r\n\t\t\t\tfloat height = (curr.max.y-curr.min.y);\r\n\t\t\t\tif(height < 4*minWallThickness + 2*minRoomDim) {\r\n\t\t\t\t\ts = Split.VER;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse { //VER\r\n\t\t\t\tfloat width = (curr.max.x-curr.min.x);\r\n\t\t\t\tif(width < 4*minWallThickness + 2*minRoomDim) {\r\n\t\t\t\t\ts = Split.HOR;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\r\n\t\t\tSubLevel s1,s2;\r\n\r\n\r\n\t\t\tif(s == Split.HOR){\r\n\t\t\t\tfloat height = (curr.max.y-curr.min.y);\r\n\r\n\t\t\t\tif(height < 4*minWallThickness + 2*minRoomDim) {\r\n\t\t\t\t\tmakeRoom(curr);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tint splitVal = Math.round(curr.min.y + height*splitMin+ rand.getRandom(Math.round((height*(splitMax-splitMin)))));\r\n\r\n\t\t\t\twhile(splitVal - curr.min.y < 2*minWallThickness + minRoomDim || curr.max.y - splitVal -1 < 2*minWallThickness + minRoomDim ) {\r\n\t\t\t\t\tif(splitAttempts >= splitTries) {\r\n\t\t\t\t\t\tmakeRoom(curr);\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tsplitAttempts++;\r\n\t\t\t\t\tsplitVal = Math.round(curr.min.y + height*splitMin+ rand.getRandom(Math.round((height*(splitMax-splitMin)))));\r\n\t\t\t\t}\r\n\r\n\t\t\t\t//S1 gets [0-splitVal], S2 gets [SplitVal+1,Max]\r\n\t\t\t\ts1 = new SubLevel(new Vec2i(curr.min.x,curr.min.y), new Vec2i(curr.max.x,splitVal), curr.depth+1);\r\n\t\t\t\ts2 = new SubLevel(new Vec2i(curr.min.x,splitVal+1), new Vec2i(curr.max.x,curr.max.y), curr.depth+1);\r\n\t\t\t}\r\n\t\t\telse { //VER\r\n\t\t\t\tfloat width = (curr.max.x-curr.min.x);\r\n\r\n\t\t\t\tif(width < 4*minWallThickness + 2*minRoomDim) {\r\n\t\t\t\t\tmakeRoom(curr);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tint maxVal = Math.round((width*(splitMax-splitMin)));\r\n\t\t\t\tint splitVal = Math.round(curr.min.x + width*splitMin+ rand.getRandom(maxVal));\r\n\r\n\t\t\t\twhile(splitVal - curr.min.x < 2*minWallThickness + minRoomDim || curr.max.x - splitVal -1 < 2*minWallThickness + minRoomDim ) {\r\n\t\t\t\t\tif(splitAttempts >= splitTries) {\r\n\t\t\t\t\t\tmakeRoom(curr);\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tsplitAttempts++;\r\n\t\t\t\t\tmaxVal = Math.round((width*(splitMax-splitMin)));\r\n\t\t\t\t\tsplitVal = Math.round(curr.min.x + width*splitMin+ rand.getRandom(maxVal));\r\n\t\t\t\t}\r\n\r\n\t\t\t\t//S1 gets [0-splitVal], S2 gets [SplitVal+1,Max]\r\n\t\t\t\ts1 = new SubLevel(new Vec2i(curr.min.x,curr.min.y), new Vec2i(splitVal,curr.max.y), curr.depth+1);\r\n\t\t\t\ts2 = new SubLevel(new Vec2i(splitVal+1,curr.min.y), new Vec2i(curr.max.x,curr.max.y), curr.depth+1);\r\n\t\t\t}\r\n\r\n\t\t\tsplitAndBuild(s1);\r\n\t\t\tsplitAndBuild(s2);\r\n\r\n\t\t\tRange range = s1.overLap(s2, s);\r\n\t\t\tif(range != null)\r\n\t\t\t{\r\n\t\t\t\tint hpt;\r\n\t\t\t\tHallwayPoint hp1;\r\n\t\t\t\tHallwayPoint hp2;\r\n\t\t\t\tdo{\r\n\t\t\t\t\thpt = rand.getRandom(range.min,range.max);\r\n\t\t\t\t\thp1 = s1.getHallwayPoint(s, true, hpt);\r\n\t\t\t\t\thp2 = s2.getHallwayPoint(s, false, hpt);\r\n\t\t\t\t}\r\n\t\t\t\twhile (!testHallway(hp1.point,hp2.point));\r\n\r\n\t\t\t\tHallway new_hallway = new Hallway(hp1.point,hp2.point);\r\n\r\n\t\t\t\tpaintHallway(hp1.point,hp2.point,true, new_hallway, TileType.FLOOR);\r\n\r\n\t\t\t\thp1.space.connectToHallway(new_hallway);\r\n\t\t\t\thp2.space.connectToHallway(new_hallway);\r\n\r\n\t\t\t\tif(hp1.space.needDoor())\r\n\t\t\t\t\tmakeDoor(hp1.point,s, new_hallway, true);\r\n\t\t\t\tif(hp2.space.needDoor())\r\n\t\t\t\t\tmakeDoor(hp2.point,s, new_hallway, false);\r\n\r\n\t\t\t\tcurr.hallways.add(new_hallway);\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\t//Make L-Shaped corridor\r\n\t\t\t\tif(s == Split.HOR) {\r\n\r\n\t\t\t\t\tHallwayPoint hp1;\r\n\t\t\t\t\tHallwayPoint hp2;\r\n\t\t\t\t\tVec2i corner;\r\n\t\t\t\t\tdo{\r\n\t\t\t\t\t\tint cx = rand.getRandom(s1.intersectMin.x, s1.intersectMax.x);\r\n\t\t\t\t\t\tint cy = rand.getRandom(s2.intersectMin.y, s2.intersectMax.y);\r\n\t\t\t\t\t\tcorner = new Vec2i(cx,cy);\r\n\r\n\t\t\t\t\t\thp1 = s1.getHallwayPoint(Split.HOR, true, cx);\r\n\t\t\t\t\t\thp2 = s2.getHallwayPoint(Split.VER, (s2.intersectMin.x < s1.intersectMax.x), cy);\r\n\t\t\t\t\t}\r\n\t\t\t\t\twhile (!testHallway(hp1.point,corner) && !testHallway(hp2.point,corner));\r\n\r\n\r\n\r\n\r\n\t\t\t\t\tHallway new_hallway1 = new Hallway(hp1.point,corner);\r\n\t\t\t\t\thp1.space.connectToHallway(new_hallway1);\r\n\r\n\t\t\t\t\tHallway new_hallway2;\r\n\r\n\t\t\t\t\tif (s2.intersectMin.x > s1.intersectMax.x) \r\n\t\t\t\t\t\tnew_hallway2 = new Hallway(hp2.point,corner);\r\n\t\t\t\t\telse \r\n\t\t\t\t\t\tnew_hallway2 = new Hallway(corner,hp2.point);\r\n\r\n\r\n\t\t\t\t\thp2.space.connectToHallway(new_hallway2);\r\n\r\n\t\t\t\t\tnew_hallway1.connectToHallway(new_hallway2);\r\n\r\n\t\t\t\t\t//Paint in\r\n\t\t\t\t\tpaintHallway(hp1.point,corner,true,new_hallway1, TileType.FLOOR);\r\n\t\t\t\t\tpaintHallway(hp2.point,corner,true,new_hallway2, TileType.FLOOR);\r\n\r\n\t\t\t\t\tif(hp1.space.needDoor())\r\n\t\t\t\t\t\tmakeDoor(hp1.point,s, new_hallway1, true);\r\n\t\t\t\t\tif(hp2.space.needDoor())\r\n\t\t\t\t\t\tmakeDoor(hp2.point,s, new_hallway2, false);\r\n\r\n\t\t\t\t\tcurr.hallways.add(new_hallway1);\r\n\t\t\t\t\tcurr.hallways.add(new_hallway2);\r\n\t\t\t\t}\r\n\t\t\t\telse{ //VER\r\n\r\n\t\t\t\t\tHallwayPoint hp1;\r\n\t\t\t\t\tHallwayPoint hp2;\r\n\t\t\t\t\tVec2i corner;\r\n\r\n\t\t\t\t\tdo{\r\n\t\t\t\t\t\tint cx = s1.intersectMin.x + rand.getRandom(s1.intersectMax.x - s1.intersectMin.x);\r\n\t\t\t\t\t\tint cy = s2.intersectMin.y + rand.getRandom(s2.intersectMax.y - s2.intersectMin.y);\r\n\t\t\t\t\t\tcorner = new Vec2i(cx,cy);\r\n\r\n\t\t\t\t\t\thp1 = s1.getHallwayPoint(Split.HOR, (s1.intersectMin.y < s2.intersectMax.y), cx);\r\n\t\t\t\t\t\thp2 = s2.getHallwayPoint(Split.VER, false, cy);\r\n\t\t\t\t\t}\r\n\t\t\t\t\twhile (!testHallway(hp1.point,corner) && !testHallway(hp2.point,corner));\r\n\r\n\t\t\t\t\tHallway new_hallway1;\r\n\t\t\t\t\tif (s1.intersectMin.y < s2.intersectMax.y)\r\n\t\t\t\t\t\tnew_hallway1 = new Hallway(hp1.point,corner);\r\n\t\t\t\t\telse \r\n\t\t\t\t\t\tnew_hallway1 = new Hallway(corner,hp1.point);\r\n\r\n\t\t\t\t\thp1.space.connectToHallway(new_hallway1);\r\n\r\n\t\t\t\t\tHallway new_hallway2 = new Hallway(corner,hp2.point);\r\n\t\t\t\t\thp2.space.connectToHallway(new_hallway2);\r\n\r\n\t\t\t\t\tnew_hallway1.connectToHallway(new_hallway2);\r\n\r\n\t\t\t\t\t//Paint in\r\n\t\t\t\t\tpaintHallway(hp1.point,corner,true, new_hallway1, TileType.FLOOR);\r\n\t\t\t\t\tpaintHallway(hp2.point,corner,true, new_hallway2, TileType.FLOOR);\r\n\r\n\t\t\t\t\tif(hp1.space.needDoor())\r\n\t\t\t\t\t\tmakeDoor(hp1.point,s,new_hallway1, true);\r\n\t\t\t\t\tif(hp2.space.needDoor())\r\n\t\t\t\t\t\tmakeDoor(hp2.point,s,new_hallway2, false);\r\n\r\n\t\t\t\t\tcurr.hallways.add(new_hallway1);\r\n\t\t\t\t\tcurr.hallways.add(new_hallway2);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t//Combine into a single sublevel\r\n\t\t\tcurr.rooms.addAll(s1.rooms);\r\n\t\t\tcurr.rooms.addAll(s2.rooms);\r\n\t\t\tcurr.hallways.addAll(s1.hallways);\r\n\t\t\tcurr.hallways.addAll(s2.hallways);\r\n\r\n\t\t\tint maxIX = Math.max(s1.intersectMax.x, s2.intersectMax.x);\r\n\t\t\tint maxIY = Math.max(s1.intersectMax.y, s2.intersectMax.y);\r\n\t\t\tint minIX = Math.min(s1.intersectMin.x, s2.intersectMin.x);\r\n\t\t\tint minIY = Math.min(s1.intersectMin.y, s2.intersectMin.y);\r\n\r\n\t\t\tcurr.intersectMax = new Vec2i(maxIX,maxIY);\r\n\t\t\tcurr.intersectMin = new Vec2i(minIX,minIY);\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\t/**Makes a door at location, using the split and side to accurately place it in the wall**/\r\n\tprivate void makeDoor(Vec2i point, Split s, Space space, boolean b) {\r\n\t\tint xOff=0;\r\n\t\tint yOff=0;\r\n\r\n\t\tif(s == Split.HOR) \r\n\t\t\tyOff = 1;\r\n\t\telse\r\n\t\t\txOff = 1;\r\n\t\tif(!b) {\r\n\t\t\txOff *= -1;\r\n\t\t\tyOff *= -1;\r\n\t\t}\r\n\r\n\t\tTile t = tiles[point.x+xOff][point.y+yOff];\r\n\t\tt.setType(TileType.DOOR);\r\n\t\tt.setSpace(space);\r\n\t}\r\n\r\n\r\n\t/**\r\n\t * Makes a room inside the sublevel\r\n\t * @param curr - the area to make the room in\r\n\t */\r\n\tprivate void makeRoom(SubLevel curr) {\r\n\t\tint maxWidth = curr.max.x - curr.min.x- 1*minWallThickness - 1;\r\n\t\tint maxHeight = curr.max.y - curr.min.y - 1*minWallThickness - 1;\r\n\r\n\r\n\t\t//Randomly Select room coordinates\r\n\t\tint minX = rand.getRandom(minWallThickness,maxWidth-minRoomDim);\r\n\t\tint maxX = rand.getRandom(minX+minRoomDim, maxWidth);\r\n\r\n\t\tint minY = rand.getRandom(minWallThickness,maxHeight-minRoomDim);\r\n\t\tint maxY = rand.getRandom(minY+minRoomDim, maxHeight);\r\n\r\n\t\t/*\r\n\t\tint minY = minWallThickness+rand.getRandom(maxHeightprivate void paintCellRectangle(Vec2i min, Vec2i max, boolean passable, TileType t) {\r\n\t\tfor(int i = min.x; i <= max.x; i++) {\r\n\t\t\tfor(int j = min.y; j <= max.y; j++) {\r\n\t\t\t\tTile x = tiles[i][j];\r\n\t\t\t\tx.setType(t);\r\n\t\t\t}\r\n\t\t}-minRoomDim);\r\n\t\tint maxY = minY + minRoomDim + rand.getRandom(maxHeight-minY-minRoomDim);\r\n\t\t */\r\n\r\n\t\tVec2i min = curr.min.plus(minX, minY);\r\n\t\tVec2i max = curr.min.plus(maxX, maxY);\r\n\r\n\t\tRoom r = new Room(min,max);\r\n\r\n\t\t//Paint room to tile array\r\n\t\tpaintCellRectangle(min,max,true, r, TileType.FLOOR);\r\n\t\tpaintCellRectangle( curr.min.plus(minX-1,minY-1), curr.min.plus(minX-1,maxY+1),false, null, TileType.WALL_VER);\r\n\t\tpaintCellRectangle( curr.min.plus(maxX+1,minY-1), curr.min.plus(maxX+1,maxY+1),false, null, TileType.WALL_VER);\r\n\t\tpaintCellRectangle( curr.min.plus(minX-1,minY-1), curr.min.plus(maxX+1,minY-1),false, null, TileType.WALL_HOR);\r\n\t\tpaintCellRectangle( curr.min.plus(minX-1,maxY+1), curr.min.plus(maxX+1,maxY+1),false, null, TileType.WALL_HOR);\r\n\t\t\r\n\t\tcurr.rooms.add(r);\r\n\r\n\t\t//Hallways dont got to ends of rooms\r\n\t\tcurr.intersectMin = min;\r\n\t\tcurr.intersectMax = max;\r\n\r\n\t\t//Hallways dont got to ends of rooms\r\n\t\t//curr.intersectMin = min.plus(1,1);\r\n\t\t//curr.intersectMax = max.plus(-1,-1);\r\n\t}\r\n\r\n\t/**\r\n\t * Puts a cell with the given attributes in the rectangle given by\r\n\t * min,max inclusive.\r\n\t */\r\n\tprivate void paintCellRectangle(Vec2i min, Vec2i max, boolean passable,\r\n\t\t\tSpace space, TileType t) {\r\n\t\tfor(int i = min.x; i <= max.x; i++) {\r\n\t\t\tfor(int j = min.y; j <= max.y; j++) {\r\n\t\t\t\tTile x = tiles[i][j];\r\n\t\t\t\tx.setSpace(space);\r\n\t\t\t\tx.setType(t);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**Tests to see if a hallway can be laid. returns true if there are no problems**/\r\n\tprivate boolean testHallway(Vec2i a, Vec2i b) {\r\n\t\tif(a.x > b.x || a.y > b.y) {\r\n\t\t\ttestHallway(b,a);\r\n\t\t}\r\n\r\n\t\tif(a.x == b.x) {\r\n\t\t\tfor(int i = a.x-1; i <= a.x+1; i++) {\r\n\t\t\t\tfor(int j = a.y+2; j <= b.y-2; j++) {\r\n\t\t\t\t\tTile x = tiles[i][j];\r\n\t\t\t\t\tif(x.getType() != TileType.SOLID) {\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse{\r\n\t\t\tfor(int y = a.y-1; y <= a.y+1; y++) {\r\n\t\t\t\tfor(int x = a.x+2; x <= b.x-2; x++) {\r\n\t\t\t\t\tTile t = tiles[x][y];\r\n\t\t\t\t\tif(t.getType() != TileType.SOLID) {\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\t/**Paints a hallway onto the tile array**/\r\n\tprivate void paintHallway(Vec2i a, Vec2i b, boolean passable, \r\n\t\t\tSpace space, TileType t) {\r\n\t\tif(a.x > b.x || a.y > b.y) {\r\n\t\t\tpaintHallway(b,a,passable, space, t);\r\n\t\t}\r\n\t\tfor(int i = a.x; i <= b.x; i++) {\r\n\t\t\tfor(int j = a.y; j <= b.y; j++) {\r\n\t\t\t\tTile x = tiles[i][j];\r\n\t\t\t\tx.setType(t);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**Fills the tiles with all walls **/\r\n\tprivate void fillWithSolids(Tile[][] tiles) {\r\n\t\tfor(int i = 0; i < tiles.length; i++) {\r\n\t\t\tfor(int j = 0; j<tiles[0].length; j++) {\r\n\t\t\t\ttiles[i][j] = new Tile(TileType.SOLID);\r\n\t\t\t\ttiles[i][j].setLocation(new Vec2i(i,j));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n}\r",
"public class SaveManager {\n\t\n\tprivate static final String fileExtension = \".rog\";\n\t\n\tprivate String saveFile;\n\n\tpublic SaveManager(String saveFile) {\n\t\tif (saveFile.endsWith(fileExtension))\n\t\t\tthis.saveFile = saveFile;\n\t\telse this.saveFile = saveFile + fileExtension;\n\t}\n\n\t/**\n\t * Saves the current level, obliterating anything that\n\t * was already there\n\t * \n\t * @throws SaveLoadException\n\t */\n\tpublic void saveLevel(Level l) throws SaveLoadException {\n\t\ttry {\n\t\t\tFileOutputStream fos = new FileOutputStream(this.saveFile);\n\t\t\tObjectOutputStream oos = new ObjectOutputStream(fos);\n\t\t\t\n\t\t\toos.writeObject(l);\n\t\t\tfos.close();\n\t\t\toos.close();\n\t\t} catch (Exception e) {\n\t\t\tthrow new SaveLoadException(e);\n\t\t}\n\t}\n\t\n\tpublic void deleteSave() {\n\t\tFile f = new File(saveFile);\n\t\tif(f.exists()) \n\t\t\tf.delete();\n\t\t\n\t}\n\n\t/**\n\t * \n\t * Attempts to load a savegame from saveFile\n\t * \n\t * @throws SaveLoadException if there was no save file\n\t */\n\tpublic Level loadLevel() throws SaveLoadException {\n\t\t\n\t\tLevel l = null;\n\n\t\ttry {\n\t\t\tFileInputStream fis = new FileInputStream(this.saveFile);\n\t\t\tObjectInputStream ois = new ObjectInputStream(fis);\n\t\t\n\t\t\tObject o = ois.readObject();\n\t\t\tois.close();\n\t\t\t\n\t\t\tif (o instanceof Level) {\n\t\t\t\tl = (Level)o;\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tthrow new SaveLoadException(\n\t\t\t\t\t\t\"Save file was not a Level object. Found: \" \n\t\t\t\t\t\t\t\t+ o + \" instead\");\n\t\t\t}\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\tthrow new SaveLoadException(e);\n\t\t}\n\t\t\n\t\treturn l;\n\t}\n\t\n\t/**\n\t * Saves the game, obliterating anything that\n\t * was already there\n\t * \n\t * @throws SaveLoadException\n\t */\n\tpublic void saveGame(Game g) throws SaveLoadException {\n\t\ttry {\n\t\t\tFileOutputStream fos = new FileOutputStream(this.saveFile);\n\t\t\tObjectOutputStream oos = new ObjectOutputStream(fos);\n\t\t\t\n\t\t\toos.writeObject(g);\n\t\t\toos.close();\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new SaveLoadException(e);\n\t\t}\n\t}\n\n\t/**\n\t * \n\t * Attempts to load a savegame from saveFile\n\t * \n\t * @throws SaveLoadException if there was no save file\n\t */\n\tpublic Game loadGame() throws SaveLoadException {\n\t\t\n\t\tGame g = null;\n\n\t\ttry {\n\t\t\tFileInputStream fis = new FileInputStream(this.saveFile);\n\t\t\tObjectInputStream ois = new ObjectInputStream(fis);\n\t\t\n\t\t\tObject o = ois.readObject();\n\t\t\tois.close();\n\t\t\t\n\t\t\tif (o instanceof Game) {\n\t\t\t\tg = (Game)o;\n\t\t\t} else {\n\t\t\t\tthrow new SaveLoadException(\n\t\t\t\t\t\t\"Save file was not a Game object. Found: \" \n\t\t\t\t\t\t\t\t+ o + \" instead\");\n\t\t\t}\n\t\t\t\n\t\t} catch (Exception e) {\n\t\t\tthrow new SaveLoadException(e);\n\t\t}\n\t\t\n\t\treturn g;\n\t}\n\n}"
] | import cs195n.Vec2i;
import edu.brown.cs.roguelike.engine.config.ConfigurationException;
import edu.brown.cs.roguelike.engine.game.CumulativeTurnManager;
import edu.brown.cs.roguelike.engine.game.Game;
import edu.brown.cs.roguelike.engine.graphics.Application;
import edu.brown.cs.roguelike.engine.proc.BSPLevelGenerator;
import edu.brown.cs.roguelike.engine.save.SaveManager; | package edu.brown.cs.roguelike.game;
public class GUIApp extends Application {
private final static Vec2i SCREEN_SIZE = new Vec2i(80,30);
private final static int POINTS_PER_TURN = 10;
private SaveManager sm; | private CumulativeTurnManager tm; | 2 |
IncQueryLabs/smarthome-cep-demonstrator | runtime/com.incquerylabs.smarthome.eventbus.api/src/main/java/com/incquerylabs/smarthome/eventbus/api/IEventSubscriber.java | [
"public class GroupItemStateChangedEvent extends ItemStateChangedEvent {\n\n\tpublic GroupItemStateChangedEvent(Item item, State newState, State oldState) {\n\t\tsuper(item, newState, oldState);\n\t}\n\t\n @Override\n public String toString() {\n return String.format(\"%s group state changed from %s to %s\", item.getName(), oldState, newState);\n }\n}",
"public class ItemAddedEvent implements ItemEvent {\n protected final Item item;\n\n\tpublic ItemAddedEvent(Item item) {\n\t\tsuper();\n\t\tthis.item = item;\n\t}\n\n\tpublic Item getItem() {\n\t\treturn item;\n\t}\n\t\n\tpublic String getName() {\n\t\treturn item.getName();\n\t}\n\t\n @Override\n public String toString() {\n return \"Item '\" + item.getName() + \"' has been added.\";\n }\n}",
"public class ItemCommandEvent extends ItemCommandBase implements ItemEvent {\n\n\tpublic ItemCommandEvent(Item item, Command command) {\n\t\tsuper(item, command);\n\t}\n}",
"public class ItemRemovedEvent implements ItemEvent {\n protected final String itemName;\n\n\tpublic ItemRemovedEvent(String itemName) {\n\t\tsuper();\n\t\tthis.itemName = itemName;\n\t}\n\t\n\tpublic String getName() {\n\t\treturn itemName;\n\t}\n\t\n @Override\n public String toString() {\n return \"Item '\" + itemName + \"' has been removed.\";\n }\n}",
"public class ItemStateChangedEvent extends ItemStateChangedBase implements ItemEvent {\n\n public ItemStateChangedEvent(Item item, State newState, State oldState) {\n super(item, newState, oldState);\n }\n}",
"public class ItemStateEvent implements ItemEvent {\n protected final Item item;\n protected final State itemState;\n\n\tpublic ItemStateEvent(Item item, State itemState) {\n\t\tsuper();\n\t\tthis.item = item;\n\t\tthis.itemState = itemState;\n\t}\n\n\tpublic Item getItem() {\n\t\treturn item;\n\t}\n\t\n public String getName() {\n return this.item.getName();\n }\n\n\tpublic State getItemState() {\n\t\treturn itemState;\n\t}\n\t\n @Override\n public String toString() {\n return String.format(\"%s updated to %s\", item.getName(), itemState);\n }\n}",
"public class ItemUpdatedEvent {\n protected final Item newItem;\n protected final String oldItemName;\n\t\n\tpublic ItemUpdatedEvent(Item newItem, String oldItemName) {\n\t\tsuper();\n\t\tthis.newItem = newItem;\n\t\tthis.oldItemName = oldItemName;\n\t}\n\n\tpublic Item getNewItem() {\n\t\treturn newItem;\n\t}\n\n\tpublic String getOldItemName() {\n\t\treturn oldItemName;\n\t}\n\t\n @Override\n public String toString() {\n return \"Item '\" + oldItemName + \"' has been updated.\";\n }\n}"
] | import java.util.Collection;
import org.eclipse.smarthome.core.items.Item;
import com.incquerylabs.smarthome.eventbus.api.events.GroupItemStateChangedEvent;
import com.incquerylabs.smarthome.eventbus.api.events.ItemAddedEvent;
import com.incquerylabs.smarthome.eventbus.api.events.ItemCommandEvent;
import com.incquerylabs.smarthome.eventbus.api.events.ItemRemovedEvent;
import com.incquerylabs.smarthome.eventbus.api.events.ItemStateChangedEvent;
import com.incquerylabs.smarthome.eventbus.api.events.ItemStateEvent;
import com.incquerylabs.smarthome.eventbus.api.events.ItemUpdatedEvent; | package com.incquerylabs.smarthome.eventbus.api;
public interface IEventSubscriber {
public void stateUpdated(ItemStateEvent event);
public void stateChanged(ItemStateChangedEvent event);
public void groupStateChanged(GroupItemStateChangedEvent event);
public void commandReceived(ItemCommandEvent event);
public void initItems(Collection<Item> items);
public void itemAdded(ItemAddedEvent event);
| public void itemRemoved(ItemRemovedEvent event); | 3 |
integeruser/jgltut | src/integeruser/jgltut/tut13/GeomImpostor.java | [
"public enum MouseButtons {\n MB_LEFT_BTN,\n MB_RIGHT_BTN,\n MB_MIDDLE_BTN\n}",
"public static class ViewData {\n public Vector3f targetPos;\n public Quaternionf orient;\n public float radius;\n public float degSpinRotation;\n\n public ViewData(Vector3f targetPos, Quaternionf orient, float radius, float degSpinRotation) {\n this.targetPos = targetPos;\n this.orient = orient;\n this.radius = radius;\n this.degSpinRotation = degSpinRotation;\n }\n\n public ViewData(ViewData viewData) {\n targetPos = new Vector3f(viewData.targetPos);\n orient = new Quaternionf(viewData.orient);\n radius = viewData.radius;\n degSpinRotation = viewData.degSpinRotation;\n }\n}",
"public static class ViewPole extends ViewProvider {\n private enum RotateMode {\n RM_DUAL_AXIS_ROTATE,\n RM_BIAXIAL_ROTATE,\n RM_XZ_AXIS_ROTATE,\n RM_Y_AXIS_ROTATE,\n RM_SPIN_VIEW_AXIS\n }\n\n private enum TargetOffsetDir {\n DIR_UP,\n DIR_DOWN,\n DIR_FORWARD,\n DIR_BACKWARD,\n DIR_RIGHT,\n DIR_LEFT\n }\n\n private ViewData currView;\n private ViewScale viewScale;\n\n private ViewData initialView;\n private MouseButtons actionButton;\n private boolean rightKeyboardCtrls;\n\n // Used when rotating.\n private boolean isDragging;\n private RotateMode rotateMode;\n\n private float degStarDragSpin;\n private Vector2i startDragMouseLoc;\n private Quaternionf startDragOrient;\n\n private Vector3f offsets[] = {\n new Vector3f(0.0f, 1.0f, 0.0f),\n new Vector3f(0.0f, -1.0f, 0.0f),\n new Vector3f(0.0f, 0.0f, -1.0f),\n new Vector3f(0.0f, 0.0f, 1.0f),\n new Vector3f(1.0f, 0.0f, 0.0f),\n new Vector3f(-1.0f, 0.0f, 0.0f)\n };\n\n ////////////////////////////////\n public ViewPole(ViewData initialView, ViewScale viewScale) {\n this(initialView, viewScale, MouseButtons.MB_LEFT_BTN, false);\n }\n\n public ViewPole(ViewData initialView, ViewScale viewScale, MouseButtons actionButton) {\n this(initialView, viewScale, actionButton, false);\n }\n\n public ViewPole(ViewData initialView, ViewScale viewScale, MouseButtons actionButton, boolean rightKeyboardCtrls) {\n currView = new ViewData(initialView);\n this.viewScale = viewScale;\n this.initialView = initialView;\n this.actionButton = actionButton;\n this.rightKeyboardCtrls = rightKeyboardCtrls;\n }\n\n ////////////////////////////////\n @Override\n public void mouseMove(Vector2i position) {\n if (isDragging) {\n onDragRotate(position);\n }\n }\n\n @Override\n public void mouseClick(MouseButtons button, boolean isPressed, MouseModifiers modifiers, Vector2i position) {\n if (isPressed) {\n // Ignore all other button presses when dragging.\n if (!isDragging) {\n if (button == actionButton) {\n if (modifiers == MouseModifiers.MM_KEY_CTRL) {\n beginDragRotate(position, RotateMode.RM_BIAXIAL_ROTATE);\n } else if (modifiers == MouseModifiers.MM_KEY_ALT) {\n beginDragRotate(position, RotateMode.RM_SPIN_VIEW_AXIS);\n } else {\n beginDragRotate(position, RotateMode.RM_DUAL_AXIS_ROTATE);\n }\n }\n }\n } else {\n // Ignore all other button releases when not dragging\n if (isDragging) {\n if (button == actionButton) {\n if (rotateMode == RotateMode.RM_DUAL_AXIS_ROTATE || rotateMode == RotateMode.RM_SPIN_VIEW_AXIS\n || rotateMode == RotateMode.RM_BIAXIAL_ROTATE) {\n endDragRotate(position);\n }\n }\n }\n }\n }\n\n @Override\n public void mouseWheel(int direction, MouseModifiers modifiers, Vector2i position) {\n if (direction > 0) {\n moveCloser(modifiers != MouseModifiers.MM_KEY_SHIFT);\n } else {\n moveAway(modifiers != MouseModifiers.MM_KEY_SHIFT);\n }\n }\n\n\n @Override\n public void charPress(int key, boolean isShiftPressed, float lastFrameDuration) {\n if (rightKeyboardCtrls) {\n switch (key) {\n case GLFW_KEY_I:\n offsetTargetPos(\n TargetOffsetDir.DIR_FORWARD,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_K:\n offsetTargetPos(\n TargetOffsetDir.DIR_BACKWARD,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_L:\n offsetTargetPos(\n TargetOffsetDir.DIR_RIGHT,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_J:\n offsetTargetPos(\n TargetOffsetDir.DIR_LEFT,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_O:\n offsetTargetPos(\n TargetOffsetDir.DIR_UP,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_U:\n offsetTargetPos(\n TargetOffsetDir.DIR_DOWN,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n }\n } else {\n switch (key) {\n case GLFW_KEY_W:\n offsetTargetPos(\n TargetOffsetDir.DIR_FORWARD,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_S:\n offsetTargetPos(\n TargetOffsetDir.DIR_BACKWARD,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_D:\n offsetTargetPos(\n TargetOffsetDir.DIR_RIGHT,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_A:\n offsetTargetPos(\n TargetOffsetDir.DIR_LEFT,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_E:\n offsetTargetPos(\n TargetOffsetDir.DIR_UP,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n\n case GLFW_KEY_Q:\n offsetTargetPos(\n TargetOffsetDir.DIR_DOWN,\n isShiftPressed ? viewScale.smallPosOffset : viewScale.largePosOffset,\n lastFrameDuration);\n break;\n }\n }\n }\n\n\n @Override\n public Matrix4f calcMatrix() {\n Matrix4f mat = new Matrix4f();\n\n // Remember: these transforms are in reverse order.\n\n // In this space, we are facing in the correct direction. Which means that the camera point\n // is directly behind us by the radius number of units.\n mat.translate(new Vector3f(0.0f, 0.0f, -currView.radius));\n\n // Rotate the world to look in the right direction.\n Quaternionf angleAxis = new Quaternionf().setAngleAxis((float) Math.toRadians(currView.degSpinRotation), 0.0f, 0.0f, 1.0f);\n Quaternionf fullRotation = angleAxis.mul(currView.orient);\n\n mat.mul(fullRotation.get(new Matrix4f()));\n\n // Translate the world by the negation of the lookat point, placing the origin at the lookat point.\n mat.translate(new Vector3f(currView.targetPos).negate());\n return mat;\n }\n\n ////////////////////////////////\n public void reset() {\n if (!isDragging) {\n currView = new ViewData(initialView);\n }\n }\n\n\n public ViewData getView() {\n return currView;\n }\n\n ////////////////////////////////\n private void beginDragRotate(Vector2i ptStart, RotateMode rotMode) {\n rotateMode = rotMode;\n startDragMouseLoc = ptStart;\n degStarDragSpin = currView.degSpinRotation;\n startDragOrient = currView.orient;\n isDragging = true;\n }\n\n\n private void onDragRotate(Vector2i ptCurr) {\n Vector2i diff = new Vector2i(ptCurr).sub(startDragMouseLoc);\n int diffX = diff.x;\n int diffY = diff.y;\n\n switch (rotateMode) {\n case RM_DUAL_AXIS_ROTATE:\n processXYChange(diffX, diffY);\n break;\n\n case RM_BIAXIAL_ROTATE:\n if (Math.abs(diffX) > Math.abs(diffY)) {\n processXChange(diffX, true);\n } else {\n processYChange(diffY, true);\n }\n break;\n\n case RM_XZ_AXIS_ROTATE:\n processXChange(diffX);\n break;\n\n case RM_Y_AXIS_ROTATE:\n processYChange(diffY);\n break;\n\n case RM_SPIN_VIEW_AXIS:\n processSpinAxis(diffX, diffY);\n break;\n }\n }\n\n\n private void endDragRotate(Vector2i ptEnd) {\n endDragRotate(ptEnd, true);\n }\n\n private void endDragRotate(Vector2i ptEnd, boolean keepResults) {\n if (keepResults) {\n onDragRotate(ptEnd);\n } else {\n currView.orient = startDragOrient;\n }\n\n isDragging = false;\n }\n\n\n private void processXChange(int diffX) {\n processXChange(diffX, false);\n }\n\n private void processXChange(int diffX, boolean clearY) {\n float degAngleDiff = diffX * viewScale.rotationScale;\n\n // Rotate about the world-space Y axis.\n Quaternionf angleAxisY = new Quaternionf().setAngleAxis((float) Math.toRadians(degAngleDiff), 0.0f, 1.0f, 0.0f);\n currView.orient = new Quaternionf(startDragOrient).mul(angleAxisY);\n }\n\n\n private void processYChange(int diffY) {\n processYChange(diffY, false);\n }\n\n private void processYChange(int diffY, boolean clearXZ) {\n float degAngleDiff = diffY * viewScale.rotationScale;\n\n // Rotate about the local-space X axis.\n Quaternionf angleAxisX = new Quaternionf().setAngleAxis((float) Math.toRadians(degAngleDiff), 1.0f, 0.0f, 0.0f);\n currView.orient = angleAxisX.mul(startDragOrient);\n }\n\n\n private void processXYChange(int diffX, int diffY) {\n float degXAngleDiff = (diffX * viewScale.rotationScale);\n float degYAngleDiff = (diffY * viewScale.rotationScale);\n\n // Rotate about the world-space Y axis.\n Quaternionf angleAxisY = new Quaternionf().setAngleAxis((float) Math.toRadians(degXAngleDiff), 0.0f, 1.0f, 0.0f);\n currView.orient = new Quaternionf(startDragOrient).mul(angleAxisY);\n // Rotate about the local-space X axis.\n Quaternionf angleAxisX = new Quaternionf().setAngleAxis((float) Math.toRadians(degYAngleDiff), 1.0f, 0.0f, 0.0f);\n currView.orient = angleAxisX.mul(currView.orient);\n }\n\n\n private void processSpinAxis(int diffX, int diffY) {\n float degSpinDiff = diffX * viewScale.rotationScale;\n currView.degSpinRotation = degSpinDiff + degStarDragSpin;\n }\n\n\n private void moveCloser(boolean largeStep) {\n if (largeStep) {\n currView.radius -= viewScale.largeRadiusDelta;\n } else {\n currView.radius -= viewScale.smallRadiusDelta;\n }\n\n if (currView.radius < viewScale.minRadius) {\n currView.radius = viewScale.minRadius;\n }\n }\n\n\n private void moveAway(boolean largeStep) {\n if (largeStep) {\n currView.radius += viewScale.largeRadiusDelta;\n } else {\n currView.radius += viewScale.smallRadiusDelta;\n }\n\n if (currView.radius > viewScale.maxRadius) {\n currView.radius = viewScale.maxRadius;\n }\n }\n\n\n private void offsetTargetPos(TargetOffsetDir dir, float worldDistance, float lastFrameDuration) {\n Vector3f offsetDir = new Vector3f(offsets[dir.ordinal()]);\n offsetTargetPos(offsetDir.mul(worldDistance).mul(lastFrameDuration), lastFrameDuration);\n }\n\n private void offsetTargetPos(Vector3f cameraOffset, float lastFrameDuration) {\n Matrix4f currMat = calcMatrix();\n Quaternionf orientation = new Quaternionf();\n currMat.getNormalizedRotation(orientation);\n\n Quaternionf invOrient = new Quaternionf(orientation).conjugate();\n Vector3f worldOffset = invOrient.transform(new Vector3f(cameraOffset));\n\n currView.targetPos.add(worldOffset);\n }\n}",
"public static class ViewScale {\n public float minRadius;\n public float maxRadius;\n public float largeRadiusDelta;\n public float smallRadiusDelta;\n public float largePosOffset;\n public float smallPosOffset;\n public float rotationScale;\n\n public ViewScale(float minRadius, float maxRadius, float largeRadiusDelta, float smallRadiusDelta,\n float largePosOffset, float smallPosOffset, float rotationScale) {\n this.minRadius = minRadius;\n this.maxRadius = maxRadius;\n this.largeRadiusDelta = largeRadiusDelta;\n this.smallRadiusDelta = smallRadiusDelta;\n this.largePosOffset = largePosOffset;\n this.smallPosOffset = smallPosOffset;\n this.rotationScale = rotationScale;\n }\n}",
"public abstract class Tutorial {\n protected long window;\n\n protected DoubleBuffer mouseBuffer1 = BufferUtils.createDoubleBuffer(1);\n protected DoubleBuffer mouseBuffer2 = BufferUtils.createDoubleBuffer(1);\n\n // Measured in seconds\n protected float elapsedTime;\n protected float lastFrameDuration;\n\n private double lastFrameTimestamp;\n\n protected FloatBuffer vec4Buffer = BufferUtils.createFloatBuffer(4);\n protected FloatBuffer mat3Buffer = BufferUtils.createFloatBuffer(9);\n protected FloatBuffer mat4Buffer = BufferUtils.createFloatBuffer(16);\n protected ByteBuffer projectionBlockBuffer = BufferUtils.createByteBuffer(ProjectionBlock.BYTES);\n protected ByteBuffer unprojectionBlockBuffer = BufferUtils.createByteBuffer(UnprojectionBlock.BYTES);\n protected ByteBuffer lightBlockBuffer = BufferUtils.createByteBuffer(LightBlock.BYTES);\n protected ByteBuffer materialBlockBuffer = BufferUtils.createByteBuffer(MaterialBlock.BYTES);\n\n ////////////////////////////////\n\n public final void start(int width, int height) {\n try {\n GLFWErrorCallback.createPrint(System.err).set();\n\n initGLFW();\n initWindow(width, height);\n\n glfwSwapInterval(1);\n GL.createCapabilities();\n\n initCallbacks();\n init();\n initViewport();\n\n printInfo();\n\n loop();\n\n glfwFreeCallbacks(window);\n glfwDestroyWindow(window);\n } finally {\n glfwTerminate();\n glfwSetErrorCallback(null).free();\n }\n }\n\n\n private void initGLFW() {\n if (!glfwInit()) throw new IllegalStateException(\"Unable to initialize GLFW\");\n\n glfwDefaultWindowHints();\n glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);\n glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);\n if (Platform.get() == Platform.MACOSX) {\n glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);\n glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);\n glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n }\n }\n\n private void initWindow(int width, int height) {\n window = glfwCreateWindow(width, height, \"jgltut\", NULL, NULL);\n if (window == NULL) throw new RuntimeException(\"Failed to create the GLFW window\");\n\n GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());\n glfwSetWindowPos(window, (vidmode.width() - width) / 2, (vidmode.height() - height) / 2);\n\n glfwMakeContextCurrent(window);\n glfwShowWindow(window);\n }\n\n private void initViewport() {\n // From http://www.glfw.org/faq.html#why-is-my-output-in-the-lower-left-corner-of-the-window:\n // \"On OS X with a Retina display, and possibly on other platforms in the future, screen coordinates and\n // pixels do not map 1:1. Use the framebuffer size, which is in pixels, instead of the window size.\"\n int[] w = new int[1], h = new int[1];\n glfwGetFramebufferSize(window, w, h);\n reshape(w[0], h[0]);\n }\n\n private void initCallbacks() {\n glfwSetFramebufferSizeCallback(window, (window, width, height) -> {\n reshape(width, height);\n });\n\n glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {\n if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) glfwSetWindowShouldClose(window, true);\n });\n }\n\n private void printInfo() {\n System.out.println();\n System.out.println(\"-----------------------------------------------------------\");\n\n System.out.format(\"%-18s%s\\n\", \"Running:\", getClass().getName());\n System.out.format(\"%-18s%s\\n\", \"OpenGL version:\", glGetString(GL_VERSION));\n\n if (!GL.getCapabilities().OpenGL33) {\n System.out.println(\"You must have at least OpenGL 3.3 to run this tutorial.\");\n }\n }\n\n private void loop() {\n long startTime = System.nanoTime();\n while (!glfwWindowShouldClose(window)) {\n elapsedTime = (float) ((System.nanoTime() - startTime) / 1000000000.0);\n\n double now = System.nanoTime();\n lastFrameDuration = (float) ((now - lastFrameTimestamp) / 1000000000.0);\n lastFrameTimestamp = now;\n\n update();\n display();\n\n glfwSwapBuffers(window);\n glfwPollEvents();\n }\n }\n\n ////////////////////////////////\n\n protected abstract void init();\n\n protected abstract void display();\n\n protected abstract void reshape(int w, int h);\n\n protected abstract void update();\n\n ////////////////////////////////\n\n protected final boolean isKeyPressed(int key) {\n return glfwGetKey(window, key) == 1;\n }\n\n protected final boolean isMouseButtonPressed(int key) {\n return glfwGetMouseButton(window, key) == 1;\n }\n}",
"public class Framework {\n public static String COMMON_DATAPATH = \"/integeruser/jgltut/data/\";\n public static String CURRENT_TUTORIAL_DATAPATH = null;\n\n\n public static String findFileOrThrow(String fileName) {\n // search the file in '/jgltut/tut##/data/'\n InputStream fileStream = Framework.class.getResourceAsStream(CURRENT_TUTORIAL_DATAPATH + fileName);\n if (fileStream != null) return CURRENT_TUTORIAL_DATAPATH + fileName;\n\n // search the file in '/jgltut/data/'\n fileStream = Framework.class.getResourceAsStream(COMMON_DATAPATH + fileName);\n if (fileStream != null) return COMMON_DATAPATH + fileName;\n\n throw new RuntimeException(\"Could not find the file \" + fileName);\n }\n\n ////////////////////////////////\n public static int loadShader(int shaderType, String shaderFilename) {\n String filePath = Framework.findFileOrThrow(shaderFilename);\n String shaderCode = loadShaderFile(filePath);\n return Shader.compileShader(shaderType, shaderCode);\n }\n\n private static String loadShaderFile(String shaderFilePath) {\n StringBuilder text = new StringBuilder();\n\n try {\n BufferedReader reader = new BufferedReader(new InputStreamReader(Framework.class.getResourceAsStream(shaderFilePath)));\n\n String line;\n while ((line = reader.readLine()) != null) {\n text.append(line).append(\"\\n\");\n }\n\n reader.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return text.toString();\n }\n\n\n public static int createProgram(ArrayList<Integer> shaders) {\n try {\n int prog = Shader.linkProgram(shaders);\n return prog;\n } finally {\n for (Integer shader : shaders) {\n glDeleteShader(shader);\n }\n }\n }\n}",
"public class Mesh {\n public Mesh(String filename) {\n ArrayList<Attribute> attribs = new ArrayList<>(16);\n ArrayList<IndexData> indexData = new ArrayList<>();\n ArrayList<NamedVAO> namedVaoList = new ArrayList<>();\n\n Document doc = null;\n try {\n DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\n DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\n\n String meshPath = Framework.findFileOrThrow(filename);\n doc = dBuilder.parse(Mesh.class.getResourceAsStream(meshPath));\n } catch (ParserConfigurationException | SAXException | IOException e) {\n e.printStackTrace();\n System.exit(-1);\n }\n\n Element meshElement = doc.getDocumentElement();\n NodeList attrs = meshElement.getElementsByTagName(\"attribute\");\n for (int i = 0; i < attrs.getLength(); i++) {\n // crea un Attribute e lo aggiunge a attribs\n Attribute a = new Attribute(attrs.item(i));\n attribs.add(a);\n }\n\n NodeList vaos = meshElement.getElementsByTagName(\"vao\");\n for (int i = 0; i < vaos.getLength(); i++) {\n // crea un NamedVAO con ProcessVAO e lo aggiunge a namedVaoList\n NamedVAO namedVao = new NamedVAO(vaos.item(i));\n namedVaoList.add(namedVao);\n }\n\n NodeList cmds = meshElement.getElementsByTagName(\"indices\");\n for (int i = 0; i < cmds.getLength(); i++) {\n // aggiunge a primitives il risultato di ProcessRenderCmd\n RenderCmd r = new RenderCmd(cmds.item(i));\n primitives.add(r);\n // aggiunge a indexData il risultato di IndexData\n IndexData in = new IndexData(cmds.item(i));\n indexData.add(in);\n }\n\n NodeList arrays = meshElement.getElementsByTagName(\"arrays\");\n for (int i = 0; i < arrays.getLength(); i++) {\n // aggiunge a primitives il risultato di ProcessRenderCmd\n RenderCmd r = new RenderCmd(arrays.item(i));\n primitives.add(r);\n }\n\n // calcola la lunghezza del buffer controllando che tutti gli array di\n // attributi abbiano la stessa lunghezza\n int iAttrbBufferSize = 0;\n ArrayList<Integer> attribStartLocs = new ArrayList<>(attribs.size());\n int iNumElements = 0;\n\n for (int i = 0; i < attribs.size(); i++) {\n iAttrbBufferSize = iAttrbBufferSize % 16 != 0 ?\n (iAttrbBufferSize + (16 - iAttrbBufferSize % 16))\n : iAttrbBufferSize;\n attribStartLocs.add(iAttrbBufferSize);\n Attribute attrib = attribs.get(i);\n\n iAttrbBufferSize += attrib.calcByteSize();\n\n if (iNumElements != 0) {\n if (iNumElements != attrib.numElements()) {\n throw new RuntimeException(\"Some of the attribute arrays have different element counts.\");\n }\n } else {\n iNumElements = attrib.numElements();\n }\n }\n\n // crea e binda il VAO\n oVAO = glGenVertexArrays();\n glBindVertexArray(oVAO);\n\n // Crea i buffer object\n oAttribArraysBuffer = glGenBuffers();\n glBindBuffer(GL_ARRAY_BUFFER, oAttribArraysBuffer);\n glBufferData(GL_ARRAY_BUFFER, iAttrbBufferSize, GL_STATIC_DRAW);\n\n // Inserisce i dati degli attributi nel buffer object\n for (int i = 0; i < attribs.size(); i++) {\n Attribute attrib = attribs.get(i);\n attrib.fillBoundBufferObject(attribStartLocs.get(i));\n attrib.setupAttributeArray(attribStartLocs.get(i));\n }\n\n // riempie i vari VAOs\n for (int i = 0; i < namedVaoList.size(); i++) {\n NamedVAO namedVao = namedVaoList.get(i);\n\n int vao = glGenVertexArrays();\n glBindVertexArray(vao);\n\n List<Integer> attributeArray = namedVao.attributes;\n for (int j = 0; j < attributeArray.size(); j++) {\n int idAttrib = attributeArray.get(j);\n int iAttribOffset = -1;\n for (int iCount = 0; iCount < attribs.size(); iCount++) {\n if (attribs.get(iCount).attribIndex == idAttrib) {\n iAttribOffset = iCount;\n break;\n }\n }\n\n Attribute attrib = attribs.get(iAttribOffset);\n attrib.setupAttributeArray(attribStartLocs.get(iAttribOffset));\n }\n\n namedVAOs.put(namedVao.name, vao);\n }\n\n glBindVertexArray(0);\n\n // Calcola la lunghezza dell'index buffer\n int iIndexBufferSize = 0;\n ArrayList<Integer> indexStartLocs = new ArrayList<>(indexData.size());\n for (int i = 0; i < indexData.size(); i++) {\n iIndexBufferSize = iIndexBufferSize % 16 != 0 ?\n (iIndexBufferSize + (16 - iIndexBufferSize % 16))\n : iIndexBufferSize;\n\n indexStartLocs.add(iIndexBufferSize);\n IndexData currData = indexData.get(i);\n\n iIndexBufferSize += currData.calcByteSize();\n }\n\n // Crea l'index buffer object\n if (iIndexBufferSize > 0) {\n glBindVertexArray(oVAO);\n\n oIndexBuffer = glGenBuffers();\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oIndexBuffer);\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, iIndexBufferSize,\n GL_STATIC_DRAW);\n\n // gli inserisce i dati\n for (int i = 0; i < indexData.size(); i++) {\n IndexData currData = indexData.get(i);\n currData.fillBoundBufferObject(indexStartLocs.get(i));\n }\n\n // crea i RenderCmd\n int iCurrIndexed = 0;\n for (int i = 0; i < primitives.size(); i++) {\n RenderCmd prim = primitives.get(i);\n if (prim.isIndexedCmd) {\n prim.start = indexStartLocs.get(iCurrIndexed);\n prim.elemCount = indexData.get(iCurrIndexed)\n .getDataNumElem();\n prim.eIndexDataType = indexData.get(iCurrIndexed).attribType.glType;\n iCurrIndexed++;\n }\n }\n\n for (Integer idVAO : namedVAOs.values()) {\n glBindVertexArray(idVAO);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, oIndexBuffer);\n }\n\n glBindVertexArray(0);\n }\n }\n\n public void render() {\n if (oVAO == 0) {\n return;\n }\n\n glBindVertexArray(oVAO);\n\n for (RenderCmd cmd : primitives) {\n cmd.render();\n }\n\n glBindVertexArray(0);\n }\n\n public void render(String meshName) {\n Integer vao = namedVAOs.get(meshName);\n if (vao == null) {\n return;\n }\n\n glBindVertexArray(vao);\n\n for (RenderCmd cmd : primitives) {\n cmd.render();\n }\n\n glBindVertexArray(0);\n }\n\n ////////////////////////////////\n private int oAttribArraysBuffer = 0;\n private int oIndexBuffer = 0;\n private int oVAO = 0;\n\n private ArrayList<RenderCmd> primitives = new ArrayList<>();\n private Map<String, Integer> namedVAOs = new HashMap<>();\n\n ////////////////////////////////\n public abstract static class ParseFunc {\n abstract public Buffer parse(String strToParse);\n }\n\n public abstract static class WriteFunc {\n abstract public void writeToBuffer(int eBuffer, Buffer theData, int iOffset);\n }\n\n\n private static class Attribute {\n Attribute(Node attributeNode) {\n NamedNodeMap attrs = attributeNode.getAttributes();\n\n {\n Node indexNode = attrs.getNamedItem(\"index\");\n if (indexNode == null) {\n throw new RuntimeException(\"Missing 'index' attribute in an 'attribute' element.\");\n }\n\n int index = Integer.parseInt(indexNode.getNodeValue());\n if (!((0 <= index) && (index < 16))) {\n throw new RuntimeException(\"Attribute index must be between 0 and 16.\");\n }\n\n attribIndex = index;\n }\n\n {\n Node sizeNode = attrs.getNamedItem(\"size\");\n if (sizeNode == null) {\n throw new RuntimeException(\"Missing 'size' attribute in an 'attribute' element.\");\n }\n\n int size = Integer.parseInt(sizeNode.getNodeValue());\n if (!((1 <= size) && (size < 5))) {\n throw new RuntimeException(\"Attribute size must be between 1 and 4.\");\n }\n\n this.size = size;\n }\n\n {\n String strType;\n Node typeNode = attrs.getNamedItem(\"type\");\n if (typeNode == null) {\n throw new RuntimeException(\"Missing 'type' attribute in an 'attribute' element.\");\n }\n\n strType = typeNode.getNodeValue();\n attribType = AttribType.get(strType);\n }\n\n {\n Node integralNode = attrs.getNamedItem(\"integral\");\n if (integralNode == null) {\n isIntegral = false;\n } else {\n String strIntegral = integralNode.getNodeValue();\n switch (strIntegral) {\n case \"true\":\n isIntegral = true;\n break;\n case \"false\":\n isIntegral = false;\n break;\n default:\n throw new RuntimeException(\"Incorrect 'integral' value for the 'attribute'.\");\n }\n\n if (attribType.normalized) {\n throw new RuntimeException(\"Attribute cannot be both 'integral' and a normalized 'type'.\");\n }\n\n if (attribType.glType == GL_FLOAT\n || attribType.glType == GL_HALF_FLOAT\n || attribType.glType == GL_DOUBLE) {\n throw new RuntimeException(\"Attribute cannot be both 'integral' and a floating-point 'type'.\");\n }\n }\n }\n\n {\n String strData = attributeNode.getChildNodes().item(0).getNodeValue();\n dataArray = attribType.parse(strData);\n }\n }\n\n\n int numElements() {\n return getDataNumElem() / size;\n }\n\n int calcByteSize() {\n return getDataNumElem() * attribType.numBytes;\n }\n\n void fillBoundBufferObject(int offset) {\n attribType.writeToBuffer(GL_ARRAY_BUFFER, dataArray, offset);\n }\n\n void setupAttributeArray(int offset) {\n glEnableVertexAttribArray(attribIndex);\n if (isIntegral) {\n glVertexAttribIPointer(attribIndex, size, attribType.glType, 0, offset);\n } else {\n glVertexAttribPointer(attribIndex, size, attribType.glType,\n attribType.normalized, 0, offset);\n }\n }\n\n ////////////////////////////////\n\n private int attribIndex = 0xFFFFFFFF;\n private AttribType attribType = null;\n private int size = -1;\n private boolean isIntegral = false;\n private Buffer dataArray;\n\n\n private int getDataNumElem() {\n return dataArray.limit();\n }\n }\n\n private static class AttribType {\n AttribType(boolean normalized, int glType, int numBytes, ParseFunc parseFunc, WriteFunc writeFunc) {\n this.normalized = normalized;\n this.glType = glType;\n this.numBytes = numBytes;\n this.parseFunc = parseFunc;\n this.writeFunc = writeFunc;\n }\n\n\n Buffer parse(String strData) {\n return parseFunc.parse(strData);\n }\n\n void writeToBuffer(int eBuffer, Buffer buffer, int offset) {\n writeFunc.writeToBuffer(eBuffer, buffer, offset);\n }\n\n\n static AttribType get(String type) {\n AttribType attType = allAttribType.get(type);\n if (attType == null) {\n throw new RuntimeException(\"Unknown 'type' field.\");\n }\n\n return attType;\n }\n\n ////////////////////////////////\n\n private static final Map<String, AttribType> allAttribType = new HashMap<>();\n private static final Map<String, Integer> allPrimitiveType = new HashMap<>();\n\n private boolean normalized;\n private int glType;\n private int numBytes;\n\n private ParseFunc parseFunc;\n private WriteFunc writeFunc;\n\n private static ParseFunc parseFloats = new ParseFunc() {\n public Buffer parse(String strToParse) {\n Scanner scn = new Scanner(strToParse);\n scn.useDelimiter(\"\\\\s+\");\n ArrayList<Float> array = new ArrayList<>();\n\n while (scn.hasNext()) {\n array.add(Float.parseFloat(scn.next()));\n }\n\n FloatBuffer buff = BufferUtils.createFloatBuffer(array.size());\n for (Float data : array) {\n buff.put(data);\n }\n buff.flip();\n\n scn.close();\n return buff;\n }\n };\n private static ParseFunc parseInts = new ParseFunc() {\n public Buffer parse(String strToParse) {\n Scanner scn = new Scanner(strToParse);\n scn.useDelimiter(\"\\\\s+\");\n ArrayList<Integer> array = new ArrayList<>();\n\n while (scn.hasNext()) {\n array.add((int) Long.parseLong(scn.next()));\n }\n\n IntBuffer buff = BufferUtils.createIntBuffer(array.size());\n for (Integer data : array) {\n buff.put(data);\n }\n buff.flip();\n\n scn.close();\n return buff;\n }\n };\n private static ParseFunc parseShorts = new ParseFunc() {\n public Buffer parse(String strToParse) {\n Scanner scn = new Scanner(strToParse);\n scn.useDelimiter(\"\\\\s+\");\n ArrayList<Short> array = new ArrayList<>();\n\n while (scn.hasNext()) {\n array.add((short) Integer.parseInt(scn.next()));\n }\n\n ShortBuffer buff = BufferUtils.createShortBuffer(array.size());\n for (Short data : array) {\n buff.put(data);\n }\n buff.flip();\n\n scn.close();\n return buff;\n }\n };\n private static ParseFunc parseBytes = new ParseFunc() {\n public Buffer parse(String strToParse) {\n Scanner scn = new Scanner(strToParse);\n scn.useDelimiter(\"\\\\s+\");\n ArrayList<Byte> array = new ArrayList<>();\n\n while (scn.hasNext()) {\n array.add((byte) Short.parseShort(scn.next()));\n }\n\n ByteBuffer buff = BufferUtils.createByteBuffer(array.size());\n for (Byte data : array) {\n buff.put(data);\n }\n buff.flip();\n\n scn.close();\n return buff;\n }\n };\n\n private static WriteFunc writeFloats = new WriteFunc() {\n public void writeToBuffer(int eBuffer, Buffer theData, int iOffset) {\n glBufferSubData(eBuffer, iOffset, (FloatBuffer) theData);\n }\n };\n private static WriteFunc writeInts = new WriteFunc() {\n public void writeToBuffer(int eBuffer, Buffer theData, int iOffset) {\n glBufferSubData(eBuffer, iOffset, (IntBuffer) theData);\n }\n };\n private static WriteFunc writeShorts = new WriteFunc() {\n public void writeToBuffer(int eBuffer, Buffer theData, int iOffset) {\n glBufferSubData(eBuffer, iOffset, (ShortBuffer) theData);\n }\n };\n private static WriteFunc writeBytes = new WriteFunc() {\n public void writeToBuffer(int eBuffer, Buffer theData, int iOffset) {\n glBufferSubData(eBuffer, iOffset, (ByteBuffer) theData);\n }\n };\n\n static {\n allAttribType.put(\"float\", new AttribType(false, GL_FLOAT,\n Float.SIZE / 8, parseFloats, writeFloats));\n // {\"half\", false, GL_HALF_FLOAT, sizeof(GLhalfARB), ParseFloats,\n // WriteFloats},\n allAttribType.put(\"int\", new AttribType(false, GL_INT,\n Integer.SIZE / 8, parseInts, writeInts));\n allAttribType.put(\"uint\", new AttribType(false, GL_UNSIGNED_INT,\n Integer.SIZE / 8, parseInts, writeInts));\n // {\"norm-int\", true, GL_INT, sizeof(GLint), ParseInts, WriteInts},\n // {\"norm-uint\", true, GL_UNSIGNED_INT, sizeof(GLuint), ParseUInts,\n // WriteUInts},\n allAttribType.put(\"short\", new AttribType(false, GL_SHORT,\n Short.SIZE / 8, parseShorts, writeShorts));\n allAttribType.put(\"ushort\",\n new AttribType(false, GL_UNSIGNED_SHORT, Short.SIZE / 8,\n parseShorts, writeShorts));\n // {\"norm-short\", true, GL_SHORT, sizeof(GLshort), ParseShorts,\n // WriteShorts},\n // {\"norm-ushort\", true, GL_UNSIGNED_SHORT, sizeof(GLushort),\n // ParseUShorts, WriteUShorts},\n allAttribType.put(\"byte\", new AttribType(false, GL_BYTE,\n Byte.SIZE / 8, parseBytes, writeBytes));\n allAttribType.put(\"ubyte\", new AttribType(false, GL_UNSIGNED_BYTE,\n Byte.SIZE / 8, parseBytes, writeBytes));\n // {\"norm-byte\", true, GL_BYTE, sizeof(GLbyte), ParseBytes,\n // WriteBytes},\n // {\"norm-ubyte\", true, GL_UNSIGNED_BYTE, sizeof(GLubyte),\n // ParseUBytes, WriteUBytes},\n\n allPrimitiveType.put(\"triangles\", GL_TRIANGLES);\n allPrimitiveType.put(\"tri-strip\", GL_TRIANGLE_STRIP);\n allPrimitiveType.put(\"tri-fan\", GL_TRIANGLE_FAN);\n allPrimitiveType.put(\"lines\", GL_LINES);\n allPrimitiveType.put(\"line-strip\", GL_LINE_STRIP);\n allPrimitiveType.put(\"line-loop\", GL_LINE_LOOP);\n allPrimitiveType.put(\"points\", GL_POINTS);\n }\n }\n\n ////////////////////////////////\n private static class RenderCmd {\n private boolean isIndexedCmd;\n private int primType;\n private int start;\n private int elemCount;\n private int eIndexDataType; // Only if isIndexedCmd is true.\n\n\n RenderCmd(Node cmdNode) {\n NamedNodeMap attrs = cmdNode.getAttributes();\n\n {\n Node cmdAttr = attrs.getNamedItem(\"cmd\");\n if (cmdAttr == null) {\n throw new RuntimeException(\"Missing 'cmd' attribute in an 'arrays' or 'indices' element.\");\n }\n\n String strCmd = cmdAttr.getNodeValue();\n Integer primitive = AttribType.allPrimitiveType.get(strCmd);\n if (primitive == null) {\n throw new RuntimeException(\"Unknown 'cmd' field.\");\n }\n\n primType = primitive;\n }\n\n if (cmdNode.getNodeName().equals(\"indices\")) {\n isIndexedCmd = true;\n } else if (cmdNode.getNodeName().equals(\"arrays\")) {\n isIndexedCmd = false;\n\n {\n Node nodeStart = cmdNode.getAttributes().getNamedItem(\"start\");\n if (nodeStart == null) {\n throw new RuntimeException(\"Missing 'start' attribute in an 'arrays' element.\");\n }\n\n int iStart = Integer.parseInt(nodeStart.getNodeValue());\n if (iStart < 0) {\n throw new RuntimeException(\"Attribute 'start' must be between 0 or greater.\");\n }\n\n start = iStart;\n }\n {\n Node nodeCount = cmdNode.getAttributes().getNamedItem(\"count\");\n if (nodeCount == null) {\n throw new RuntimeException(\"Missing 'count' attribute in an 'arrays' element.\");\n }\n\n int iCount = Integer.parseInt(nodeCount.getNodeValue());\n if (iCount <= 0) {\n throw new RuntimeException(\"Attribute 'count' must be greater than 0.\");\n }\n\n elemCount = iCount;\n }\n } else {\n throw new RuntimeException(\"Bad element. Must be 'indices' or 'arrays'.\");\n }\n }\n\n\n void render() {\n if (isIndexedCmd) {\n glDrawElements(primType, elemCount, eIndexDataType, start);\n } else {\n glDrawArrays(primType, start, elemCount);\n }\n }\n }\n\n private static class IndexData {\n private AttribType attribType;\n private Buffer dataArray;\n\n\n IndexData(Node indexElem) {\n NamedNodeMap attrs = indexElem.getAttributes();\n // controlla che type sia valido\n {\n Node typeAttr = attrs.getNamedItem(\"type\");\n if (typeAttr == null) {\n throw new RuntimeException(\"Missing 'type' attribute in an 'index' element.\");\n }\n\n String strType = typeAttr.getNodeValue();\n if (!(strType.equals(\"uint\") || strType.equals(\"ushort\") || strType.equals(\"ubyte\"))) {\n throw new RuntimeException(\"Improper 'type' attribute value on 'index' element.\");\n }\n\n attribType = AttribType.get(strType);\n }\n\n // legge gli indici\n {\n String strIndex = indexElem.getChildNodes().item(0).getNodeValue();\n dataArray = attribType.parse(strIndex);\n if (dataArray.limit() == 0) {\n throw new RuntimeException(\"The index element must have an array of values.\");\n }\n }\n }\n\n\n void fillBoundBufferObject(int iOffset) {\n attribType.writeToBuffer(GL_ELEMENT_ARRAY_BUFFER, dataArray,\n iOffset);\n }\n\n int getDataNumElem() {\n return dataArray.limit();\n }\n\n int calcByteSize() {\n return getDataNumElem() * attribType.numBytes;\n }\n }\n\n private static class NamedVAO {\n private String name;\n private ArrayList<Integer> attributes;\n\n\n NamedVAO(Node itemVao) {\n attributes = new ArrayList<>();\n\n NamedNodeMap attrs = itemVao.getAttributes();\n {\n Node nameAttr = attrs.getNamedItem(\"name\");\n if (nameAttr == null) {\n throw new RuntimeException(\"Missing 'name' attribute in an 'vao' element.\");\n }\n\n name = nameAttr.getNodeValue();\n }\n\n Element elemVao = (Element) itemVao;\n NodeList sources = elemVao.getElementsByTagName(\"source\");\n for (int sourceIndex = 0; sourceIndex < sources.getLength(); sourceIndex++) {\n Node attrib = sources.item(sourceIndex).getAttributes().getNamedItem(\"attrib\");\n if (attrib == null) {\n throw new RuntimeException(\"Missing 'attrib' attribute in an 'source' element.\");\n }\n\n attributes.add(Integer.parseInt(attrib.getNodeValue()));\n }\n }\n }\n}",
"public class MousePole {\n public static void forwardMouseMotion(Pole forward, int x, int y) {\n forward.mouseMove(new Vector2i(x, y));\n }\n\n public static void forwardMouseButton(long window, Pole forwardPole, int button, boolean state, int x, int y) {\n MouseModifiers modifiers = calcModifiers(window);\n Vector2i mouseLoc = new Vector2i(x, y);\n MouseButtons mouseButtons = null;\n\n switch (button) {\n case 0:\n mouseButtons = MouseButtons.MB_LEFT_BTN;\n break;\n\n case 1:\n mouseButtons = MouseButtons.MB_RIGHT_BTN;\n break;\n\n case 2:\n mouseButtons = MouseButtons.MB_MIDDLE_BTN;\n break;\n }\n\n forwardPole.mouseClick(mouseButtons, state, modifiers, mouseLoc);\n }\n\n public static void forwardMouseWheel(long window, Pole forward, int direction, int x, int y) {\n forward.mouseWheel(direction, calcModifiers(window), new Vector2i(x, y));\n }\n\n\n private static MouseModifiers calcModifiers(long window) {\n if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == 1 || glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == 1)\n return MouseModifiers.MM_KEY_SHIFT;\n if (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == 1 || glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == 1)\n return MouseModifiers.MM_KEY_CTRL;\n if (glfwGetKey(window, GLFW_KEY_MENU) == 1)\n return MouseModifiers.MM_KEY_ALT;\n return null;\n }\n}",
"public class Timer {\n public enum Type {\n LOOP,\n SINGLE\n }\n\n ////////////////////////////////\n public Timer(Type type, float duration) {\n this.type = type;\n secDuration = duration;\n }\n\n ////////////////////////////////\n\n /**\n * Updates the time for the timer. Returns true if the timer has reached the end.\n * Will only return true for SINGLE timers that have reached their duration.\n *\n * @param elapsedTime the time passed since the application start (in milliseconds)\n */\n public boolean update(float elapsedTime) {\n float absCurrTime = elapsedTime;\n\n if (!hasUpdated) {\n absPrevTime = absCurrTime;\n hasUpdated = true;\n }\n\n if (isPaused) {\n absPrevTime = absCurrTime;\n return false;\n }\n\n float deltaTime = absCurrTime - absPrevTime;\n secAccumTime += deltaTime;\n\n absPrevTime = absCurrTime;\n return type == Type.SINGLE && secAccumTime > secDuration;\n }\n\n\n /**\n * Subtracts secRewind from the current time and continues from there.\n */\n public void rewind(float secRewind) {\n secAccumTime -= secRewind;\n\n if (secAccumTime < 0.0f) {\n secAccumTime = 0.0f;\n }\n }\n\n /**\n * Adds secRewind to the current time and continues from there.\n */\n public void fastForward(float secFF) {\n secAccumTime += secFF;\n }\n\n\n /**\n * Returns true if the timer is paused.\n */\n public boolean isPaused() {\n return isPaused;\n }\n\n /**\n * Pauses/unpauses. Returns true if the timer is paused after the toggling.\n */\n public boolean togglePause() {\n isPaused = !isPaused;\n return isPaused;\n }\n\n /**\n * Sets the pause state to the given value.\n */\n public void setPause(boolean pause) {\n isPaused = pause;\n }\n\n\n /**\n * Returns a number [0, 1], representing progress through the duration.\n * Only used for SINGLE and LOOP timers.\n */\n public float getAlpha() {\n switch (type) {\n case LOOP:\n return (secAccumTime % secDuration) / secDuration;\n\n case SINGLE:\n return Math.min(Math.max(secAccumTime / secDuration, 0.0f), 1.0f);\n\n default:\n break;\n }\n\n return -1.0f; // Garbage.\n }\n\n ////////////////////////////////\n\n private Type type;\n private float secDuration;\n\n private boolean hasUpdated;\n private boolean isPaused;\n\n private float absPrevTime;\n private float secAccumTime;\n}"
] | import integeruser.jglsdk.glutil.MousePoles.MouseButtons;
import integeruser.jglsdk.glutil.MousePoles.ViewData;
import integeruser.jglsdk.glutil.MousePoles.ViewPole;
import integeruser.jglsdk.glutil.MousePoles.ViewScale;
import integeruser.jgltut.Tutorial;
import integeruser.jgltut.commons.*;
import integeruser.jgltut.framework.Framework;
import integeruser.jgltut.framework.Mesh;
import integeruser.jgltut.framework.MousePole;
import integeruser.jgltut.framework.Timer;
import org.joml.*;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL15;
import java.lang.Math;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.*;
import static org.lwjgl.opengl.GL31.*;
import static org.lwjgl.opengl.GL32.*; | package integeruser.jgltut.tut13;
/**
* Visit https://github.com/integeruser/jgltut for info and updates.
* Original: https://bitbucket.org/alfonse/gltut/src/default/Tut%2013%20Impostors/GeomImpostor.cpp
* <p>
* Part III. Illumination
* Chapter 13. Lies and Impostors
* <p>
* W,A,S,D - move the cameras forward/backwards and left/right, relative to the camera's current orientation. Holding
* SHIFT with these keys will move in smaller increments.
* Q,E - raise and lower the camera, relative to its current orientation. Holding SHIFT with these keys will move
* in smaller increments.
* P - toggle pausing on/off.
* -,= - rewind/jump forward time by 0.5 second (of real-time).
* T - toggle viewing the look-at point.
* G - toggle the drawing of the light source.
* <p>
* LEFT CLICKING and DRAGGING - rotate the camera around the target point, both horizontally and vertically.
* LEFT CLICKING and DRAGGING + CTRL - rotate the camera around the target point, either horizontally or vertically.
* LEFT CLICKING and DRAGGING + ALT - change the camera's up direction.
* WHEEL SCROLLING - move the camera closer to it's target point or farther away.
*/
public class GeomImpostor extends Tutorial {
public static void main(String[] args) {
Framework.CURRENT_TUTORIAL_DATAPATH = "/integeruser/jgltut/tut13/data/";
new GeomImpostor().start(500, 500);
}
@Override
protected void init() {
initializePrograms();
planeMesh = new Mesh("LargePlane.xml");
cubeMesh = new Mesh("UnitCube.xml");
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CW);
final float depthZNear = 0.0f;
final float depthZFar = 1.0f;
glEnable(GL_DEPTH_TEST);
glDepthMask(true);
glDepthFunc(GL_LEQUAL);
glDepthRange(depthZNear, depthZFar);
glEnable(GL_DEPTH_CLAMP);
// Setup our Uniform Buffers
lightUniformBuffer = glGenBuffers();
glBindBuffer(GL_UNIFORM_BUFFER, lightUniformBuffer);
GL15.glBufferData(GL_UNIFORM_BUFFER, LightBlock.BYTES, GL_DYNAMIC_DRAW);
projectionUniformBuffer = glGenBuffers();
glBindBuffer(GL_UNIFORM_BUFFER, projectionUniformBuffer);
glBufferData(GL_UNIFORM_BUFFER, ProjectionBlock.BYTES, GL_DYNAMIC_DRAW);
// Bind the static buffers.
glBindBufferRange(GL_UNIFORM_BUFFER, lightBlockIndex, lightUniformBuffer, 0, LightBlock.BYTES);
glBindBufferRange(GL_UNIFORM_BUFFER, projectionBlockIndex, projectionUniformBuffer, 0, ProjectionBlock.BYTES);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
imposterVBO = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, imposterVBO);
glBufferData(GL_ARRAY_BUFFER, NUMBER_OF_SPHERES * 4 * Float.BYTES, GL_STREAM_DRAW);
imposterVAO = glGenVertexArrays();
glBindVertexArray(imposterVAO);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, false, 16, 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 1, GL_FLOAT, false, 16, 12);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnable(GL_PROGRAM_POINT_SIZE);
createMaterials();
glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {
if (action == GLFW_PRESS) {
switch (key) {
case GLFW_KEY_P:
sphereTimer.togglePause();
break;
case GLFW_KEY_MINUS:
sphereTimer.rewind(0.5f);
break;
case GLFW_KEY_EQUAL:
sphereTimer.fastForward(0.5f);
break;
case GLFW_KEY_T:
drawCameraPos = !drawCameraPos;
break;
case GLFW_KEY_G:
drawLights = !drawLights;
break;
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, true);
break;
}
}
});
glfwSetMouseButtonCallback(window, (window, button, action, mods) -> {
boolean pressed = action == GLFW_PRESS;
glfwGetCursorPos(window, mouseBuffer1, mouseBuffer2);
int x = (int) mouseBuffer1.get(0);
int y = (int) mouseBuffer2.get(0); | MousePole.forwardMouseButton(window, viewPole, button, pressed, x, y); | 7 |
CagataySonmez/EdgeCloudSim | src/edu/boun/edgecloudsim/applications/sample_app2/SampleNetworkModel.java | [
"public class SimManager extends SimEntity {\r\n\tprivate static final int CREATE_TASK = 0;\r\n\tprivate static final int CHECK_ALL_VM = 1;\r\n\tprivate static final int GET_LOAD_LOG = 2;\r\n\tprivate static final int PRINT_PROGRESS = 3;\r\n\tprivate static final int STOP_SIMULATION = 4;\r\n\t\r\n\tprivate String simScenario;\r\n\tprivate String orchestratorPolicy;\r\n\tprivate int numOfMobileDevice;\r\n\tprivate NetworkModel networkModel;\r\n\tprivate MobilityModel mobilityModel;\r\n\tprivate ScenarioFactory scenarioFactory;\r\n\tprivate EdgeOrchestrator edgeOrchestrator;\r\n\tprivate EdgeServerManager edgeServerManager;\r\n\tprivate CloudServerManager cloudServerManager;\r\n\tprivate MobileServerManager mobileServerManager;\r\n\tprivate LoadGeneratorModel loadGeneratorModel;\r\n\tprivate MobileDeviceManager mobileDeviceManager;\r\n\t\r\n\tprivate static SimManager instance = null;\r\n\t\r\n\tpublic SimManager(ScenarioFactory _scenarioFactory, int _numOfMobileDevice, String _simScenario, String _orchestratorPolicy) throws Exception {\r\n\t\tsuper(\"SimManager\");\r\n\t\tsimScenario = _simScenario;\r\n\t\tscenarioFactory = _scenarioFactory;\r\n\t\tnumOfMobileDevice = _numOfMobileDevice;\r\n\t\torchestratorPolicy = _orchestratorPolicy;\r\n\r\n\t\tSimLogger.print(\"Creating tasks...\");\r\n\t\tloadGeneratorModel = scenarioFactory.getLoadGeneratorModel();\r\n\t\tloadGeneratorModel.initializeModel();\r\n\t\tSimLogger.printLine(\"Done, \");\r\n\t\t\r\n\t\tSimLogger.print(\"Creating device locations...\");\r\n\t\tmobilityModel = scenarioFactory.getMobilityModel();\r\n\t\tmobilityModel.initialize();\r\n\t\tSimLogger.printLine(\"Done.\");\r\n\r\n\t\t//Generate network model\r\n\t\tnetworkModel = scenarioFactory.getNetworkModel();\r\n\t\tnetworkModel.initialize();\r\n\t\t\r\n\t\t//Generate edge orchestrator\r\n\t\tedgeOrchestrator = scenarioFactory.getEdgeOrchestrator();\r\n\t\tedgeOrchestrator.initialize();\r\n\t\t\r\n\t\t//Create Physical Servers\r\n\t\tedgeServerManager = scenarioFactory.getEdgeServerManager();\r\n\t\tedgeServerManager.initialize();\r\n\t\t\r\n\t\t//Create Physical Servers on cloud\r\n\t\tcloudServerManager = scenarioFactory.getCloudServerManager();\r\n\t\tcloudServerManager.initialize();\r\n\t\t\r\n\t\t//Create Physical Servers on mobile devices\r\n\t\tmobileServerManager = scenarioFactory.getMobileServerManager();\r\n\t\tmobileServerManager.initialize();\r\n\r\n\t\t//Create Client Manager\r\n\t\tmobileDeviceManager = scenarioFactory.getMobileDeviceManager();\r\n\t\tmobileDeviceManager.initialize();\r\n\t\t\r\n\t\tinstance = this;\r\n\t}\r\n\t\r\n\tpublic static SimManager getInstance(){\r\n\t\treturn instance;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Triggering CloudSim to start simulation\r\n\t */\r\n\tpublic void startSimulation() throws Exception{\r\n\t\t//Starts the simulation\r\n\t\tSimLogger.print(super.getName()+\" is starting...\");\r\n\t\t\r\n\t\t//Start Edge Datacenters & Generate VMs\r\n\t\tedgeServerManager.startDatacenters();\r\n\t\tedgeServerManager.createVmList(mobileDeviceManager.getId());\r\n\t\t\r\n\t\t//Start Edge Datacenters & Generate VMs\r\n\t\tcloudServerManager.startDatacenters();\r\n\t\tcloudServerManager.createVmList(mobileDeviceManager.getId());\r\n\t\t\r\n\t\t//Start Mobile Datacenters & Generate VMs\r\n\t\tmobileServerManager.startDatacenters();\r\n\t\tmobileServerManager.createVmList(mobileDeviceManager.getId());\r\n\t\t\r\n\t\tCloudSim.startSimulation();\r\n\t}\r\n\r\n\tpublic String getSimulationScenario(){\r\n\t\treturn simScenario;\r\n\t}\r\n\r\n\tpublic String getOrchestratorPolicy(){\r\n\t\treturn orchestratorPolicy;\r\n\t}\r\n\t\r\n\tpublic ScenarioFactory getScenarioFactory(){\r\n\t\treturn scenarioFactory;\r\n\t}\r\n\t\r\n\tpublic int getNumOfMobileDevice(){\r\n\t\treturn numOfMobileDevice;\r\n\t}\r\n\t\r\n\tpublic NetworkModel getNetworkModel(){\r\n\t\treturn networkModel;\r\n\t}\r\n\r\n\tpublic MobilityModel getMobilityModel(){\r\n\t\treturn mobilityModel;\r\n\t}\r\n\t\r\n\tpublic EdgeOrchestrator getEdgeOrchestrator(){\r\n\t\treturn edgeOrchestrator;\r\n\t}\r\n\t\r\n\tpublic EdgeServerManager getEdgeServerManager(){\r\n\t\treturn edgeServerManager;\r\n\t}\r\n\t\r\n\tpublic CloudServerManager getCloudServerManager(){\r\n\t\treturn cloudServerManager;\r\n\t}\r\n\t\r\n\tpublic MobileServerManager getMobileServerManager(){\r\n\t\treturn mobileServerManager;\r\n\t}\r\n\r\n\tpublic LoadGeneratorModel getLoadGeneratorModel(){\r\n\t\treturn loadGeneratorModel;\r\n\t}\r\n\t\r\n\tpublic MobileDeviceManager getMobileDeviceManager(){\r\n\t\treturn mobileDeviceManager;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void startEntity() {\r\n\t\tint hostCounter=0;\r\n\r\n\t\tfor(int i= 0; i<edgeServerManager.getDatacenterList().size(); i++) {\r\n\t\t\tList<? extends Host> list = edgeServerManager.getDatacenterList().get(i).getHostList();\r\n\t\t\tfor (int j=0; j < list.size(); j++) {\r\n\t\t\t\tmobileDeviceManager.submitVmList(edgeServerManager.getVmList(hostCounter));\r\n\t\t\t\thostCounter++;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tfor(int i = 0; i<SimSettings.getInstance().getNumOfCloudHost(); i++) {\r\n\t\t\tmobileDeviceManager.submitVmList(cloudServerManager.getVmList(i));\r\n\t\t}\r\n\r\n\t\tfor(int i=0; i<numOfMobileDevice; i++){\r\n\t\t\tif(mobileServerManager.getVmList(i) != null)\r\n\t\t\t\tmobileDeviceManager.submitVmList(mobileServerManager.getVmList(i));\r\n\t\t}\r\n\t\t\r\n\t\t//Creation of tasks are scheduled here!\r\n\t\tfor(int i=0; i< loadGeneratorModel.getTaskList().size(); i++)\r\n\t\t\tschedule(getId(), loadGeneratorModel.getTaskList().get(i).getStartTime(), CREATE_TASK, loadGeneratorModel.getTaskList().get(i));\r\n\t\t\r\n\t\t//Periodic event loops starts from here!\r\n\t\tschedule(getId(), 5, CHECK_ALL_VM);\r\n\t\tschedule(getId(), SimSettings.getInstance().getSimulationTime()/100, PRINT_PROGRESS);\r\n\t\tschedule(getId(), SimSettings.getInstance().getVmLoadLogInterval(), GET_LOAD_LOG);\r\n\t\tschedule(getId(), SimSettings.getInstance().getSimulationTime(), STOP_SIMULATION);\r\n\t\t\r\n\t\tSimLogger.printLine(\"Done.\");\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void processEvent(SimEvent ev) {\r\n\t\tsynchronized(this){\r\n\t\t\tswitch (ev.getTag()) {\r\n\t\t\tcase CREATE_TASK:\r\n\t\t\t\ttry {\r\n\t\t\t\t\tTaskProperty edgeTask = (TaskProperty) ev.getData();\r\n\t\t\t\t\tmobileDeviceManager.submitTask(edgeTask);\t\t\t\t\t\t\r\n\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\tSystem.exit(1);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase CHECK_ALL_VM:\r\n\t\t\t\tint totalNumOfVm = SimSettings.getInstance().getNumOfEdgeVMs();\r\n\t\t\t\tif(EdgeVmAllocationPolicy_Custom.getCreatedVmNum() != totalNumOfVm){\r\n\t\t\t\t\tSimLogger.printLine(\"All VMs cannot be created! Terminating simulation...\");\r\n\t\t\t\t\tSystem.exit(1);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase GET_LOAD_LOG:\r\n\t\t\t\tSimLogger.getInstance().addVmUtilizationLog(\r\n\t\t\t\t\t\tCloudSim.clock(),\r\n\t\t\t\t\t\tedgeServerManager.getAvgUtilization(),\r\n\t\t\t\t\t\tcloudServerManager.getAvgUtilization(),\r\n\t\t\t\t\t\tmobileServerManager.getAvgUtilization());\r\n\t\t\t\t\r\n\t\t\t\tschedule(getId(), SimSettings.getInstance().getVmLoadLogInterval(), GET_LOAD_LOG);\r\n\t\t\t\tbreak;\r\n\t\t\tcase PRINT_PROGRESS:\r\n\t\t\t\tint progress = (int)((CloudSim.clock()*100)/SimSettings.getInstance().getSimulationTime());\r\n\t\t\t\tif(progress % 10 == 0)\r\n\t\t\t\t\tSimLogger.print(Integer.toString(progress));\r\n\t\t\t\telse\r\n\t\t\t\t\tSimLogger.print(\".\");\r\n\t\t\t\tif(CloudSim.clock() < SimSettings.getInstance().getSimulationTime())\r\n\t\t\t\t\tschedule(getId(), SimSettings.getInstance().getSimulationTime()/100, PRINT_PROGRESS);\r\n\r\n\t\t\t\tbreak;\r\n\t\t\tcase STOP_SIMULATION:\r\n\t\t\t\tSimLogger.printLine(\"100\");\r\n\t\t\t\tCloudSim.terminateSimulation();\r\n\t\t\t\ttry {\r\n\t\t\t\t\tSimLogger.getInstance().simStopped();\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\tSystem.exit(1);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tSimLogger.printLine(getName() + \": unknown event type\");\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void shutdownEntity() {\r\n\t\tedgeServerManager.terminateDatacenters();\r\n\t\tcloudServerManager.terminateDatacenters();\r\n\t\tmobileServerManager.terminateDatacenters();\r\n\t}\r\n}\r",
"public class SimSettings {\r\n\tprivate static SimSettings instance = null;\r\n\tprivate Document edgeDevicesDoc = null;\r\n\r\n\tpublic static final double CLIENT_ACTIVITY_START_TIME = 10;\r\n\r\n\t//enumarations for the VM types\r\n\tpublic static enum VM_TYPES { MOBILE_VM, EDGE_VM, CLOUD_VM }\r\n\r\n\t//enumarations for the VM types\r\n\tpublic static enum NETWORK_DELAY_TYPES { WLAN_DELAY, MAN_DELAY, WAN_DELAY, GSM_DELAY }\r\n\r\n\t//predifined IDs for the components.\r\n\tpublic static final int CLOUD_DATACENTER_ID = 1000;\r\n\tpublic static final int MOBILE_DATACENTER_ID = 1001;\r\n\tpublic static final int EDGE_ORCHESTRATOR_ID = 1002;\r\n\tpublic static final int GENERIC_EDGE_DEVICE_ID = 1003;\r\n\r\n\t//delimiter for output file.\r\n\tpublic static final String DELIMITER = \";\";\r\n\r\n\tprivate double SIMULATION_TIME; //minutes unit in properties file\r\n\tprivate double WARM_UP_PERIOD; //minutes unit in properties file\r\n\tprivate double INTERVAL_TO_GET_VM_LOAD_LOG; //minutes unit in properties file\r\n\tprivate double INTERVAL_TO_GET_LOCATION_LOG; //minutes unit in properties file\r\n\tprivate double INTERVAL_TO_GET_AP_DELAY_LOG; //minutes unit in properties file\r\n\tprivate boolean FILE_LOG_ENABLED; //boolean to check file logging option\r\n\tprivate boolean DEEP_FILE_LOG_ENABLED; //boolean to check deep file logging option\r\n\r\n\tprivate int MIN_NUM_OF_MOBILE_DEVICES;\r\n\tprivate int MAX_NUM_OF_MOBILE_DEVICES;\r\n\tprivate int MOBILE_DEVICE_COUNTER_SIZE;\r\n\tprivate int WLAN_RANGE;\r\n\r\n\tprivate int NUM_OF_EDGE_DATACENTERS;\r\n\tprivate int NUM_OF_EDGE_HOSTS;\r\n\tprivate int NUM_OF_EDGE_VMS;\r\n\tprivate int NUM_OF_PLACE_TYPES;\r\n\r\n\tprivate double WAN_PROPAGATION_DELAY; //seconds unit in properties file\r\n\tprivate double GSM_PROPAGATION_DELAY; //seconds unit in properties file\r\n\tprivate double LAN_INTERNAL_DELAY; //seconds unit in properties file\r\n\tprivate int BANDWITH_WLAN; //Mbps unit in properties file\r\n\tprivate int BANDWITH_MAN; //Mbps unit in properties file\r\n\tprivate int BANDWITH_WAN; //Mbps unit in properties file\r\n\tprivate int BANDWITH_GSM; //Mbps unit in properties file\r\n\r\n\tprivate int NUM_OF_HOST_ON_CLOUD_DATACENTER;\r\n\tprivate int NUM_OF_VM_ON_CLOUD_HOST;\r\n\tprivate int CORE_FOR_CLOUD_VM;\r\n\tprivate int MIPS_FOR_CLOUD_VM; //MIPS\r\n\tprivate int RAM_FOR_CLOUD_VM; //MB\r\n\tprivate int STORAGE_FOR_CLOUD_VM; //Byte\r\n\r\n\tprivate int CORE_FOR_VM;\r\n\tprivate int MIPS_FOR_VM; //MIPS\r\n\tprivate int RAM_FOR_VM; //MB\r\n\tprivate int STORAGE_FOR_VM; //Byte\r\n\r\n\tprivate String[] SIMULATION_SCENARIOS;\r\n\tprivate String[] ORCHESTRATOR_POLICIES;\r\n\r\n\tprivate double NORTHERN_BOUND;\r\n\tprivate double EASTERN_BOUND;\r\n\tprivate double SOUTHERN_BOUND;\r\n\tprivate double WESTERN_BOUND;\r\n\r\n\t// mean waiting time (minute) is stored for each place types\r\n\tprivate double[] mobilityLookUpTable;\r\n\r\n\t// following values are stored for each applications defined in applications.xml\r\n\t// [0] usage percentage (%)\r\n\t// [1] prob. of selecting cloud (%)\r\n\t// [2] poisson mean (sec)\r\n\t// [3] active period (sec)\r\n\t// [4] idle period (sec)\r\n\t// [5] avg data upload (KB)\r\n\t// [6] avg data download (KB)\r\n\t// [7] avg task length (MI)\r\n\t// [8] required # of cores\r\n\t// [9] vm utilization on edge (%)\r\n\t// [10] vm utilization on cloud (%)\r\n\t// [11] vm utilization on mobile (%)\r\n\t// [12] delay sensitivity [0-1]\r\n\tprivate double[][] taskLookUpTable = null;\r\n\r\n\tprivate String[] taskNames = null;\r\n\r\n\tprivate SimSettings() {\r\n\t\tNUM_OF_PLACE_TYPES = 0;\r\n\t}\r\n\r\n\tpublic static SimSettings getInstance() {\r\n\t\tif(instance == null) {\r\n\t\t\tinstance = new SimSettings();\r\n\t\t}\r\n\t\treturn instance;\r\n\t}\r\n\r\n\t/**\r\n\t * Reads configuration file and stores information to local variables\r\n\t * @param propertiesFile\r\n\t * @return\r\n\t */\r\n\tpublic boolean initialize(String propertiesFile, String edgeDevicesFile, String applicationsFile){\r\n\t\tboolean result = false;\r\n\t\tInputStream input = null;\r\n\t\ttry {\r\n\t\t\tinput = new FileInputStream(propertiesFile);\r\n\r\n\t\t\t// load a properties file\r\n\t\t\tProperties prop = new Properties();\r\n\t\t\tprop.load(input);\r\n\r\n\t\t\tSIMULATION_TIME = (double)60 * Double.parseDouble(prop.getProperty(\"simulation_time\")); //seconds\r\n\t\t\tWARM_UP_PERIOD = (double)60 * Double.parseDouble(prop.getProperty(\"warm_up_period\")); //seconds\r\n\t\t\tINTERVAL_TO_GET_VM_LOAD_LOG = (double)60 * Double.parseDouble(prop.getProperty(\"vm_load_check_interval\")); //seconds\r\n\t\t\tINTERVAL_TO_GET_LOCATION_LOG = (double)60 * Double.parseDouble(prop.getProperty(\"location_check_interval\")); //seconds\r\n\t\t\tINTERVAL_TO_GET_AP_DELAY_LOG = (double)60 * Double.parseDouble(prop.getProperty(\"ap_delay_check_interval\", \"0\")); //seconds\t\t\r\n\t\t\tFILE_LOG_ENABLED = Boolean.parseBoolean(prop.getProperty(\"file_log_enabled\"));\r\n\t\t\tDEEP_FILE_LOG_ENABLED = Boolean.parseBoolean(prop.getProperty(\"deep_file_log_enabled\"));\r\n\r\n\t\t\tMIN_NUM_OF_MOBILE_DEVICES = Integer.parseInt(prop.getProperty(\"min_number_of_mobile_devices\"));\r\n\t\t\tMAX_NUM_OF_MOBILE_DEVICES = Integer.parseInt(prop.getProperty(\"max_number_of_mobile_devices\"));\r\n\t\t\tMOBILE_DEVICE_COUNTER_SIZE = Integer.parseInt(prop.getProperty(\"mobile_device_counter_size\"));\r\n\t\t\tWLAN_RANGE = Integer.parseInt(prop.getProperty(\"wlan_range\", \"0\"));\r\n\r\n\t\t\tWAN_PROPAGATION_DELAY = Double.parseDouble(prop.getProperty(\"wan_propagation_delay\", \"0\"));\r\n\t\t\tGSM_PROPAGATION_DELAY = Double.parseDouble(prop.getProperty(\"gsm_propagation_delay\", \"0\"));\r\n\t\t\tLAN_INTERNAL_DELAY = Double.parseDouble(prop.getProperty(\"lan_internal_delay\", \"0\"));\r\n\t\t\tBANDWITH_WLAN = 1000 * Integer.parseInt(prop.getProperty(\"wlan_bandwidth\"));\r\n\t\t\tBANDWITH_MAN = 1000 * Integer.parseInt(prop.getProperty(\"man_bandwidth\", \"0\"));\r\n\t\t\tBANDWITH_WAN = 1000 * Integer.parseInt(prop.getProperty(\"wan_bandwidth\", \"0\"));\r\n\t\t\tBANDWITH_GSM = 1000 * Integer.parseInt(prop.getProperty(\"gsm_bandwidth\", \"0\"));\r\n\r\n\t\t\tNUM_OF_HOST_ON_CLOUD_DATACENTER = Integer.parseInt(prop.getProperty(\"number_of_host_on_cloud_datacenter\"));\r\n\t\t\tNUM_OF_VM_ON_CLOUD_HOST = Integer.parseInt(prop.getProperty(\"number_of_vm_on_cloud_host\"));\r\n\t\t\tCORE_FOR_CLOUD_VM = Integer.parseInt(prop.getProperty(\"core_for_cloud_vm\"));\r\n\t\t\tMIPS_FOR_CLOUD_VM = Integer.parseInt(prop.getProperty(\"mips_for_cloud_vm\"));\r\n\t\t\tRAM_FOR_CLOUD_VM = Integer.parseInt(prop.getProperty(\"ram_for_cloud_vm\"));\r\n\t\t\tSTORAGE_FOR_CLOUD_VM = Integer.parseInt(prop.getProperty(\"storage_for_cloud_vm\"));\r\n\r\n\t\t\tRAM_FOR_VM = Integer.parseInt(prop.getProperty(\"ram_for_mobile_vm\"));\r\n\t\t\tCORE_FOR_VM = Integer.parseInt(prop.getProperty(\"core_for_mobile_vm\"));\r\n\t\t\tMIPS_FOR_VM = Integer.parseInt(prop.getProperty(\"mips_for_mobile_vm\"));\r\n\t\t\tSTORAGE_FOR_VM = Integer.parseInt(prop.getProperty(\"storage_for_mobile_vm\"));\r\n\r\n\t\t\tORCHESTRATOR_POLICIES = prop.getProperty(\"orchestrator_policies\").split(\",\");\r\n\r\n\t\t\tSIMULATION_SCENARIOS = prop.getProperty(\"simulation_scenarios\").split(\",\");\r\n\r\n\t\t\tNORTHERN_BOUND = Double.parseDouble(prop.getProperty(\"northern_bound\", \"0\"));\r\n\t\t\tSOUTHERN_BOUND = Double.parseDouble(prop.getProperty(\"southern_bound\", \"0\"));\r\n\t\t\tEASTERN_BOUND = Double.parseDouble(prop.getProperty(\"eastern_bound\", \"0\"));\r\n\t\t\tWESTERN_BOUND = Double.parseDouble(prop.getProperty(\"western_bound\", \"0\"));\r\n\r\n\t\t\t//avg waiting time in a place (min)\r\n\t\t\tdouble place1_mean_waiting_time = Double.parseDouble(prop.getProperty(\"attractiveness_L1_mean_waiting_time\"));\r\n\t\t\tdouble place2_mean_waiting_time = Double.parseDouble(prop.getProperty(\"attractiveness_L2_mean_waiting_time\"));\r\n\t\t\tdouble place3_mean_waiting_time = Double.parseDouble(prop.getProperty(\"attractiveness_L3_mean_waiting_time\"));\r\n\r\n\t\t\t//mean waiting time (minute)\r\n\t\t\tmobilityLookUpTable = new double[]{\r\n\t\t\t\t\tplace1_mean_waiting_time, //ATTRACTIVENESS_L1\r\n\t\t\t\t\tplace2_mean_waiting_time, //ATTRACTIVENESS_L2\r\n\t\t\t\t\tplace3_mean_waiting_time //ATTRACTIVENESS_L3\r\n\t\t\t};\r\n\r\n\r\n\t\t} catch (IOException ex) {\r\n\t\t\tex.printStackTrace();\r\n\t\t} finally {\r\n\t\t\tif (input != null) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tinput.close();\r\n\t\t\t\t\tresult = true;\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tparseApplicationsXML(applicationsFile);\r\n\t\tparseEdgeDevicesXML(edgeDevicesFile);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the parsed XML document for edge_devices.xml\r\n\t */\r\n\tpublic Document getEdgeDevicesDocument(){\r\n\t\treturn edgeDevicesDoc;\r\n\t}\r\n\r\n\r\n\t/**\r\n\t * returns simulation time (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getSimulationTime()\r\n\t{\r\n\t\treturn SIMULATION_TIME;\r\n\t}\r\n\r\n\t/**\r\n\t * returns warm up period (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getWarmUpPeriod()\r\n\t{\r\n\t\treturn WARM_UP_PERIOD; \r\n\t}\r\n\r\n\t/**\r\n\t * returns VM utilization log collection interval (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getVmLoadLogInterval()\r\n\t{\r\n\t\treturn INTERVAL_TO_GET_VM_LOAD_LOG; \r\n\t}\r\n\r\n\t/**\r\n\t * returns VM location log collection interval (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getLocationLogInterval()\r\n\t{\r\n\t\treturn INTERVAL_TO_GET_LOCATION_LOG; \r\n\t}\r\n\r\n\t/**\r\n\t * returns VM location log collection interval (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getApDelayLogInterval()\r\n\t{\r\n\t\treturn INTERVAL_TO_GET_AP_DELAY_LOG; \r\n\t}\r\n\r\n\t/**\r\n\t * returns deep statistics logging status from properties file\r\n\t */\r\n\tpublic boolean getDeepFileLoggingEnabled()\r\n\t{\r\n\t\treturn FILE_LOG_ENABLED && DEEP_FILE_LOG_ENABLED; \r\n\t}\r\n\r\n\t/**\r\n\t * returns deep statistics logging status from properties file\r\n\t */\r\n\tpublic boolean getFileLoggingEnabled()\r\n\t{\r\n\t\treturn FILE_LOG_ENABLED; \r\n\t}\r\n\r\n\t/**\r\n\t * returns WAN propagation delay (in second unit) from properties file\r\n\t */\r\n\tpublic double getWanPropagationDelay()\r\n\t{\r\n\t\treturn WAN_PROPAGATION_DELAY;\r\n\t}\r\n\r\n\t/**\r\n\t * returns GSM propagation delay (in second unit) from properties file\r\n\t */\r\n\tpublic double getGsmPropagationDelay()\r\n\t{\r\n\t\treturn GSM_PROPAGATION_DELAY;\r\n\t}\r\n\r\n\t/**\r\n\t * returns internal LAN propagation delay (in second unit) from properties file\r\n\t */\r\n\tpublic double getInternalLanDelay()\r\n\t{\r\n\t\treturn LAN_INTERNAL_DELAY;\r\n\t}\r\n\r\n\t/**\r\n\t * returns WLAN bandwidth (in Mbps unit) from properties file\r\n\t */\r\n\tpublic int getWlanBandwidth()\r\n\t{\r\n\t\treturn BANDWITH_WLAN;\r\n\t}\r\n\r\n\t/**\r\n\t * returns MAN bandwidth (in Mbps unit) from properties file\r\n\t */\r\n\tpublic int getManBandwidth()\r\n\t{\r\n\t\treturn BANDWITH_MAN;\r\n\t}\r\n\r\n\t/**\r\n\t * returns WAN bandwidth (in Mbps unit) from properties file\r\n\t */\r\n\tpublic int getWanBandwidth()\r\n\t{\r\n\t\treturn BANDWITH_WAN; \r\n\t}\r\n\r\n\t/**\r\n\t * returns GSM bandwidth (in Mbps unit) from properties file\r\n\t */\r\n\tpublic int getGsmBandwidth()\r\n\t{\r\n\t\treturn BANDWITH_GSM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the minimum number of the mobile devices used in the simulation\r\n\t */\r\n\tpublic int getMinNumOfMobileDev()\r\n\t{\r\n\t\treturn MIN_NUM_OF_MOBILE_DEVICES;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the maximum number of the mobile devices used in the simulation\r\n\t */\r\n\tpublic int getMaxNumOfMobileDev()\r\n\t{\r\n\t\treturn MAX_NUM_OF_MOBILE_DEVICES;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of increase on mobile devices\r\n\t * while iterating from min to max mobile device\r\n\t */\r\n\tpublic int getMobileDevCounterSize()\r\n\t{\r\n\t\treturn MOBILE_DEVICE_COUNTER_SIZE;\r\n\t}\r\n\r\n\t/**\r\n\t * returns edge device range in meter\r\n\t */\r\n\tpublic int getWlanRange()\r\n\t{\r\n\t\treturn WLAN_RANGE;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of edge datacenters\r\n\t */\r\n\tpublic int getNumOfEdgeDatacenters()\r\n\t{\r\n\t\treturn NUM_OF_EDGE_DATACENTERS;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of edge hosts running on the datacenters\r\n\t */\r\n\tpublic int getNumOfEdgeHosts()\r\n\t{\r\n\t\treturn NUM_OF_EDGE_HOSTS;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of edge VMs running on the hosts\r\n\t */\r\n\tpublic int getNumOfEdgeVMs()\r\n\t{\r\n\t\treturn NUM_OF_EDGE_VMS;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of different place types\r\n\t */\r\n\tpublic int getNumOfPlaceTypes()\r\n\t{\r\n\t\treturn NUM_OF_PLACE_TYPES;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of cloud datacenters\r\n\t */\r\n\tpublic int getNumOfCloudHost()\r\n\t{\r\n\t\treturn NUM_OF_HOST_ON_CLOUD_DATACENTER;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of cloud VMs per Host\r\n\t */\r\n\tpublic int getNumOfCloudVMsPerHost()\r\n\t{\r\n\t\treturn NUM_OF_VM_ON_CLOUD_HOST;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the total number of cloud VMs\r\n\t */\r\n\tpublic int getNumOfCloudVMs()\r\n\t{\r\n\t\treturn NUM_OF_VM_ON_CLOUD_HOST * NUM_OF_HOST_ON_CLOUD_DATACENTER;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of cores for cloud VMs\r\n\t */\r\n\tpublic int getCoreForCloudVM()\r\n\t{\r\n\t\treturn CORE_FOR_CLOUD_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns MIPS of the central cloud VMs\r\n\t */\r\n\tpublic int getMipsForCloudVM()\r\n\t{\r\n\t\treturn MIPS_FOR_CLOUD_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns RAM of the central cloud VMs\r\n\t */\r\n\tpublic int getRamForCloudVM()\r\n\t{\r\n\t\treturn RAM_FOR_CLOUD_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns Storage of the central cloud VMs\r\n\t */\r\n\tpublic int getStorageForCloudVM()\r\n\t{\r\n\t\treturn STORAGE_FOR_CLOUD_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns RAM of the mobile (processing unit) VMs\r\n\t */\r\n\tpublic int getRamForMobileVM()\r\n\t{\r\n\t\treturn RAM_FOR_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of cores for mobile VMs\r\n\t */\r\n\tpublic int getCoreForMobileVM()\r\n\t{\r\n\t\treturn CORE_FOR_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns MIPS of the mobile (processing unit) VMs\r\n\t */\r\n\tpublic int getMipsForMobileVM()\r\n\t{\r\n\t\treturn MIPS_FOR_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns Storage of the mobile (processing unit) VMs\r\n\t */\r\n\tpublic int getStorageForMobileVM()\r\n\t{\r\n\t\treturn STORAGE_FOR_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns simulation screnarios as string\r\n\t */\r\n\tpublic String[] getSimulationScenarios()\r\n\t{\r\n\t\treturn SIMULATION_SCENARIOS;\r\n\t}\r\n\r\n\t/**\r\n\t * returns orchestrator policies as string\r\n\t */\r\n\tpublic String[] getOrchestratorPolicies()\r\n\t{\r\n\t\treturn ORCHESTRATOR_POLICIES;\r\n\t}\r\n\r\n\r\n\tpublic double getNorthernBound() {\r\n\t\treturn NORTHERN_BOUND;\r\n\t}\r\n\r\n\tpublic double getEasternBound() {\r\n\t\treturn EASTERN_BOUND;\r\n\t}\r\n\r\n\tpublic double getSouthernBound() {\r\n\t\treturn SOUTHERN_BOUND;\r\n\t}\r\n\r\n\tpublic double getWesternBound() {\r\n\t\treturn WESTERN_BOUND;\r\n\t}\r\n\r\n\t/**\r\n\t * returns mobility characteristic within an array\r\n\t * the result includes mean waiting time (minute) or each place type\r\n\t */ \r\n\tpublic double[] getMobilityLookUpTable()\r\n\t{\r\n\t\treturn mobilityLookUpTable;\r\n\t}\r\n\r\n\t/**\r\n\t * returns application characteristic within two dimensional array\r\n\t * the result includes the following values for each application type\r\n\t * [0] usage percentage (%)\r\n\t * [1] prob. of selecting cloud (%)\r\n\t * [2] poisson mean (sec)\r\n\t * [3] active period (sec)\r\n\t * [4] idle period (sec)\r\n\t * [5] avg data upload (KB)\r\n\t * [6] avg data download (KB)\r\n\t * [7] avg task length (MI)\r\n\t * [8] required # of cores\r\n\t * [9] vm utilization on edge (%)\r\n\t * [10] vm utilization on cloud (%)\r\n\t * [11] vm utilization on mobile (%)\r\n\t * [12] delay sensitivity [0-1]\r\n\t * [13] maximum delay requirement (sec)\r\n\t */ \r\n\tpublic double[][] getTaskLookUpTable()\r\n\t{\r\n\t\treturn taskLookUpTable;\r\n\t}\r\n\r\n\tpublic double[] getTaskProperties(String taskName) {\r\n\t\tdouble[] result = null;\r\n\t\tint index = -1;\r\n\t\tfor (int i=0;i<taskNames.length;i++) {\r\n\t\t\tif (taskNames[i].equals(taskName)) {\r\n\t\t\t\tindex = i;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif(index >= 0 && index < taskLookUpTable.length)\r\n\t\t\tresult = taskLookUpTable[index];\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tpublic String getTaskName(int taskType)\r\n\t{\r\n\t\treturn taskNames[taskType];\r\n\t}\r\n\r\n\tprivate void isAttributePresent(Element element, String key) {\r\n\t\tString value = element.getAttribute(key);\r\n\t\tif (value.isEmpty() || value == null){\r\n\t\t\tthrow new IllegalArgumentException(\"Attribute '\" + key + \"' is not found in '\" + element.getNodeName() +\"'\");\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void isElementPresent(Element element, String key) {\r\n\t\ttry {\r\n\t\t\tString value = element.getElementsByTagName(key).item(0).getTextContent();\r\n\t\t\tif (value.isEmpty() || value == null){\r\n\t\t\t\tthrow new IllegalArgumentException(\"Element '\" + key + \"' is not found in '\" + element.getNodeName() +\"'\");\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new IllegalArgumentException(\"Element '\" + key + \"' is not found in '\" + element.getNodeName() +\"'\");\r\n\t\t}\r\n\t}\r\n\r\n\tprivate Boolean checkElement(Element element, String key) {\r\n\t\tBoolean result = true;\r\n\t\ttry {\r\n\t\t\tString value = element.getElementsByTagName(key).item(0).getTextContent();\r\n\t\t\tif (value.isEmpty() || value == null){\r\n\t\t\t\tresult = false;\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tresult = false;\r\n\t\t}\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tprivate void parseApplicationsXML(String filePath)\r\n\t{\r\n\t\tDocument doc = null;\r\n\t\ttry {\t\r\n\t\t\tFile devicesFile = new File(filePath);\r\n\t\t\tDocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\r\n\t\t\tDocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\r\n\t\t\tdoc = dBuilder.parse(devicesFile);\r\n\t\t\tdoc.getDocumentElement().normalize();\r\n\r\n\t\t\tString mandatoryAttributes[] = {\r\n\t\t\t\t\t\"usage_percentage\", //usage percentage [0-100]\r\n\t\t\t\t\t\"prob_cloud_selection\", //prob. of selecting cloud [0-100]\r\n\t\t\t\t\t\"poisson_interarrival\", //poisson mean (sec)\r\n\t\t\t\t\t\"active_period\", //active period (sec)\r\n\t\t\t\t\t\"idle_period\", //idle period (sec)\r\n\t\t\t\t\t\"data_upload\", //avg data upload (KB)\r\n\t\t\t\t\t\"data_download\", //avg data download (KB)\r\n\t\t\t\t\t\"task_length\", //avg task length (MI)\r\n\t\t\t\t\t\"required_core\", //required # of core\r\n\t\t\t\t\t\"vm_utilization_on_edge\", //vm utilization on edge vm [0-100]\r\n\t\t\t\t\t\"vm_utilization_on_cloud\", //vm utilization on cloud vm [0-100]\r\n\t\t\t\t\t\"vm_utilization_on_mobile\", //vm utilization on mobile vm [0-100]\r\n\t\t\t\"delay_sensitivity\"}; //delay_sensitivity [0-1]\r\n\r\n\t\t\tString optionalAttributes[] = {\r\n\t\t\t\"max_delay_requirement\"}; //maximum delay requirement (sec)\r\n\r\n\t\t\tNodeList appList = doc.getElementsByTagName(\"application\");\r\n\t\t\ttaskLookUpTable = new double[appList.getLength()]\r\n\t\t\t\t\t[mandatoryAttributes.length + optionalAttributes.length];\r\n\r\n\t\t\ttaskNames = new String[appList.getLength()];\r\n\t\t\tfor (int i = 0; i < appList.getLength(); i++) {\r\n\t\t\t\tNode appNode = appList.item(i);\r\n\r\n\t\t\t\tElement appElement = (Element) appNode;\r\n\t\t\t\tisAttributePresent(appElement, \"name\");\r\n\t\t\t\tString taskName = appElement.getAttribute(\"name\");\r\n\t\t\t\ttaskNames[i] = taskName;\r\n\r\n\t\t\t\tfor(int m=0; m<mandatoryAttributes.length; m++){\r\n\t\t\t\t\tisElementPresent(appElement, mandatoryAttributes[m]);\r\n\t\t\t\t\ttaskLookUpTable[i][m] = Double.parseDouble(appElement.\r\n\t\t\t\t\t\t\tgetElementsByTagName(mandatoryAttributes[m]).item(0).getTextContent());\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfor(int o=0; o<optionalAttributes.length; o++){\r\n\t\t\t\t\tdouble value = 0;\r\n\t\t\t\t\tif(checkElement(appElement, optionalAttributes[o]))\r\n\t\t\t\t\t\tvalue = Double.parseDouble(appElement.getElementsByTagName(optionalAttributes[o]).item(0).getTextContent());\r\n\r\n\t\t\t\t\ttaskLookUpTable[i][mandatoryAttributes.length + o] = value;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tSimLogger.printLine(\"Edge Devices XML cannot be parsed! Terminating simulation...\");\r\n\t\t\te.printStackTrace();\r\n\t\t\tSystem.exit(1);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void parseEdgeDevicesXML(String filePath)\r\n\t{\r\n\t\ttry {\t\r\n\t\t\tFile devicesFile = new File(filePath);\r\n\t\t\tDocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\r\n\t\t\tDocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\r\n\t\t\tedgeDevicesDoc = dBuilder.parse(devicesFile);\r\n\t\t\tedgeDevicesDoc.getDocumentElement().normalize();\r\n\r\n\t\t\tNodeList datacenterList = edgeDevicesDoc.getElementsByTagName(\"datacenter\");\r\n\t\t\tfor (int i = 0; i < datacenterList.getLength(); i++) {\r\n\t\t\t\tNUM_OF_EDGE_DATACENTERS++;\r\n\t\t\t\tNode datacenterNode = datacenterList.item(i);\r\n\r\n\t\t\t\tElement datacenterElement = (Element) datacenterNode;\r\n\t\t\t\tisAttributePresent(datacenterElement, \"arch\");\r\n\t\t\t\tisAttributePresent(datacenterElement, \"os\");\r\n\t\t\t\tisAttributePresent(datacenterElement, \"vmm\");\r\n\t\t\t\tisElementPresent(datacenterElement, \"costPerBw\");\r\n\t\t\t\tisElementPresent(datacenterElement, \"costPerSec\");\r\n\t\t\t\tisElementPresent(datacenterElement, \"costPerMem\");\r\n\t\t\t\tisElementPresent(datacenterElement, \"costPerStorage\");\r\n\r\n\t\t\t\tElement location = (Element)datacenterElement.getElementsByTagName(\"location\").item(0);\r\n\t\t\t\tisElementPresent(location, \"attractiveness\");\r\n\t\t\t\tisElementPresent(location, \"wlan_id\");\r\n\t\t\t\tisElementPresent(location, \"x_pos\");\r\n\t\t\t\tisElementPresent(location, \"y_pos\");\r\n\r\n\t\t\t\tString attractiveness = location.getElementsByTagName(\"attractiveness\").item(0).getTextContent();\r\n\t\t\t\tint placeTypeIndex = Integer.parseInt(attractiveness);\r\n\t\t\t\tif(NUM_OF_PLACE_TYPES < placeTypeIndex+1)\r\n\t\t\t\t\tNUM_OF_PLACE_TYPES = placeTypeIndex+1;\r\n\r\n\t\t\t\tNodeList hostList = datacenterElement.getElementsByTagName(\"host\");\r\n\t\t\t\tfor (int j = 0; j < hostList.getLength(); j++) {\r\n\t\t\t\t\tNUM_OF_EDGE_HOSTS++;\r\n\t\t\t\t\tNode hostNode = hostList.item(j);\r\n\r\n\t\t\t\t\tElement hostElement = (Element) hostNode;\r\n\t\t\t\t\tisElementPresent(hostElement, \"core\");\r\n\t\t\t\t\tisElementPresent(hostElement, \"mips\");\r\n\t\t\t\t\tisElementPresent(hostElement, \"ram\");\r\n\t\t\t\t\tisElementPresent(hostElement, \"storage\");\r\n\r\n\t\t\t\t\tNodeList vmList = hostElement.getElementsByTagName(\"VM\");\r\n\t\t\t\t\tfor (int k = 0; k < vmList.getLength(); k++) {\r\n\t\t\t\t\t\tNUM_OF_EDGE_VMS++;\r\n\t\t\t\t\t\tNode vmNode = vmList.item(k);\r\n\r\n\t\t\t\t\t\tElement vmElement = (Element) vmNode;\r\n\t\t\t\t\t\tisAttributePresent(vmElement, \"vmm\");\r\n\t\t\t\t\t\tisElementPresent(vmElement, \"core\");\r\n\t\t\t\t\t\tisElementPresent(vmElement, \"mips\");\r\n\t\t\t\t\t\tisElementPresent(vmElement, \"ram\");\r\n\t\t\t\t\t\tisElementPresent(vmElement, \"storage\");\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t} catch (Exception e) {\r\n\t\t\tSimLogger.printLine(\"Edge Devices XML cannot be parsed! Terminating simulation...\");\r\n\t\t\te.printStackTrace();\r\n\t\t\tSystem.exit(1);\r\n\t\t}\r\n\t}\r\n}\r",
"public class Task extends Cloudlet {\r\n\tprivate Location submittedLocation;\r\n\tprivate double creationTime;\r\n\tprivate int type;\r\n\tprivate int mobileDeviceId;\r\n\tprivate int hostIndex;\r\n\tprivate int vmIndex;\r\n\tprivate int datacenterId;\r\n\r\n\tpublic Task(int _mobileDeviceId, int cloudletId, long cloudletLength, int pesNumber,\r\n\t\t\tlong cloudletFileSize, long cloudletOutputSize,\r\n\t\t\tUtilizationModel utilizationModelCpu,\r\n\t\t\tUtilizationModel utilizationModelRam,\r\n\t\t\tUtilizationModel utilizationModelBw) {\r\n\t\tsuper(cloudletId, cloudletLength, pesNumber, cloudletFileSize,\r\n\t\t\t\tcloudletOutputSize, utilizationModelCpu, utilizationModelRam,\r\n\t\t\t\tutilizationModelBw);\r\n\t\t\r\n\t\tmobileDeviceId = _mobileDeviceId;\r\n\t\tcreationTime = CloudSim.clock();\r\n\t}\r\n\r\n\t\r\n\tpublic void setSubmittedLocation(Location _submittedLocation){\r\n\t\tsubmittedLocation =_submittedLocation;\r\n\t}\r\n\r\n\tpublic void setAssociatedDatacenterId(int _datacenterId){\r\n\t\tdatacenterId=_datacenterId;\r\n\t}\r\n\t\r\n\tpublic void setAssociatedHostId(int _hostIndex){\r\n\t\thostIndex=_hostIndex;\r\n\t}\r\n\r\n\tpublic void setAssociatedVmId(int _vmIndex){\r\n\t\tvmIndex=_vmIndex;\r\n\t}\r\n\t\r\n\tpublic void setTaskType(int _type){\r\n\t\ttype=_type;\r\n\t}\r\n\r\n\tpublic int getMobileDeviceId(){\r\n\t\treturn mobileDeviceId;\r\n\t}\r\n\t\r\n\tpublic Location getSubmittedLocation(){\r\n\t\treturn submittedLocation;\r\n\t}\r\n\t\r\n\tpublic int getAssociatedDatacenterId(){\r\n\t\treturn datacenterId;\r\n\t}\r\n\t\r\n\tpublic int getAssociatedHostId(){\r\n\t\treturn hostIndex;\r\n\t}\r\n\r\n\tpublic int getAssociatedVmId(){\r\n\t\treturn vmIndex;\r\n\t}\r\n\t\r\n\tpublic int getTaskType(){\r\n\t\treturn type;\r\n\t}\r\n\t\r\n\tpublic double getCreationTime() {\r\n\t\treturn creationTime;\r\n\t}\r\n}\r",
"public abstract class NetworkModel {\r\n\tprotected int numberOfMobileDevices;\r\n\tprotected String simScenario;\r\n\r\n\tpublic NetworkModel(int _numberOfMobileDevices, String _simScenario){\r\n\t\tnumberOfMobileDevices=_numberOfMobileDevices;\r\n\t\tsimScenario = _simScenario;\r\n\t};\r\n\r\n\t/**\r\n\t * initializes custom network model\r\n\t */\r\n\tpublic abstract void initialize();\r\n\r\n\t/**\r\n\t * calculates the upload delay from source to destination device\r\n\t */\r\n\tpublic abstract double getUploadDelay(int sourceDeviceId, int destDeviceId, Task task);\r\n\r\n\t/**\r\n\t * calculates the download delay from source to destination device\r\n\t */\r\n\tpublic abstract double getDownloadDelay(int sourceDeviceId, int destDeviceId, Task task);\r\n\r\n\t/**\r\n\t * Mobile device manager should inform network manager about the network operation\r\n\t * This information may be important for some network delay models\r\n\t */\r\n\tpublic abstract void uploadStarted(Location accessPointLocation, int destDeviceId);\r\n\tpublic abstract void uploadFinished(Location accessPointLocation, int destDeviceId);\r\n\tpublic abstract void downloadStarted(Location accessPointLocation, int sourceDeviceId);\r\n\tpublic abstract void downloadFinished(Location accessPointLocation, int sourceDeviceId);\r\n}\r",
"public class Location {\r\n\tprivate int xPos;\r\n\tprivate int yPos;\r\n\tprivate int servingWlanId;\r\n\tprivate int placeTypeIndex;\r\n\tpublic Location(int _placeTypeIndex, int _servingWlanId, int _xPos, int _yPos){\r\n\t\tservingWlanId = _servingWlanId;\r\n\t\tplaceTypeIndex=_placeTypeIndex;\r\n\t\txPos = _xPos;\r\n\t\tyPos = _yPos;\r\n\t}\r\n\t\r\n\t/*\r\n\t * Default Constructor: Creates an empty Location\r\n\t */\r\n\tpublic Location() {\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic boolean equals(Object other){\r\n\t\tboolean result = false;\r\n\t if (other == null) return false;\r\n\t if (!(other instanceof Location))return false;\r\n\t if (other == this) return true;\r\n\t \r\n\t Location otherLocation = (Location)other;\r\n\t if(this.xPos == otherLocation.xPos && this.yPos == otherLocation.yPos)\r\n\t \tresult = true;\r\n\r\n\t return result;\r\n\t}\r\n\r\n\tpublic int getServingWlanId(){\r\n\t\treturn servingWlanId;\r\n\t}\r\n\t\r\n\tpublic int getPlaceTypeIndex(){\r\n\t\treturn placeTypeIndex;\r\n\t}\r\n\t\r\n\tpublic int getXPos(){\r\n\t\treturn xPos;\r\n\t}\r\n\t\r\n\tpublic int getYPos(){\r\n\t\treturn yPos;\r\n\t}\r\n}\r",
"public class SimLogger {\r\n\tpublic static enum TASK_STATUS {\r\n\t\tCREATED, UPLOADING, PROCESSING, DOWNLOADING, COMLETED,\r\n\t\tREJECTED_DUE_TO_VM_CAPACITY, REJECTED_DUE_TO_BANDWIDTH,\r\n\t\tUNFINISHED_DUE_TO_BANDWIDTH, UNFINISHED_DUE_TO_MOBILITY,\r\n\t\tREJECTED_DUE_TO_WLAN_COVERAGE\r\n\t}\r\n\t\r\n\tpublic static enum NETWORK_ERRORS {\r\n\t\tLAN_ERROR, MAN_ERROR, WAN_ERROR, GSM_ERROR, NONE\r\n\t}\r\n\r\n\tprivate long startTime;\r\n\tprivate long endTime;\r\n\tprivate static boolean fileLogEnabled;\r\n\tprivate static boolean printLogEnabled;\r\n\tprivate String filePrefix;\r\n\tprivate String outputFolder;\r\n\tprivate Map<Integer, LogItem> taskMap;\r\n\tprivate LinkedList<VmLoadLogItem> vmLoadList;\r\n\tprivate LinkedList<ApDelayLogItem> apDelayList;\r\n\r\n\tprivate static SimLogger singleton = new SimLogger();\r\n\t\r\n\tprivate int numOfAppTypes;\r\n\t\r\n\tprivate File successFile = null, failFile = null;\r\n\tprivate FileWriter successFW = null, failFW = null;\r\n\tprivate BufferedWriter successBW = null, failBW = null;\r\n\r\n\t// extract following values for each app type.\r\n\t// last index is average of all app types\r\n\tprivate int[] uncompletedTask = null;\r\n\tprivate int[] uncompletedTaskOnCloud = null;\r\n\tprivate int[] uncompletedTaskOnEdge = null;\r\n\tprivate int[] uncompletedTaskOnMobile = null;\r\n\r\n\tprivate int[] completedTask = null;\r\n\tprivate int[] completedTaskOnCloud = null;\r\n\tprivate int[] completedTaskOnEdge = null;\r\n\tprivate int[] completedTaskOnMobile = null;\r\n\r\n\tprivate int[] failedTask = null;\r\n\tprivate int[] failedTaskOnCloud = null;\r\n\tprivate int[] failedTaskOnEdge = null;\r\n\tprivate int[] failedTaskOnMobile = null;\r\n\r\n\tprivate double[] networkDelay = null;\r\n\tprivate double[] gsmDelay = null;\r\n\tprivate double[] wanDelay = null;\r\n\tprivate double[] manDelay = null;\r\n\tprivate double[] lanDelay = null;\r\n\t\r\n\tprivate double[] gsmUsage = null;\r\n\tprivate double[] wanUsage = null;\r\n\tprivate double[] manUsage = null;\r\n\tprivate double[] lanUsage = null;\r\n\r\n\tprivate double[] serviceTime = null;\r\n\tprivate double[] serviceTimeOnCloud = null;\r\n\tprivate double[] serviceTimeOnEdge = null;\r\n\tprivate double[] serviceTimeOnMobile = null;\r\n\r\n\tprivate double[] processingTime = null;\r\n\tprivate double[] processingTimeOnCloud = null;\r\n\tprivate double[] processingTimeOnEdge = null;\r\n\tprivate double[] processingTimeOnMobile = null;\r\n\r\n\tprivate int[] failedTaskDueToVmCapacity = null;\r\n\tprivate int[] failedTaskDueToVmCapacityOnCloud = null;\r\n\tprivate int[] failedTaskDueToVmCapacityOnEdge = null;\r\n\tprivate int[] failedTaskDueToVmCapacityOnMobile = null;\r\n\t\r\n\tprivate double[] cost = null;\r\n\tprivate double[] QoE = null;\r\n\tprivate int[] failedTaskDuetoBw = null;\r\n\tprivate int[] failedTaskDuetoLanBw = null;\r\n\tprivate int[] failedTaskDuetoManBw = null;\r\n\tprivate int[] failedTaskDuetoWanBw = null;\r\n\tprivate int[] failedTaskDuetoGsmBw = null;\r\n\tprivate int[] failedTaskDuetoMobility = null;\r\n\tprivate int[] refectedTaskDuetoWlanRange = null;\r\n\t\r\n\tprivate double[] orchestratorOverhead = null;\r\n\r\n\t/*\r\n\t * A private Constructor prevents any other class from instantiating.\r\n\t */\r\n\tprivate SimLogger() {\r\n\t\tfileLogEnabled = false;\r\n\t\tprintLogEnabled = false;\r\n\t}\r\n\r\n\t/* Static 'instance' method */\r\n\tpublic static SimLogger getInstance() {\r\n\t\treturn singleton;\r\n\t}\r\n\r\n\tpublic static void enableFileLog() {\r\n\t\tfileLogEnabled = true;\r\n\t}\r\n\r\n\tpublic static void enablePrintLog() {\r\n\t\tprintLogEnabled = true;\r\n\t}\r\n\r\n\tpublic static boolean isFileLogEnabled() {\r\n\t\treturn fileLogEnabled;\r\n\t}\r\n\r\n\tpublic static void disableFileLog() {\r\n\t\tfileLogEnabled = false;\r\n\t}\r\n\t\r\n\tpublic static void disablePrintLog() {\r\n\t\tprintLogEnabled = false;\r\n\t}\r\n\t\r\n\tpublic String getOutputFolder() {\r\n\t\treturn outputFolder;\r\n\t}\r\n\r\n\tprivate void appendToFile(BufferedWriter bw, String line) throws IOException {\r\n\t\tbw.write(line);\r\n\t\tbw.newLine();\r\n\t}\r\n\r\n\tpublic static void printLine(String msg) {\r\n\t\tif (printLogEnabled)\r\n\t\t\tSystem.out.println(msg);\r\n\t}\r\n\r\n\tpublic static void print(String msg) {\r\n\t\tif (printLogEnabled)\r\n\t\t\tSystem.out.print(msg);\r\n\t}\r\n\r\n\tpublic void simStarted(String outFolder, String fileName) {\r\n\t\tstartTime = System.currentTimeMillis();\r\n\t\tfilePrefix = fileName;\r\n\t\toutputFolder = outFolder;\r\n\t\ttaskMap = new HashMap<Integer, LogItem>();\r\n\t\tvmLoadList = new LinkedList<VmLoadLogItem>();\r\n\t\tapDelayList = new LinkedList<ApDelayLogItem>();\r\n\t\t\r\n\t\tnumOfAppTypes = SimSettings.getInstance().getTaskLookUpTable().length;\r\n\t\t\r\n\t\tif (SimSettings.getInstance().getDeepFileLoggingEnabled()) {\r\n\t\t\ttry {\r\n\t\t\t\tsuccessFile = new File(outputFolder, filePrefix + \"_SUCCESS.log\");\r\n\t\t\t\tsuccessFW = new FileWriter(successFile, true);\r\n\t\t\t\tsuccessBW = new BufferedWriter(successFW);\r\n\r\n\t\t\t\tfailFile = new File(outputFolder, filePrefix + \"_FAIL.log\");\r\n\t\t\t\tfailFW = new FileWriter(failFile, true);\r\n\t\t\t\tfailBW = new BufferedWriter(failFW);\r\n\t\t\t\t\r\n\t\t\t\tappendToFile(successBW, \"#auto generated file!\");\r\n\t\t\t\tappendToFile(failBW, \"#auto generated file!\");\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t\tSystem.exit(1);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// extract following values for each app type.\r\n\t\t// last index is average of all app types\r\n\t\tuncompletedTask = new int[numOfAppTypes + 1];\r\n\t\tuncompletedTaskOnCloud = new int[numOfAppTypes + 1];\r\n\t\tuncompletedTaskOnEdge = new int[numOfAppTypes + 1];\r\n\t\tuncompletedTaskOnMobile = new int[numOfAppTypes + 1];\r\n\r\n\t\tcompletedTask = new int[numOfAppTypes + 1];\r\n\t\tcompletedTaskOnCloud = new int[numOfAppTypes + 1];\r\n\t\tcompletedTaskOnEdge = new int[numOfAppTypes + 1];\r\n\t\tcompletedTaskOnMobile = new int[numOfAppTypes + 1];\r\n\r\n\t\tfailedTask = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskOnCloud = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskOnEdge = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskOnMobile = new int[numOfAppTypes + 1];\r\n\r\n\t\tnetworkDelay = new double[numOfAppTypes + 1];\r\n\t\tgsmDelay = new double[numOfAppTypes + 1];\r\n\t\twanDelay = new double[numOfAppTypes + 1];\r\n\t\tmanDelay = new double[numOfAppTypes + 1];\r\n\t\tlanDelay = new double[numOfAppTypes + 1];\r\n\t\t\r\n\t\tgsmUsage = new double[numOfAppTypes + 1];\r\n\t\twanUsage = new double[numOfAppTypes + 1];\r\n\t\tmanUsage = new double[numOfAppTypes + 1];\r\n\t\tlanUsage = new double[numOfAppTypes + 1];\r\n\r\n\t\tserviceTime = new double[numOfAppTypes + 1];\r\n\t\tserviceTimeOnCloud = new double[numOfAppTypes + 1];\r\n\t\tserviceTimeOnEdge = new double[numOfAppTypes + 1];\r\n\t\tserviceTimeOnMobile = new double[numOfAppTypes + 1];\r\n\r\n\t\tprocessingTime = new double[numOfAppTypes + 1];\r\n\t\tprocessingTimeOnCloud = new double[numOfAppTypes + 1];\r\n\t\tprocessingTimeOnEdge = new double[numOfAppTypes + 1];\r\n\t\tprocessingTimeOnMobile = new double[numOfAppTypes + 1];\r\n\r\n\t\tfailedTaskDueToVmCapacity = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDueToVmCapacityOnCloud = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDueToVmCapacityOnEdge = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDueToVmCapacityOnMobile = new int[numOfAppTypes + 1];\r\n\t\t\r\n\t\tcost = new double[numOfAppTypes + 1];\r\n\t\tQoE = new double[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoLanBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoManBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoWanBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoGsmBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoMobility = new int[numOfAppTypes + 1];\r\n\t\trefectedTaskDuetoWlanRange = new int[numOfAppTypes + 1];\r\n\r\n\t\torchestratorOverhead = new double[numOfAppTypes + 1];\r\n\t}\r\n\r\n\tpublic void addLog(int deviceId, int taskId, int taskType,\r\n\t\t\tint taskLenght, int taskInputType, int taskOutputSize) {\r\n\t\t// printLine(taskId+\"->\"+taskStartTime);\r\n\t\ttaskMap.put(taskId, new LogItem(deviceId, taskType, taskLenght, taskInputType, taskOutputSize));\r\n\t}\r\n\r\n\tpublic void taskStarted(int taskId, double time) {\r\n\t\ttaskMap.get(taskId).taskStarted(time);\r\n\t}\r\n\r\n\tpublic void setUploadDelay(int taskId, double delay, NETWORK_DELAY_TYPES delayType) {\r\n\t\ttaskMap.get(taskId).setUploadDelay(delay, delayType);\r\n\t}\r\n\r\n\tpublic void setDownloadDelay(int taskId, double delay, NETWORK_DELAY_TYPES delayType) {\r\n\t\ttaskMap.get(taskId).setDownloadDelay(delay, delayType);\r\n\t}\r\n\t\r\n\tpublic void taskAssigned(int taskId, int datacenterId, int hostId, int vmId, int vmType) {\r\n\t\ttaskMap.get(taskId).taskAssigned(datacenterId, hostId, vmId, vmType);\r\n\t}\r\n\r\n\tpublic void taskExecuted(int taskId) {\r\n\t\ttaskMap.get(taskId).taskExecuted();\r\n\t}\r\n\r\n\tpublic void taskEnded(int taskId, double time) {\r\n\t\ttaskMap.get(taskId).taskEnded(time);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n\tpublic void rejectedDueToVMCapacity(int taskId, double time, int vmType) {\r\n\t\ttaskMap.get(taskId).taskRejectedDueToVMCapacity(time, vmType);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n public void rejectedDueToWlanCoverage(int taskId, double time, int vmType) {\r\n \ttaskMap.get(taskId).taskRejectedDueToWlanCoverage(time, vmType);\r\n\t\trecordLog(taskId);\r\n }\r\n \r\n\tpublic void rejectedDueToBandwidth(int taskId, double time, int vmType, NETWORK_DELAY_TYPES delayType) {\r\n\t\ttaskMap.get(taskId).taskRejectedDueToBandwidth(time, vmType, delayType);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n\tpublic void failedDueToBandwidth(int taskId, double time, NETWORK_DELAY_TYPES delayType) {\r\n\t\ttaskMap.get(taskId).taskFailedDueToBandwidth(time, delayType);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n\tpublic void failedDueToMobility(int taskId, double time) {\r\n\t\ttaskMap.get(taskId).taskFailedDueToMobility(time);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n\tpublic void setQoE(int taskId, double QoE){\r\n\t\ttaskMap.get(taskId).setQoE(QoE);\r\n\t}\r\n\t\r\n\tpublic void setOrchestratorOverhead(int taskId, double overhead){\r\n\t\ttaskMap.get(taskId).setOrchestratorOverhead(overhead);\r\n\t}\r\n\r\n\tpublic void addVmUtilizationLog(double time, double loadOnEdge, double loadOnCloud, double loadOnMobile) {\r\n\t\tif(SimSettings.getInstance().getLocationLogInterval() != 0)\r\n\t\t\tvmLoadList.add(new VmLoadLogItem(time, loadOnEdge, loadOnCloud, loadOnMobile));\r\n\t}\r\n\r\n\tpublic void addApDelayLog(double time, double[] apUploadDelays, double[] apDownloadDelays) {\r\n\t\tif(SimSettings.getInstance().getApDelayLogInterval() != 0)\r\n\t\t\tapDelayList.add(new ApDelayLogItem(time, apUploadDelays, apDownloadDelays));\r\n\t}\r\n\t\r\n\tpublic void simStopped() throws IOException {\r\n\t\tendTime = System.currentTimeMillis();\r\n\t\tFile vmLoadFile = null, locationFile = null, apUploadDelayFile = null, apDownloadDelayFile = null;\r\n\t\tFileWriter vmLoadFW = null, locationFW = null, apUploadDelayFW = null, apDownloadDelayFW = null;\r\n\t\tBufferedWriter vmLoadBW = null, locationBW = null, apUploadDelayBW = null, apDownloadDelayBW = null;\r\n\r\n\t\t// Save generic results to file for each app type. last index is average\r\n\t\t// of all app types\r\n\t\tFile[] genericFiles = new File[numOfAppTypes + 1];\r\n\t\tFileWriter[] genericFWs = new FileWriter[numOfAppTypes + 1];\r\n\t\tBufferedWriter[] genericBWs = new BufferedWriter[numOfAppTypes + 1];\r\n\r\n\t\t// open all files and prepare them for write\r\n\t\tif (fileLogEnabled) {\r\n\t\t\tvmLoadFile = new File(outputFolder, filePrefix + \"_VM_LOAD.log\");\r\n\t\t\tvmLoadFW = new FileWriter(vmLoadFile, true);\r\n\t\t\tvmLoadBW = new BufferedWriter(vmLoadFW);\r\n\r\n\t\t\tlocationFile = new File(outputFolder, filePrefix + \"_LOCATION.log\");\r\n\t\t\tlocationFW = new FileWriter(locationFile, true);\r\n\t\t\tlocationBW = new BufferedWriter(locationFW);\r\n\r\n\t\t\tapUploadDelayFile = new File(outputFolder, filePrefix + \"_AP_UPLOAD_DELAY.log\");\r\n\t\t\tapUploadDelayFW = new FileWriter(apUploadDelayFile, true);\r\n\t\t\tapUploadDelayBW = new BufferedWriter(apUploadDelayFW);\r\n\r\n\t\t\tapDownloadDelayFile = new File(outputFolder, filePrefix + \"_AP_DOWNLOAD_DELAY.log\");\r\n\t\t\tapDownloadDelayFW = new FileWriter(apDownloadDelayFile, true);\r\n\t\t\tapDownloadDelayBW = new BufferedWriter(apDownloadDelayFW);\r\n\r\n\t\t\tfor (int i = 0; i < numOfAppTypes + 1; i++) {\r\n\t\t\t\tString fileName = \"ALL_APPS_GENERIC.log\";\r\n\r\n\t\t\t\tif (i < numOfAppTypes) {\r\n\t\t\t\t\t// if related app is not used in this simulation, just discard it\r\n\t\t\t\t\tif (SimSettings.getInstance().getTaskLookUpTable()[i][0] == 0)\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfileName = SimSettings.getInstance().getTaskName(i) + \"_GENERIC.log\";\r\n\t\t\t\t}\r\n\r\n\t\t\t\tgenericFiles[i] = new File(outputFolder, filePrefix + \"_\" + fileName);\r\n\t\t\t\tgenericFWs[i] = new FileWriter(genericFiles[i], true);\r\n\t\t\t\tgenericBWs[i] = new BufferedWriter(genericFWs[i]);\r\n\t\t\t\tappendToFile(genericBWs[i], \"#auto generated file!\");\r\n\t\t\t}\r\n\r\n\t\t\tappendToFile(vmLoadBW, \"#auto generated file!\");\r\n\t\t\tappendToFile(locationBW, \"#auto generated file!\");\r\n\t\t\tappendToFile(apUploadDelayBW, \"#auto generated file!\");\r\n\t\t\tappendToFile(apDownloadDelayBW, \"#auto generated file!\");\r\n\t\t}\r\n\r\n\t\t//the tasks in the map is not completed yet!\r\n\t\tfor (Map.Entry<Integer, LogItem> entry : taskMap.entrySet()) {\r\n\t\t\tLogItem value = entry.getValue();\r\n\r\n\t\t\tuncompletedTask[value.getTaskType()]++;\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal())\r\n\t\t\t\tuncompletedTaskOnCloud[value.getTaskType()]++;\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal())\r\n\t\t\t\tuncompletedTaskOnMobile[value.getTaskType()]++;\r\n\t\t\telse\r\n\t\t\t\tuncompletedTaskOnEdge[value.getTaskType()]++;\r\n\t\t}\r\n\r\n\t\t// calculate total values\r\n\t\tuncompletedTask[numOfAppTypes] = IntStream.of(uncompletedTask).sum();\r\n\t\tuncompletedTaskOnCloud[numOfAppTypes] = IntStream.of(uncompletedTaskOnCloud).sum();\r\n\t\tuncompletedTaskOnEdge[numOfAppTypes] = IntStream.of(uncompletedTaskOnEdge).sum();\r\n\t\tuncompletedTaskOnMobile[numOfAppTypes] = IntStream.of(uncompletedTaskOnMobile).sum();\r\n\r\n\t\tcompletedTask[numOfAppTypes] = IntStream.of(completedTask).sum();\r\n\t\tcompletedTaskOnCloud[numOfAppTypes] = IntStream.of(completedTaskOnCloud).sum();\r\n\t\tcompletedTaskOnEdge[numOfAppTypes] = IntStream.of(completedTaskOnEdge).sum();\r\n\t\tcompletedTaskOnMobile[numOfAppTypes] = IntStream.of(completedTaskOnMobile).sum();\r\n\r\n\t\tfailedTask[numOfAppTypes] = IntStream.of(failedTask).sum();\r\n\t\tfailedTaskOnCloud[numOfAppTypes] = IntStream.of(failedTaskOnCloud).sum();\r\n\t\tfailedTaskOnEdge[numOfAppTypes] = IntStream.of(failedTaskOnEdge).sum();\r\n\t\tfailedTaskOnMobile[numOfAppTypes] = IntStream.of(failedTaskOnMobile).sum();\r\n\r\n\t\tnetworkDelay[numOfAppTypes] = DoubleStream.of(networkDelay).sum();\r\n\t\tlanDelay[numOfAppTypes] = DoubleStream.of(lanDelay).sum();\r\n\t\tmanDelay[numOfAppTypes] = DoubleStream.of(manDelay).sum();\r\n\t\twanDelay[numOfAppTypes] = DoubleStream.of(wanDelay).sum();\r\n\t\tgsmDelay[numOfAppTypes] = DoubleStream.of(gsmDelay).sum();\r\n\t\t\r\n\t\tlanUsage[numOfAppTypes] = DoubleStream.of(lanUsage).sum();\r\n\t\tmanUsage[numOfAppTypes] = DoubleStream.of(manUsage).sum();\r\n\t\twanUsage[numOfAppTypes] = DoubleStream.of(wanUsage).sum();\r\n\t\tgsmUsage[numOfAppTypes] = DoubleStream.of(gsmUsage).sum();\r\n\r\n\t\tserviceTime[numOfAppTypes] = DoubleStream.of(serviceTime).sum();\r\n\t\tserviceTimeOnCloud[numOfAppTypes] = DoubleStream.of(serviceTimeOnCloud).sum();\r\n\t\tserviceTimeOnEdge[numOfAppTypes] = DoubleStream.of(serviceTimeOnEdge).sum();\r\n\t\tserviceTimeOnMobile[numOfAppTypes] = DoubleStream.of(serviceTimeOnMobile).sum();\r\n\r\n\t\tprocessingTime[numOfAppTypes] = DoubleStream.of(processingTime).sum();\r\n\t\tprocessingTimeOnCloud[numOfAppTypes] = DoubleStream.of(processingTimeOnCloud).sum();\r\n\t\tprocessingTimeOnEdge[numOfAppTypes] = DoubleStream.of(processingTimeOnEdge).sum();\r\n\t\tprocessingTimeOnMobile[numOfAppTypes] = DoubleStream.of(processingTimeOnMobile).sum();\r\n\r\n\t\tfailedTaskDueToVmCapacity[numOfAppTypes] = IntStream.of(failedTaskDueToVmCapacity).sum();\r\n\t\tfailedTaskDueToVmCapacityOnCloud[numOfAppTypes] = IntStream.of(failedTaskDueToVmCapacityOnCloud).sum();\r\n\t\tfailedTaskDueToVmCapacityOnEdge[numOfAppTypes] = IntStream.of(failedTaskDueToVmCapacityOnEdge).sum();\r\n\t\tfailedTaskDueToVmCapacityOnMobile[numOfAppTypes] = IntStream.of(failedTaskDueToVmCapacityOnMobile).sum();\r\n\t\t\r\n\t\tcost[numOfAppTypes] = DoubleStream.of(cost).sum();\r\n\t\tQoE[numOfAppTypes] = DoubleStream.of(QoE).sum();\r\n\t\tfailedTaskDuetoBw[numOfAppTypes] = IntStream.of(failedTaskDuetoBw).sum();\r\n\t\tfailedTaskDuetoGsmBw[numOfAppTypes] = IntStream.of(failedTaskDuetoGsmBw).sum();\r\n\t\tfailedTaskDuetoWanBw[numOfAppTypes] = IntStream.of(failedTaskDuetoWanBw).sum();\r\n\t\tfailedTaskDuetoManBw[numOfAppTypes] = IntStream.of(failedTaskDuetoManBw).sum();\r\n\t\tfailedTaskDuetoLanBw[numOfAppTypes] = IntStream.of(failedTaskDuetoLanBw).sum();\r\n\t\tfailedTaskDuetoMobility[numOfAppTypes] = IntStream.of(failedTaskDuetoMobility).sum();\r\n\t\trefectedTaskDuetoWlanRange[numOfAppTypes] = IntStream.of(refectedTaskDuetoWlanRange).sum();\r\n\r\n\t\torchestratorOverhead[numOfAppTypes] = DoubleStream.of(orchestratorOverhead).sum();\r\n\t\t\r\n\t\t// calculate server load\r\n\t\tdouble totalVmLoadOnEdge = 0;\r\n\t\tdouble totalVmLoadOnCloud = 0;\r\n\t\tdouble totalVmLoadOnMobile = 0;\r\n\t\tfor (VmLoadLogItem entry : vmLoadList) {\r\n\t\t\ttotalVmLoadOnEdge += entry.getEdgeLoad();\r\n\t\t\ttotalVmLoadOnCloud += entry.getCloudLoad();\r\n\t\t\ttotalVmLoadOnMobile += entry.getMobileLoad();\r\n\t\t\tif (fileLogEnabled && SimSettings.getInstance().getVmLoadLogInterval() != 0)\r\n\t\t\t\tappendToFile(vmLoadBW, entry.toString());\r\n\t\t}\r\n\r\n\t\tif (fileLogEnabled) {\r\n\t\t\t// write location info to file for each location\r\n\t\t\t// assuming each location has only one access point\r\n\t\t\tdouble locationLogInterval = SimSettings.getInstance().getLocationLogInterval();\r\n\t\t\tif(locationLogInterval != 0) {\r\n\t\t\t\tfor (int t = 1; t < (SimSettings.getInstance().getSimulationTime() / locationLogInterval); t++) {\r\n\t\t\t\t\tint[] locationInfo = new int[SimSettings.getInstance().getNumOfEdgeDatacenters()];\r\n\t\t\t\t\tDouble time = t * SimSettings.getInstance().getLocationLogInterval();\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (time < SimSettings.CLIENT_ACTIVITY_START_TIME)\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfor (int i = 0; i < SimManager.getInstance().getNumOfMobileDevice(); i++) {\r\n\t\t\t\t\t\tLocation loc = SimManager.getInstance().getMobilityModel().getLocation(i, time);\r\n\t\t\t\t\t\tlocationInfo[loc.getServingWlanId()]++;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tlocationBW.write(time.toString());\r\n\t\t\t\t\tfor (int i = 0; i < locationInfo.length; i++)\r\n\t\t\t\t\t\tlocationBW.write(SimSettings.DELIMITER + locationInfo[i]);\r\n\r\n\t\t\t\t\tlocationBW.newLine();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// write delay info to file for each access point\r\n\t\t\tif(SimSettings.getInstance().getApDelayLogInterval() != 0) {\r\n\t\t\t\tfor (ApDelayLogItem entry : apDelayList) {\r\n\t\t\t\t\tappendToFile(apUploadDelayBW, entry.getUploadStat());\r\n\t\t\t\t\tappendToFile(apDownloadDelayBW, entry.getDownloadStat());\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tfor (int i = 0; i < numOfAppTypes + 1; i++) {\r\n\r\n\t\t\t\tif (i < numOfAppTypes) {\r\n\t\t\t\t\t// if related app is not used in this simulation, just discard it\r\n\t\t\t\t\tif (SimSettings.getInstance().getTaskLookUpTable()[i][0] == 0)\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// check if the divisor is zero in order to avoid division by\r\n\t\t\t\t// zero problem\r\n\t\t\t\tdouble _serviceTime = (completedTask[i] == 0) ? 0.0 : (serviceTime[i] / (double) completedTask[i]);\r\n\t\t\t\tdouble _networkDelay = (completedTask[i] == 0) ? 0.0 : (networkDelay[i] / ((double) completedTask[i] - (double)completedTaskOnMobile[i]));\r\n\t\t\t\tdouble _processingTime = (completedTask[i] == 0) ? 0.0 : (processingTime[i] / (double) completedTask[i]);\r\n\t\t\t\tdouble _vmLoadOnEdge = (vmLoadList.size() == 0) ? 0.0 : (totalVmLoadOnEdge / (double) vmLoadList.size());\r\n\t\t\t\tdouble _vmLoadOnClould = (vmLoadList.size() == 0) ? 0.0 : (totalVmLoadOnCloud / (double) vmLoadList.size());\r\n\t\t\t\tdouble _vmLoadOnMobile = (vmLoadList.size() == 0) ? 0.0 : (totalVmLoadOnMobile / (double) vmLoadList.size());\r\n\t\t\t\tdouble _cost = (completedTask[i] == 0) ? 0.0 : (cost[i] / (double) completedTask[i]);\r\n\t\t\t\tdouble _QoE1 = (completedTask[i] == 0) ? 0.0 : (QoE[i] / (double) completedTask[i]);\r\n\t\t\t\tdouble _QoE2 = (completedTask[i] == 0) ? 0.0 : (QoE[i] / (double) (failedTask[i] + completedTask[i]));\r\n\r\n\t\t\t\tdouble _lanDelay = (lanUsage[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (lanDelay[i] / (double) lanUsage[i]);\r\n\t\t\t\tdouble _manDelay = (manUsage[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (manDelay[i] / (double) manUsage[i]);\r\n\t\t\t\tdouble _wanDelay = (wanUsage[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (wanDelay[i] / (double) wanUsage[i]);\r\n\t\t\t\tdouble _gsmDelay = (gsmUsage[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (gsmDelay[i] / (double) gsmUsage[i]);\r\n\t\t\t\t\r\n\t\t\t\t// write generic results\r\n\t\t\t\tString genericResult1 = Integer.toString(completedTask[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTask[i]) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(uncompletedTask[i]) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoBw[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_serviceTime) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_processingTime) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_networkDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(0) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_cost) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDueToVmCapacity[i]) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoMobility[i]) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_QoE1) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_QoE2) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(refectedTaskDuetoWlanRange[i]);\r\n\r\n\t\t\t\t// check if the divisor is zero in order to avoid division by zero problem\r\n\t\t\t\tdouble _serviceTimeOnEdge = (completedTaskOnEdge[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (serviceTimeOnEdge[i] / (double) completedTaskOnEdge[i]);\r\n\t\t\t\tdouble _processingTimeOnEdge = (completedTaskOnEdge[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (processingTimeOnEdge[i] / (double) completedTaskOnEdge[i]);\r\n\t\t\t\tString genericResult2 = Integer.toString(completedTaskOnEdge[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskOnEdge[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(uncompletedTaskOnEdge[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_serviceTimeOnEdge) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_processingTimeOnEdge) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(0.0) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_vmLoadOnEdge) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDueToVmCapacityOnEdge[i]);\r\n\r\n\t\t\t\t// check if the divisor is zero in order to avoid division by zero problem\r\n\t\t\t\tdouble _serviceTimeOnCloud = (completedTaskOnCloud[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (serviceTimeOnCloud[i] / (double) completedTaskOnCloud[i]);\r\n\t\t\t\tdouble _processingTimeOnCloud = (completedTaskOnCloud[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (processingTimeOnCloud[i] / (double) completedTaskOnCloud[i]);\r\n\t\t\t\tString genericResult3 = Integer.toString(completedTaskOnCloud[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskOnCloud[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(uncompletedTaskOnCloud[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_serviceTimeOnCloud) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_processingTimeOnCloud) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(0.0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_vmLoadOnClould) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDueToVmCapacityOnCloud[i]);\r\n\t\t\t\t\r\n\t\t\t\t// check if the divisor is zero in order to avoid division by zero problem\r\n\t\t\t\tdouble _serviceTimeOnMobile = (completedTaskOnMobile[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (serviceTimeOnMobile[i] / (double) completedTaskOnMobile[i]);\r\n\t\t\t\tdouble _processingTimeOnMobile = (completedTaskOnMobile[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (processingTimeOnMobile[i] / (double) completedTaskOnMobile[i]);\r\n\t\t\t\tString genericResult4 = Integer.toString(completedTaskOnMobile[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskOnMobile[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(uncompletedTaskOnMobile[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_serviceTimeOnMobile) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_processingTimeOnMobile) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(0.0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_vmLoadOnMobile) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDueToVmCapacityOnMobile[i]);\r\n\t\t\t\t\r\n\t\t\t\tString genericResult5 = Double.toString(_lanDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_manDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_wanDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_gsmDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoLanBw[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoManBw[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoWanBw[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoGsmBw[i]);\r\n\t\t\t\t\r\n\t\t\t\t//performance related values\r\n\t\t\t\tdouble _orchestratorOverhead = orchestratorOverhead[i] / (double) (failedTask[i] + completedTask[i]);\r\n\t\t\t\t\r\n\t\t\t\tString genericResult6 = Long.toString((endTime-startTime)/60) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_orchestratorOverhead);\r\n\t\t\t\t\t\t\r\n\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult1);\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult2);\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult3);\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult4);\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult5);\r\n\t\t\t\t\r\n\t\t\t\t//append performance related values only to ALL_ALLPS file\r\n\t\t\t\tif(i == numOfAppTypes) {\r\n\t\t\t\t\tappendToFile(genericBWs[i], genericResult6);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tprintLine(SimSettings.getInstance().getTaskName(i));\r\n\t\t\t\t\tprintLine(\"# of tasks (Edge/Cloud): \"\r\n\t\t\t\t\t\t\t+ (failedTask[i] + completedTask[i]) + \"(\"\r\n\t\t\t\t\t\t\t+ (failedTaskOnEdge[i] + completedTaskOnEdge[i]) + \"/\" \r\n\t\t\t\t\t\t\t+ (failedTaskOnCloud[i]+ completedTaskOnCloud[i]) + \")\" );\r\n\t\t\t\t\t\r\n\t\t\t\t\tprintLine(\"# of failed tasks (Edge/Cloud): \"\r\n\t\t\t\t\t\t\t+ failedTask[i] + \"(\"\r\n\t\t\t\t\t\t\t+ failedTaskOnEdge[i] + \"/\"\r\n\t\t\t\t\t\t\t+ failedTaskOnCloud[i] + \")\");\r\n\t\t\t\t\t\r\n\t\t\t\t\tprintLine(\"# of completed tasks (Edge/Cloud): \"\r\n\t\t\t\t\t\t\t+ completedTask[i] + \"(\"\r\n\t\t\t\t\t\t\t+ completedTaskOnEdge[i] + \"/\"\r\n\t\t\t\t\t\t\t+ completedTaskOnCloud[i] + \")\");\r\n\t\t\t\t\t\r\n\t\t\t\t\tprintLine(\"---------------------------------------\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t// close open files\r\n\t\t\tif (SimSettings.getInstance().getDeepFileLoggingEnabled()) {\r\n\t\t\t\tsuccessBW.close();\r\n\t\t\t\tfailBW.close();\r\n\t\t\t}\r\n\t\t\tvmLoadBW.close();\r\n\t\t\tlocationBW.close();\r\n\t\t\tapUploadDelayBW.close();\r\n\t\t\tapDownloadDelayBW.close();\r\n\t\t\tfor (int i = 0; i < numOfAppTypes + 1; i++) {\r\n\t\t\t\tif (i < numOfAppTypes) {\r\n\t\t\t\t\t// if related app is not used in this simulation, just\r\n\t\t\t\t\t// discard it\r\n\t\t\t\t\tif (SimSettings.getInstance().getTaskLookUpTable()[i][0] == 0)\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tgenericBWs[i].close();\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\r\n\t\t// printout important results\r\n\t\tprintLine(\"# of tasks (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ (failedTask[numOfAppTypes] + completedTask[numOfAppTypes]) + \"(\"\r\n\t\t\t\t+ (failedTaskOnEdge[numOfAppTypes] + completedTaskOnEdge[numOfAppTypes]) + \"/\" \r\n\t\t\t\t+ (failedTaskOnCloud[numOfAppTypes]+ completedTaskOnCloud[numOfAppTypes]) + \"/\" \r\n\t\t\t\t+ (failedTaskOnMobile[numOfAppTypes]+ completedTaskOnMobile[numOfAppTypes]) + \")\");\r\n\t\t\r\n\t\tprintLine(\"# of failed tasks (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ failedTask[numOfAppTypes] + \"(\"\r\n\t\t\t\t+ failedTaskOnEdge[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ failedTaskOnCloud[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ failedTaskOnMobile[numOfAppTypes] + \")\");\r\n\t\t\r\n\t\tprintLine(\"# of completed tasks (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ completedTask[numOfAppTypes] + \"(\"\r\n\t\t\t\t+ completedTaskOnEdge[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ completedTaskOnCloud[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ completedTaskOnMobile[numOfAppTypes] + \")\");\r\n\t\t\r\n\t\tprintLine(\"# of uncompleted tasks (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ uncompletedTask[numOfAppTypes] + \"(\"\r\n\t\t\t\t+ uncompletedTaskOnEdge[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ uncompletedTaskOnCloud[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ uncompletedTaskOnMobile[numOfAppTypes] + \")\");\r\n\r\n\t\tprintLine(\"# of failed tasks due to vm capacity (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ failedTaskDueToVmCapacity[numOfAppTypes] + \"(\"\r\n\t\t\t\t+ failedTaskDueToVmCapacityOnEdge[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ failedTaskDueToVmCapacityOnCloud[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ failedTaskDueToVmCapacityOnMobile[numOfAppTypes] + \")\");\r\n\t\t\r\n\t\tprintLine(\"# of failed tasks due to Mobility/WLAN Range/Network(WLAN/MAN/WAN/GSM): \"\r\n\t\t\t\t+ failedTaskDuetoMobility[numOfAppTypes]\r\n\t\t\t\t+ \"/\" + refectedTaskDuetoWlanRange[numOfAppTypes]\r\n\t\t\t\t+ \"/\" + failedTaskDuetoBw[numOfAppTypes] \r\n\t\t\t\t+ \"(\" + failedTaskDuetoLanBw[numOfAppTypes] \r\n\t\t\t\t+ \"/\" + failedTaskDuetoManBw[numOfAppTypes] \r\n\t\t\t\t+ \"/\" + failedTaskDuetoWanBw[numOfAppTypes] \r\n\t\t\t\t+ \"/\" + failedTaskDuetoGsmBw[numOfAppTypes] + \")\");\r\n\t\t\r\n\t\tprintLine(\"percentage of failed tasks: \"\r\n\t\t\t\t+ String.format(\"%.6f\", ((double) failedTask[numOfAppTypes] * (double) 100)\r\n\t\t\t\t\t\t/ (double) (completedTask[numOfAppTypes] + failedTask[numOfAppTypes]))\r\n\t\t\t\t+ \"%\");\r\n\r\n\t\tprintLine(\"average service time: \"\r\n\t\t\t\t+ String.format(\"%.6f\", serviceTime[numOfAppTypes] / (double) completedTask[numOfAppTypes])\r\n\t\t\t\t+ \" seconds. (\" + \"on Edge: \"\r\n\t\t\t\t+ String.format(\"%.6f\", serviceTimeOnEdge[numOfAppTypes] / (double) completedTaskOnEdge[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"on Cloud: \"\r\n\t\t\t\t+ String.format(\"%.6f\", serviceTimeOnCloud[numOfAppTypes] / (double) completedTaskOnCloud[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"on Mobile: \"\r\n\t\t\t\t+ String.format(\"%.6f\", serviceTimeOnMobile[numOfAppTypes] / (double) completedTaskOnMobile[numOfAppTypes])\r\n\t\t\t\t+ \")\");\r\n\r\n\t\tprintLine(\"average processing time: \"\r\n\t\t\t\t+ String.format(\"%.6f\", processingTime[numOfAppTypes] / (double) completedTask[numOfAppTypes])\r\n\t\t\t\t+ \" seconds. (\" + \"on Edge: \"\r\n\t\t\t\t+ String.format(\"%.6f\", processingTimeOnEdge[numOfAppTypes] / (double) completedTaskOnEdge[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"on Cloud: \" \r\n\t\t\t\t+ String.format(\"%.6f\", processingTimeOnCloud[numOfAppTypes] / (double) completedTaskOnCloud[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"on Mobile: \" \r\n\t\t\t\t+ String.format(\"%.6f\", processingTimeOnMobile[numOfAppTypes] / (double) completedTaskOnMobile[numOfAppTypes])\r\n\t\t\t\t+ \")\");\r\n\r\n\t\tprintLine(\"average network delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", networkDelay[numOfAppTypes] / ((double) completedTask[numOfAppTypes] - (double) completedTaskOnMobile[numOfAppTypes]))\r\n\t\t\t\t+ \" seconds. (\" + \"LAN delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", lanDelay[numOfAppTypes] / (double) lanUsage[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"MAN delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", manDelay[numOfAppTypes] / (double) manUsage[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"WAN delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", wanDelay[numOfAppTypes] / (double) wanUsage[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"GSM delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", gsmDelay[numOfAppTypes] / (double) gsmUsage[numOfAppTypes]) + \")\");\r\n\r\n\t\tprintLine(\"average server utilization Edge/Cloud/Mobile: \" \r\n\t\t\t\t+ String.format(\"%.6f\", totalVmLoadOnEdge / (double) vmLoadList.size()) + \"/\"\r\n\t\t\t\t+ String.format(\"%.6f\", totalVmLoadOnCloud / (double) vmLoadList.size()) + \"/\"\r\n\t\t\t\t+ String.format(\"%.6f\", totalVmLoadOnMobile / (double) vmLoadList.size()));\r\n\r\n\t\tprintLine(\"average cost: \" + cost[numOfAppTypes] / completedTask[numOfAppTypes] + \"$\");\r\n\t\tprintLine(\"average overhead: \" + orchestratorOverhead[numOfAppTypes] / (failedTask[numOfAppTypes] + completedTask[numOfAppTypes]) + \" ns\");\r\n\t\tprintLine(\"average QoE (for all): \" + QoE[numOfAppTypes] / (failedTask[numOfAppTypes] + completedTask[numOfAppTypes]) + \"%\");\r\n\t\tprintLine(\"average QoE (for executed): \" + QoE[numOfAppTypes] / completedTask[numOfAppTypes] + \"%\");\r\n\r\n\t\t// clear related collections (map list etc.)\r\n\t\ttaskMap.clear();\r\n\t\tvmLoadList.clear();\r\n\t\tapDelayList.clear();\r\n\t}\r\n\t\r\n\tprivate void recordLog(int taskId){\r\n\t\tLogItem value = taskMap.remove(taskId);\r\n\t\t\r\n\t\tif (value.isInWarmUpPeriod())\r\n\t\t\treturn;\r\n\r\n\t\tif (value.getStatus() == SimLogger.TASK_STATUS.COMLETED) {\r\n\t\t\tcompletedTask[value.getTaskType()]++;\r\n\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal())\r\n\t\t\t\tcompletedTaskOnCloud[value.getTaskType()]++;\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal())\r\n\t\t\t\tcompletedTaskOnMobile[value.getTaskType()]++;\r\n\t\t\telse\r\n\t\t\t\tcompletedTaskOnEdge[value.getTaskType()]++;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tfailedTask[value.getTaskType()]++;\r\n\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal())\r\n\t\t\t\tfailedTaskOnCloud[value.getTaskType()]++;\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal())\r\n\t\t\t\tfailedTaskOnMobile[value.getTaskType()]++;\r\n\t\t\telse\r\n\t\t\t\tfailedTaskOnEdge[value.getTaskType()]++;\r\n\t\t}\r\n\r\n\t\tif (value.getStatus() == SimLogger.TASK_STATUS.COMLETED) {\r\n\t\t\tcost[value.getTaskType()] += value.getCost();\r\n\t\t\tQoE[value.getTaskType()] += value.getQoE();\r\n\t\t\tserviceTime[value.getTaskType()] += value.getServiceTime();\r\n\t\t\tnetworkDelay[value.getTaskType()] += value.getNetworkDelay();\r\n\t\t\tprocessingTime[value.getTaskType()] += (value.getServiceTime() - value.getNetworkDelay());\r\n\t\t\torchestratorOverhead[value.getTaskType()] += value.getOrchestratorOverhead();\r\n\t\t\t\r\n\t\t\tif(value.getNetworkDelay(NETWORK_DELAY_TYPES.WLAN_DELAY) != 0) {\r\n\t\t\t\tlanUsage[value.getTaskType()]++;\r\n\t\t\t\tlanDelay[value.getTaskType()] += value.getNetworkDelay(NETWORK_DELAY_TYPES.WLAN_DELAY);\r\n\t\t\t}\r\n\t\t\tif(value.getNetworkDelay(NETWORK_DELAY_TYPES.MAN_DELAY) != 0) {\r\n\t\t\t\tmanUsage[value.getTaskType()]++;\r\n\t\t\t\tmanDelay[value.getTaskType()] += value.getNetworkDelay(NETWORK_DELAY_TYPES.MAN_DELAY);\r\n\t\t\t}\r\n\t\t\tif(value.getNetworkDelay(NETWORK_DELAY_TYPES.WAN_DELAY) != 0) {\r\n\t\t\t\twanUsage[value.getTaskType()]++;\r\n\t\t\t\twanDelay[value.getTaskType()] += value.getNetworkDelay(NETWORK_DELAY_TYPES.WAN_DELAY);\r\n\t\t\t}\r\n\t\t\tif(value.getNetworkDelay(NETWORK_DELAY_TYPES.GSM_DELAY) != 0) {\r\n\t\t\t\tgsmUsage[value.getTaskType()]++;\r\n\t\t\t\tgsmDelay[value.getTaskType()] += value.getNetworkDelay(NETWORK_DELAY_TYPES.GSM_DELAY);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal()) {\r\n\t\t\t\tserviceTimeOnCloud[value.getTaskType()] += value.getServiceTime();\r\n\t\t\t\tprocessingTimeOnCloud[value.getTaskType()] += (value.getServiceTime() - value.getNetworkDelay());\r\n\t\t\t}\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal()) {\r\n\t\t\t\tserviceTimeOnMobile[value.getTaskType()] += value.getServiceTime();\r\n\t\t\t\tprocessingTimeOnMobile[value.getTaskType()] += value.getServiceTime();\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tserviceTimeOnEdge[value.getTaskType()] += value.getServiceTime();\r\n\t\t\t\tprocessingTimeOnEdge[value.getTaskType()] += (value.getServiceTime() - value.getNetworkDelay());\r\n\t\t\t}\r\n\t\t} else if (value.getStatus() == SimLogger.TASK_STATUS.REJECTED_DUE_TO_VM_CAPACITY) {\r\n\t\t\tfailedTaskDueToVmCapacity[value.getTaskType()]++;\r\n\t\t\t\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal())\r\n\t\t\t\tfailedTaskDueToVmCapacityOnCloud[value.getTaskType()]++;\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal())\r\n\t\t\t\tfailedTaskDueToVmCapacityOnMobile[value.getTaskType()]++;\r\n\t\t\telse\r\n\t\t\t\tfailedTaskDueToVmCapacityOnEdge[value.getTaskType()]++;\r\n\t\t} else if (value.getStatus() == SimLogger.TASK_STATUS.REJECTED_DUE_TO_BANDWIDTH\r\n\t\t\t\t|| value.getStatus() == SimLogger.TASK_STATUS.UNFINISHED_DUE_TO_BANDWIDTH) {\r\n\t\t\tfailedTaskDuetoBw[value.getTaskType()]++;\r\n\t\t\tif (value.getNetworkError() == NETWORK_ERRORS.LAN_ERROR)\r\n\t\t\t\tfailedTaskDuetoLanBw[value.getTaskType()]++;\r\n\t\t\telse if (value.getNetworkError() == NETWORK_ERRORS.MAN_ERROR)\r\n\t\t\t\tfailedTaskDuetoManBw[value.getTaskType()]++;\r\n\t\t\telse if (value.getNetworkError() == NETWORK_ERRORS.WAN_ERROR)\r\n\t\t\t\tfailedTaskDuetoWanBw[value.getTaskType()]++;\r\n\t\t\telse if (value.getNetworkError() == NETWORK_ERRORS.GSM_ERROR)\r\n\t\t\t\tfailedTaskDuetoGsmBw[value.getTaskType()]++;\r\n\t\t} else if (value.getStatus() == SimLogger.TASK_STATUS.UNFINISHED_DUE_TO_MOBILITY) {\r\n\t\t\tfailedTaskDuetoMobility[value.getTaskType()]++;\r\n\t\t} else if (value.getStatus() == SimLogger.TASK_STATUS.REJECTED_DUE_TO_WLAN_COVERAGE) {\r\n\t\t\trefectedTaskDuetoWlanRange[value.getTaskType()]++;;\r\n }\r\n\t\t\r\n\t\t//if deep file logging is enabled, record every task result\r\n\t\tif (SimSettings.getInstance().getDeepFileLoggingEnabled()){\r\n\t\t\ttry {\r\n\t\t\t\tif (value.getStatus() == SimLogger.TASK_STATUS.COMLETED)\r\n\t\t\t\t\tappendToFile(successBW, value.toString(taskId));\r\n\t\t\t\telse\r\n\t\t\t\t\tappendToFile(failBW, value.toString(taskId));\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t\tSystem.exit(1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r"
] | import org.cloudbus.cloudsim.core.CloudSim;
import edu.boun.edgecloudsim.core.SimManager;
import edu.boun.edgecloudsim.core.SimSettings;
import edu.boun.edgecloudsim.edge_client.Task;
import edu.boun.edgecloudsim.network.NetworkModel;
import edu.boun.edgecloudsim.utils.Location;
import edu.boun.edgecloudsim.utils.SimLogger;
| /*
* Title: EdgeCloudSim - Network Model
*
* Description:
* SampleNetworkModel uses
* -> the result of an empirical study for the WLAN and WAN delays
* The experimental network model is developed
* by taking measurements from the real life deployments.
*
* -> MMPP/MMPP/1 queue model for MAN delay
* MAN delay is observed via a single server queue model with
* Markov-modulated Poisson process (MMPP) arrivals.
*
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
* Copyright (c) 2017, Bogazici University, Istanbul, Turkey
*/
package edu.boun.edgecloudsim.applications.sample_app2;
public class SampleNetworkModel extends NetworkModel {
public static enum NETWORK_TYPE {WLAN, LAN};
public static enum LINK_TYPE {DOWNLOAD, UPLOAD};
public static double MAN_BW = 1300*1024; //Kbps
@SuppressWarnings("unused")
private int manClients;
private int[] wanClients;
private int[] wlanClients;
private double lastMM1QueueUpdateTime;
private double ManPoissonMeanForDownload; //seconds
private double ManPoissonMeanForUpload; //seconds
private double avgManTaskInputSize; //bytes
private double avgManTaskOutputSize; //bytes
//record last n task statistics during MM1_QUEUE_MODEL_UPDATE_INTEVAL seconds to simulate mmpp/m/1 queue model
private double totalManTaskInputSize;
private double totalManTaskOutputSize;
private double numOfManTaskForDownload;
private double numOfManTaskForUpload;
public static final double[] experimentalWlanDelay = {
/*1 Client*/ 88040.279 /*(Kbps)*/,
/*2 Clients*/ 45150.982 /*(Kbps)*/,
/*3 Clients*/ 30303.641 /*(Kbps)*/,
/*4 Clients*/ 27617.211 /*(Kbps)*/,
/*5 Clients*/ 24868.616 /*(Kbps)*/,
/*6 Clients*/ 22242.296 /*(Kbps)*/,
/*7 Clients*/ 20524.064 /*(Kbps)*/,
/*8 Clients*/ 18744.889 /*(Kbps)*/,
/*9 Clients*/ 17058.827 /*(Kbps)*/,
/*10 Clients*/ 15690.455 /*(Kbps)*/,
/*11 Clients*/ 14127.744 /*(Kbps)*/,
/*12 Clients*/ 13522.408 /*(Kbps)*/,
/*13 Clients*/ 13177.631 /*(Kbps)*/,
/*14 Clients*/ 12811.330 /*(Kbps)*/,
/*15 Clients*/ 12584.387 /*(Kbps)*/,
/*15 Clients*/ 12135.161 /*(Kbps)*/,
/*16 Clients*/ 11705.638 /*(Kbps)*/,
/*17 Clients*/ 11276.116 /*(Kbps)*/,
/*18 Clients*/ 10846.594 /*(Kbps)*/,
/*19 Clients*/ 10417.071 /*(Kbps)*/,
/*20 Clients*/ 9987.549 /*(Kbps)*/,
/*21 Clients*/ 9367.587 /*(Kbps)*/,
/*22 Clients*/ 8747.625 /*(Kbps)*/,
/*23 Clients*/ 8127.663 /*(Kbps)*/,
/*24 Clients*/ 7907.701 /*(Kbps)*/,
/*25 Clients*/ 7887.739 /*(Kbps)*/,
/*26 Clients*/ 7690.831 /*(Kbps)*/,
/*27 Clients*/ 7393.922 /*(Kbps)*/,
/*28 Clients*/ 7297.014 /*(Kbps)*/,
/*29 Clients*/ 7100.106 /*(Kbps)*/,
/*30 Clients*/ 6903.197 /*(Kbps)*/,
/*31 Clients*/ 6701.986 /*(Kbps)*/,
/*32 Clients*/ 6500.776 /*(Kbps)*/,
/*33 Clients*/ 6399.565 /*(Kbps)*/,
/*34 Clients*/ 6098.354 /*(Kbps)*/,
/*35 Clients*/ 5897.143 /*(Kbps)*/,
/*36 Clients*/ 5552.127 /*(Kbps)*/,
/*37 Clients*/ 5207.111 /*(Kbps)*/,
/*38 Clients*/ 4862.096 /*(Kbps)*/,
/*39 Clients*/ 4517.080 /*(Kbps)*/,
/*40 Clients*/ 4172.064 /*(Kbps)*/,
/*41 Clients*/ 4092.922 /*(Kbps)*/,
/*42 Clients*/ 4013.781 /*(Kbps)*/,
/*43 Clients*/ 3934.639 /*(Kbps)*/,
/*44 Clients*/ 3855.498 /*(Kbps)*/,
/*45 Clients*/ 3776.356 /*(Kbps)*/,
/*46 Clients*/ 3697.215 /*(Kbps)*/,
/*47 Clients*/ 3618.073 /*(Kbps)*/,
/*48 Clients*/ 3538.932 /*(Kbps)*/,
/*49 Clients*/ 3459.790 /*(Kbps)*/,
/*50 Clients*/ 3380.649 /*(Kbps)*/,
/*51 Clients*/ 3274.611 /*(Kbps)*/,
/*52 Clients*/ 3168.573 /*(Kbps)*/,
/*53 Clients*/ 3062.536 /*(Kbps)*/,
/*54 Clients*/ 2956.498 /*(Kbps)*/,
/*55 Clients*/ 2850.461 /*(Kbps)*/,
/*56 Clients*/ 2744.423 /*(Kbps)*/,
/*57 Clients*/ 2638.386 /*(Kbps)*/,
/*58 Clients*/ 2532.348 /*(Kbps)*/,
/*59 Clients*/ 2426.310 /*(Kbps)*/,
/*60 Clients*/ 2320.273 /*(Kbps)*/,
/*61 Clients*/ 2283.828 /*(Kbps)*/,
/*62 Clients*/ 2247.383 /*(Kbps)*/,
/*63 Clients*/ 2210.939 /*(Kbps)*/,
/*64 Clients*/ 2174.494 /*(Kbps)*/,
/*65 Clients*/ 2138.049 /*(Kbps)*/,
/*66 Clients*/ 2101.604 /*(Kbps)*/,
/*67 Clients*/ 2065.160 /*(Kbps)*/,
/*68 Clients*/ 2028.715 /*(Kbps)*/,
/*69 Clients*/ 1992.270 /*(Kbps)*/,
/*70 Clients*/ 1955.825 /*(Kbps)*/,
/*71 Clients*/ 1946.788 /*(Kbps)*/,
/*72 Clients*/ 1937.751 /*(Kbps)*/,
/*73 Clients*/ 1928.714 /*(Kbps)*/,
/*74 Clients*/ 1919.677 /*(Kbps)*/,
/*75 Clients*/ 1910.640 /*(Kbps)*/,
/*76 Clients*/ 1901.603 /*(Kbps)*/,
/*77 Clients*/ 1892.566 /*(Kbps)*/,
/*78 Clients*/ 1883.529 /*(Kbps)*/,
/*79 Clients*/ 1874.492 /*(Kbps)*/,
/*80 Clients*/ 1865.455 /*(Kbps)*/,
/*81 Clients*/ 1833.185 /*(Kbps)*/,
/*82 Clients*/ 1800.915 /*(Kbps)*/,
/*83 Clients*/ 1768.645 /*(Kbps)*/,
/*84 Clients*/ 1736.375 /*(Kbps)*/,
/*85 Clients*/ 1704.106 /*(Kbps)*/,
/*86 Clients*/ 1671.836 /*(Kbps)*/,
/*87 Clients*/ 1639.566 /*(Kbps)*/,
/*88 Clients*/ 1607.296 /*(Kbps)*/,
/*89 Clients*/ 1575.026 /*(Kbps)*/,
/*90 Clients*/ 1542.756 /*(Kbps)*/,
/*91 Clients*/ 1538.544 /*(Kbps)*/,
/*92 Clients*/ 1534.331 /*(Kbps)*/,
/*93 Clients*/ 1530.119 /*(Kbps)*/,
/*94 Clients*/ 1525.906 /*(Kbps)*/,
/*95 Clients*/ 1521.694 /*(Kbps)*/,
/*96 Clients*/ 1517.481 /*(Kbps)*/,
/*97 Clients*/ 1513.269 /*(Kbps)*/,
/*98 Clients*/ 1509.056 /*(Kbps)*/,
/*99 Clients*/ 1504.844 /*(Kbps)*/,
/*100 Clients*/ 1500.631 /*(Kbps)*/
};
public static final double[] experimentalWanDelay = {
/*1 Client*/ 20703.973 /*(Kbps)*/,
/*2 Clients*/ 12023.957 /*(Kbps)*/,
/*3 Clients*/ 9887.785 /*(Kbps)*/,
/*4 Clients*/ 8915.775 /*(Kbps)*/,
/*5 Clients*/ 8259.277 /*(Kbps)*/,
/*6 Clients*/ 7560.574 /*(Kbps)*/,
/*7 Clients*/ 7262.140 /*(Kbps)*/,
/*8 Clients*/ 7155.361 /*(Kbps)*/,
/*9 Clients*/ 7041.153 /*(Kbps)*/,
/*10 Clients*/ 6994.595 /*(Kbps)*/,
/*11 Clients*/ 6653.232 /*(Kbps)*/,
/*12 Clients*/ 6111.868 /*(Kbps)*/,
/*13 Clients*/ 5570.505 /*(Kbps)*/,
/*14 Clients*/ 5029.142 /*(Kbps)*/,
/*15 Clients*/ 4487.779 /*(Kbps)*/,
/*16 Clients*/ 3899.729 /*(Kbps)*/,
/*17 Clients*/ 3311.680 /*(Kbps)*/,
/*18 Clients*/ 2723.631 /*(Kbps)*/,
/*19 Clients*/ 2135.582 /*(Kbps)*/,
/*20 Clients*/ 1547.533 /*(Kbps)*/,
/*21 Clients*/ 1500.252 /*(Kbps)*/,
/*22 Clients*/ 1452.972 /*(Kbps)*/,
/*23 Clients*/ 1405.692 /*(Kbps)*/,
/*24 Clients*/ 1358.411 /*(Kbps)*/,
/*25 Clients*/ 1311.131 /*(Kbps)*/
};
public SampleNetworkModel(int _numberOfMobileDevices, String _simScenario) {
super(_numberOfMobileDevices, _simScenario);
}
@Override
public void initialize() {
wanClients = new int[SimSettings.getInstance().getNumOfEdgeDatacenters()]; //we have one access point for each datacenter
wlanClients = new int[SimSettings.getInstance().getNumOfEdgeDatacenters()]; //we have one access point for each datacenter
int numOfApp = SimSettings.getInstance().getTaskLookUpTable().length;
SimSettings SS = SimSettings.getInstance();
for(int taskIndex=0; taskIndex<numOfApp; taskIndex++) {
if(SS.getTaskLookUpTable()[taskIndex][0] == 0) {
SimLogger.printLine("Usage percentage of task " + taskIndex + " is 0! Terminating simulation...");
System.exit(0);
}
else{
double weight = SS.getTaskLookUpTable()[taskIndex][0]/(double)100;
//assume half of the tasks use the MAN at the beginning
ManPoissonMeanForDownload += ((SS.getTaskLookUpTable()[taskIndex][2])*weight) * 4;
ManPoissonMeanForUpload = ManPoissonMeanForDownload;
avgManTaskInputSize += SS.getTaskLookUpTable()[taskIndex][5]*weight;
avgManTaskOutputSize += SS.getTaskLookUpTable()[taskIndex][6]*weight;
}
}
ManPoissonMeanForDownload = ManPoissonMeanForDownload/numOfApp;
ManPoissonMeanForUpload = ManPoissonMeanForUpload/numOfApp;
avgManTaskInputSize = avgManTaskInputSize/numOfApp;
avgManTaskOutputSize = avgManTaskOutputSize/numOfApp;
lastMM1QueueUpdateTime = SimSettings.CLIENT_ACTIVITY_START_TIME;
totalManTaskOutputSize = 0;
numOfManTaskForDownload = 0;
totalManTaskInputSize = 0;
numOfManTaskForUpload = 0;
}
/**
* source device is always mobile device in our simulation scenarios!
*/
@Override
public double getUploadDelay(int sourceDeviceId, int destDeviceId, Task task) {
double delay = 0;
//special case for man communication
if(sourceDeviceId == destDeviceId && sourceDeviceId == SimSettings.GENERIC_EDGE_DEVICE_ID){
return delay = getManUploadDelay();
}
| Location accessPointLocation = SimManager.getInstance().getMobilityModel().getLocation(sourceDeviceId,CloudSim.clock());
| 4 |
aurbroszniowski/Rainfall-core | src/main/java/io/rainfall/execution/Executions.java | ["public abstract class Execution {\n\n public enum ExecutionState {\n UNKNOWN,\n BEGINNING,\(...TRUNCATED) | "import io.rainfall.Execution;\nimport io.rainfall.Unit;\nimport io.rainfall.unit.Every;\nimport io.(...TRUNCATED) | "/*\n * Copyright (c) 2014-2022 Aurélien Broszniowski\n *\n * Licensed under the Apache License, Ve(...TRUNCATED) | public static InParallel inParallel(int count, Unit unit, Every every, Over over) { | 4 |
jenkinsci/ghprb-plugin | "src/test/java/org/jenkinsci/plugins/ghprb/manager/impl/downstreambuilds/BuildFlowBuildManagerTest.j(...TRUNCATED) | ["public abstract class GhprbITBaseTestCase {\n\n @Mock\n protected GHCommitPointer commitPoin(...TRUNCATED) | "import com.cloudbees.plugins.flow.BuildFlow;\nimport com.cloudbees.plugins.flow.FlowRun;\nimport co(...TRUNCATED) | "package org.jenkinsci.plugins.ghprb.manager.impl.downstreambuilds;\n\n\n\n\n/**\n * @author mdelape(...TRUNCATED) | public JenkinsRuleWithBuildFlow jenkinsRule = new JenkinsRuleWithBuildFlow(); | 4 |
criticalmaps/criticalmaps-android | app/src/main/java/de/stephanlindauer/criticalmaps/service/ServerSyncService.java | ["public class App extends Application {\n\n private static AppComponent appComponent;\n\n pub(...TRUNCATED) | "import android.app.Service;\nimport android.content.Intent;\nimport android.os.IBinder;\nimport and(...TRUNCATED) | "package de.stephanlindauer.criticalmaps.service;\n\n\n\n\n\n\n\npublic class ServerSyncService exte(...TRUNCATED) | EventBus eventBus; | 4 |
w3c/epubcheck | src/main/java/com/adobe/epubcheck/bitmap/BitmapChecker.java | ["public final class EPUBLocation implements Comparable<EPUBLocation>\n{\n\n public static EPUBLoca(...TRUNCATED) | "import javax.imageio.stream.FileImageInputStream;\nimport javax.imageio.stream.ImageInputStream;\ni(...TRUNCATED) | "/*\n * Copyright (c) 2007 Adobe Systems Incorporated\n *\n * Permission is hereby granted, free of(...TRUNCATED) | private final Report report; | 1 |
sorinMD/MCTS | src/main/java/mcts/tree/selection/PUCT.java | ["public interface Game {\n\n\t/**\n\t * @return a clone of the game state\n\t */\n\tpublic int[] ge(...TRUNCATED) | "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.concurrent.ThreadLocal(...TRUNCATED) | "package mcts.tree.selection;\n\n\n\n\n/**\n * PUCT selection policy for handling a prior probabilit(...TRUNCATED) | " protected Selection selectChild(StandardNode node, Tree tree, GameFactory factory, Game obsGame(...TRUNCATED) | 6 |
Dataset Card for RepoBench-R
Dataset Summary
RepoBench-R (Retrieval) is a subtask of RepoBench(GitHub, arXiv), targeting the retrieval component of a repository-level auto-completion system, focusing on retrieving the most relevant code snippet from a project repository for next-line code prediction.
Settings
cff
: short for cross_file_first, indicating the cross-file module in next line is first used in the current file.cfr
: short for cross_file_random, indicating the cross-file module in next line is not first used in the current file.
Supported Tasks
The dataset has 4 subsets:
python_cff
: python dataset withcff
setting.python_cfr
: python dataset withcfr
setting.java_cff
: java dataset withcff
setting.java_cfr
: java dataset withcfr
setting.
Each subset has 4 splits:
train_easy
: training set with easy difficulty, where the number of code snippets in the context satisfies .train_hard
: training set with hard difficulty, where the number of code snippets in the context satisfies .test_easy
: testing set with easy difficulty.test_hard
: testing set with hard difficulty.
Loading Data
For example, if you want to load the test
cross_file_first
python
dataset with easy
difficulty, you can use the following code:
from datasets import load_dataset
dataset = load_dataset("tianyang/repobench-r", "python_cff", split="test_easy")
Note: The
split
argument is optional. If not provided, the entire dataset (including, train and test data with easy and hard level) will be loaded.
Dataset Structure
{
"repo_name": "repository name of the data point",
"file_path": "path/to/file",
"context": [
"snippet 1",
"snippet 2",
// ...
"snippet k"
],
"import_statement": "all import statements in the file",
"gold_snippet_idex": 2, // the index of the gold snippet in the context list, 0~k-1
"code": "the code for next-line prediction",
"next_line": "the next line of the code"
}
Licensing Information
CC BY-NC-ND 4.0
Citation Information
@misc{liu2023repobench,
title={RepoBench: Benchmarking Repository-Level Code Auto-Completion Systems},
author={Tianyang Liu and Canwen Xu and Julian McAuley},
year={2023},
eprint={2306.03091},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
Contributions
Thanks to @Leolty for adding this dataset.
- Downloads last month
- 204