index
int64
130
4.67k
file_id
stringlengths
6
9
content
stringlengths
407
11.9k
repo
stringlengths
11
72
path
stringlengths
11
133
token_length
int64
146
3.59k
original_comment
stringlengths
17
507
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
362
11.8k
Inclusion
stringclasses
1 value
Exclusion
stringclasses
1 value
__index_level_0__
int64
1.95k
2.15k
file-tokens-Qwen/CodeQwen1.5-7B
int64
146
3.59k
comment-tokens-Qwen/CodeQwen1.5-7B
int64
6
144
comment_tail_length_Qwen/CodeQwen1.5-7B
int64
4
101
file-tokens-bigcode/starcoder2-7b
int64
141
3.69k
comment-tokens-bigcode/starcoder2-7b
int64
7
145
comment_tail_length_bigcode/starcoder2-7b
int64
5
104
file-tokens-google/codegemma-7b
int64
130
3.6k
comment-tokens-google/codegemma-7b
int64
5
125
comment_tail_length_google/codegemma-7b
int64
3
82
file-tokens-ibm-granite/granite-8b-code-base
int64
141
3.69k
comment-tokens-ibm-granite/granite-8b-code-base
int64
7
145
comment_tail_length_ibm-granite/granite-8b-code-base
int64
5
104
file-tokens-meta-llama/CodeLlama-7b-hf
int64
146
3.96k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
7
161
comment_tail_length_meta-llama/CodeLlama-7b-hf
int64
5
106
excluded-based-on-tokenizer-Qwen/CodeQwen1.5-7B
bool
2 classes
excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool
2 classes
excluded-based-on-tokenizer-google/codegemma-7b
bool
2 classes
excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool
2 classes
excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool
2 classes
include-for-inference
bool
2 classes
882
111092_3
package nl.hva.ict.data.MongoDB; import com.mongodb.MongoException; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import nl.hva.ict.MainApplication; import nl.hva.ict.data.Data; import org.bson.Document; /** * MongoDB class die de verbinding maakt met de Mongo server * @author Pieter Leek */ public abstract class MongoDB implements Data { protected MongoCollection<Document> collection; private MongoClient mongoClient; private MongoDatabase mongoDatabase; /** * Verbind direct met de server als dit object wordt aangemaakt */ public MongoDB() { connect(); } // connect database private void connect() { // Heb je geen gegevens in de MainApplication staan slaat hij het maken van de verbinding over if (MainApplication.getNosqlHost().equals("")) return; // Verbind alleen als er nog geen actieve verbinding is. if (this.mongoClient == null) { try { // Open pijpleiding this.mongoClient = MongoClients.create(MainApplication.getNosqlHost()); // Selecteer de juiste database this.mongoDatabase = mongoClient.getDatabase(MainApplication.getNosqlDatabase()); } catch (MongoException e) { e.printStackTrace(); } } } /** * Selecteer de juiste collection * @param collection */ public void selectedCollection(String collection) { this.collection = mongoDatabase.getCollection(collection); } }
JuniorBrPr/DB2V2
src/nl/hva/ict/data/MongoDB/MongoDB.java
477
// Verbind alleen als er nog geen actieve verbinding is.
line_comment
nl
package nl.hva.ict.data.MongoDB; import com.mongodb.MongoException; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import nl.hva.ict.MainApplication; import nl.hva.ict.data.Data; import org.bson.Document; /** * MongoDB class die de verbinding maakt met de Mongo server * @author Pieter Leek */ public abstract class MongoDB implements Data { protected MongoCollection<Document> collection; private MongoClient mongoClient; private MongoDatabase mongoDatabase; /** * Verbind direct met de server als dit object wordt aangemaakt */ public MongoDB() { connect(); } // connect database private void connect() { // Heb je geen gegevens in de MainApplication staan slaat hij het maken van de verbinding over if (MainApplication.getNosqlHost().equals("")) return; // Verbind alleen<SUF> if (this.mongoClient == null) { try { // Open pijpleiding this.mongoClient = MongoClients.create(MainApplication.getNosqlHost()); // Selecteer de juiste database this.mongoDatabase = mongoClient.getDatabase(MainApplication.getNosqlDatabase()); } catch (MongoException e) { e.printStackTrace(); } } } /** * Selecteer de juiste collection * @param collection */ public void selectedCollection(String collection) { this.collection = mongoDatabase.getCollection(collection); } }
True
False
1,952
477
14
12
392
17
15
401
13
11
392
17
15
455
15
13
false
false
false
false
false
true
1,899
88062_9
package bin.model; import java.util.List; import bin.logic.Field; import bin.logic.Location; /** * A simple model of a grass. * Grasss age, move, breed, and die. * * @author Ieme, Jermo, Yisong * @version 2012.01.29 */ public class Grass extends Plant { // Characteristics shared by all grass (class variables). // The age at which a grass can start to breed. private static int breeding_age = 3; // The age to which a grass can live. private static int max_age = 12; // The likelihood of a grass breeding. private static double breeding_probability = 0.09; // The maximum number of births. private static int max_litter_size = 6; /** * Create a new grass. A grass may be created with age * zero (a new born) or with a random age. * * @param randomAge If true, the grass will have a random age. * @param field The field currently occupied. * @param location The location within the field. */ public Grass(boolean randomAge, Field field, Location location) { super(field, location); setAge(0); if(randomAge) { setAge(getRandom().nextInt(max_age)); } } /** * This is what the grass does most of the time - it runs * around. Sometimes it will breed or die of old age. * @param newGrasss A list to return newly born grasss. */ public void act(List<Actor> newGrass) { incrementAge(); if(isAlive()) { giveBirth(newGrass); // Try to move into a free location. Location newLocation = getField().freeAdjacentLocation(getLocation()); if(newLocation != null) { setLocation(newLocation); } else { // Overcrowding. setDead(); } } } /** * Zorgt er voor dat er geen nakomeling worden geboren als er te weinig voesel zijn. * @return true als genoeg voedsel zijn * @return false als niet genoeg voedsel zijn */ public boolean survivalInstinct() { // MainProgram.getSimulator().getSimulatorView().getStats().getPopulation(); return true; } /** * check if grass is surround by grassvirus. * @return true if it is */ /** * Check whether or not this grass is to give birth at this step. * New births will be made into free adjacent locations. * @param newGrasss A list to return newly born grasss. */ private void giveBirth(List<Actor> newGrass) { // New grasss are born into adjacent locations. // Get a list of adjacent free locations. Field field = getField(); List<Location> free = field.getFreeAdjacentLocations(getLocation()); int births = breed(); for(int b = 0; b < births && free.size() > 0; b++) { Location loc = free.remove(0); Grass young = new Grass(false, field, loc); newGrass.add(young); } } /** * A grass can breed if it has reached the breeding age. * @return true if the grass can breed, false otherwise. */ protected boolean canBreed() { return getAge() >= getBreedingAge(); } /** * setter voor breeding_age * @param breeding_age */ public static void setBreedingAge(int breeding_age) { if (breeding_age >= 0) Grass.breeding_age = breeding_age; } /** * setter voor max_age * @param max_age */ public static void setMaxAge(int max_age) { if (max_age >= 1) Grass.max_age = max_age; } /** * setter voor breeding_probability * @param breeding_probability */ public static void setBreedingProbability(double breeding_probability) { if (breeding_probability >= 0) Grass.breeding_probability = breeding_probability; } /** * setter voor max_litter_size * @param max_litter_size */ public static void setMaxLitterSize(int max_litter_size) { if (max_litter_size >= 1) Grass.max_litter_size = max_litter_size; } /** * default settings */ public static void setDefault() { breeding_age = 1; max_age = 100; breeding_probability = 0.02; max_litter_size = 100; } /** * Getter om breeding_age op te halen */ protected int getBreedingAge() { return breeding_age; } /** * returns the maximum age of a grass can live * @return int maximum age of a grass can live */ protected int getMaxAge() { return max_age; } /** * Getter om max_litter_size op te halen * @return max_litter_size maximum litter */ protected int getMaxLitterSize() { return max_litter_size; } /** * Getter om breeding_probability op te halen * @return breeding_probability breeding kansen */ protected double getBreedingProbability() { return breeding_probability; } /** * getter om grass_infection op te halen * @return grass_infection */ }
X08/Vossen-en-Konijnen
bin/model/Grass.java
1,593
/** * Zorgt er voor dat er geen nakomeling worden geboren als er te weinig voesel zijn. * @return true als genoeg voedsel zijn * @return false als niet genoeg voedsel zijn */
block_comment
nl
package bin.model; import java.util.List; import bin.logic.Field; import bin.logic.Location; /** * A simple model of a grass. * Grasss age, move, breed, and die. * * @author Ieme, Jermo, Yisong * @version 2012.01.29 */ public class Grass extends Plant { // Characteristics shared by all grass (class variables). // The age at which a grass can start to breed. private static int breeding_age = 3; // The age to which a grass can live. private static int max_age = 12; // The likelihood of a grass breeding. private static double breeding_probability = 0.09; // The maximum number of births. private static int max_litter_size = 6; /** * Create a new grass. A grass may be created with age * zero (a new born) or with a random age. * * @param randomAge If true, the grass will have a random age. * @param field The field currently occupied. * @param location The location within the field. */ public Grass(boolean randomAge, Field field, Location location) { super(field, location); setAge(0); if(randomAge) { setAge(getRandom().nextInt(max_age)); } } /** * This is what the grass does most of the time - it runs * around. Sometimes it will breed or die of old age. * @param newGrasss A list to return newly born grasss. */ public void act(List<Actor> newGrass) { incrementAge(); if(isAlive()) { giveBirth(newGrass); // Try to move into a free location. Location newLocation = getField().freeAdjacentLocation(getLocation()); if(newLocation != null) { setLocation(newLocation); } else { // Overcrowding. setDead(); } } } /** * Zorgt er voor<SUF>*/ public boolean survivalInstinct() { // MainProgram.getSimulator().getSimulatorView().getStats().getPopulation(); return true; } /** * check if grass is surround by grassvirus. * @return true if it is */ /** * Check whether or not this grass is to give birth at this step. * New births will be made into free adjacent locations. * @param newGrasss A list to return newly born grasss. */ private void giveBirth(List<Actor> newGrass) { // New grasss are born into adjacent locations. // Get a list of adjacent free locations. Field field = getField(); List<Location> free = field.getFreeAdjacentLocations(getLocation()); int births = breed(); for(int b = 0; b < births && free.size() > 0; b++) { Location loc = free.remove(0); Grass young = new Grass(false, field, loc); newGrass.add(young); } } /** * A grass can breed if it has reached the breeding age. * @return true if the grass can breed, false otherwise. */ protected boolean canBreed() { return getAge() >= getBreedingAge(); } /** * setter voor breeding_age * @param breeding_age */ public static void setBreedingAge(int breeding_age) { if (breeding_age >= 0) Grass.breeding_age = breeding_age; } /** * setter voor max_age * @param max_age */ public static void setMaxAge(int max_age) { if (max_age >= 1) Grass.max_age = max_age; } /** * setter voor breeding_probability * @param breeding_probability */ public static void setBreedingProbability(double breeding_probability) { if (breeding_probability >= 0) Grass.breeding_probability = breeding_probability; } /** * setter voor max_litter_size * @param max_litter_size */ public static void setMaxLitterSize(int max_litter_size) { if (max_litter_size >= 1) Grass.max_litter_size = max_litter_size; } /** * default settings */ public static void setDefault() { breeding_age = 1; max_age = 100; breeding_probability = 0.02; max_litter_size = 100; } /** * Getter om breeding_age op te halen */ protected int getBreedingAge() { return breeding_age; } /** * returns the maximum age of a grass can live * @return int maximum age of a grass can live */ protected int getMaxAge() { return max_age; } /** * Getter om max_litter_size op te halen * @return max_litter_size maximum litter */ protected int getMaxLitterSize() { return max_litter_size; } /** * Getter om breeding_probability op te halen * @return breeding_probability breeding kansen */ protected double getBreedingProbability() { return breeding_probability; } /** * getter om grass_infection op te halen * @return grass_infection */ }
True
False
1,957
1,593
56
40
1,441
60
48
1,486
49
33
1,443
60
48
1,646
60
44
false
false
false
false
false
true
3,043
70446_1
package ap.be.backend.security.jwt; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.web.filter.OncePerRequestFilter; import ap.be.backend.security.services.UserDetailsServiceImpl; public class AuthTokenFilter extends OncePerRequestFilter{ @Autowired private JwtUtils jwtUtils; @Autowired private UserDetailsServiceImpl userDetailsService; @Value("${Leap.app.tokenBearer}") private String bearer; private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class); /** * Vraagt de hele request header op om ze daarna te ontleden en de JSON Web Token eruit te halen. * @param request nodig om de request header te kunnen aanvragen. * @return geeft de JSON Web Token terug. */ private String parseJwt(HttpServletRequest request) { String headerAuth = request.getHeader("Authorization"); if(StringUtils.hasText(headerAuth) && headerAuth.startsWith(bearer + " ")) { return headerAuth.substring(7, headerAuth.length()); } return null; } /** * Controleert of de gebruiker en token bij elkaar horen. * @param request interface dat wordt gebruikt om authenticatie details aan te vragen. * @param response interface dat wordt gebruikt om HTTP specifieke functionaliteiten binnen te krijgen. * @param filterChain vuurt de volgende filter in de kettingreactie af. * @throws ServletException wordt afgevuurd bij een algemene fout. * @throws IOException wordt afgevuurd bij gefaalde of onderbroken i/o processen. */ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { String jwt = parseJwt(request); if(jwt != null && jwtUtils.validateJwtToken(jwt)) { String username = jwtUtils.getUserNameFromJwtToken(jwt); UserDetails userDetails = userDetailsService.loadUserByUsername(username); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (Exception e) { logger.error("Cannot set user authentication: {}", e); } filterChain.doFilter(request, response); } }
iDeebSee/LEAP
backend/src/main/java/ap/be/backend/security/jwt/AuthTokenFilter.java
845
/** * Controleert of de gebruiker en token bij elkaar horen. * @param request interface dat wordt gebruikt om authenticatie details aan te vragen. * @param response interface dat wordt gebruikt om HTTP specifieke functionaliteiten binnen te krijgen. * @param filterChain vuurt de volgende filter in de kettingreactie af. * @throws ServletException wordt afgevuurd bij een algemene fout. * @throws IOException wordt afgevuurd bij gefaalde of onderbroken i/o processen. */
block_comment
nl
package ap.be.backend.security.jwt; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.web.filter.OncePerRequestFilter; import ap.be.backend.security.services.UserDetailsServiceImpl; public class AuthTokenFilter extends OncePerRequestFilter{ @Autowired private JwtUtils jwtUtils; @Autowired private UserDetailsServiceImpl userDetailsService; @Value("${Leap.app.tokenBearer}") private String bearer; private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class); /** * Vraagt de hele request header op om ze daarna te ontleden en de JSON Web Token eruit te halen. * @param request nodig om de request header te kunnen aanvragen. * @return geeft de JSON Web Token terug. */ private String parseJwt(HttpServletRequest request) { String headerAuth = request.getHeader("Authorization"); if(StringUtils.hasText(headerAuth) && headerAuth.startsWith(bearer + " ")) { return headerAuth.substring(7, headerAuth.length()); } return null; } /** * Controleert of de<SUF>*/ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { String jwt = parseJwt(request); if(jwt != null && jwtUtils.validateJwtToken(jwt)) { String username = jwtUtils.getUserNameFromJwtToken(jwt); UserDetails userDetails = userDetailsService.loadUserByUsername(username); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authentication); } } catch (Exception e) { logger.error("Cannot set user authentication: {}", e); } filterChain.doFilter(request, response); } }
True
False
1,962
845
132
96
724
129
102
731
118
82
724
129
102
839
142
106
true
false
true
false
true
false
348
56970_2
/* * Commons eID Project. * Copyright (C) 2008-2013 FedICT. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version * 3.0 as published by the Free Software Foundation. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, see * http://www.gnu.org/licenses/. */ package be.fedict.commons.eid.consumer; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * Enumeration for eID Document Type. * * @author Frank Cornelis * */ public enum DocumentType implements Serializable { BELGIAN_CITIZEN("1"), KIDS_CARD("6"), BOOTSTRAP_CARD("7"), HABILITATION_CARD("8"), /** * Bewijs van inschrijving in het vreemdelingenregister ??? Tijdelijk * verblijf */ FOREIGNER_A("11"), /** * Bewijs van inschrijving in het vreemdelingenregister */ FOREIGNER_B("12"), /** * Identiteitskaart voor vreemdeling */ FOREIGNER_C("13"), /** * EG-Langdurig ingezetene */ FOREIGNER_D("14"), /** * (Verblijfs)kaart van een onderdaan van een lidstaat der EEG Verklaring * van inschrijving */ FOREIGNER_E("15"), /** * Document ter staving van duurzaam verblijf van een EU onderdaan */ FOREIGNER_E_PLUS("16"), /** * Kaart voor niet-EU familieleden van een EU-onderdaan of van een Belg * Verblijfskaart van een familielid van een burger van de Unie */ FOREIGNER_F("17"), /** * Duurzame verblijfskaart van een familielid van een burger van de Unie */ FOREIGNER_F_PLUS("18"), /** * H. Europese blauwe kaart. Toegang en verblijf voor onderdanen van derde * landen. */ EUROPEAN_BLUE_CARD_H("19"); private final int key; private DocumentType(final String value) { this.key = toKey(value); } private int toKey(final String value) { final char c1 = value.charAt(0); int key = c1 - '0'; if (2 == value.length()) { key *= 10; final char c2 = value.charAt(1); key += c2 - '0'; } return key; } private static int toKey(final byte[] value) { int key = value[0] - '0'; if (2 == value.length) { key *= 10; key += value[1] - '0'; } return key; } private static Map<Integer, DocumentType> documentTypes; static { final Map<Integer, DocumentType> documentTypes = new HashMap<Integer, DocumentType>(); for (DocumentType documentType : DocumentType.values()) { final int encodedValue = documentType.key; if (documentTypes.containsKey(encodedValue)) { throw new RuntimeException("duplicate document type enum: " + encodedValue); } documentTypes.put(encodedValue, documentType); } DocumentType.documentTypes = documentTypes; } public int getKey() { return this.key; } public static DocumentType toDocumentType(final byte[] value) { final int key = DocumentType.toKey(value); final DocumentType documentType = DocumentType.documentTypes.get(key); /* * If the key is unknown, we simply return null. */ return documentType; } public static String toString(final byte[] documentTypeValue) { return Integer.toString(DocumentType.toKey(documentTypeValue)); } }
Corilus/commons-eid
commons-eid-consumer/src/main/java/be/fedict/commons/eid/consumer/DocumentType.java
1,169
/** * Bewijs van inschrijving in het vreemdelingenregister ??? Tijdelijk * verblijf */
block_comment
nl
/* * Commons eID Project. * Copyright (C) 2008-2013 FedICT. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License version * 3.0 as published by the Free Software Foundation. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, see * http://www.gnu.org/licenses/. */ package be.fedict.commons.eid.consumer; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * Enumeration for eID Document Type. * * @author Frank Cornelis * */ public enum DocumentType implements Serializable { BELGIAN_CITIZEN("1"), KIDS_CARD("6"), BOOTSTRAP_CARD("7"), HABILITATION_CARD("8"), /** * Bewijs van inschrijving<SUF>*/ FOREIGNER_A("11"), /** * Bewijs van inschrijving in het vreemdelingenregister */ FOREIGNER_B("12"), /** * Identiteitskaart voor vreemdeling */ FOREIGNER_C("13"), /** * EG-Langdurig ingezetene */ FOREIGNER_D("14"), /** * (Verblijfs)kaart van een onderdaan van een lidstaat der EEG Verklaring * van inschrijving */ FOREIGNER_E("15"), /** * Document ter staving van duurzaam verblijf van een EU onderdaan */ FOREIGNER_E_PLUS("16"), /** * Kaart voor niet-EU familieleden van een EU-onderdaan of van een Belg * Verblijfskaart van een familielid van een burger van de Unie */ FOREIGNER_F("17"), /** * Duurzame verblijfskaart van een familielid van een burger van de Unie */ FOREIGNER_F_PLUS("18"), /** * H. Europese blauwe kaart. Toegang en verblijf voor onderdanen van derde * landen. */ EUROPEAN_BLUE_CARD_H("19"); private final int key; private DocumentType(final String value) { this.key = toKey(value); } private int toKey(final String value) { final char c1 = value.charAt(0); int key = c1 - '0'; if (2 == value.length()) { key *= 10; final char c2 = value.charAt(1); key += c2 - '0'; } return key; } private static int toKey(final byte[] value) { int key = value[0] - '0'; if (2 == value.length) { key *= 10; key += value[1] - '0'; } return key; } private static Map<Integer, DocumentType> documentTypes; static { final Map<Integer, DocumentType> documentTypes = new HashMap<Integer, DocumentType>(); for (DocumentType documentType : DocumentType.values()) { final int encodedValue = documentType.key; if (documentTypes.containsKey(encodedValue)) { throw new RuntimeException("duplicate document type enum: " + encodedValue); } documentTypes.put(encodedValue, documentType); } DocumentType.documentTypes = documentTypes; } public int getKey() { return this.key; } public static DocumentType toDocumentType(final byte[] value) { final int key = DocumentType.toKey(value); final DocumentType documentType = DocumentType.documentTypes.get(key); /* * If the key is unknown, we simply return null. */ return documentType; } public static String toString(final byte[] documentTypeValue) { return Integer.toString(DocumentType.toKey(documentTypeValue)); } }
True
False
1,967
1,169
33
21
1,108
32
24
1,073
27
16
1,108
32
24
1,275
34
22
false
false
false
false
false
true
307
97783_17
/** * Copyright (C) 2012 GridLine <info@gridline.nl> * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * */ package nl.gridline.model.upr; import java.util.Date; import java.util.NavigableMap; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import nl.gridline.zieook.api.Updatable; /** * Tracks what url's a user has visited in the UPR, specifically it tracks the URL's of collection items. * <p /> * Project upr-api<br /> * Visited.java created 7 dec. 2011 * <p /> * Copyright, all rights reserved 2011 GridLine Amsterdam * @author <a href="mailto:job@gridline.nl">Job</a> * @version $Revision:$, $Date:$ */ @XmlRootElement(name = "visited") @XmlAccessorType(XmlAccessType.FIELD) public class Visit extends EventLog implements Updatable<Visit> { @XmlElement(name = "recommender") private String recommender; @XmlElement(name = "recommender-apikey") private String apikey; @XmlElement(name = "url") private String url; @XmlElement(name = "user_id") private Long userId; @XmlElement(name = "content_provider") private String cp; /** * */ private static final long serialVersionUID = 3593628095422562232L; public Visit() { } /** * @param cp * @param url * @param userId */ public Visit(String recommender, String url, String cp, Long userId) { this.userId = userId; this.cp = cp; this.recommender = recommender; this.url = url; } public Visit(String recommender, String url, String cp, Long userId, Date created, Date updated) { super(created, updated); this.userId = userId; this.cp = cp; this.recommender = recommender; this.url = url; } public Visit(NavigableMap<byte[], byte[]> map) { super(map); userId = ModelConstants.getUserId(map); url = ModelConstants.getUrl(map); recommender = ModelConstants.getRecommender(map); apikey = ModelConstants.getApiKey(map); cp = ModelConstants.getCp(map); } /* * (non-Javadoc) * * @see nl.gridline.model.upr.EventLog#toMap() */ @Override public NavigableMap<byte[], byte[]> toMap() { NavigableMap<byte[], byte[]> map = super.toMap(); return toMap(map); } /* * (non-Javadoc) * * @see nl.gridline.model.upr.EventLog#toMap(java.util.NavigableMap) */ @Override public NavigableMap<byte[], byte[]> toMap(NavigableMap<byte[], byte[]> map) { super.toMap(map); ModelConstants.putUserId(map, userId); ModelConstants.putUrl(map, url); ModelConstants.putRecommender(map, recommender); ModelConstants.putApiKey(map, apikey); ModelConstants.putCp(map, cp); return map; } /* * (non-Javadoc) * * @see nl.gridline.zieook.api.Updatable#update(java.lang.Object) */ @Override public Visit update(Visit updates) { if (updates == null) { return this; } super.update(updates); if (updates.apikey != null) { apikey = updates.apikey; } if (updates.url != null) { url = updates.url; } if (updates.recommender != null) { recommender = updates.recommender; } if (updates.userId != null) { userId = updates.userId; } if (updates.cp != null) { cp = updates.cp; } return this; } /** * @return The recommender. */ public String getRecommender() { return recommender; } /** * @param recommender The cp to set. */ public void setRecommender(String recommender) { this.recommender = recommender; } /** * @return The url. */ public String getUrl() { return url; } /** * @param url The url to set. */ public void setUrl(String url) { this.url = url; } /** * @return The userId. */ public Long getUserId() { return userId; } /** * @param userId The userId to set. */ public void setUserId(Long userId) { this.userId = userId; } /** * @return The apikey. */ public String getApikey() { return apikey; } /** * @param apikey The apikey to set. */ public void setApikey(String apikey) { this.apikey = apikey; } public String getCp() { return cp; } public void setCp(String cp) { this.cp = cp; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((apikey == null) ? 0 : apikey.hashCode()); result = prime * result + ((cp == null) ? 0 : cp.hashCode()); result = prime * result + ((recommender == null) ? 0 : recommender.hashCode()); result = prime * result + ((url == null) ? 0 : url.hashCode()); result = prime * result + ((userId == null) ? 0 : userId.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } Visit other = (Visit) obj; if (apikey == null) { if (other.apikey != null) { return false; } } else if (!apikey.equals(other.apikey)) { return false; } if (cp == null) { if (other.cp != null) { return false; } } else if (!cp.equals(other.cp)) { return false; } if (recommender == null) { if (other.recommender != null) { return false; } } else if (!recommender.equals(other.recommender)) { return false; } if (url == null) { if (other.url != null) { return false; } } else if (!url.equals(other.url)) { return false; } if (userId == null) { if (other.userId != null) { return false; } } else if (!userId.equals(other.userId)) { return false; } return true; } // naam van instelling // URL waarop actie is uitgevoerd // Timestamp van actie }
CatchPlus/User-Profile-Repository
upr-api/src/main/java/nl/gridline/model/upr/Visit.java
2,436
// URL waarop actie is uitgevoerd
line_comment
nl
/** * Copyright (C) 2012 GridLine <info@gridline.nl> * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * */ package nl.gridline.model.upr; import java.util.Date; import java.util.NavigableMap; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import nl.gridline.zieook.api.Updatable; /** * Tracks what url's a user has visited in the UPR, specifically it tracks the URL's of collection items. * <p /> * Project upr-api<br /> * Visited.java created 7 dec. 2011 * <p /> * Copyright, all rights reserved 2011 GridLine Amsterdam * @author <a href="mailto:job@gridline.nl">Job</a> * @version $Revision:$, $Date:$ */ @XmlRootElement(name = "visited") @XmlAccessorType(XmlAccessType.FIELD) public class Visit extends EventLog implements Updatable<Visit> { @XmlElement(name = "recommender") private String recommender; @XmlElement(name = "recommender-apikey") private String apikey; @XmlElement(name = "url") private String url; @XmlElement(name = "user_id") private Long userId; @XmlElement(name = "content_provider") private String cp; /** * */ private static final long serialVersionUID = 3593628095422562232L; public Visit() { } /** * @param cp * @param url * @param userId */ public Visit(String recommender, String url, String cp, Long userId) { this.userId = userId; this.cp = cp; this.recommender = recommender; this.url = url; } public Visit(String recommender, String url, String cp, Long userId, Date created, Date updated) { super(created, updated); this.userId = userId; this.cp = cp; this.recommender = recommender; this.url = url; } public Visit(NavigableMap<byte[], byte[]> map) { super(map); userId = ModelConstants.getUserId(map); url = ModelConstants.getUrl(map); recommender = ModelConstants.getRecommender(map); apikey = ModelConstants.getApiKey(map); cp = ModelConstants.getCp(map); } /* * (non-Javadoc) * * @see nl.gridline.model.upr.EventLog#toMap() */ @Override public NavigableMap<byte[], byte[]> toMap() { NavigableMap<byte[], byte[]> map = super.toMap(); return toMap(map); } /* * (non-Javadoc) * * @see nl.gridline.model.upr.EventLog#toMap(java.util.NavigableMap) */ @Override public NavigableMap<byte[], byte[]> toMap(NavigableMap<byte[], byte[]> map) { super.toMap(map); ModelConstants.putUserId(map, userId); ModelConstants.putUrl(map, url); ModelConstants.putRecommender(map, recommender); ModelConstants.putApiKey(map, apikey); ModelConstants.putCp(map, cp); return map; } /* * (non-Javadoc) * * @see nl.gridline.zieook.api.Updatable#update(java.lang.Object) */ @Override public Visit update(Visit updates) { if (updates == null) { return this; } super.update(updates); if (updates.apikey != null) { apikey = updates.apikey; } if (updates.url != null) { url = updates.url; } if (updates.recommender != null) { recommender = updates.recommender; } if (updates.userId != null) { userId = updates.userId; } if (updates.cp != null) { cp = updates.cp; } return this; } /** * @return The recommender. */ public String getRecommender() { return recommender; } /** * @param recommender The cp to set. */ public void setRecommender(String recommender) { this.recommender = recommender; } /** * @return The url. */ public String getUrl() { return url; } /** * @param url The url to set. */ public void setUrl(String url) { this.url = url; } /** * @return The userId. */ public Long getUserId() { return userId; } /** * @param userId The userId to set. */ public void setUserId(Long userId) { this.userId = userId; } /** * @return The apikey. */ public String getApikey() { return apikey; } /** * @param apikey The apikey to set. */ public void setApikey(String apikey) { this.apikey = apikey; } public String getCp() { return cp; } public void setCp(String cp) { this.cp = cp; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((apikey == null) ? 0 : apikey.hashCode()); result = prime * result + ((cp == null) ? 0 : cp.hashCode()); result = prime * result + ((recommender == null) ? 0 : recommender.hashCode()); result = prime * result + ((url == null) ? 0 : url.hashCode()); result = prime * result + ((userId == null) ? 0 : userId.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } Visit other = (Visit) obj; if (apikey == null) { if (other.apikey != null) { return false; } } else if (!apikey.equals(other.apikey)) { return false; } if (cp == null) { if (other.cp != null) { return false; } } else if (!cp.equals(other.cp)) { return false; } if (recommender == null) { if (other.recommender != null) { return false; } } else if (!recommender.equals(other.recommender)) { return false; } if (url == null) { if (other.url != null) { return false; } } else if (!url.equals(other.url)) { return false; } if (userId == null) { if (other.userId != null) { return false; } } else if (!userId.equals(other.userId)) { return false; } return true; } // naam van instelling // URL waarop<SUF> // Timestamp van actie }
True
False
1,970
2,436
10
9
2,244
11
10
2,281
6
5
2,244
11
10
2,671
11
10
false
false
false
false
false
true
1,336
83193_1
package customComponents; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; public class Filehandling { final static Charset ENCODING = StandardCharsets.UTF_8; public Filehandling(){ } //route uitlezen uit een file en de file controleren public Filedata readRouteFile(String aFileName){ Path path = Paths.get(aFileName); try { List<String> routebestand = Files.readAllLines(path, ENCODING); if(routebestand.size() == 0 || !routebestand.get(0).contains("broboticsrouteplanner")){ JOptionPane.showConfirmDialog(null, "Route niet geldig!", "Alert: " + "Fout", JOptionPane.INFORMATION_MESSAGE); System.out.println("Route bestand niet geldig!"); }else{ String[] sizesplitarray = routebestand.get(1).split(","); String[] corsplitarray = routebestand.get(2).split(";"); String[] stepsplitarray = routebestand.get(3).split(","); ArrayList<ArrayList<Integer>> corarray = new ArrayList<ArrayList<Integer>>(); ArrayList<Character> steps = new ArrayList<Character>(); Filedata file = new Filedata(); file.setColumns(Integer.parseInt(sizesplitarray[1])); file.setRows(Integer.parseInt(sizesplitarray[0])); for(String cor:corsplitarray){ String[] temparray = cor.split(","); corarray.add(new ArrayList<Integer>()); corarray.get(corarray.size()-1).add(0, Integer.parseInt(temparray[0])); corarray.get(corarray.size()-1).add(1, Integer.parseInt(temparray[1])); } for(String step:stepsplitarray){ steps.add(step.toCharArray()[0]); } file.setCordinates(corarray); file.setSteps(steps); System.out.println(file.getCordinates()); return file; } } catch (IOException e) { JOptionPane.showMessageDialog(null, "Route niet geldig!", "Alert: " + "Fout", JOptionPane.INFORMATION_MESSAGE); System.out.println("Route bestand niet geldig!"); } return null; } //route file schrijven public void writeRouteFile(int maxx, int maxy, ArrayList<ArrayList<Integer>> route, ArrayList<Character> steps, String aFileName){ Path path = Paths.get(aFileName); List<String> file = new ArrayList<String>(); String routestring = ""; for(ArrayList<Integer> cor:route){ routestring += cor.get(0) + "," + cor.get(1) + ";" ; } String stepstring = ""; for(Character c:steps){ stepstring += c +","; } file.add("broboticsrouteplanner"); file.add(maxx+","+maxy); file.add(routestring); file.add(stepstring); try { Files.write(path, file, ENCODING); } catch (IOException e) { e.printStackTrace(); } } //nieuwe routefile aanmaken public void createRouteFile(String filename, List<String> aLines, String aFileName) throws IOException { File file = new File("example.txt"); Path path = Paths.get(aFileName); Files.write(path, aLines, ENCODING); } }
ProjectgroepA8/BroBot
gui/customComponents/Filehandling.java
1,100
//route file schrijven
line_comment
nl
package customComponents; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; public class Filehandling { final static Charset ENCODING = StandardCharsets.UTF_8; public Filehandling(){ } //route uitlezen uit een file en de file controleren public Filedata readRouteFile(String aFileName){ Path path = Paths.get(aFileName); try { List<String> routebestand = Files.readAllLines(path, ENCODING); if(routebestand.size() == 0 || !routebestand.get(0).contains("broboticsrouteplanner")){ JOptionPane.showConfirmDialog(null, "Route niet geldig!", "Alert: " + "Fout", JOptionPane.INFORMATION_MESSAGE); System.out.println("Route bestand niet geldig!"); }else{ String[] sizesplitarray = routebestand.get(1).split(","); String[] corsplitarray = routebestand.get(2).split(";"); String[] stepsplitarray = routebestand.get(3).split(","); ArrayList<ArrayList<Integer>> corarray = new ArrayList<ArrayList<Integer>>(); ArrayList<Character> steps = new ArrayList<Character>(); Filedata file = new Filedata(); file.setColumns(Integer.parseInt(sizesplitarray[1])); file.setRows(Integer.parseInt(sizesplitarray[0])); for(String cor:corsplitarray){ String[] temparray = cor.split(","); corarray.add(new ArrayList<Integer>()); corarray.get(corarray.size()-1).add(0, Integer.parseInt(temparray[0])); corarray.get(corarray.size()-1).add(1, Integer.parseInt(temparray[1])); } for(String step:stepsplitarray){ steps.add(step.toCharArray()[0]); } file.setCordinates(corarray); file.setSteps(steps); System.out.println(file.getCordinates()); return file; } } catch (IOException e) { JOptionPane.showMessageDialog(null, "Route niet geldig!", "Alert: " + "Fout", JOptionPane.INFORMATION_MESSAGE); System.out.println("Route bestand niet geldig!"); } return null; } //route file<SUF> public void writeRouteFile(int maxx, int maxy, ArrayList<ArrayList<Integer>> route, ArrayList<Character> steps, String aFileName){ Path path = Paths.get(aFileName); List<String> file = new ArrayList<String>(); String routestring = ""; for(ArrayList<Integer> cor:route){ routestring += cor.get(0) + "," + cor.get(1) + ";" ; } String stepstring = ""; for(Character c:steps){ stepstring += c +","; } file.add("broboticsrouteplanner"); file.add(maxx+","+maxy); file.add(routestring); file.add(stepstring); try { Files.write(path, file, ENCODING); } catch (IOException e) { e.printStackTrace(); } } //nieuwe routefile aanmaken public void createRouteFile(String filename, List<String> aLines, String aFileName) throws IOException { File file = new File("example.txt"); Path path = Paths.get(aFileName); Files.write(path, aLines, ENCODING); } }
True
False
1,971
1,100
6
4
931
7
5
954
5
3
931
7
5
1,150
7
5
false
false
false
false
false
true
1,863
71894_2
package Domain.Task; import Domain.DataClasses.Time; import Domain.User.Role; import Domain.User.User; import Domain.User.UserAlreadyAssignedToTaskException; /** * Task state class governing the task transitions from the PENDING state */ public class PendingState implements TaskState { @Override public void start(Task task, Time startTime, User currentUser, Role role) throws IncorrectTaskStatusException, IncorrectRoleException, UserAlreadyAssignedToTaskException { if (!task.getUnfulfilledRoles().contains(role)) { throw new IncorrectRoleException("Given role is not required in this task"); } for (Task prevTask : task.getPrevTasks()) { if (prevTask.getEndTime() == null || prevTask.getEndTime().after(startTime)) { throw new IncorrectTaskStatusException("Start time is before end time previous task"); } } currentUser.assignTask(task, role); task.commitUser(currentUser, role); if (task.getUnfulfilledRoles().size() == 0) { task.setState(new ExecutingState()); task.setStartTime(startTime); } else { task.setState(new PendingState()); // als user al op deze task werkte als enige kan het zijn dat de status // terug available wordt bij het verwijderen van deze } } @Override public void undoStart(Task task) { if (task.getCommittedUsers().size() - 1 == 0) { task.setState(new AvailableState()); } } @Override public Status getStatus() { return Status.PENDING; } @Override public void unassignUser(Task task, User user) { task.uncommitUser(user); if (task.getCommittedUsers().size() == 0) { task.setState(new AvailableState()); } } @Override public String toString() { return getStatus().toString(); } }
WardGr/SWOP
src/Domain/Task/PendingState.java
522
// terug available wordt bij het verwijderen van deze
line_comment
nl
package Domain.Task; import Domain.DataClasses.Time; import Domain.User.Role; import Domain.User.User; import Domain.User.UserAlreadyAssignedToTaskException; /** * Task state class governing the task transitions from the PENDING state */ public class PendingState implements TaskState { @Override public void start(Task task, Time startTime, User currentUser, Role role) throws IncorrectTaskStatusException, IncorrectRoleException, UserAlreadyAssignedToTaskException { if (!task.getUnfulfilledRoles().contains(role)) { throw new IncorrectRoleException("Given role is not required in this task"); } for (Task prevTask : task.getPrevTasks()) { if (prevTask.getEndTime() == null || prevTask.getEndTime().after(startTime)) { throw new IncorrectTaskStatusException("Start time is before end time previous task"); } } currentUser.assignTask(task, role); task.commitUser(currentUser, role); if (task.getUnfulfilledRoles().size() == 0) { task.setState(new ExecutingState()); task.setStartTime(startTime); } else { task.setState(new PendingState()); // als user al op deze task werkte als enige kan het zijn dat de status // terug available<SUF> } } @Override public void undoStart(Task task) { if (task.getCommittedUsers().size() - 1 == 0) { task.setState(new AvailableState()); } } @Override public Status getStatus() { return Status.PENDING; } @Override public void unassignUser(Task task, User user) { task.uncommitUser(user); if (task.getCommittedUsers().size() == 0) { task.setState(new AvailableState()); } } @Override public String toString() { return getStatus().toString(); } }
True
False
1,972
522
13
12
447
13
12
477
9
8
447
13
12
529
12
11
false
false
false
false
false
true
1,255
62851_21
/*_x000D_ * To change this license header, choose License Headers in Project Properties._x000D_ * To change this template file, choose Tools | Templates_x000D_ * and open the template in the editor._x000D_ */_x000D_ package conversion.pdf.util;_x000D_ _x000D_ import java.io.ByteArrayInputStream;_x000D_ import java.io.ByteArrayOutputStream;_x000D_ import java.io.IOException;_x000D_ import java.io.ObjectInputStream;_x000D_ import java.io.ObjectOutputStream;_x000D_ import java.util.ArrayList;_x000D_ import objects.PPTObject;_x000D_ import org.apache.pdfbox.cos.COSStream;_x000D_ import org.apache.pdfbox.pdmodel.PDPage;_x000D_ import org.apache.pdfbox.pdmodel.PDResources;_x000D_ import org.apache.pdfbox.util.PDFTextStripper;_x000D_ import org.apache.pdfbox.util.TextPosition;_x000D_ _x000D_ /**_x000D_ * TextExtractor overrides certain methodes from PDFTextStripper in order to put_x000D_ * information in the arrayList of PPTObjects objecten._x000D_ *_x000D_ * @author Gertjan_x000D_ */_x000D_ public class PDFTextExtractor extends PDFTextStripper {_x000D_ _x000D_ private TekenPlus teken = new TekenPlus();_x000D_ private ArrayList<TekenPlus> woord = new ArrayList<>();_x000D_ private boolean isNewWord = true;_x000D_ private ArrayList<PPTObject> objecten = new ArrayList<>();_x000D_ private Info2Object Inf2Obj = new Info2Object();_x000D_ _x000D_ public TekenPlus getTekenPlus() {_x000D_ return this.teken;_x000D_ }_x000D_ /*get geeft niet alleen de objecten terug maar maakt de lijst ook weer leeg, dit is zodat je telkens je ze ophaalt_x000D_ je een hele pagina ophaalt... */_x000D_ _x000D_ public ArrayList<PPTObject> getObjecten() {_x000D_ try {_x000D_ return objecten;_x000D_ } finally {_x000D_ objecten = new ArrayList<>();_x000D_ }_x000D_ _x000D_ }_x000D_ _x000D_ @Override_x000D_ public void processStream(PDPage aPage, PDResources resources, COSStream cosStream) throws IOException {_x000D_ super.processStream(aPage, resources, cosStream); //To change body of generated methods, choose Tools | Templates._x000D_ //en dan een persoonlijke naverwerking:_x000D_ objecten.add(Inf2Obj.convert(woord));_x000D_ woord = new ArrayList<>();_x000D_ }_x000D_ _x000D_ public PDFTextExtractor() throws IOException {_x000D_ super.setSortByPosition(true);_x000D_ _x000D_ }_x000D_ _x000D_ @Override_x000D_ protected void processTextPosition(TextPosition text) {_x000D_ /*deze methode haalt letters met info uit de text... hier gaan we de tekst opvangen _x000D_ en opslaan in woorden, de woorden hebben een fontsize en een schaal... aan de hand van de _x000D_ coordinaten xdir en ydir wordt de lijn en inspringing bepaald... */_x000D_ _x000D_ /*Het idee is om tekstdelen terug te geven uiteindelijk want dat heb je nodig_x000D_ Daarom is er de klasse tekstpartMaker die een enorme string van char's met hun info binnen krijgt_x000D_ -> char's met info = nieuwe klasse!! _x000D_ */_x000D_ teken.setTeken(text.getCharacter());_x000D_ teken.setFontsize(text.getFontSize());_x000D_ teken.setHeigt(text.getHeightDir());_x000D_ teken.setPosX(text.getXDirAdj());_x000D_ teken.setPosY(text.getYDirAdj());_x000D_ teken.setSpace(text.getWidthOfSpace());_x000D_ teken.setXscale(text.getXScale());_x000D_ _x000D_ //System.out.println(text.getFont().getFontDescriptor());_x000D_ if (text.getFont().getBaseFont().toLowerCase().contains("bold")) {_x000D_ teken.setBold(true);_x000D_ //System.out.println("made bold!");_x000D_ } else {_x000D_ teken.setBold(false);_x000D_ }_x000D_ if (text.getFont().getBaseFont().toLowerCase().contains("italic")) {_x000D_ teken.setItalic(true);_x000D_ //System.out.println("made italic!");_x000D_ } else {_x000D_ teken.setItalic(false);_x000D_ }_x000D_ /*enum bepalen -> kijken watvoor letter het is gebeurt hier al!!!*/_x000D_ if (text.getCharacter().matches("[A-Za-z]")) {_x000D_ //System.out.println("letter gevonden!!!" + text.getCharacter());_x000D_ teken.setType(TekenPlus.type.LETTER);_x000D_ } else if (text.getCharacter().matches("[0-9]")) {_x000D_ //System.out.println("---cijfer gevonden!!!" + text.getCharacter());_x000D_ teken.setType(TekenPlus.type.CIJFER);_x000D_ } else if (text.getCharacter().matches("[--?()., ]")) { //OPM laat die - vanvoor staan anders klopt regex niet!!!_x000D_ //System.out.println("+++niet splitsend symbool" + text.getCharacter());_x000D_ teken.setType(TekenPlus.type.NONSPLITTING);_x000D_ } /*BELANGRIJKE OPM: een spatie is geen split teken... een spatie houdt meestal dingen gewoon samen...*/ else {_x000D_ //System.out.println(">>>onbekend split teken gevonden" + text.getCharacter());_x000D_ teken.setType(TekenPlus.type.SPLITTING);_x000D_ }_x000D_ _x000D_ //teken.schrijfPlus();_x000D_ _x000D_ /*_x000D_ System.out.println("Methode die info over tekst eruit haalt");_x000D_ System.out.println("String[" + text.getXDirAdj() + ","_x000D_ + text.getYDirAdj() + " fs=" + text.getFontSize() + " xscale="_x000D_ + text.getXScale() + " height=" + text.getHeightDir() + " space="_x000D_ + text.getWidthOfSpace() + " width="_x000D_ + text.getWidthDirAdj() + "]" + text.getCharacter());_x000D_ */_x000D_ //een korte commercial break om ons teken nu ook hogerop te krijgen!_x000D_ verwerkTeken(teken);_x000D_ _x000D_ }_x000D_ _x000D_ private void verwerkTeken(TekenPlus teken) {_x000D_ /*Het idee is als volgt, indien het teken de zelfde eigenschappen heeft als het vorige dan wordt het_x000D_ erbij gepusht in een tijdelijk tekstdeel, is het anders dan wordt het in een nieuw tekstdeel gezet*/_x000D_ /*_x000D_ tekstdeel moet vervolgens nog tekst worden... OPM tekst wordt niet gesplitst op basis van spaties!!_x000D_ */_x000D_ //System.out.println("te verwerken teken: " + teken.getTeken());_x000D_ if (isNewWord) {_x000D_ // System.out.println("gekozen voor : new word optie");_x000D_ woord = new ArrayList<>();_x000D_ isNewWord = false;_x000D_ }_x000D_ //anders gewoon verder schrijven aan je arraylist..._x000D_ /*Hier wordt onderzocht welke soort delimiter je hebt, is het een ander teken dan gewone tekst dan splits je daarop ook...*/_x000D_ if (teken.getType() == TekenPlus.type.SPLITTING) {_x000D_ //System.out.println("gekozen voor: splitting optie");_x000D_ // System.out.println("SPLITTING teken");_x000D_ objecten.add(Inf2Obj.convert(woord));_x000D_ woord = new ArrayList<>();_x000D_ }_x000D_ _x000D_ if (!woord.isEmpty() && !tekenControle(teken)) { //doet hetzelfde als kijken of het splitting is! _x000D_ //controle op leeg zijn anders nullpointers!!_x000D_ //System.out.println("INFO splitting");_x000D_ objecten.add(Inf2Obj.convert(woord));_x000D_ woord = new ArrayList<>();_x000D_ }_x000D_ _x000D_ //even een kopie nemen, hij doet iets vreemd anders..._x000D_ try {_x000D_ ByteArrayOutputStream baos = new ByteArrayOutputStream();_x000D_ ObjectOutputStream oos = new ObjectOutputStream(baos);_x000D_ oos.writeObject(teken);_x000D_ ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());_x000D_ ObjectInputStream ois = new ObjectInputStream(bais);_x000D_ TekenPlus kopie = (TekenPlus) ois.readObject();_x000D_ _x000D_ woord.add(kopie);_x000D_ } catch (Exception e) {_x000D_ System.out.println("fout bij kopiëren..." + e.getMessage());_x000D_ }_x000D_ _x000D_ }_x000D_ _x000D_ /**_x000D_ * Checks if a symbol belongs to the same word or not...._x000D_ * returns false upon a splitting event (like a defferent font etc.)_x000D_ * @param teken_x000D_ * @return _x000D_ */_x000D_ private boolean tekenControle(TekenPlus teken) {_x000D_ _x000D_ TekenPlus vorigeLetter = woord.get(woord.size() - 1); //dit haalt de laatste letter eraf..._x000D_ //System.out.print("De vorige letter was: ");_x000D_ //vorigeLetter.schrijfPlus();_x000D_ //opm = xpos is dat hori of verti? (programma assen of menselijker... :p_x000D_ if (vorigeLetter.getPosY() != teken.getPosY()) {_x000D_ //System.out.println("split op PosY!");_x000D_ return false;_x000D_ _x000D_ }_x000D_ if (vorigeLetter.getFontsize() != teken.getFontsize()) {_x000D_ //System.out.println("split op FontSize");_x000D_ return false;_x000D_ }_x000D_ if (vorigeLetter.isBold() != teken.isBold()) {_x000D_ return false;_x000D_ }_x000D_ if (vorigeLetter.isItalic() != teken.isItalic()) {_x000D_ return false;_x000D_ }_x000D_ _x000D_ if ((teken.getPosX() - vorigeLetter.getPosX()) > 100) {_x000D_ //100 is arbitrair gekozen, merk op dat deze test enkel gedaan wordt voor woorden met zelfde fontsize op zelfde lijn!_x000D_ //System.out.println("verschil tekens: " + (teken.getPosX() - vorigeLetter.getPosX()));_x000D_ return false;_x000D_ }_x000D_ _x000D_ return true;_x000D_ }_x000D_ _x000D_ }_x000D_
OpenWebslides/conversion-tool
WebslideConversionLib/src/conversion/pdf/util/PDFTextExtractor.java
2,619
/*Hier wordt onderzocht welke soort delimiter je hebt, is het een ander teken dan gewone tekst dan splits je daarop ook...*/
block_comment
nl
/*_x000D_ * To change this license header, choose License Headers in Project Properties._x000D_ * To change this template file, choose Tools | Templates_x000D_ * and open the template in the editor._x000D_ */_x000D_ package conversion.pdf.util;_x000D_ _x000D_ import java.io.ByteArrayInputStream;_x000D_ import java.io.ByteArrayOutputStream;_x000D_ import java.io.IOException;_x000D_ import java.io.ObjectInputStream;_x000D_ import java.io.ObjectOutputStream;_x000D_ import java.util.ArrayList;_x000D_ import objects.PPTObject;_x000D_ import org.apache.pdfbox.cos.COSStream;_x000D_ import org.apache.pdfbox.pdmodel.PDPage;_x000D_ import org.apache.pdfbox.pdmodel.PDResources;_x000D_ import org.apache.pdfbox.util.PDFTextStripper;_x000D_ import org.apache.pdfbox.util.TextPosition;_x000D_ _x000D_ /**_x000D_ * TextExtractor overrides certain methodes from PDFTextStripper in order to put_x000D_ * information in the arrayList of PPTObjects objecten._x000D_ *_x000D_ * @author Gertjan_x000D_ */_x000D_ public class PDFTextExtractor extends PDFTextStripper {_x000D_ _x000D_ private TekenPlus teken = new TekenPlus();_x000D_ private ArrayList<TekenPlus> woord = new ArrayList<>();_x000D_ private boolean isNewWord = true;_x000D_ private ArrayList<PPTObject> objecten = new ArrayList<>();_x000D_ private Info2Object Inf2Obj = new Info2Object();_x000D_ _x000D_ public TekenPlus getTekenPlus() {_x000D_ return this.teken;_x000D_ }_x000D_ /*get geeft niet alleen de objecten terug maar maakt de lijst ook weer leeg, dit is zodat je telkens je ze ophaalt_x000D_ je een hele pagina ophaalt... */_x000D_ _x000D_ public ArrayList<PPTObject> getObjecten() {_x000D_ try {_x000D_ return objecten;_x000D_ } finally {_x000D_ objecten = new ArrayList<>();_x000D_ }_x000D_ _x000D_ }_x000D_ _x000D_ @Override_x000D_ public void processStream(PDPage aPage, PDResources resources, COSStream cosStream) throws IOException {_x000D_ super.processStream(aPage, resources, cosStream); //To change body of generated methods, choose Tools | Templates._x000D_ //en dan een persoonlijke naverwerking:_x000D_ objecten.add(Inf2Obj.convert(woord));_x000D_ woord = new ArrayList<>();_x000D_ }_x000D_ _x000D_ public PDFTextExtractor() throws IOException {_x000D_ super.setSortByPosition(true);_x000D_ _x000D_ }_x000D_ _x000D_ @Override_x000D_ protected void processTextPosition(TextPosition text) {_x000D_ /*deze methode haalt letters met info uit de text... hier gaan we de tekst opvangen _x000D_ en opslaan in woorden, de woorden hebben een fontsize en een schaal... aan de hand van de _x000D_ coordinaten xdir en ydir wordt de lijn en inspringing bepaald... */_x000D_ _x000D_ /*Het idee is om tekstdelen terug te geven uiteindelijk want dat heb je nodig_x000D_ Daarom is er de klasse tekstpartMaker die een enorme string van char's met hun info binnen krijgt_x000D_ -> char's met info = nieuwe klasse!! _x000D_ */_x000D_ teken.setTeken(text.getCharacter());_x000D_ teken.setFontsize(text.getFontSize());_x000D_ teken.setHeigt(text.getHeightDir());_x000D_ teken.setPosX(text.getXDirAdj());_x000D_ teken.setPosY(text.getYDirAdj());_x000D_ teken.setSpace(text.getWidthOfSpace());_x000D_ teken.setXscale(text.getXScale());_x000D_ _x000D_ //System.out.println(text.getFont().getFontDescriptor());_x000D_ if (text.getFont().getBaseFont().toLowerCase().contains("bold")) {_x000D_ teken.setBold(true);_x000D_ //System.out.println("made bold!");_x000D_ } else {_x000D_ teken.setBold(false);_x000D_ }_x000D_ if (text.getFont().getBaseFont().toLowerCase().contains("italic")) {_x000D_ teken.setItalic(true);_x000D_ //System.out.println("made italic!");_x000D_ } else {_x000D_ teken.setItalic(false);_x000D_ }_x000D_ /*enum bepalen -> kijken watvoor letter het is gebeurt hier al!!!*/_x000D_ if (text.getCharacter().matches("[A-Za-z]")) {_x000D_ //System.out.println("letter gevonden!!!" + text.getCharacter());_x000D_ teken.setType(TekenPlus.type.LETTER);_x000D_ } else if (text.getCharacter().matches("[0-9]")) {_x000D_ //System.out.println("---cijfer gevonden!!!" + text.getCharacter());_x000D_ teken.setType(TekenPlus.type.CIJFER);_x000D_ } else if (text.getCharacter().matches("[--?()., ]")) { //OPM laat die - vanvoor staan anders klopt regex niet!!!_x000D_ //System.out.println("+++niet splitsend symbool" + text.getCharacter());_x000D_ teken.setType(TekenPlus.type.NONSPLITTING);_x000D_ } /*BELANGRIJKE OPM: een spatie is geen split teken... een spatie houdt meestal dingen gewoon samen...*/ else {_x000D_ //System.out.println(">>>onbekend split teken gevonden" + text.getCharacter());_x000D_ teken.setType(TekenPlus.type.SPLITTING);_x000D_ }_x000D_ _x000D_ //teken.schrijfPlus();_x000D_ _x000D_ /*_x000D_ System.out.println("Methode die info over tekst eruit haalt");_x000D_ System.out.println("String[" + text.getXDirAdj() + ","_x000D_ + text.getYDirAdj() + " fs=" + text.getFontSize() + " xscale="_x000D_ + text.getXScale() + " height=" + text.getHeightDir() + " space="_x000D_ + text.getWidthOfSpace() + " width="_x000D_ + text.getWidthDirAdj() + "]" + text.getCharacter());_x000D_ */_x000D_ //een korte commercial break om ons teken nu ook hogerop te krijgen!_x000D_ verwerkTeken(teken);_x000D_ _x000D_ }_x000D_ _x000D_ private void verwerkTeken(TekenPlus teken) {_x000D_ /*Het idee is als volgt, indien het teken de zelfde eigenschappen heeft als het vorige dan wordt het_x000D_ erbij gepusht in een tijdelijk tekstdeel, is het anders dan wordt het in een nieuw tekstdeel gezet*/_x000D_ /*_x000D_ tekstdeel moet vervolgens nog tekst worden... OPM tekst wordt niet gesplitst op basis van spaties!!_x000D_ */_x000D_ //System.out.println("te verwerken teken: " + teken.getTeken());_x000D_ if (isNewWord) {_x000D_ // System.out.println("gekozen voor : new word optie");_x000D_ woord = new ArrayList<>();_x000D_ isNewWord = false;_x000D_ }_x000D_ //anders gewoon verder schrijven aan je arraylist..._x000D_ /*Hier wordt onderzocht<SUF>*/_x000D_ if (teken.getType() == TekenPlus.type.SPLITTING) {_x000D_ //System.out.println("gekozen voor: splitting optie");_x000D_ // System.out.println("SPLITTING teken");_x000D_ objecten.add(Inf2Obj.convert(woord));_x000D_ woord = new ArrayList<>();_x000D_ }_x000D_ _x000D_ if (!woord.isEmpty() && !tekenControle(teken)) { //doet hetzelfde als kijken of het splitting is! _x000D_ //controle op leeg zijn anders nullpointers!!_x000D_ //System.out.println("INFO splitting");_x000D_ objecten.add(Inf2Obj.convert(woord));_x000D_ woord = new ArrayList<>();_x000D_ }_x000D_ _x000D_ //even een kopie nemen, hij doet iets vreemd anders..._x000D_ try {_x000D_ ByteArrayOutputStream baos = new ByteArrayOutputStream();_x000D_ ObjectOutputStream oos = new ObjectOutputStream(baos);_x000D_ oos.writeObject(teken);_x000D_ ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());_x000D_ ObjectInputStream ois = new ObjectInputStream(bais);_x000D_ TekenPlus kopie = (TekenPlus) ois.readObject();_x000D_ _x000D_ woord.add(kopie);_x000D_ } catch (Exception e) {_x000D_ System.out.println("fout bij kopiëren..." + e.getMessage());_x000D_ }_x000D_ _x000D_ }_x000D_ _x000D_ /**_x000D_ * Checks if a symbol belongs to the same word or not...._x000D_ * returns false upon a splitting event (like a defferent font etc.)_x000D_ * @param teken_x000D_ * @return _x000D_ */_x000D_ private boolean tekenControle(TekenPlus teken) {_x000D_ _x000D_ TekenPlus vorigeLetter = woord.get(woord.size() - 1); //dit haalt de laatste letter eraf..._x000D_ //System.out.print("De vorige letter was: ");_x000D_ //vorigeLetter.schrijfPlus();_x000D_ //opm = xpos is dat hori of verti? (programma assen of menselijker... :p_x000D_ if (vorigeLetter.getPosY() != teken.getPosY()) {_x000D_ //System.out.println("split op PosY!");_x000D_ return false;_x000D_ _x000D_ }_x000D_ if (vorigeLetter.getFontsize() != teken.getFontsize()) {_x000D_ //System.out.println("split op FontSize");_x000D_ return false;_x000D_ }_x000D_ if (vorigeLetter.isBold() != teken.isBold()) {_x000D_ return false;_x000D_ }_x000D_ if (vorigeLetter.isItalic() != teken.isItalic()) {_x000D_ return false;_x000D_ }_x000D_ _x000D_ if ((teken.getPosX() - vorigeLetter.getPosX()) > 100) {_x000D_ //100 is arbitrair gekozen, merk op dat deze test enkel gedaan wordt voor woorden met zelfde fontsize op zelfde lijn!_x000D_ //System.out.println("verschil tekens: " + (teken.getPosX() - vorigeLetter.getPosX()));_x000D_ return false;_x000D_ }_x000D_ _x000D_ return true;_x000D_ }_x000D_ _x000D_ }_x000D_
True
False
1,976
3,519
35
31
3,691
39
35
3,599
28
24
3,691
39
35
3,963
36
32
false
false
false
false
false
true
1,865
19764_4
import java.util.Scanner; import java.util.*; public class Main { static class Metingen { String linkerSchaal, rechterSchaal, weegResul; Metingen(String linkerSchaalC, String rechterSchaalC, String weegResulC){ this.linkerSchaal=linkerSchaalC; this.rechterSchaal=rechterSchaalC; this.weegResul=weegResulC; } String getAlleLetters() { return this.linkerSchaal + this.rechterSchaal; } String getLinkerSchaal() { return this.linkerSchaal; } String getRechterSchaal() { return this.rechterSchaal; } String getWeegResul() { return this.weegResul; } boolean vergelijkLinks(Metingen meting) { return this.linkerSchaal.equals(meting.getLinkerSchaal()); } boolean vergelijkRechts(Metingen meting) { return this.rechterSchaal.equals(meting.getRechterSchaal()); } boolean vergelijkResul(Metingen meting) { return this.weegResul.equals(meting.getWeegResul()); } } static void berekeningen(Metingen[] data) { Set<Character> gebalanceerd = new HashSet<>(); Set<Character> alleLetters = new HashSet<>(); for(int j=0; j<data.length; j++) { boolean evenwicht = (data[j].getWeegResul().equals("evenwicht") ? true : false); for(char c : data[j].getAlleLetters().toCharArray()) { alleLetters.add(c); if(evenwicht) { gebalanceerd.add(c); } } } //twee lijsten van elkaar aftrekken Set<Character> overige = new HashSet<>(alleLetters); overige.removeAll(gebalanceerd); if(overige.size()==1) { char c = overige.iterator().next(); for(int i=0; i<data.length; i++) { //Als de munt is links en de schaal gaat naar boven ==> zwaarder //Of de munt is rechts en de schaal gaat naar beneden ==> zwaarder if((data[i].getLinkerSchaal().indexOf(c) >= 0 && data[i].getWeegResul().contentEquals("omhoog")) || (data[i].getRechterSchaal().indexOf(c) >= 0 && data[i].getWeegResul().contentEquals("omlaag"))) { System.out.println("Het valse geldstuk " + c + " is zwaarder."); return; //Als de munt is links en de schaal gaat naar beneden ==> lichter //Of de munt is rechts en de schaal gaat naar boven ==> lichter } else if((data[i].getLinkerSchaal().indexOf(c) >= 0 && data[i].getWeegResul().contentEquals("omlaag")) || (data[i].getRechterSchaal().indexOf(c) >= 0 && data[i].getWeegResul().contentEquals("omhoog"))) { System.out.println("Het valse geldstuk " + c + " is lichter."); return; } } } else { if(overige.size() > 1) { for(Metingen meting1 : data) { for(Metingen meting2 : data) { //De verschillende gevallen na elkaar uitgeschreven if((meting1.vergelijkLinks(meting2) && !meting1.vergelijkResul(meting2)) || (!meting1.vergelijkLinks(meting2) && !meting1.vergelijkRechts(meting2) && meting1.vergelijkResul(meting2))) { System.out.println("Inconsistente gegevens."); return; } if((meting1.getLinkerSchaal().equals(meting2.getRechterSchaal()) ^ meting1.getRechterSchaal().equals(meting2.getLinkerSchaal())) && !meting1.vergelijkResul(meting2)) { if(meting1.getLinkerSchaal().length() > 1 || meting1.getRechterSchaal().length() > 1 || meting2.getLinkerSchaal().length() > 1 || meting2.getRechterSchaal().length() > 1) { System.out.println("Te weinig gegevens."); return; } System.out.println("Het valse geldstuk " + (meting1.getLinkerSchaal().equals(meting2.getRechterSchaal()) ? meting1.getLinkerSchaal() : meting1.getRechterSchaal()) + " is " + (!meting1.vergelijkResul(meting2) ? "lichter" : "zwaarder") + "."); return; } if((meting1.vergelijkLinks(meting2) ^ meting1.vergelijkRechts(meting2)) && meting1.vergelijkResul(meting2)) { System.out.println("Het valse geldstuk " + (meting1.getLinkerSchaal().equals(meting2.getRechterSchaal()) ? meting1.getRechterSchaal() : meting1.getLinkerSchaal()) + " is " + (meting1.vergelijkResul(meting2) ? "zwaarder" : " lichter") + "."); return; } } } } //Als er geen munten meer zijn ==> inconsistent else if(overige.size() < 1) { System.out.println("Inconsistente gegevens."); return; } } } public static void main(String[] args) { int aantalPakketten=0; int aantalWegingen=0; String lijn; Scanner sc = new Scanner(System.in); lijn = sc.nextLine(); aantalPakketten = Integer.parseInt(lijn); for(int i=0; i<aantalPakketten; i++) { // voor aantal muntpaketten lijn = sc.nextLine(); aantalWegingen = Integer.parseInt(lijn); //Onmogelijk te bepalen als er maar 1 weging is if(aantalWegingen==1) { lijn=sc.nextLine(); System.out.println("Te weinig gegevens."); } else { Metingen[] data = new Metingen[aantalWegingen]; for(int j=0; j<aantalWegingen; j++) { lijn=sc.nextLine(); //opsplitsen van string/weging String[] temp=lijn.split(" "); data[j] = new Metingen(temp[0], temp[1], temp[2]); } berekeningen(data); } } sc.close(); } }
Waterboy1602/DatastructurenEnAlgoritmen_VPW
ValsGeld/src/Main.java
1,993
//Of de munt is rechts en de schaal gaat naar boven ==> lichter
line_comment
nl
import java.util.Scanner; import java.util.*; public class Main { static class Metingen { String linkerSchaal, rechterSchaal, weegResul; Metingen(String linkerSchaalC, String rechterSchaalC, String weegResulC){ this.linkerSchaal=linkerSchaalC; this.rechterSchaal=rechterSchaalC; this.weegResul=weegResulC; } String getAlleLetters() { return this.linkerSchaal + this.rechterSchaal; } String getLinkerSchaal() { return this.linkerSchaal; } String getRechterSchaal() { return this.rechterSchaal; } String getWeegResul() { return this.weegResul; } boolean vergelijkLinks(Metingen meting) { return this.linkerSchaal.equals(meting.getLinkerSchaal()); } boolean vergelijkRechts(Metingen meting) { return this.rechterSchaal.equals(meting.getRechterSchaal()); } boolean vergelijkResul(Metingen meting) { return this.weegResul.equals(meting.getWeegResul()); } } static void berekeningen(Metingen[] data) { Set<Character> gebalanceerd = new HashSet<>(); Set<Character> alleLetters = new HashSet<>(); for(int j=0; j<data.length; j++) { boolean evenwicht = (data[j].getWeegResul().equals("evenwicht") ? true : false); for(char c : data[j].getAlleLetters().toCharArray()) { alleLetters.add(c); if(evenwicht) { gebalanceerd.add(c); } } } //twee lijsten van elkaar aftrekken Set<Character> overige = new HashSet<>(alleLetters); overige.removeAll(gebalanceerd); if(overige.size()==1) { char c = overige.iterator().next(); for(int i=0; i<data.length; i++) { //Als de munt is links en de schaal gaat naar boven ==> zwaarder //Of de munt is rechts en de schaal gaat naar beneden ==> zwaarder if((data[i].getLinkerSchaal().indexOf(c) >= 0 && data[i].getWeegResul().contentEquals("omhoog")) || (data[i].getRechterSchaal().indexOf(c) >= 0 && data[i].getWeegResul().contentEquals("omlaag"))) { System.out.println("Het valse geldstuk " + c + " is zwaarder."); return; //Als de munt is links en de schaal gaat naar beneden ==> lichter //Of de<SUF> } else if((data[i].getLinkerSchaal().indexOf(c) >= 0 && data[i].getWeegResul().contentEquals("omlaag")) || (data[i].getRechterSchaal().indexOf(c) >= 0 && data[i].getWeegResul().contentEquals("omhoog"))) { System.out.println("Het valse geldstuk " + c + " is lichter."); return; } } } else { if(overige.size() > 1) { for(Metingen meting1 : data) { for(Metingen meting2 : data) { //De verschillende gevallen na elkaar uitgeschreven if((meting1.vergelijkLinks(meting2) && !meting1.vergelijkResul(meting2)) || (!meting1.vergelijkLinks(meting2) && !meting1.vergelijkRechts(meting2) && meting1.vergelijkResul(meting2))) { System.out.println("Inconsistente gegevens."); return; } if((meting1.getLinkerSchaal().equals(meting2.getRechterSchaal()) ^ meting1.getRechterSchaal().equals(meting2.getLinkerSchaal())) && !meting1.vergelijkResul(meting2)) { if(meting1.getLinkerSchaal().length() > 1 || meting1.getRechterSchaal().length() > 1 || meting2.getLinkerSchaal().length() > 1 || meting2.getRechterSchaal().length() > 1) { System.out.println("Te weinig gegevens."); return; } System.out.println("Het valse geldstuk " + (meting1.getLinkerSchaal().equals(meting2.getRechterSchaal()) ? meting1.getLinkerSchaal() : meting1.getRechterSchaal()) + " is " + (!meting1.vergelijkResul(meting2) ? "lichter" : "zwaarder") + "."); return; } if((meting1.vergelijkLinks(meting2) ^ meting1.vergelijkRechts(meting2)) && meting1.vergelijkResul(meting2)) { System.out.println("Het valse geldstuk " + (meting1.getLinkerSchaal().equals(meting2.getRechterSchaal()) ? meting1.getRechterSchaal() : meting1.getLinkerSchaal()) + " is " + (meting1.vergelijkResul(meting2) ? "zwaarder" : " lichter") + "."); return; } } } } //Als er geen munten meer zijn ==> inconsistent else if(overige.size() < 1) { System.out.println("Inconsistente gegevens."); return; } } } public static void main(String[] args) { int aantalPakketten=0; int aantalWegingen=0; String lijn; Scanner sc = new Scanner(System.in); lijn = sc.nextLine(); aantalPakketten = Integer.parseInt(lijn); for(int i=0; i<aantalPakketten; i++) { // voor aantal muntpaketten lijn = sc.nextLine(); aantalWegingen = Integer.parseInt(lijn); //Onmogelijk te bepalen als er maar 1 weging is if(aantalWegingen==1) { lijn=sc.nextLine(); System.out.println("Te weinig gegevens."); } else { Metingen[] data = new Metingen[aantalWegingen]; for(int j=0; j<aantalWegingen; j++) { lijn=sc.nextLine(); //opsplitsen van string/weging String[] temp=lijn.split(" "); data[j] = new Metingen(temp[0], temp[1], temp[2]); } berekeningen(data); } } sc.close(); } }
True
False
1,985
1,993
18
15
1,904
24
22
1,741
16
14
1,904
24
22
2,195
20
18
false
false
false
false
false
true
747
55362_0
package main.application; /** * De schimmel F. ellipsoidea wordt erg groot. De fibonacci reeks bepaald het aantal * centimeters dat de schimmel dagelijks in diameter toeneemt. * Bereken de omtrek van de schimmel na 1000 dagen groeien. * Antwoord in centimeters en gebruik de wetenschappelijke notatie, * rond af op 4 cijfers achter de komma, bijvoorbeeld: 1.0903E+231 */ public class VraagQuattro { public static void main(String[] args) { double a = 0; double b = 1; double c = 0; double d = 2; for (int i = 3; i <= 1000; i++) { c = a + b; d += c; a = b; b = c; } System.out.println(formatToString(d*Math.PI)); //Answer is: 2.2094E+209 } private static String formatToString(double d) { String num = Double.toString(d); String [] decimal = num.split("\\."); String [] eNum = num.split("E"); String output = decimal[0] + "."; char c[] = decimal[1].toCharArray(); for (int i = 0; i < 4; i++){ output += c[i]; } output += "E+" + eNum[1]; return output; } }
Igoranze/Martyrs-mega-project-list
tweakers-devv-contest/src/main/application/VraagQuattro.java
396
/** * De schimmel F. ellipsoidea wordt erg groot. De fibonacci reeks bepaald het aantal * centimeters dat de schimmel dagelijks in diameter toeneemt. * Bereken de omtrek van de schimmel na 1000 dagen groeien. * Antwoord in centimeters en gebruik de wetenschappelijke notatie, * rond af op 4 cijfers achter de komma, bijvoorbeeld: 1.0903E+231 */
block_comment
nl
package main.application; /** * De schimmel F.<SUF>*/ public class VraagQuattro { public static void main(String[] args) { double a = 0; double b = 1; double c = 0; double d = 2; for (int i = 3; i <= 1000; i++) { c = a + b; d += c; a = b; b = c; } System.out.println(formatToString(d*Math.PI)); //Answer is: 2.2094E+209 } private static String formatToString(double d) { String num = Double.toString(d); String [] decimal = num.split("\\."); String [] eNum = num.split("E"); String output = decimal[0] + "."; char c[] = decimal[1].toCharArray(); for (int i = 0; i < 4; i++){ output += c[i]; } output += "E+" + eNum[1]; return output; } }
True
False
1,989
396
117
83
405
135
97
376
101
61
405
135
97
439
125
85
false
true
false
true
false
false
3,128
13751_3
package afvink3; /** * Race class * Class Race maakt gebruik van de class Paard * * @author Martijn van der Bruggen * @version alpha - aanroep van cruciale methodes ontbreekt * (c) 2009 Hogeschool van Arnhem en Nijmegen * * Note: deze code is bewust niet op alle punten generiek * dit om nog onbekende constructies te vermijden. * * Updates * 2010: verduidelijking van opdrachten in de code MvdB * 2011: verbetering leesbaarheid code MvdB * 2012: verbetering layout code en aanpassing commentaar MvdB * 2013: commentaar aangepast aan nieuwe opdracht MvdB * ************************************************* * Afvinkopdracht: werken met methodes en objecten ************************************************* * Opdrachten zitten verwerkt in de code * 1) Declaratie constante * 2) Declaratie van Paard (niet instantiering) * 3) Declareer een button * 4) Zet breedte en hoogte van het frame * 5) Teken een finish streep * 6) Creatie van 4 paarden * 7) Pauzeer * 8) Teken 4 paarden * 9) Plaats tekst op de button * 10) Start de race, methode aanroep * * */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Race extends JFrame implements ActionListener { /** declaratie van variabelen */ /* (1) Declareer hier een constante int met de naam lengte en een waarde van 250 */ private final int lengte = 250; /* (2) Declareer hier h1, h2, h3, h4 van het type Paard * Deze paarden instantieer je later in het programma */ private Paard h1, h2, h3, h4, h5; /* (3) Declareer een button met de naam button van het type JButton */ private JPanel panel; private JButton button; /** Applicatie - main functie voor runnen applicatie */ public static void main(String[] args) { Race frame = new Race(); /* (4) Geef het frame een breedte van 400 en hoogte van 140 */ frame.setSize(400, 170); frame.createGUI(); frame.setVisible(true); } /** Loop de race */ private void startRace(Graphics g) { panel.setBackground(Color.white); /** Tekenen van de finish streep */ /* (5) Geef de finish streep een rode kleur */ /**(6) Creatie van 4 paarden * Dit is een instantiering van de 4 paard objecten * Bij de instantiering geef je de paarden een naam en een kleur mee * Kijk in de class Paard hoe je de paarden * kunt initialiseren. */ h1 = new Paard("Glitterhoof", Toolkit.getDefaultToolkit().getImage("src/afvink3/glit.jpg")); h2 = new Paard("Usain Bolt", Toolkit.getDefaultToolkit().getImage("src/afvink3/bolt.jpg")); h3 = new Paard("Konijn", Toolkit.getDefaultToolkit().getImage("src/afvink3/konijn.jpg")); h4 = new Paard("John", Toolkit.getDefaultToolkit().getImage("src/afvink3/paard2.jpg")); h5 = new Paard("Henk", Toolkit.getDefaultToolkit().getImage("src/afvink3/henk.jpg")); /** Loop tot een paard over de finish is*/ while (h1.getAfstand() < lengte && h2.getAfstand() < lengte && h3.getAfstand() < lengte && h4.getAfstand() < lengte && h5.getAfstand() < lengte) { g.setColor(Color.WHITE); g.fillRect(0, 0, 500, 500); g.setColor(Color.RED); g.fillRect(lengte, 0, 3, 130); h1.run(); h2.run(); h3.run(); h4.run(); h5.run(); /* (7) Voeg hier een aanroep van de methode pauzeer toe zodanig * dat er 1 seconde pauze is. De methode pauzeer is onderdeel * van deze class */ /* (8) Voeg hier code in om 4 paarden te tekenen die rennen * Dus een call van de methode tekenPaard */ tekenPaard(g, h1); tekenPaard(g, h2); tekenPaard(g, h3); tekenPaard(g, h4); tekenPaard(g, h5); pauzeer(1000); } /** Kijk welk paard gewonnen heeft */ if (h1.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h1.getNaam() + " gewonnen!"); } if (h2.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h2.getNaam() + " gewonnen!"); } if (h3.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h3.getNaam() + " gewonnen!"); } if (h4.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h4.getNaam() + " gewonnen!"); } if (h5.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h5.getNaam() + " gewonnen!"); } } /** Creatie van de GUI*/ private void createGUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); panel = new JPanel(); panel.setPreferredSize(new Dimension(300, 120)); panel.setBackground(Color.white); window.add(panel); /* (9) Zet hier de tekst Run! op de button */ button = new JButton("Run!"); window.add(button); button.addActionListener(this); } /** Teken het paard */ private void tekenPaard(Graphics g, Paard h) { if (h.getKleur() == null) { g.drawImage(h.getImage(), h.getAfstand(), 20 * h.getPaardNummer(), 15, 15, null); } else { g.setColor(h.getKleur()); g.fillRect(h.getAfstand(), 20 * h.getPaardNummer(), 15, 15); } } /** Actie indien de button geklikt is*/ public void actionPerformed(ActionEvent event) { Graphics paper = panel.getGraphics(); /* (10) Roep hier de methode startrace aan met de juiste parameterisering */ startRace (paper); } /** Pauzeer gedurende x millisecondes*/ public void pauzeer(int msec) { try { Thread.sleep(msec); } catch (InterruptedException e) { System.out.println("Pauze interruptie"); } } }
itbc-bin/1819-owe5a-afvinkopdracht3-Casvanrijbroek
afvink3/Race.java
2,009
/* (2) Declareer hier h1, h2, h3, h4 van het type Paard * Deze paarden instantieer je later in het programma */
block_comment
nl
package afvink3; /** * Race class * Class Race maakt gebruik van de class Paard * * @author Martijn van der Bruggen * @version alpha - aanroep van cruciale methodes ontbreekt * (c) 2009 Hogeschool van Arnhem en Nijmegen * * Note: deze code is bewust niet op alle punten generiek * dit om nog onbekende constructies te vermijden. * * Updates * 2010: verduidelijking van opdrachten in de code MvdB * 2011: verbetering leesbaarheid code MvdB * 2012: verbetering layout code en aanpassing commentaar MvdB * 2013: commentaar aangepast aan nieuwe opdracht MvdB * ************************************************* * Afvinkopdracht: werken met methodes en objecten ************************************************* * Opdrachten zitten verwerkt in de code * 1) Declaratie constante * 2) Declaratie van Paard (niet instantiering) * 3) Declareer een button * 4) Zet breedte en hoogte van het frame * 5) Teken een finish streep * 6) Creatie van 4 paarden * 7) Pauzeer * 8) Teken 4 paarden * 9) Plaats tekst op de button * 10) Start de race, methode aanroep * * */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Race extends JFrame implements ActionListener { /** declaratie van variabelen */ /* (1) Declareer hier een constante int met de naam lengte en een waarde van 250 */ private final int lengte = 250; /* (2) Declareer hier<SUF>*/ private Paard h1, h2, h3, h4, h5; /* (3) Declareer een button met de naam button van het type JButton */ private JPanel panel; private JButton button; /** Applicatie - main functie voor runnen applicatie */ public static void main(String[] args) { Race frame = new Race(); /* (4) Geef het frame een breedte van 400 en hoogte van 140 */ frame.setSize(400, 170); frame.createGUI(); frame.setVisible(true); } /** Loop de race */ private void startRace(Graphics g) { panel.setBackground(Color.white); /** Tekenen van de finish streep */ /* (5) Geef de finish streep een rode kleur */ /**(6) Creatie van 4 paarden * Dit is een instantiering van de 4 paard objecten * Bij de instantiering geef je de paarden een naam en een kleur mee * Kijk in de class Paard hoe je de paarden * kunt initialiseren. */ h1 = new Paard("Glitterhoof", Toolkit.getDefaultToolkit().getImage("src/afvink3/glit.jpg")); h2 = new Paard("Usain Bolt", Toolkit.getDefaultToolkit().getImage("src/afvink3/bolt.jpg")); h3 = new Paard("Konijn", Toolkit.getDefaultToolkit().getImage("src/afvink3/konijn.jpg")); h4 = new Paard("John", Toolkit.getDefaultToolkit().getImage("src/afvink3/paard2.jpg")); h5 = new Paard("Henk", Toolkit.getDefaultToolkit().getImage("src/afvink3/henk.jpg")); /** Loop tot een paard over de finish is*/ while (h1.getAfstand() < lengte && h2.getAfstand() < lengte && h3.getAfstand() < lengte && h4.getAfstand() < lengte && h5.getAfstand() < lengte) { g.setColor(Color.WHITE); g.fillRect(0, 0, 500, 500); g.setColor(Color.RED); g.fillRect(lengte, 0, 3, 130); h1.run(); h2.run(); h3.run(); h4.run(); h5.run(); /* (7) Voeg hier een aanroep van de methode pauzeer toe zodanig * dat er 1 seconde pauze is. De methode pauzeer is onderdeel * van deze class */ /* (8) Voeg hier code in om 4 paarden te tekenen die rennen * Dus een call van de methode tekenPaard */ tekenPaard(g, h1); tekenPaard(g, h2); tekenPaard(g, h3); tekenPaard(g, h4); tekenPaard(g, h5); pauzeer(1000); } /** Kijk welk paard gewonnen heeft */ if (h1.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h1.getNaam() + " gewonnen!"); } if (h2.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h2.getNaam() + " gewonnen!"); } if (h3.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h3.getNaam() + " gewonnen!"); } if (h4.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h4.getNaam() + " gewonnen!"); } if (h5.getAfstand() > lengte) { JOptionPane.showMessageDialog(null, h5.getNaam() + " gewonnen!"); } } /** Creatie van de GUI*/ private void createGUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); panel = new JPanel(); panel.setPreferredSize(new Dimension(300, 120)); panel.setBackground(Color.white); window.add(panel); /* (9) Zet hier de tekst Run! op de button */ button = new JButton("Run!"); window.add(button); button.addActionListener(this); } /** Teken het paard */ private void tekenPaard(Graphics g, Paard h) { if (h.getKleur() == null) { g.drawImage(h.getImage(), h.getAfstand(), 20 * h.getPaardNummer(), 15, 15, null); } else { g.setColor(h.getKleur()); g.fillRect(h.getAfstand(), 20 * h.getPaardNummer(), 15, 15); } } /** Actie indien de button geklikt is*/ public void actionPerformed(ActionEvent event) { Graphics paper = panel.getGraphics(); /* (10) Roep hier de methode startrace aan met de juiste parameterisering */ startRace (paper); } /** Pauzeer gedurende x millisecondes*/ public void pauzeer(int msec) { try { Thread.sleep(msec); } catch (InterruptedException e) { System.out.println("Pauze interruptie"); } } }
True
False
1,994
2,009
44
26
1,856
41
25
1,804
41
23
1,856
41
25
2,044
42
24
false
false
false
false
false
true
1,503
39015_0
/* - De private functies die doen een operatie van source naar destination, waarna destination de nieuwe fileWriter is. - De public tegenhangers kopieren de file naar een tijdelijke kopie, en doen de operatie daarna van de tijdelijke kopie naar de originele file, zodat de checkpointFile ongewijzigd blijft - init zorgt dat uiteindelijk de originele checkpointfile gebruikt wordt */ package ibis.satin.impl.checkPointing; import ibis.ipl.IbisIdentifier; import ibis.satin.impl.faultTolerance.GlobalResultTable; import ibis.satin.impl.spawnSync.ReturnRecord; import ibis.satin.impl.spawnSync.Stamp; import java.io.EOFException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.StreamCorruptedException; import java.util.ArrayList; import java.util.Set; import org.gridlab.gat.GAT; import org.gridlab.gat.GATContext; import org.gridlab.gat.URI; import org.gridlab.gat.io.File; import org.gridlab.gat.io.FileInputStream; import org.gridlab.gat.io.FileOutputStream; public class CheckpointFile { private String filename = null; private FileOutputStream fileStream = null; private ObjectOutputStream fileWriter = null; private ArrayList<Stamp> checkpoints = new ArrayList<Stamp>(); private long maxFileSize = 0; private boolean stopWriting = true; public CheckpointFile(String filename) { this(filename, 0); } public CheckpointFile(String filename, long maxFileSize) { this.filename = filename; this.maxFileSize = maxFileSize; } // when a global result table is passed, this function will insert // the results into the grt, and return the number of read checkpoints public int init(GlobalResultTable grt) { GATContext context = new GATContext(); try { File f = GAT.createFile(context, new URI(filename)); if (f.exists()) { if (maxFileSize > 0 && f.length() > maxFileSize) { restore(filename, filename + "_TMP", grt); compress(filename + "_TMP", filename); delete(filename + "_TMP"); } else { move(filename, filename + "_TMP"); restore(filename + "_TMP", filename, grt); delete(filename + "_TMP"); } } else { open(filename); } } catch (Exception e) { System.out.println("init calling fatal"); fatal(e); return checkpoints.size(); } stopWriting = false; return checkpoints.size(); } /** * Writes newCheckpoints to the checkpointFile and checks the filesize of * the checkpointfile for compression afterwards. Every exception is fatal * and results in no write-possibilities in the future whatsoever **/ public void write(ArrayList<Checkpoint> newCheckpoints) { if (stopWriting) { return; } if (fileStream == null || fileWriter == null) { return; } try { while (newCheckpoints.size() > 0) { Checkpoint cp = newCheckpoints.remove(0); fileWriter.writeObject(cp); if (cp == null) { System.out.println("OOPS2: cp = null"); } else if (cp.rr == null) { System.out.println("OOPS3: cp.rr = null"); } checkpoints.add(cp.rr.getStamp()); } } catch (IOException e) { System.out.println("iox while writing checkpoints: " + e); } try { GATContext context = new GATContext(); if (maxFileSize > 0 && GAT.createFile(context, new URI(filename)).length() > maxFileSize) { compress(); if (GAT.createFile(context, new URI(filename)).length() > maxFileSize) { System.out .println("compression resulted in too big file. Checkpointing aborted"); stopWriting = true; } } } catch (Exception e) { System.out.println("write calling fatal"); fatal(e); } } /** * Retrieves all the checkpoints which belonged to 'id' from the * checkpoint-file and stores them in 'grt'. if id == null, all checkpoints * belonging to any node will be stored in 'grt.' */ public int read(Set<IbisIdentifier> id, GlobalResultTable grt) { int result = 0; FileInputStream tempInputFile = null; ObjectInputStream tempReader = null; try { GATContext context = new GATContext(); tempInputFile = GAT.createFileInputStream(context, new URI(filename)); tempReader = new ObjectInputStream(tempInputFile); while (tempInputFile.available() > 0) { Checkpoint cp = (Checkpoint) tempReader.readObject(); if (id == null || id.contains(cp.sender)) { ReturnRecord record = cp.rr; synchronized (grt.s) { grt.storeResult(record); } result++; } } } catch (Exception e) { System.out.println("[CheckpointFile|read] exception: " + e); } try { tempInputFile.close(); tempReader.close(); } catch (Exception e) { } return result; } /** * Tries to compress the checkpointfile. Every exception is fatal and * results in no write-possibilities in the future whatsoever **/ public void compress() { if (fileStream == null || fileWriter == null) { return; } try { close(); move(filename, filename + "_TMP"); compress(filename + "_TMP", filename); delete(filename + "_TMP"); } catch (Exception e) { System.out.println("compress calling fatal"); fatal(e); } } /** * Tries to restore the old checkpointFile. Every Exception is fatal and * leads to no write-possibiliets in the future whatsoever **/ public void restore(GlobalResultTable grt) { if (fileStream == null || fileWriter == null) { return; } try { close(); move(filename, filename + "_TMP"); restore(filename + "_TMP", filename, grt); delete(filename + "_TMP"); } catch (Exception e) { System.out.println("restore calling fatal"); fatal(e); } } /** * First finds all the checkpoints which don't have any parents which are * also available, and copies only these checkpoints to dest. **/ private void compress(String source, String dest) throws Exception { // find out which checkpoints are needed int i = 0; while (i < checkpoints.size()) { int j = i + 1; Stamp stamp1 = checkpoints.get(i); if (stamp1 == null) { checkpoints.remove(i); continue; } while (j < checkpoints.size()) { Stamp stamp2 = checkpoints.get(j); // stamp2 can be removed if it is null, equal to stamp1, // or a descendent of stamp1. if (stamp2 == null || stamp2.equals(stamp1) || stamp2.isDescendentOf(stamp1)) { checkpoints.remove(j); continue; } // stamp1 can be removed if it is a descendent of stamp2. if (stamp1.isDescendentOf(stamp2)) { checkpoints.remove(i); i--; break; } j++; } i++; } // write these checkpoints to the file 'dest' FileOutputStream tempOutputFile = null; ; ObjectOutputStream tempWriter = null; FileInputStream tempInputFile = null; ObjectInputStream tempReader = null; GATContext context = new GATContext(); tempOutputFile = GAT.createFileOutputStream(context, new URI(dest), false); tempWriter = new ObjectOutputStream(tempOutputFile); tempInputFile = GAT.createFileInputStream(context, new URI(source)); tempReader = new ObjectInputStream(tempInputFile); i = 0; while (tempInputFile.available() > 0) { Checkpoint cp = (Checkpoint) tempReader.readObject(); if (cp.rr.getStamp().stampEquals(checkpoints.get(i))) { tempWriter.writeObject(cp); } i++; } try { fileStream.close(); fileWriter.close(); tempInputFile.close(); tempReader.close(); } catch (Exception e) { } // make 'dest' the checkpointFile fileStream = tempOutputFile; fileWriter = tempWriter; } /** * Copies all the objects from the old checkpointfile to the new copy until * a StreamCorruptedException occurs. Everything that was written after this * points is lost. **/ private void restore(String source, String dest, GlobalResultTable grt) throws Exception { FileOutputStream tempOutputFile = null; ObjectOutputStream tempWriter = null; FileInputStream tempInputFile = null; ObjectInputStream tempReader = null; try { GATContext context = new GATContext(); tempOutputFile = GAT.createFileOutputStream(context, new URI(dest), false); tempWriter = new ObjectOutputStream(tempOutputFile); tempInputFile = GAT.createFileInputStream(context, new URI(source)); tempReader = new ObjectInputStream(tempInputFile); checkpoints = new ArrayList<Stamp>(); while (tempInputFile.available() > 0) { Checkpoint cp = (Checkpoint) tempReader.readObject(); tempWriter.writeObject(cp); tempWriter.flush(); if (grt != null) { synchronized (grt.s) { grt.storeResult(cp.rr); } // propagate updates after every 1000 updates try { if (checkpoints.size() % 1000 == 999) { long begin = System.currentTimeMillis(); grt.sendUpdates(); long end = System.currentTimeMillis(); System.out.println("update took " + (end - begin) + " ms"); } } catch (Exception e) { // nullpointerException if !GRT_MESSAGE_COMBINING } } checkpoints.add(cp.rr.getStamp()); } } catch (StreamCorruptedException e) { System.out.println("restored " + checkpoints.size() + " from a corrupted checkpoint file"); } catch (EOFException e) { System.out.println("restored " + checkpoints.size() + " from a corrupted checkpoint file"); } try { fileStream.close(); fileWriter.close(); tempInputFile.close(); tempReader.close(); } catch (Exception e) { } fileStream = tempOutputFile; fileWriter = tempWriter; } /** * Tries to delete the file filename **/ private void delete(String filename) { try { GATContext context = new GATContext(); GAT.createFile(context, new URI(filename)).delete(); } catch (Exception e) { } } /** * Moves the file source to dest **/ private void move(String source, String dest) throws Exception { GATContext context = new GATContext(); GAT.createFile(context, new URI(source)).move(new URI(dest)); } /** * Tries to open filename, so that it will be used for future * write-operations **/ private void open(String filename) throws Exception { GATContext context = new GATContext(); fileStream = GAT.createFileOutputStream(context, new URI(filename), false); fileWriter = new ObjectOutputStream(fileStream); } /** * Prints Exception e, closes all streams and deletes all temporary files. * Cosequently, all future write-operations will fail. The read-operations * might still succeed if fatal wasn't called on a moment the original file * (i.e. filename) didn't exist **/ private void fatal(Exception e) { System.out.println("CheckpointFile: Fatal Exception: " + e); e.printStackTrace(System.out); close(); delete(filename + "_TMP"); fileStream = null; fileWriter = null; stopWriting = true; } public void close() { try { fileWriter.close(); fileStream.close(); } catch (Exception e) { } } }
RvanNieuwpoort/satin
src/main/java/ibis/satin/impl/checkPointing/CheckpointFile.java
3,558
/* - De private functies die doen een operatie van source naar destination, waarna destination de nieuwe fileWriter is. - De public tegenhangers kopieren de file naar een tijdelijke kopie, en doen de operatie daarna van de tijdelijke kopie naar de originele file, zodat de checkpointFile ongewijzigd blijft - init zorgt dat uiteindelijk de originele checkpointfile gebruikt wordt */
block_comment
nl
/* - De private<SUF>*/ package ibis.satin.impl.checkPointing; import ibis.ipl.IbisIdentifier; import ibis.satin.impl.faultTolerance.GlobalResultTable; import ibis.satin.impl.spawnSync.ReturnRecord; import ibis.satin.impl.spawnSync.Stamp; import java.io.EOFException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.StreamCorruptedException; import java.util.ArrayList; import java.util.Set; import org.gridlab.gat.GAT; import org.gridlab.gat.GATContext; import org.gridlab.gat.URI; import org.gridlab.gat.io.File; import org.gridlab.gat.io.FileInputStream; import org.gridlab.gat.io.FileOutputStream; public class CheckpointFile { private String filename = null; private FileOutputStream fileStream = null; private ObjectOutputStream fileWriter = null; private ArrayList<Stamp> checkpoints = new ArrayList<Stamp>(); private long maxFileSize = 0; private boolean stopWriting = true; public CheckpointFile(String filename) { this(filename, 0); } public CheckpointFile(String filename, long maxFileSize) { this.filename = filename; this.maxFileSize = maxFileSize; } // when a global result table is passed, this function will insert // the results into the grt, and return the number of read checkpoints public int init(GlobalResultTable grt) { GATContext context = new GATContext(); try { File f = GAT.createFile(context, new URI(filename)); if (f.exists()) { if (maxFileSize > 0 && f.length() > maxFileSize) { restore(filename, filename + "_TMP", grt); compress(filename + "_TMP", filename); delete(filename + "_TMP"); } else { move(filename, filename + "_TMP"); restore(filename + "_TMP", filename, grt); delete(filename + "_TMP"); } } else { open(filename); } } catch (Exception e) { System.out.println("init calling fatal"); fatal(e); return checkpoints.size(); } stopWriting = false; return checkpoints.size(); } /** * Writes newCheckpoints to the checkpointFile and checks the filesize of * the checkpointfile for compression afterwards. Every exception is fatal * and results in no write-possibilities in the future whatsoever **/ public void write(ArrayList<Checkpoint> newCheckpoints) { if (stopWriting) { return; } if (fileStream == null || fileWriter == null) { return; } try { while (newCheckpoints.size() > 0) { Checkpoint cp = newCheckpoints.remove(0); fileWriter.writeObject(cp); if (cp == null) { System.out.println("OOPS2: cp = null"); } else if (cp.rr == null) { System.out.println("OOPS3: cp.rr = null"); } checkpoints.add(cp.rr.getStamp()); } } catch (IOException e) { System.out.println("iox while writing checkpoints: " + e); } try { GATContext context = new GATContext(); if (maxFileSize > 0 && GAT.createFile(context, new URI(filename)).length() > maxFileSize) { compress(); if (GAT.createFile(context, new URI(filename)).length() > maxFileSize) { System.out .println("compression resulted in too big file. Checkpointing aborted"); stopWriting = true; } } } catch (Exception e) { System.out.println("write calling fatal"); fatal(e); } } /** * Retrieves all the checkpoints which belonged to 'id' from the * checkpoint-file and stores them in 'grt'. if id == null, all checkpoints * belonging to any node will be stored in 'grt.' */ public int read(Set<IbisIdentifier> id, GlobalResultTable grt) { int result = 0; FileInputStream tempInputFile = null; ObjectInputStream tempReader = null; try { GATContext context = new GATContext(); tempInputFile = GAT.createFileInputStream(context, new URI(filename)); tempReader = new ObjectInputStream(tempInputFile); while (tempInputFile.available() > 0) { Checkpoint cp = (Checkpoint) tempReader.readObject(); if (id == null || id.contains(cp.sender)) { ReturnRecord record = cp.rr; synchronized (grt.s) { grt.storeResult(record); } result++; } } } catch (Exception e) { System.out.println("[CheckpointFile|read] exception: " + e); } try { tempInputFile.close(); tempReader.close(); } catch (Exception e) { } return result; } /** * Tries to compress the checkpointfile. Every exception is fatal and * results in no write-possibilities in the future whatsoever **/ public void compress() { if (fileStream == null || fileWriter == null) { return; } try { close(); move(filename, filename + "_TMP"); compress(filename + "_TMP", filename); delete(filename + "_TMP"); } catch (Exception e) { System.out.println("compress calling fatal"); fatal(e); } } /** * Tries to restore the old checkpointFile. Every Exception is fatal and * leads to no write-possibiliets in the future whatsoever **/ public void restore(GlobalResultTable grt) { if (fileStream == null || fileWriter == null) { return; } try { close(); move(filename, filename + "_TMP"); restore(filename + "_TMP", filename, grt); delete(filename + "_TMP"); } catch (Exception e) { System.out.println("restore calling fatal"); fatal(e); } } /** * First finds all the checkpoints which don't have any parents which are * also available, and copies only these checkpoints to dest. **/ private void compress(String source, String dest) throws Exception { // find out which checkpoints are needed int i = 0; while (i < checkpoints.size()) { int j = i + 1; Stamp stamp1 = checkpoints.get(i); if (stamp1 == null) { checkpoints.remove(i); continue; } while (j < checkpoints.size()) { Stamp stamp2 = checkpoints.get(j); // stamp2 can be removed if it is null, equal to stamp1, // or a descendent of stamp1. if (stamp2 == null || stamp2.equals(stamp1) || stamp2.isDescendentOf(stamp1)) { checkpoints.remove(j); continue; } // stamp1 can be removed if it is a descendent of stamp2. if (stamp1.isDescendentOf(stamp2)) { checkpoints.remove(i); i--; break; } j++; } i++; } // write these checkpoints to the file 'dest' FileOutputStream tempOutputFile = null; ; ObjectOutputStream tempWriter = null; FileInputStream tempInputFile = null; ObjectInputStream tempReader = null; GATContext context = new GATContext(); tempOutputFile = GAT.createFileOutputStream(context, new URI(dest), false); tempWriter = new ObjectOutputStream(tempOutputFile); tempInputFile = GAT.createFileInputStream(context, new URI(source)); tempReader = new ObjectInputStream(tempInputFile); i = 0; while (tempInputFile.available() > 0) { Checkpoint cp = (Checkpoint) tempReader.readObject(); if (cp.rr.getStamp().stampEquals(checkpoints.get(i))) { tempWriter.writeObject(cp); } i++; } try { fileStream.close(); fileWriter.close(); tempInputFile.close(); tempReader.close(); } catch (Exception e) { } // make 'dest' the checkpointFile fileStream = tempOutputFile; fileWriter = tempWriter; } /** * Copies all the objects from the old checkpointfile to the new copy until * a StreamCorruptedException occurs. Everything that was written after this * points is lost. **/ private void restore(String source, String dest, GlobalResultTable grt) throws Exception { FileOutputStream tempOutputFile = null; ObjectOutputStream tempWriter = null; FileInputStream tempInputFile = null; ObjectInputStream tempReader = null; try { GATContext context = new GATContext(); tempOutputFile = GAT.createFileOutputStream(context, new URI(dest), false); tempWriter = new ObjectOutputStream(tempOutputFile); tempInputFile = GAT.createFileInputStream(context, new URI(source)); tempReader = new ObjectInputStream(tempInputFile); checkpoints = new ArrayList<Stamp>(); while (tempInputFile.available() > 0) { Checkpoint cp = (Checkpoint) tempReader.readObject(); tempWriter.writeObject(cp); tempWriter.flush(); if (grt != null) { synchronized (grt.s) { grt.storeResult(cp.rr); } // propagate updates after every 1000 updates try { if (checkpoints.size() % 1000 == 999) { long begin = System.currentTimeMillis(); grt.sendUpdates(); long end = System.currentTimeMillis(); System.out.println("update took " + (end - begin) + " ms"); } } catch (Exception e) { // nullpointerException if !GRT_MESSAGE_COMBINING } } checkpoints.add(cp.rr.getStamp()); } } catch (StreamCorruptedException e) { System.out.println("restored " + checkpoints.size() + " from a corrupted checkpoint file"); } catch (EOFException e) { System.out.println("restored " + checkpoints.size() + " from a corrupted checkpoint file"); } try { fileStream.close(); fileWriter.close(); tempInputFile.close(); tempReader.close(); } catch (Exception e) { } fileStream = tempOutputFile; fileWriter = tempWriter; } /** * Tries to delete the file filename **/ private void delete(String filename) { try { GATContext context = new GATContext(); GAT.createFile(context, new URI(filename)).delete(); } catch (Exception e) { } } /** * Moves the file source to dest **/ private void move(String source, String dest) throws Exception { GATContext context = new GATContext(); GAT.createFile(context, new URI(source)).move(new URI(dest)); } /** * Tries to open filename, so that it will be used for future * write-operations **/ private void open(String filename) throws Exception { GATContext context = new GATContext(); fileStream = GAT.createFileOutputStream(context, new URI(filename), false); fileWriter = new ObjectOutputStream(fileStream); } /** * Prints Exception e, closes all streams and deletes all temporary files. * Cosequently, all future write-operations will fail. The read-operations * might still succeed if fatal wasn't called on a moment the original file * (i.e. filename) didn't exist **/ private void fatal(Exception e) { System.out.println("CheckpointFile: Fatal Exception: " + e); e.printStackTrace(System.out); close(); delete(filename + "_TMP"); fileStream = null; fileWriter = null; stopWriting = true; } public void close() { try { fileWriter.close(); fileStream.close(); } catch (Exception e) { } } }
True
False
1,995
3,558
119
93
3,106
116
99
3,302
101
75
3,106
116
99
3,655
118
92
false
false
false
false
false
true
1,610
122913_5
package be.uantwerpen.sc.controllers.mqtt; import be.uantwerpen.sc.services.JobService; import be.uantwerpen.sc.tools.Terminal; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by Thomas on 01/06/2016. */ /* Class waar de berichten van de mqtt worden opgevangen */ public class MqttJobSubscriberCallback implements MqttCallback { private Logger logger = LoggerFactory.getLogger(MqttJobSubscriberCallback.class); private JobService jobService; private MqttJobSubscriber subscriber; public MqttJobSubscriberCallback(MqttJobSubscriber subscriber, JobService jobService) { this.subscriber = subscriber; this.jobService = jobService; } @Override public void connectionLost(Throwable cause) { //This is called when the connection is lost. We could reconnect here. logger.error("connection lost to mqtt broker"); } //bericht wordt ontvangen @Override public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception { //TODO Process message logger.info("mqtt message ontvangen"); logger.info("Topic: " + topic + ", Message: " + mqttMessage); String payloadString = new String(mqttMessage.getPayload()); logger.info("payload = " + payloadString); try { jobService.parseJob(payloadString); //ontvangen bericht toevoegen aan de jobs } catch(Exception e) { System.err.println("Could not parse job from message: " + payloadString); System.err.println(e.getMessage()); } } @Override public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { } }
SmartCity-UAntwerpen/RobotCore
src/main/java/be/uantwerpen/sc/controllers/mqtt/MqttJobSubscriberCallback.java
579
//ontvangen bericht toevoegen aan de jobs
line_comment
nl
package be.uantwerpen.sc.controllers.mqtt; import be.uantwerpen.sc.services.JobService; import be.uantwerpen.sc.tools.Terminal; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by Thomas on 01/06/2016. */ /* Class waar de berichten van de mqtt worden opgevangen */ public class MqttJobSubscriberCallback implements MqttCallback { private Logger logger = LoggerFactory.getLogger(MqttJobSubscriberCallback.class); private JobService jobService; private MqttJobSubscriber subscriber; public MqttJobSubscriberCallback(MqttJobSubscriber subscriber, JobService jobService) { this.subscriber = subscriber; this.jobService = jobService; } @Override public void connectionLost(Throwable cause) { //This is called when the connection is lost. We could reconnect here. logger.error("connection lost to mqtt broker"); } //bericht wordt ontvangen @Override public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception { //TODO Process message logger.info("mqtt message ontvangen"); logger.info("Topic: " + topic + ", Message: " + mqttMessage); String payloadString = new String(mqttMessage.getPayload()); logger.info("payload = " + payloadString); try { jobService.parseJob(payloadString); //ontvangen bericht<SUF> } catch(Exception e) { System.err.println("Could not parse job from message: " + payloadString); System.err.println(e.getMessage()); } } @Override public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { } }
True
False
1,996
579
12
11
482
14
13
496
9
8
482
14
13
586
12
11
false
false
false
false
false
true
2,290
58043_6
/* * This file is part of wegenenverkeer common-resteasy. * Copyright (c) AWV Agentschap Wegen en Verkeer, Vlaamse Gemeenschap * The program is available in open source according to the Apache License, Version 2.0. * For full licensing details, see LICENSE.txt in the project root. */ package be.wegenenverkeer.common.resteasy.logging; import be.eliwan.profiling.api.ProfilingSink; import be.wegenenverkeer.common.resteasy.exception.AbstractRestException; import be.wegenenverkeer.common.resteasy.exception.ExceptionUtil; import be.wegenenverkeer.common.resteasy.exception.ServiceException; import be.wegenenverkeer.common.resteasy.json.InputStreamSerializer; import be.wegenenverkeer.common.resteasy.json.RestJsonMapper; import org.jboss.resteasy.annotations.interception.ServerInterceptor; import org.jboss.resteasy.core.ResourceMethodInvoker; import org.jboss.resteasy.core.ServerResponse; import org.jboss.resteasy.spi.Failure; import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.interception.MessageBodyReaderContext; import org.jboss.resteasy.spi.interception.MessageBodyReaderInterceptor; import org.jboss.resteasy.spi.interception.PostProcessInterceptor; import org.jboss.resteasy.spi.interception.PreProcessInterceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.util.List; import java.util.Map; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.Provider; /** * Deze klasse is een resteasy interceptor die zichzelf tevens exposed als een spring-bean. De interceptor haakt * zichzelf voor en na elke call en realiseert degelijke logging van elke call waarbij getracht wordt data van * verschillende stadia van de executie van eenzelfde request samen te houden in het kader van concurrent logs. De * interceptor kan gebruikt worden als logger voor servicecode: de logging van de gebruiker wordt dan mee in de output * van deze logger gestopt. */ @Provider @Component("loggerInterceptor") @ServerInterceptor public class PreProcessLoggingInterceptor implements InitializingBean, PreProcessInterceptor, MessageBodyReaderInterceptor, PostProcessInterceptor { private static final Logger LOG = LoggerFactory.getLogger(PreProcessLoggingInterceptor.class); private static final RestJsonMapper MAPPER = new RestJsonMapper(); private static final String NEWLINE = "\n"; private static final String INDENT = "\n\t"; private static final String ARROW = " -> "; private static final ThreadLocal<StringBuilder> STRING_BUILDER = new ThreadLocal<>(); /** * String indicating the grouping for the profiling. Each service handled independently.. */ public static final ThreadLocal<String> PROFILE_GROUP = new ThreadLocal<>(); /** * Service request URL. */ public static final ThreadLocal<Long> START_MOMENT = new ThreadLocal<>(); @Autowired(required = false) @Qualifier("restProfilingRegistrar") private ProfilingSink profilingContainer = (group, duration) -> { // do nothing }; @Override public void afterPropertiesSet() throws Exception { MAPPER.addClassSerializer(InputStream.class, new InputStreamSerializer()); } /** * Implementatie van de PreProcessInterceptor interface. * * @param request De request * @param method De method * @return De server response * @throws Failure De failure exception * @throws WebApplicationException De web application exception */ @Override public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException { START_MOMENT.set(System.currentTimeMillis()); PROFILE_GROUP.set(method.getMethod().getDeclaringClass().getSimpleName() + ":" + method.getMethod().getName()); STRING_BUILDER.set(new StringBuilder("Service: ")); StringBuilder sb = STRING_BUILDER.get(); sb.append(request.getHttpMethod()); sb.append(' '); sb.append(request.getUri().getAbsolutePath().toASCIIString()); // log HTTP request headers sb.append("\nHTTP request headers:"); for (Map.Entry<String, List<String>> entry : request.getHttpHeaders().getRequestHeaders().entrySet()) { sb.append("\n ").append(entry.getKey()).append(": "); String sep = ""; for (String s : entry.getValue()) { sb.append(sep); sep = ", "; sb.append(s); } } if (null != method.getConsumes()) { sb.append("\nRequest types"); for (MediaType mediaType : method.getConsumes()) { sb.append(' ').append(mediaType.toString()); } } if (null != method.getProduces()) { sb.append("\nResponse types"); for (MediaType mediaType : method.getProduces()) { sb.append(' ').append(mediaType.toString()); } } sb.append("\nCookies: "); Map<String, Cookie> cookies = request.getHttpHeaders().getCookies(); for (Map.Entry<String, Cookie> entry : cookies.entrySet()) { sb.append(INDENT); sb.append(entry.getKey()); sb.append(ARROW); sb.append(entry.getValue()); } sb.append("\nQuery Parameters: "); MultivaluedMap<String, String> params = request.getUri().getQueryParameters(); for (Map.Entry<String, List<String>> entry : params.entrySet()) { sb.append(INDENT); sb.append(entry.getKey()); sb.append(ARROW); sb.append(entry.getValue()); } sb.append("\nPath parameters: "); MultivaluedMap<String, String> pathParams = request.getUri().getPathParameters(); for (Map.Entry<String, List<String>> entry : pathParams.entrySet()) { sb.append(INDENT); sb.append(entry.getKey()); sb.append(ARROW); sb.append(entry.getValue()); } return null; } /** * Implementatie van de MessageBodyReaderInterceptor interface. * * @param context de service context * @return deze methode geeft gewoon het antwoord van de volgende reader in de chain terug * @throws IOException indien de vorige reader deze exception gooit */ @Override public Object read(MessageBodyReaderContext context) throws IOException { Object result = context.proceed(); StringBuilder sb = STRING_BUILDER.get(); sb.append("\nDocument body type: ").append(result.getClass().toString()); sb.append("\nDocument content:\n"); if (result.getClass().isAnnotationPresent(DoNotLog.class)) { sb.append("<Not serialized " + result.getClass().toString() + ">"); } else if (result.getClass().isAnnotationPresent(LogUsingToString.class)) { sb.append(result.toString()); } else { sb.append(MAPPER.writeValueAsString(result)); } return result; } /** * Implementatie van de PostProcessInterceptor interface. * * @param response server response */ @Override public void postProcess(ServerResponse response) { StringBuilder sb = STRING_BUILDER.get(); if (null == sb) { sb = new StringBuilder(); STRING_BUILDER.set(sb); } Object result = response.getEntity(); if (result != null) { sb.append("\nReply type: "); sb.append(result.getClass().toString()); sb.append("\nOutput document:\n"); try { if (result.getClass().isAnnotationPresent(DoNotLog.class)) { sb.append("<Not serialized " + result.getClass().toString() + ">"); } else if (contains(response.getAnnotations(), DoNotLogResponse.class)) { sb.append(String.format("<Not serialized response from method '%s>", PROFILE_GROUP.get())); } else if (result.getClass().isAnnotationPresent(LogUsingToString.class)) { sb.append(result.toString()); } else if (result instanceof String) { sb.append(result); } else { String output = MAPPER.writeValueAsString(result); sb.append(output); } } catch (IOException e) { LOG.warn("JSON probleem met " + result, e); } } finishCall(false); } /** * Afsluitende logging in geval van een error. * * @param exception te loggen fout * @param msg boodschap */ public void postProcessError(Exception exception, String msg) { StringBuilder sb = STRING_BUILDER.get(); if (null == sb) { sb = new StringBuilder(); STRING_BUILDER.set(sb); } sb.append("\nOOPS: ").append(msg).append(NEWLINE); ExceptionUtil eu = new ExceptionUtil(exception); if (exception instanceof AbstractRestException && !(exception instanceof ServiceException)) { // no stack trace, log at info level finishCall(false); } else { sb.append(eu.getStackTrace()); finishCall(true); } } private void finishCall(boolean isError) { StringBuilder sb = STRING_BUILDER.get(); long now = System.currentTimeMillis(); Long start = START_MOMENT.get(); if (null != start) { long time = now - start; profilingContainer.register(PROFILE_GROUP.get(), time); sb.append(String.format("%nDuur: %.3fs", time / 1000.0)); } else { sb.append("\nDuur: Onbekend, kan starttijd niet bepalen."); } if (isError) { LOG.error(sb.toString()); } else { LOG.info(sb.toString()); } PROFILE_GROUP.remove(); START_MOMENT.remove(); STRING_BUILDER.remove(); } private boolean contains(Annotation[] list, Class<?> annotation) { if (null != list) { for (Annotation test : list) { if (annotation.isAssignableFrom(test.getClass())) { return true; } } } return false; } }
bramp/common-resteasy
resteasy/src/main/java/be/wegenenverkeer/common/resteasy/logging/PreProcessLoggingInterceptor.java
2,965
/** * Implementatie van de MessageBodyReaderInterceptor interface. * * @param context de service context * @return deze methode geeft gewoon het antwoord van de volgende reader in de chain terug * @throws IOException indien de vorige reader deze exception gooit */
block_comment
nl
/* * This file is part of wegenenverkeer common-resteasy. * Copyright (c) AWV Agentschap Wegen en Verkeer, Vlaamse Gemeenschap * The program is available in open source according to the Apache License, Version 2.0. * For full licensing details, see LICENSE.txt in the project root. */ package be.wegenenverkeer.common.resteasy.logging; import be.eliwan.profiling.api.ProfilingSink; import be.wegenenverkeer.common.resteasy.exception.AbstractRestException; import be.wegenenverkeer.common.resteasy.exception.ExceptionUtil; import be.wegenenverkeer.common.resteasy.exception.ServiceException; import be.wegenenverkeer.common.resteasy.json.InputStreamSerializer; import be.wegenenverkeer.common.resteasy.json.RestJsonMapper; import org.jboss.resteasy.annotations.interception.ServerInterceptor; import org.jboss.resteasy.core.ResourceMethodInvoker; import org.jboss.resteasy.core.ServerResponse; import org.jboss.resteasy.spi.Failure; import org.jboss.resteasy.spi.HttpRequest; import org.jboss.resteasy.spi.interception.MessageBodyReaderContext; import org.jboss.resteasy.spi.interception.MessageBodyReaderInterceptor; import org.jboss.resteasy.spi.interception.PostProcessInterceptor; import org.jboss.resteasy.spi.interception.PreProcessInterceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.util.List; import java.util.Map; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.Provider; /** * Deze klasse is een resteasy interceptor die zichzelf tevens exposed als een spring-bean. De interceptor haakt * zichzelf voor en na elke call en realiseert degelijke logging van elke call waarbij getracht wordt data van * verschillende stadia van de executie van eenzelfde request samen te houden in het kader van concurrent logs. De * interceptor kan gebruikt worden als logger voor servicecode: de logging van de gebruiker wordt dan mee in de output * van deze logger gestopt. */ @Provider @Component("loggerInterceptor") @ServerInterceptor public class PreProcessLoggingInterceptor implements InitializingBean, PreProcessInterceptor, MessageBodyReaderInterceptor, PostProcessInterceptor { private static final Logger LOG = LoggerFactory.getLogger(PreProcessLoggingInterceptor.class); private static final RestJsonMapper MAPPER = new RestJsonMapper(); private static final String NEWLINE = "\n"; private static final String INDENT = "\n\t"; private static final String ARROW = " -> "; private static final ThreadLocal<StringBuilder> STRING_BUILDER = new ThreadLocal<>(); /** * String indicating the grouping for the profiling. Each service handled independently.. */ public static final ThreadLocal<String> PROFILE_GROUP = new ThreadLocal<>(); /** * Service request URL. */ public static final ThreadLocal<Long> START_MOMENT = new ThreadLocal<>(); @Autowired(required = false) @Qualifier("restProfilingRegistrar") private ProfilingSink profilingContainer = (group, duration) -> { // do nothing }; @Override public void afterPropertiesSet() throws Exception { MAPPER.addClassSerializer(InputStream.class, new InputStreamSerializer()); } /** * Implementatie van de PreProcessInterceptor interface. * * @param request De request * @param method De method * @return De server response * @throws Failure De failure exception * @throws WebApplicationException De web application exception */ @Override public ServerResponse preProcess(HttpRequest request, ResourceMethodInvoker method) throws Failure, WebApplicationException { START_MOMENT.set(System.currentTimeMillis()); PROFILE_GROUP.set(method.getMethod().getDeclaringClass().getSimpleName() + ":" + method.getMethod().getName()); STRING_BUILDER.set(new StringBuilder("Service: ")); StringBuilder sb = STRING_BUILDER.get(); sb.append(request.getHttpMethod()); sb.append(' '); sb.append(request.getUri().getAbsolutePath().toASCIIString()); // log HTTP request headers sb.append("\nHTTP request headers:"); for (Map.Entry<String, List<String>> entry : request.getHttpHeaders().getRequestHeaders().entrySet()) { sb.append("\n ").append(entry.getKey()).append(": "); String sep = ""; for (String s : entry.getValue()) { sb.append(sep); sep = ", "; sb.append(s); } } if (null != method.getConsumes()) { sb.append("\nRequest types"); for (MediaType mediaType : method.getConsumes()) { sb.append(' ').append(mediaType.toString()); } } if (null != method.getProduces()) { sb.append("\nResponse types"); for (MediaType mediaType : method.getProduces()) { sb.append(' ').append(mediaType.toString()); } } sb.append("\nCookies: "); Map<String, Cookie> cookies = request.getHttpHeaders().getCookies(); for (Map.Entry<String, Cookie> entry : cookies.entrySet()) { sb.append(INDENT); sb.append(entry.getKey()); sb.append(ARROW); sb.append(entry.getValue()); } sb.append("\nQuery Parameters: "); MultivaluedMap<String, String> params = request.getUri().getQueryParameters(); for (Map.Entry<String, List<String>> entry : params.entrySet()) { sb.append(INDENT); sb.append(entry.getKey()); sb.append(ARROW); sb.append(entry.getValue()); } sb.append("\nPath parameters: "); MultivaluedMap<String, String> pathParams = request.getUri().getPathParameters(); for (Map.Entry<String, List<String>> entry : pathParams.entrySet()) { sb.append(INDENT); sb.append(entry.getKey()); sb.append(ARROW); sb.append(entry.getValue()); } return null; } /** * Implementatie van de<SUF>*/ @Override public Object read(MessageBodyReaderContext context) throws IOException { Object result = context.proceed(); StringBuilder sb = STRING_BUILDER.get(); sb.append("\nDocument body type: ").append(result.getClass().toString()); sb.append("\nDocument content:\n"); if (result.getClass().isAnnotationPresent(DoNotLog.class)) { sb.append("<Not serialized " + result.getClass().toString() + ">"); } else if (result.getClass().isAnnotationPresent(LogUsingToString.class)) { sb.append(result.toString()); } else { sb.append(MAPPER.writeValueAsString(result)); } return result; } /** * Implementatie van de PostProcessInterceptor interface. * * @param response server response */ @Override public void postProcess(ServerResponse response) { StringBuilder sb = STRING_BUILDER.get(); if (null == sb) { sb = new StringBuilder(); STRING_BUILDER.set(sb); } Object result = response.getEntity(); if (result != null) { sb.append("\nReply type: "); sb.append(result.getClass().toString()); sb.append("\nOutput document:\n"); try { if (result.getClass().isAnnotationPresent(DoNotLog.class)) { sb.append("<Not serialized " + result.getClass().toString() + ">"); } else if (contains(response.getAnnotations(), DoNotLogResponse.class)) { sb.append(String.format("<Not serialized response from method '%s>", PROFILE_GROUP.get())); } else if (result.getClass().isAnnotationPresent(LogUsingToString.class)) { sb.append(result.toString()); } else if (result instanceof String) { sb.append(result); } else { String output = MAPPER.writeValueAsString(result); sb.append(output); } } catch (IOException e) { LOG.warn("JSON probleem met " + result, e); } } finishCall(false); } /** * Afsluitende logging in geval van een error. * * @param exception te loggen fout * @param msg boodschap */ public void postProcessError(Exception exception, String msg) { StringBuilder sb = STRING_BUILDER.get(); if (null == sb) { sb = new StringBuilder(); STRING_BUILDER.set(sb); } sb.append("\nOOPS: ").append(msg).append(NEWLINE); ExceptionUtil eu = new ExceptionUtil(exception); if (exception instanceof AbstractRestException && !(exception instanceof ServiceException)) { // no stack trace, log at info level finishCall(false); } else { sb.append(eu.getStackTrace()); finishCall(true); } } private void finishCall(boolean isError) { StringBuilder sb = STRING_BUILDER.get(); long now = System.currentTimeMillis(); Long start = START_MOMENT.get(); if (null != start) { long time = now - start; profilingContainer.register(PROFILE_GROUP.get(), time); sb.append(String.format("%nDuur: %.3fs", time / 1000.0)); } else { sb.append("\nDuur: Onbekend, kan starttijd niet bepalen."); } if (isError) { LOG.error(sb.toString()); } else { LOG.info(sb.toString()); } PROFILE_GROUP.remove(); START_MOMENT.remove(); STRING_BUILDER.remove(); } private boolean contains(Annotation[] list, Class<?> annotation) { if (null != list) { for (Annotation test : list) { if (annotation.isAssignableFrom(test.getClass())) { return true; } } } return false; } }
True
False
2,000
2,965
70
47
2,519
67
50
2,655
62
39
2,519
67
50
2,950
72
49
false
false
false
false
false
true
1,875
22054_14
/** * * CVS: $Header: /export/home0/cvsroot/socsg/DRAMA/Sources/be/ac/kuleuven/cs/drama/simulator/devices/CVO/PTW.java,v 1.1.1.1 2001/09/07 09:41:38 dirkw Exp $ * * (C) 2000 * Katholieke Universiteit Leuven * Developed at Dept. Computer Science * */ package be.ac.kuleuven.cs.drama.simulator.devices.CVO; import be.ac.kuleuven.cs.drama.simulator.basis.*; import be.ac.kuleuven.cs.drama.events.*; /** Klasse voor bewerkingen op PTWs (PTW=programmatoestandswoord)* * @version 1.2 19 APR 2015 * @author Tom Vekemans * @author Jo-Thijs Daelman */ public abstract class PTW extends Register { private PTWChangeEvent evt = new PTWChangeEvent(this, null); private PTWChangeListener _myListener; /**instantieer een nieuw PTW */ public PTW() { try { _myListener = ((PTWChangeListener)GeneralEventAdapter.instance(). getEventAdapter("PTWChangeEventAdapter")); } catch (Exception e) { System.out.println(e.toString() + " : " + evt.toString()); } } /**initialiseer dit PTW */ public abstract void init(); /**geef de bevelenteller van dit PTW @return de waarde van de bevelenteller van dit PTW */ public abstract long getBT(); /**zet de waarde van de bevelenteller @param value de nieuwe waarde van de bevelenteller */ public abstract void setBT(long value); /**geef de conditiecode @return de waarde van de conditiecode van dit PTW */ public abstract int getCC(); /**zet de waarde van de conditiecode @param value de nieuwe waarde van de conditiecode */ public abstract void setCC(int value); /**geef de overloopindicator @return de waarde van de overloopindicator van dit PTW */ public abstract boolean getOVI(); /**zet de waarde van de overloopindicator @param value de nieuwe waarde van de overloopindicator */ public abstract void setOVI(boolean value); /**geef de stapeloverloopindicator @return de waarde van de stapeloverloopindicator van dit PTW */ public abstract boolean getSOI(); /**zet de waarde van de stapeloverloopindicator @param value de nieuwe waarde van de stapeloverloopindicator */ public abstract void setSOI(boolean value); /**geef de supervisie status terug @return de waarde van de S/P masker van dit PTW */ public abstract boolean getSupervisionState(); /**geef de geheugen beheer eenheid @return de waarde van de conditiecode van dit PTW */ public abstract long getGBE(); /**zet de waarde van de geheugen beheer eenheid @param value de nieuwe waarde van de geheugen beheer eenheid */ public abstract void setGBE(long value); /**zet de waarde van het "waarde" deel van dit PTW. Het "waarde" deel is het deel van het PTW zonder maskervlaggen @param value de waarde die het "waarde" deel moet krijgen */ public abstract void setValue(long value); /**zet de waarde van het "masker" deel van dit PTW. Het "masker" deel bestaat uit de maskervlaggen van het PTW @param value de waarde die het "masker" deel moet krijgen */ public abstract void setMaskerValue(long value); /**verwittig de objecten die geïnteresseerd zijn in veranderingen van het PTW dat er een wijziging is opgetreden */ protected final void notifyListeners() { try { evt.setPTW(this); _myListener.PTWChange(evt); } catch (Exception e) { System.out.println(e.toString() + " : " + evt.toString()); } } public abstract boolean getInterruptFlag(int flag); public abstract void setInterruptFlag(int flag, boolean value); }
WillemDeGroef/drama
src/be/ac/kuleuven/cs/drama/simulator/devices/CVO/PTW.java
1,211
/**zet de waarde van de geheugen beheer eenheid @param value de nieuwe waarde van de geheugen beheer eenheid */
block_comment
nl
/** * * CVS: $Header: /export/home0/cvsroot/socsg/DRAMA/Sources/be/ac/kuleuven/cs/drama/simulator/devices/CVO/PTW.java,v 1.1.1.1 2001/09/07 09:41:38 dirkw Exp $ * * (C) 2000 * Katholieke Universiteit Leuven * Developed at Dept. Computer Science * */ package be.ac.kuleuven.cs.drama.simulator.devices.CVO; import be.ac.kuleuven.cs.drama.simulator.basis.*; import be.ac.kuleuven.cs.drama.events.*; /** Klasse voor bewerkingen op PTWs (PTW=programmatoestandswoord)* * @version 1.2 19 APR 2015 * @author Tom Vekemans * @author Jo-Thijs Daelman */ public abstract class PTW extends Register { private PTWChangeEvent evt = new PTWChangeEvent(this, null); private PTWChangeListener _myListener; /**instantieer een nieuw PTW */ public PTW() { try { _myListener = ((PTWChangeListener)GeneralEventAdapter.instance(). getEventAdapter("PTWChangeEventAdapter")); } catch (Exception e) { System.out.println(e.toString() + " : " + evt.toString()); } } /**initialiseer dit PTW */ public abstract void init(); /**geef de bevelenteller van dit PTW @return de waarde van de bevelenteller van dit PTW */ public abstract long getBT(); /**zet de waarde van de bevelenteller @param value de nieuwe waarde van de bevelenteller */ public abstract void setBT(long value); /**geef de conditiecode @return de waarde van de conditiecode van dit PTW */ public abstract int getCC(); /**zet de waarde van de conditiecode @param value de nieuwe waarde van de conditiecode */ public abstract void setCC(int value); /**geef de overloopindicator @return de waarde van de overloopindicator van dit PTW */ public abstract boolean getOVI(); /**zet de waarde van de overloopindicator @param value de nieuwe waarde van de overloopindicator */ public abstract void setOVI(boolean value); /**geef de stapeloverloopindicator @return de waarde van de stapeloverloopindicator van dit PTW */ public abstract boolean getSOI(); /**zet de waarde van de stapeloverloopindicator @param value de nieuwe waarde van de stapeloverloopindicator */ public abstract void setSOI(boolean value); /**geef de supervisie status terug @return de waarde van de S/P masker van dit PTW */ public abstract boolean getSupervisionState(); /**geef de geheugen beheer eenheid @return de waarde van de conditiecode van dit PTW */ public abstract long getGBE(); /**zet de waarde<SUF>*/ public abstract void setGBE(long value); /**zet de waarde van het "waarde" deel van dit PTW. Het "waarde" deel is het deel van het PTW zonder maskervlaggen @param value de waarde die het "waarde" deel moet krijgen */ public abstract void setValue(long value); /**zet de waarde van het "masker" deel van dit PTW. Het "masker" deel bestaat uit de maskervlaggen van het PTW @param value de waarde die het "masker" deel moet krijgen */ public abstract void setMaskerValue(long value); /**verwittig de objecten die geïnteresseerd zijn in veranderingen van het PTW dat er een wijziging is opgetreden */ protected final void notifyListeners() { try { evt.setPTW(this); _myListener.PTWChange(evt); } catch (Exception e) { System.out.println(e.toString() + " : " + evt.toString()); } } public abstract boolean getInterruptFlag(int flag); public abstract void setInterruptFlag(int flag, boolean value); }
True
False
2,003
1,211
39
31
1,117
41
36
1,078
31
24
1,117
41
36
1,218
37
30
false
false
false
false
false
true
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
33
Edit dataset card