code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
package pl.wroc.pwr.ankieta.ankietaService.entity;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import org.hibernate.annotations.NamedQuery;
@Entity
public class Zajecia {
@Id
@GeneratedValue
private Integer id;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "Zajecia_Uzytkownik", joinColumns = {
@JoinColumn(name = "zajecia_id", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "ankietowany_id",
nullable = false, updatable = false) })
private Collection<Ankietowany> ankietowani;
@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.REFRESH})
@JoinTable(name = "Zajecia_Nauczyciel", joinColumns = {
@JoinColumn(name = "zajecia_id", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "nauczyciel_id",
nullable = false, updatable = false) })
private Collection<Nauczyciel> nauczyciele;
@OneToMany(mappedBy = "zajecia", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Collection<Ankieta> ankiety;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "kurs_id", nullable = false)
private Kurs kurs;
private DzienTygodnia dzienTygodnia;
private String godzinaRozpoczecia;
private String godzinaZakonczenia;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Collection<Ankietowany> getAnkietowani() {
return ankietowani;
}
public void setAnkietowani(Collection<Ankietowany> ankietowani) {
this.ankietowani = ankietowani;
}
public Collection<Nauczyciel> getNauczyciele() {
return nauczyciele;
}
public void setNauczyciele(Collection<Nauczyciel> nauczyciele) {
this.nauczyciele = nauczyciele;
}
public Collection<Ankieta> getAnkiety() {
return ankiety;
}
public void setAnkiety(Collection<Ankieta> ankiety) {
this.ankiety = ankiety;
}
public Kurs getKurs() {
return kurs;
}
public void setKurs(Kurs kurs) {
this.kurs = kurs;
}
public DzienTygodnia getDzienTygodnia() {
return dzienTygodnia;
}
public void setDzienTygodnia(DzienTygodnia dzienTygodnia) {
this.dzienTygodnia = dzienTygodnia;
}
public String getGodzinaRozpoczecia() {
return godzinaRozpoczecia;
}
public void setGodzinaRozpoczecia(String godzinaRozpoczecia) {
this.godzinaRozpoczecia = godzinaRozpoczecia;
}
public String getGodzinaZakonczenia() {
return godzinaZakonczenia;
}
public void setGodzinaZakonczenia(String godzinaZakonczenia) {
this.godzinaZakonczenia = godzinaZakonczenia;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(getDzienTygodnia().toString());
builder.append(" ");
builder.append(getGodzinaRozpoczecia());
builder.append("-");
builder.append(getGodzinaZakonczenia());
return builder.toString();
}
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.entity;
import javax.persistence.Entity;
@Entity
public class Otwarte extends Pytanie {
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.entity;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
@Entity
public class Ankietowany extends Uzytkownik {
@OneToMany(targetEntity=AnkietaAnkietowanego.class, mappedBy="ankietowany", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Collection<AnkietaAnkietowanego> ankietaAnkietowanego;
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "grupaAnkietowanych")
private Collection<Ankieta> ankiety;
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "ankietowani")
private Collection<Zajecia> zajecia;
public Collection<AnkietaAnkietowanego> getAnkietaAnkietowanego() {
return ankietaAnkietowanego;
}
public void setAnkietaAnkietowanego(Collection<AnkietaAnkietowanego> ankietaAnkietowanego) {
this.ankietaAnkietowanego = ankietaAnkietowanego;
}
public Collection<Ankieta> getAnkiety() {
return ankiety;
}
public void setAnkiety(Collection<Ankieta> ankiety) {
this.ankiety = ankiety;
}
public Collection<Zajecia> getZajecia() {
return zajecia;
}
public void setZajecia(Collection<Zajecia> zajecia) {
this.zajecia = zajecia;
}
public void addAnkietaAnkietowanego(AnkietaAnkietowanego wypelnionaAnkieta) {
this.ankietaAnkietowanego.add(wypelnionaAnkieta);
}
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.entity;
import java.util.*;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
@Entity
public class Nauczyciel extends Uzytkownik {
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "nauczyciele")
private Collection<Zajecia> zajecia;
private String nazwisko;
private String imie;
private String tytulNaukowy;
public Collection<Zajecia> getZajecia() {
return zajecia;
}
public void setZajecia(Collection<Zajecia> zajecia) {
this.zajecia = zajecia;
}
public String getNazwisko() {
return nazwisko;
}
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
}
public String getImie() {
return imie;
}
public void setImie(String imie) {
this.imie = imie;
}
public String getTytulNaukowy() {
return tytulNaukowy;
}
public void setTytulNaukowy(String tytulNaukowy) {
this.tytulNaukowy = tytulNaukowy;
}
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.entity;
import java.util.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
@Entity
public class Zamkniete extends Pytanie {
@OneToMany(mappedBy = "pytanieZamkniete", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Collection<WariantOdpowiedzi> wariantyOdpowiedzi = new LinkedList<WariantOdpowiedzi>();
public void addWariantOdpowiedzi(WariantOdpowiedzi wariantOdpowiedzi) {
wariantyOdpowiedzi.add(wariantOdpowiedzi);
}
public Collection<WariantOdpowiedzi> getWariantyOdpowiedzi() {
return wariantyOdpowiedzi;
}
public void setWariantyOdpowiedzi(
Collection<WariantOdpowiedzi> wariantyOdpowiedzi) {
this.wariantyOdpowiedzi = wariantyOdpowiedzi;
}
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.entity;
import java.util.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
@Entity
public abstract class Pytanie {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "ankieta_id", nullable = false)
private Ankieta ankieta;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "szablon_id", nullable = true)
private Szablon szablon;
@OneToMany(mappedBy = "pytanie", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Collection<Odpowiedz> odpowiedz;
@Id
@GeneratedValue
private Integer id;
private String tresc;
public Ankieta getAnkieta() {
return ankieta;
}
public void setAnkieta(Ankieta ankieta) {
this.ankieta = ankieta;
}
public String getTresc() {
return tresc;
}
public void setTresc(String tresc) {
this.tresc = tresc;
}
public String toString() {
return tresc;
}
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.entity;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class WybranaOdpowiedz extends Odpowiedz {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "wariant_id", nullable = true)
private WariantOdpowiedzi wariantOdpowiedzi;
public WybranaOdpowiedz() {}
public WybranaOdpowiedz(WariantOdpowiedzi wariantOdpowiedzi) {
super();
this.wariantOdpowiedzi = wariantOdpowiedzi;
}
public WariantOdpowiedzi getWariantOdpowiedzi() {
return wariantOdpowiedzi;
}
public void setWariantOdpowiedzi(WariantOdpowiedzi wariantOdpowiedzi) {
this.wariantOdpowiedzi = wariantOdpowiedzi;
}
public String toString() {
return wariantOdpowiedzi.toString();
}
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.entity;
import javax.persistence.Entity;
@Entity
public class OdpowiedzPytanieOtwarte extends Odpowiedz {
private String tresc;
public String getTresc() {
return tresc;
}
public OdpowiedzPytanieOtwarte() {
super();
}
public OdpowiedzPytanieOtwarte(String tresc) {
super();
this.tresc = tresc;
}
public void setTresc(String tresc) {
this.tresc = tresc;
}
public String toString() {
return tresc;
}
} | Java |
package pl.wroc.pwr.ankieta.ankietaService.entity;
import java.util.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
@Entity
public class Audytor extends Uzytkownik {
@OneToMany(targetEntity=Ankieta.class, mappedBy="audytor", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
private Collection<Ankieta> ankiety;
public Collection<Ankieta> getAnkiety() {
return ankiety;
}
public void setAnkiety(Collection<Ankieta> ankiety) {
this.ankiety = ankiety;
}
} | Java |
package pl.wroc.pwr.ankieta.model;
import java.util.List;
import pl.wroc.pwr.ankieta.entity.Ankietowany;
import pl.wroc.pwr.ankieta.entity.Nauczyciel;
import pl.wroc.pwr.ankieta.entity.Pytanie;
import pl.wroc.pwr.ankieta.entity.Szablon;
import pl.wroc.pwr.ankieta.entity.Zajecia;
public class AnkietaModel {
private String tytul;
private List<Nauczyciel> nauczyciele;
private Nauczyciel nauczyciel;
private List<Zajecia> zajeciaDlaNauczyciela;
private List<Szablon> szablony;
private List<Pytanie> pytaniaDlaSzablonu;
private List<Pytanie> pytania;
private List<Ankietowany> ankietowani;
private List<Ankietowany> ankietowaniDlaZajec;
public Nauczyciel getNauczyciel() {
return this.nauczyciel;
}
} | Java |
package pl.wroc.pwr.ankieta.model;
import java.util.List;
public class WypelnianieAnkietyModel {
private List<String> odpowiedziOtwarte;
private List<Integer> odpowiedziZamkniete;
} | Java |
package pl.wroc.pwr.ankieta.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import pl.wroc.pwr.ankieta.model.AnkietaModel;
import pl.wroc.pwr.ankieta.service.AnkietaService;
import pl.wroc.pwr.ankieta.service.AnkietowanyService;
import pl.wroc.pwr.ankieta.service.NauczycielService;
import pl.wroc.pwr.ankieta.service.PytanieService;
import pl.wroc.pwr.ankieta.service.SzablonService;
import pl.wroc.pwr.ankieta.service.ZajeciaService;
@Controller
public class NowaAnkietaController {
NauczycielService nauczycielService;
ZajeciaService zajeciaService;
AnkietowanyService ankietowanyService;
SzablonService szablonService;
PytanieService pytanieSzablon;
AnkietaService ankietaService;
@RequestMapping("/nowaAnkieta")
public String loadKrok1(AnkietaModel model1) {
return "nowaAnkieta";
}
public String loadKrok2(AnkietaModel model2) {
return "";
}
public String loadKrok3(AnkietaModel model3) {
return "";
}
public String applySzablon(AnkietaModel model) {
return "";
}
public String createAnkieta(AnkietaModel model) {
return "";
}
} | Java |
package pl.wroc.pwr.ankieta.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController {
@RequestMapping("/login")
public String login() {
return "login";
}
}
| Java |
package pl.wroc.pwr.ankieta.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/index")
public String index() {
return "index";
}
}
| Java |
package pl.wroc.pwr.ankieta.service;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.entity.Ankieta;
import pl.wroc.pwr.ankieta.model.AnkietaModel;
import pl.wroc.pwr.ankieta.repository.AnkietaRepository;
@Service
public class AnkietaService {
AnkietaRepository repository;
public Ankieta loadAnkieta(Integer idAnkiety) {
throw new UnsupportedOperationException();
}
public Ankieta createAnkieta(AnkietaModel model) {
return null;
}
public Ankieta save(Ankieta ankieta) {
throw new UnsupportedOperationException();
}
} | Java |
package pl.wroc.pwr.ankieta.service;
import java.util.List;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.entity.Szablon;
import pl.wroc.pwr.ankieta.repository.SzablonRepository;
@Service
public class SzablonService {
SzablonRepository repository;
public List<Szablon> findAll() {
throw new UnsupportedOperationException();
}
} | Java |
package pl.wroc.pwr.ankieta.service;
import java.util.List;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.entity.Pytanie;
import pl.wroc.pwr.ankieta.entity.Szablon;
import pl.wroc.pwr.ankieta.repository.PytanieRepository;
@Service
public class PytanieService {
PytanieRepository repository;
public List<Pytanie> findAllForSzablon(Szablon szablon) {
throw new UnsupportedOperationException();
}
} | Java |
package pl.wroc.pwr.ankieta.service;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.entity.AnkietaAnkietowanego;
import pl.wroc.pwr.ankieta.model.WypelnianieAnkietyModel;
import pl.wroc.pwr.ankieta.repository.AnkietaAnkietowanegoRepository;
@Service
public class AnkietaAnkietowanegoService {
AnkietaAnkietowanegoRepository ankietaAnkietowanegoRepository;
public AnkietaAnkietowanego createAmloetaAnkietowanego(WypelnianieAnkietyModel model) {
return null;
}
public AnkietaAnkietowanego save(AnkietaAnkietowanego ankietaAnkietowanego) {
throw new UnsupportedOperationException();
}
} | Java |
package pl.wroc.pwr.ankieta.service;
import java.util.List;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.entity.Ankietowany;
import pl.wroc.pwr.ankieta.entity.Zajecia;
import pl.wroc.pwr.ankieta.repository.AnkietowanyRepository;
@Service
public class AnkietowanyService {
AnkietowanyRepository repository;
public List<Ankietowany> findAllForZajecia(Zajecia zajecia) {
throw new UnsupportedOperationException();
}
} | Java |
package pl.wroc.pwr.ankieta.service;
import java.util.List;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.entity.Uzytkownik;
import pl.wroc.pwr.ankieta.repository.UzytkownikRepository;
@Service
@Transactional
@PersistenceContext(type = PersistenceContextType.EXTENDED)
public class UzytkownikService {
@Autowired
private UzytkownikRepository uzytkownikRepository;
private BCryptPasswordEncoder encoder;
public BCryptPasswordEncoder getEncoder() {
if (encoder == null) {
encoder = new BCryptPasswordEncoder();
}
return encoder;
}
public List<Uzytkownik> findAll() {
return uzytkownikRepository.findAll();
}
public Uzytkownik findOne(String email) {
return uzytkownikRepository.findByEmail(email);
}
public Uzytkownik getLoggedUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return findOne(authentication.getName());
}
public Uzytkownik registerUser(Uzytkownik user) {
user.setHaslo(encryptPassword(user.getHaslo()));
return uzytkownikRepository.save(user);
}
public Uzytkownik updatePassword(String name, String password) {
Uzytkownik user = findOne(name);
user.setHaslo(encryptPassword(password));
return uzytkownikRepository.save(user);
}
public String encryptPassword(String plainPassword) {
return getEncoder().encode(plainPassword);
}
public Boolean isLoggedUserPasswordCorrect(String password) {
Uzytkownik loggedUser = getLoggedUser();
return getEncoder().matches(password, loggedUser.getHaslo());
}
public Boolean canChangePassword(String oldPassword, String newPassword, String confirmPassword) {
return isLoggedUserPasswordCorrect(oldPassword) && newPassword.equals(confirmPassword);
}
}
| Java |
package pl.wroc.pwr.ankieta.service;
import java.util.List;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.entity.Nauczyciel;
import pl.wroc.pwr.ankieta.repository.NauczycielRepository;
@Service
public class NauczycielService {
NauczycielRepository repository;
public List<Nauczyciel> findAll() {
throw new UnsupportedOperationException();
}
} | Java |
package pl.wroc.pwr.ankieta.service;
import java.util.List;
import org.springframework.stereotype.Service;
import pl.wroc.pwr.ankieta.entity.Nauczyciel;
import pl.wroc.pwr.ankieta.entity.Zajecia;
import pl.wroc.pwr.ankieta.repository.ZajeciaRepository;
@Service
public class ZajeciaService {
ZajeciaRepository repository;
public List<Zajecia> findAllForNauczyciel(Nauczyciel nauczyciel) {
throw new UnsupportedOperationException();
}
} | Java |
package pl.wroc.pwr.ankieta.annotation;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Target({ FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = { UniqueEmailValidator.class })
public @interface UniqueEmail {
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
| Java |
package pl.wroc.pwr.ankieta.annotation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import pl.wroc.pwr.ankieta.repository.UzytkownikRepository;
public class UniqueEmailValidator implements ConstraintValidator<UniqueEmail, String>{
@Autowired
private UzytkownikRepository userRepository;
@Override
public void initialize(UniqueEmail constraintAnnotation) {
}
@Override
public boolean isValid(String email, ConstraintValidatorContext context) {
if (userRepository == null) {
return true;
}
return userRepository.findByEmail(email) == null;
}
}
| Java |
package pl.wroc.pwr.ankieta.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.ankieta.entity.Audytor;
public interface AudytorRepository extends JpaRepository<Audytor, Integer> {
}
| Java |
package pl.wroc.pwr.ankieta.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.ankieta.entity.Kurs;
public interface KursRepository extends JpaRepository<Kurs, Integer> {
}
| Java |
package pl.wroc.pwr.ankieta.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.ankieta.entity.Zajecia;
public interface ZajeciaRepository extends JpaRepository<Zajecia, Integer> {
//TODO:public List<Zajecia> findAllForNauczyciel(Nauczyciel nauczyciel);
} | Java |
package pl.wroc.pwr.ankieta.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.ankieta.entity.Pytanie;
public interface PytanieRepository extends JpaRepository<Pytanie, Integer> {
//TODO:public List<Pytanie> findAllForSzablon(Szablon szablon);
} | Java |
package pl.wroc.pwr.ankieta.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.ankieta.entity.Ankieta;
public interface AnkietaRepository extends JpaRepository<Ankieta, Integer> {
//TODO:public Ankieta loadAnkieta(Integer idAnkiety);
} | Java |
package pl.wroc.pwr.ankieta.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.ankieta.entity.Uzytkownik;
public interface UzytkownikRepository extends JpaRepository<Uzytkownik, Integer> {
Uzytkownik findByEmail(String email);
}
| Java |
package pl.wroc.pwr.ankieta.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.ankieta.entity.Szablon;
public interface SzablonRepository extends JpaRepository<Szablon, Integer> {
public List<Szablon> findAll();
} | Java |
package pl.wroc.pwr.ankieta.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.ankieta.entity.AnkietaAnkietowanego;
public interface AnkietaAnkietowanegoRepository extends JpaRepository<AnkietaAnkietowanego, Integer> {
} | Java |
package pl.wroc.pwr.ankieta.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.ankieta.entity.Nauczyciel;
public interface NauczycielRepository extends JpaRepository<Nauczyciel, Integer> {
public List<Nauczyciel> findAll();
} | Java |
package pl.wroc.pwr.ankieta.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.wroc.pwr.ankieta.entity.Ankietowany;
public interface AnkietowanyRepository extends JpaRepository<Ankietowany, Integer> {
//TODO:public List<Ankietowany> findAllForZajecia(Zajecia zajecia);
} | Java |
package pl.wroc.pwr.ankieta.entity;
import java.util.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
@Entity
public class Synonim {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "nadrzedny_id", nullable = false)
private Synonim synonimNadrzedny;
@OneToMany(mappedBy="synonimNadrzedny", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
private Collection<Synonim> synonimy;
@Id
@GeneratedValue
private Integer id;
private String slowo;
} | Java |
package pl.wroc.pwr.ankieta.entity;
import javax.persistence.Entity;
@Entity
public class Otwarte extends Pytanie {
} | Java |
package pl.wroc.pwr.ankieta.entity;
import java.util.*;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
@Entity
public class Nauczyciel extends Uzytkownik {
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "nauczyciele")
private Collection<Zajecia> zajecia;
private String nazwisko;
private String imie;
private String tytulNaukowy;
public Collection<Zajecia> getZajecia() {
return zajecia;
}
public void setZajecia(Collection<Zajecia> zajecia) {
this.zajecia = zajecia;
}
public String getNazwisko() {
return nazwisko;
}
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
}
public String getImie() {
return imie;
}
public void setImie(String imie) {
this.imie = imie;
}
public String getTytulNaukowy() {
return tytulNaukowy;
}
public void setTytulNaukowy(String tytulNaukowy) {
this.tytulNaukowy = tytulNaukowy;
}
} | Java |
package pl.wroc.pwr.ankieta.entity;
import java.util.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
@Entity
public abstract class Pytanie {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "ankieta_id", nullable = false)
private Ankieta ankieta;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "szablon_id", nullable = false)
private Szablon szablon;
@OneToMany(mappedBy = "pytanie", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Collection<Odpowiedz> odpowiedz;
@Id
@GeneratedValue
private Integer id;
private String tresc;
} | Java |
package pl.wroc.pwr.ankieta.entity;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class WybranaOdpowiedz extends Odpowiedz {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "wariant_id", nullable = false)
private WariantOdpowiedzi wariantOdpowiedzi;
} | Java |
package pl.wroc.pwr.ankieta.entity;
import javax.persistence.Entity;
@Entity
public class OdpowiedzPytanieOtwarte extends Odpowiedz {
private String tresc;
} | Java |
package pl.wroc.pwr.ankieta.entity;
import java.util.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
@Entity
public class Audytor extends Uzytkownik {
@OneToMany(targetEntity=Ankieta.class, mappedBy="audytor", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
private Collection<Ankieta> ankiety;
public Collection<Ankieta> getAnkiety() {
return ankiety;
}
public void setAnkiety(Collection<Ankieta> ankiety) {
this.ankiety = ankiety;
}
} | Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dbcreator.common;
/**
* @author yrtimid
*
*/
public interface INotificationManager {
public abstract void notify(int id, Notification2 notification);
} | Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dbcreator.common;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.logging.Logger;
import il.yrtimid.osm.osmpoi.ImportSettings;
import il.yrtimid.osm.osmpoi.ItemPipe;
import il.yrtimid.osm.osmpoi.dal.IDbCachedFiller;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.EntityType;
import il.yrtimid.osm.osmpoi.domain.Node;
import il.yrtimid.osm.osmpoi.domain.Way;
import il.yrtimid.osm.osmpoi.pbf.OsmImporter;
import il.yrtimid.osm.osmpoi.pbf.ProgressNotifier;
/**
* @author yrtimid
*
*/
public class DbCreator {
static final int IMPORT_TO_DB = 1;
public static final int BUILD_GRID = 40;
INotificationManager notificationManager;
IDbCachedFiller poiDbHelper;
IDbCachedFiller addressDbHelper;
private static final Logger LOG = Logger.getLogger(DbCreator.class.getName());
/**
*
*/
public DbCreator(IDbCachedFiller poiDB, IDbCachedFiller addrDB, INotificationManager notificationManager) {
this.poiDbHelper = poiDB;
this.addressDbHelper = addrDB;
this.notificationManager = notificationManager;
}
/**
* @throws Exception
*
*/
public void createEmptyDatabases() throws Exception {
poiDbHelper.create();
addressDbHelper.create();
}
public void importToDB(String sourceFilePath, ImportSettings settings) {
try {
LOG.finest("Importing file: "+sourceFilePath);
File sourceFile = new File(sourceFilePath);
if ((sourceFile.exists() && sourceFile.canRead())){
long startTime = System.currentTimeMillis();
final Notification2 notif = new Notification2("Importing file into DB", System.currentTimeMillis());
notif.flags |= Notification2.FLAG_ONGOING_EVENT | Notification2.FLAG_NO_CLEAR;
notif.setLatestEventInfo("PBF Import", "Clearing DB...");
notificationManager.notify(IMPORT_TO_DB, notif);
if (settings.isClearBeforeImport()){
poiDbHelper.clearAll();
addressDbHelper.clearAll();
}
notif.setLatestEventInfo("PBF Import", "Importing in progress...");
notificationManager.notify(IMPORT_TO_DB, notif);
InputStream input;
if (settings.isImportRelations()){
input = new BufferedInputStream(new FileInputStream(sourceFile));
importRelations(input, notif, settings);
LOG.finest("Finished importing relations");
}
if (settings.isImportWays()){
input = new BufferedInputStream(new FileInputStream(sourceFile));
importWays(input, notif, settings);
LOG.finest("Finished importing ways");
}
if (settings.isImportNodes()){
input = new BufferedInputStream(new FileInputStream(sourceFile));
importNodes(input, notif, settings);
LOG.finest("Finished importing nodes");
}
notif.setLatestEventInfo("PBF Import", "Post-import calculations...");
notificationManager.notify(IMPORT_TO_DB, notif);
if(settings.isBuildGrid()){
notif.setLatestEventInfo("PBF Import", "Creating grid...");
notificationManager.notify(IMPORT_TO_DB, notif);
poiDbHelper.initGrid();
notif.setLatestEventInfo("PBF Import", "Optimizing grid...");
notificationManager.notify(IMPORT_TO_DB, notif);
poiDbHelper.optimizeGrid(settings.getGridCellSize());
}
long endTime = System.currentTimeMillis();
int workTime = Math.round((endTime-startTime)/1000/60);
Notification2 finalNotif = new Notification2("Importing file into DB", System.currentTimeMillis());
finalNotif.flags |= Notification2.FLAG_AUTO_CANCEL;
finalNotif.setLatestEventInfo("PBF Import", "Import done successfully. ("+workTime+"min.)");
notificationManager.notify(IMPORT_TO_DB, finalNotif);
}else {
Notification2 finalNotif = new Notification2("Importing file into DB", System.currentTimeMillis());
finalNotif.flags |= Notification2.FLAG_AUTO_CANCEL;
finalNotif.setLatestEventInfo("PBF Import", "Import failed. File not found.");
notificationManager.notify(IMPORT_TO_DB, finalNotif);
}
} catch (Exception ex) {
ex.printStackTrace();
LOG.severe("Exception while importing PBF into DB. "+ ex.toString());
}
}
protected Long importRelations(final InputStream input, final Notification2 notif, final ImportSettings settings) {
Long count = 0L;
try{
poiDbHelper.beginAdd();
addressDbHelper.beginAdd();
count = OsmImporter.processAll(input, new ItemPipe<Entity>() {
@Override
public void pushItem(Entity item) {
try{
if (item.getType() == EntityType.Relation){
settings.cleanTags(item);
if (settings.isPoi(item))
poiDbHelper.addEntity(item);
if (settings.isImportAddresses() && settings.isAddress(item))
addressDbHelper.addEntity(item);
}
}catch(Exception e){
e.printStackTrace();
}
}
}, new ProgressNotifier() {
@Override
public void onProgressChange(Progress progress) {
notif.setLatestEventInfo("PBF Import", "Importing relations: " + progress.toString());
notificationManager.notify(IMPORT_TO_DB, notif);
}
});
if (count == -1L){
notif.setLatestEventInfo("PBF Import", "Relations import failed");
}
poiDbHelper.endAdd();
addressDbHelper.endAdd();
}catch(Exception ex){
ex.printStackTrace();
}
return count;
}
protected Long importWays(final InputStream input, final Notification2 notif, final ImportSettings settings) {
poiDbHelper.beginAdd();
addressDbHelper.beginAdd();
Long count = OsmImporter.processAll(input, new ItemPipe<Entity>() {
@Override
public void pushItem(Entity item) {
try{
if (item.getType() == EntityType.Way){
settings.cleanTags(item);
if (settings.isPoi(item))
poiDbHelper.addEntity(item);
else if (settings.isImportRelations()){
Way w = (Way)item;
poiDbHelper.addWayIfBelongsToRelation(w);
}
if (settings.isImportAddresses()){
if (settings.isAddress(item))
addressDbHelper.addEntity(item);
else if (settings.isImportRelations()){
Way w = (Way)item;
addressDbHelper.addWayIfBelongsToRelation(w);
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}, new ProgressNotifier() {
@Override
public void onProgressChange(Progress progress) {
notif.setLatestEventInfo("PBF Import", "Importing ways: " + progress.toString());
notificationManager.notify(IMPORT_TO_DB, notif);
}
});
if (count == -1L){
notif.setLatestEventInfo("PBF Import", "Nodes import failed");
}
poiDbHelper.endAdd();
addressDbHelper.endAdd();
return count;
}
protected Long importNodes(final InputStream input, final Notification2 notif, final ImportSettings settings) {
poiDbHelper.beginAdd();
addressDbHelper.beginAdd();
Long count = OsmImporter.processAll(input, new ItemPipe<Entity>() {
@Override
public void pushItem(Entity item) {
try{
if (item.getType() == EntityType.Node){
settings.cleanTags(item);
if (settings.isImportAddresses()){
if (settings.isAddress(item))
addressDbHelper.addEntity(item);
else {
Node n = (Node)item;
if (settings.isImportWays()){
addressDbHelper.addNodeIfBelongsToWay(n);
}
if (settings.isImportRelations()){
addressDbHelper.addNodeIfBelongsToRelation(n);
}
}
}
if (settings.isPoi(item))
poiDbHelper.addEntity(item);
else {
Node n = (Node)item;
if (settings.isImportWays()){
poiDbHelper.addNodeIfBelongsToWay(n);
}
if (settings.isImportRelations()){
poiDbHelper.addNodeIfBelongsToRelation(n);
}
}
}else if (item.getType() == EntityType.Bound){
poiDbHelper.addEntity(item);
}
}catch(Exception e){
e.printStackTrace();
}
}
}, new ProgressNotifier() {
@Override
public void onProgressChange(Progress progress) {
notif.setLatestEventInfo("PBF Import", "Importing nodes: " + progress.toString());
notificationManager.notify(IMPORT_TO_DB, notif);
}
});
if (count == -1L){
notif.setLatestEventInfo("PBF Import", "Nodes import failed");
}
addressDbHelper.endAdd();
poiDbHelper.endAdd();
return count;
}
public void rebuildGrid(final ImportSettings settings){
try {
long startTime = System.currentTimeMillis();
final Notification2 notif = new Notification2("Rebuilding grid", System.currentTimeMillis());
notif.flags |= Notification2.FLAG_ONGOING_EVENT | Notification2.FLAG_NO_CLEAR;
notif.setLatestEventInfo("Rebuilding grid", "Clearing old grid...");
notificationManager.notify(BUILD_GRID, notif);
notif.setLatestEventInfo("Rebuilding grid", "Creating grid...");
notificationManager.notify(BUILD_GRID, notif);
poiDbHelper.initGrid();
notif.setLatestEventInfo("Rebuilding grid", "Optimizing grid...");
notificationManager.notify(BUILD_GRID, notif);
poiDbHelper.optimizeGrid(settings.getGridCellSize());
long endTime = System.currentTimeMillis();
int workTime = Math.round((endTime-startTime)/1000/60);
Notification2 finalNotif = new Notification2("Rebuilding grid", System.currentTimeMillis());
finalNotif.flags |= Notification2.FLAG_AUTO_CANCEL;
finalNotif.setLatestEventInfo("Rebuilding grid", "Done successfully. ("+workTime+"min)");
notificationManager.notify(IMPORT_TO_DB, finalNotif);
} catch (Exception ex) {
LOG.severe("Exception while rebuilding grid. "+ex.toString());
}
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dbcreator.common;
/**
* @author yrtimid
*
*/
public class Notification2 {
public String tickerText;
public String title;
public String text;
public long when;
/**
* Bit to be bitwise-ored into the {@link #flags} field that should be
* set if you want the LED on for this notification.
* <ul>
* <li>To turn the LED off, pass 0 in the alpha channel for colorARGB
* or 0 for both ledOnMS and ledOffMS.</li>
* <li>To turn the LED on, pass 1 for ledOnMS and 0 for ledOffMS.</li>
* <li>To flash the LED, pass the number of milliseconds that it should
* be on and off to ledOnMS and ledOffMS.</li>
* </ul>
* <p>
* Since hardware varies, you are not guaranteed that any of the values
* you pass are honored exactly. Use the system defaults (TODO) if possible
* because they will be set to values that work on any given hardware.
* <p>
* The alpha channel must be set for forward compatibility.
*
*/
public static final int FLAG_SHOW_LIGHTS = 0x00000001;
/**
* Bit to be bitwise-ored into the {@link #flags} field that should be
* set if this notification is in reference to something that is ongoing,
* like a phone call. It should not be set if this notification is in
* reference to something that happened at a particular point in time,
* like a missed phone call.
*/
public static final int FLAG_ONGOING_EVENT = 0x00000002;
/**
* Bit to be bitwise-ored into the {@link #flags} field that if set,
* the audio will be repeated until the notification is
* cancelled or the notification window is opened.
*/
public static final int FLAG_INSISTENT = 0x00000004;
/**
* Bit to be bitwise-ored into the {@link #flags} field that should be
* set if you want the sound and/or vibration play each time the
* notification is sent, even if it has not been canceled before that.
*/
public static final int FLAG_ONLY_ALERT_ONCE = 0x00000008;
/**
* Bit to be bitwise-ored into the {@link #flags} field that should be
* set if the notification should be canceled when it is clicked by the
* user.
*/
public static final int FLAG_AUTO_CANCEL = 0x00000010;
/**
* Bit to be bitwise-ored into the {@link #flags} field that should be
* set if the notification should not be canceled when the user clicks
* the Clear all button.
*/
public static final int FLAG_NO_CLEAR = 0x00000020;
/**
* Bit to be bitwise-ored into the {@link #flags} field that should be
* set if this notification represents a currently running service. This
* will normally be set for you by {@link Service#startForeground}.
*/
public static final int FLAG_FOREGROUND_SERVICE = 0x00000040;
public int flags;
public Notification2(String tickerText, long when) {
this.tickerText = tickerText;
this.when = when;
}
public void setLatestEventInfo(String title, String text) {
this.title = title;
this.text = text;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.pbf;
/**
* Maintains state about execution progress. It calculates when the next update
* is due, and provides statistics on execution.
*
* @author Brett Henderson
*/
public class ProgressTracker {
private int interval;
private boolean initialized;
private long firstUpdateTimestamp;
private long lastUpdateTimestamp;
private long objectCount;
private double objectsPerSecond;
/**
* Creates a new instance.
*
* @param interval
* The interval between logging progress reports in milliseconds.
*/
public ProgressTracker(int interval) {
this.interval = interval;
initialized = false;
}
/**
* Indicates if an update is due. This should be called once per object that
* is processed.
*
* @return True if an update is due.
*/
public boolean updateRequired() {
if (!initialized) {
lastUpdateTimestamp = System.currentTimeMillis();
firstUpdateTimestamp = System.currentTimeMillis();
objectCount = 0;
objectsPerSecond = 0;
initialized = true;
return false;
} else {
long currentTimestamp;
long duration;
// Calculate the time since the last update.
currentTimestamp = System.currentTimeMillis();
duration = currentTimestamp - lastUpdateTimestamp;
// Increment the processed object count.
objectCount++;
if (duration > interval || duration < 0) {
lastUpdateTimestamp = currentTimestamp;
// Calculate the number of objects processed per second.
objectsPerSecond = (double) objectCount * 1000 / (currentTimestamp-firstUpdateTimestamp);
return true;
} else {
return false;
}
}
}
/**
* Provides the number of objects processed per second. This only becomes
* valid after updateRequired returns true for the first time.
*
* @return The number of objects processed per second in the last timing
* interval.
*/
public double getObjectsPerSecond() {
return objectsPerSecond;
}
}
| Java |
package il.yrtimid.osm.osmpoi.pbf;
import il.yrtimid.osm.osmpoi.ItemPipe;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6.Sink;
public class EntityHandler implements Sink {
ItemPipe<Entity> itemPipe;
int maximumEntries = Integer.MAX_VALUE;
public EntityHandler(ItemPipe<Entity> itemPipe) {
this.itemPipe = itemPipe;
}
public void setMaximumEntries(int max) {
this.maximumEntries = max;
}
@Override
public void complete() {
// TODO Auto-generated method stub
}
@Override
public void release() {
// TODO Auto-generated method stub
}
@Override
public void process(Entity entity) {
if (maximumEntries > 0) {
this.itemPipe.pushItem(entity);
maximumEntries--;
}
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.pbf;
import org.openstreetmap.osmosis.core.task.v0_6.SinkSource;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6.Sink;
/**
* @author yrtimid
*
*/
public class PeriodicProgressNotifier implements SinkSource {
private Sink sink;
private ProgressTracker progressTracker;
private ProgressNotifier progressNotifier;
private Long count = 0L;
public PeriodicProgressNotifier(int interval, ProgressNotifier notifier) {
progressTracker = new ProgressTracker(interval);
progressNotifier = notifier;
}
public Long getCount(){
return count;
}
public void process(Entity entity) {
count++;
if (progressTracker.updateRequired() && progressNotifier != null) {
progressNotifier.onProgressChange(new ProgressNotifier.Progress(count, (int)progressTracker.getObjectsPerSecond()+ " obj/sec"));
}
sink.process(entity);
}
public void complete() {
if (progressNotifier != null){
progressNotifier.onProgressChange(new ProgressNotifier.Progress(count, count, (int)progressTracker.getObjectsPerSecond()+ " obj/sec"));
}
sink.complete();
}
public void release() {
sink.release();
}
public void setSink(Sink sink) {
this.sink = sink;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.pbf;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.Tag;
import il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher;
/**
* @author yrtimid
*
*/
public class EntityMatcher {
TagMatcher tagMatcher;
public EntityMatcher(TagMatcher tagMatcher) {
this.tagMatcher = tagMatcher;
}
public boolean isMatch(Entity entity){
for(Tag t:entity.getTags()){
if (tagMatcher.isMatch(t.getKey(), t.getValue()))
return true;
}
return false;
}
}
| Java |
package il.yrtimid.osm.osmpoi.pbf;
import il.yrtimid.osm.osmpoi.ItemPipe;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6.NullSink;
import java.io.InputStream;
import crosby.binary.file.BlockInputStream;
import crosby.binary.osmosis.OsmosisBinaryParser;
public class OsmImporter {
public static Long countEntities(InputStream input, ProgressNotifier progressNotifier){
Long result = 0L;
try {
OsmosisBinaryParser parser = new OsmosisBinaryParser();
PeriodicProgressNotifier counter = new PeriodicProgressNotifier(5000, progressNotifier);
parser.setSink(counter);
counter.setSink(new NullSink());
BlockInputStream stream = new BlockInputStream(input, parser);
stream.process();
stream.close();
result = counter.getCount();
}catch(Exception ioe){
ioe.printStackTrace();
result = -1L;
}
return result;
}
public static Long processAll(InputStream input, ItemPipe<Entity> newItemNotifier, ProgressNotifier progressNotifier){
Long result = 0L;
try {
OsmosisBinaryParser parser = new OsmosisBinaryParser();
PeriodicProgressNotifier counter = new PeriodicProgressNotifier(5000, progressNotifier);
EntityHandler handler = new EntityHandler(newItemNotifier);
parser.setSink(counter);
counter.setSink(handler);
BlockInputStream stream = new BlockInputStream(input, parser);
stream.process();
stream.close();
result = counter.getCount();
}catch(Exception ioe){
ioe.printStackTrace();
result = -1L;
}
return result;
}
}
| Java |
package il.yrtimid.osm.osmpoi.pbf;
public interface ProgressNotifier {
public void onProgressChange(Progress newProgress);
public class Progress{
private Long count;
private String message;
private Long maximum;
public Progress(Long count){
this.count = count;
}
public Progress(Long count, Long maximum){
this.count = count;
this.maximum = maximum;
}
public Progress(Long count, String message){
this.count = count;
this.message = message;
}
public Progress(Long count, Long maximum, String message){
this.count = count;
this.maximum = maximum;
this.message = message;
}
public Progress(String message){
this.message = message;
}
public Long getCount(){return count;}
public String getMessage(){return message;}
public Long getMaximum(){return maximum;}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder b = new StringBuilder();
if (count != null) b.append(count);
if (maximum != null) b.append("/").append(maximum);
if (message != null) b.append("; ").append(message);
return b.toString();
}
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package crosby.binary.osmosis;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6.Sink;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.openstreetmap.osmosis.core.OsmosisConstants;
import org.openstreetmap.osmosis.core.OsmosisRuntimeException;
import crosby.binary.BinaryParser;
import crosby.binary.Osmformat;
import crosby.binary.Osmformat.DenseInfo;
/** Class that reads and parses binary files and sends the contained entities to the sink. */
public class OsmosisBinaryParser extends BinaryParser {
@Override
public void complete() {
sink.complete();
sink.release();
}
/** The magic number used to indicate no version number metadata for this entity. */
static final int NOVERSION = -1;
/** The magic number used to indicate no changeset metadata for this entity. */
static final int NOCHANGESET = -1;
@Override
protected void parseNodes(List<Osmformat.Node> nodes) {
for (Osmformat.Node i : nodes) {
List<Tag> tags = new ArrayList<Tag>();
for (int j = 0; j < i.getKeysCount(); j++) {
tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j))));
}
// long id, int version, Date timestamp, OsmUser user,
// long changesetId, Collection<Tag> tags,
// double latitude, double longitude
Node tmp;
long id = i.getId();
double latf = parseLat(i.getLat()), lonf = parseLon(i.getLon());
if (i.hasInfo()) {
Osmformat.Info info = i.getInfo();
tmp = new Node(new CommonEntityData(id, getDate(info), tags), latf, lonf);
} else {
tmp = new Node(new CommonEntityData(id, NODATE, tags), latf, lonf);
}
sink.process(tmp);
}
}
@Override
protected void parseDense(Osmformat.DenseNodes nodes) {
long lastId = 0, lastLat = 0, lastLon = 0;
int j = 0; // Index into the keysvals array.
// Stuff for dense info
long lasttimestamp = 0, lastchangeset = 0;
int lastuserSid = 0, lastuid = 0;
DenseInfo di = null;
if (nodes.hasDenseinfo()) {
di = nodes.getDenseinfo();
}
for (int i = 0; i < nodes.getIdCount(); i++) {
Node tmp;
List<Tag> tags = new ArrayList<Tag>(0);
long lat = nodes.getLat(i) + lastLat;
lastLat = lat;
long lon = nodes.getLon(i) + lastLon;
lastLon = lon;
long id = nodes.getId(i) + lastId;
lastId = id;
double latf = parseLat(lat), lonf = parseLon(lon);
// If empty, assume that nothing here has keys or vals.
if (nodes.getKeysValsCount() > 0) {
while (nodes.getKeysVals(j) != 0) {
int keyid = nodes.getKeysVals(j++);
int valid = nodes.getKeysVals(j++);
tags.add(new Tag(getStringById(keyid), getStringById(valid)));
}
j++; // Skip over the '0' delimiter.
}
// Handle dense info.
if (di != null) {
int uid = di.getUid(i) + lastuid; lastuid = uid;
int userSid = di.getUserSid(i) + lastuserSid; lastuserSid = userSid;
long timestamp = di.getTimestamp(i) + lasttimestamp; lasttimestamp = timestamp;
@SuppressWarnings("unused")
int version = di.getVersion(i);
long changeset = di.getChangeset(i) + lastchangeset; lastchangeset = changeset;
Date date = new Date(date_granularity * timestamp);
tmp = new Node(new CommonEntityData(id, date, tags), latf, lonf);
} else {
tmp = new Node(new CommonEntityData(id, NODATE, tags), latf, lonf);
}
sink.process(tmp);
}
}
@Override
protected void parseWays(List<Osmformat.Way> ways) {
for (Osmformat.Way i : ways) {
List<Tag> tags = new ArrayList<Tag>();
for (int j = 0; j < i.getKeysCount(); j++) {
tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j))));
}
long lastId = 0;
List<Node> nodes = new ArrayList<Node>();
for (long j : i.getRefsList()) {
nodes.add(new Node(j + lastId));
lastId = j + lastId;
}
long id = i.getId();
// long id, int version, Date timestamp, OsmUser user,
// long changesetId, Collection<Tag> tags,
// List<WayNode> wayNodes
Way tmp;
if (i.hasInfo()) {
Osmformat.Info info = i.getInfo();
tmp = new Way(new CommonEntityData(id, getDate(info), tags), nodes);
} else {
tmp = new Way(new CommonEntityData(id, NODATE, tags), nodes);
}
sink.process(tmp);
}
}
@Override
protected void parseRelations(List<Osmformat.Relation> rels) {
for (Osmformat.Relation i : rels) {
List<Tag> tags = new ArrayList<Tag>();
for (int j = 0; j < i.getKeysCount(); j++) {
tags.add(new Tag(getStringById(i.getKeys(j)), getStringById(i.getVals(j))));
}
long id = i.getId();
long lastMid = 0;
List<RelationMember> nodes = new ArrayList<RelationMember>();
for (int j = 0; j < i.getMemidsCount(); j++) {
long mid = lastMid + i.getMemids(j);
lastMid = mid;
String role = getStringById(i.getRolesSid(j));
EntityType etype = null;
if (i.getTypes(j) == Osmformat.Relation.MemberType.NODE) {
etype = EntityType.Node;
} else if (i.getTypes(j) == Osmformat.Relation.MemberType.WAY) {
etype = EntityType.Way;
} else if (i.getTypes(j) == Osmformat.Relation.MemberType.RELATION) {
etype = EntityType.Relation;
} else {
assert false; // TODO; Illegal file?
}
nodes.add(new RelationMember(mid, etype, role));
}
// long id, int version, TimestampContainer timestampContainer,
// OsmUser user,
// long changesetId, Collection<Tag> tags,
// List<RelationMember> members
Relation tmp;
if (i.hasInfo()) {
Osmformat.Info info = i.getInfo();
tmp = new Relation(new CommonEntityData(id, getDate(info), tags), nodes);
} else {
tmp = new Relation(new CommonEntityData(id, NODATE, tags), nodes);
}
sink.process(tmp);
}
}
@Override
public void parse(Osmformat.HeaderBlock block) {
for (String s : block.getRequiredFeaturesList()) {
if (s.equals("OsmSchema-V0.6")) {
continue; // We can parse this.
}
if (s.equals("DenseNodes")) {
continue; // We can parse this.
}
throw new OsmosisRuntimeException("File requires unknown feature: " + s);
}
if (block.hasBbox()) {
String source = OsmosisConstants.VERSION;
if (block.hasSource()) {
source = block.getSource();
}
double multiplier = .000000001;
double rightf = block.getBbox().getRight() * multiplier;
double leftf = block.getBbox().getLeft() * multiplier;
double topf = block.getBbox().getTop() * multiplier;
double bottomf = block.getBbox().getBottom() * multiplier;
Bound bounds = new Bound(rightf, leftf, topf, bottomf, source);
sink.process(bounds);
}
}
/**
* {@inheritDoc}
*/
public void setSink(Sink sink) {
this.sink = sink;
}
private Sink sink;
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
@SuppressWarnings("serial")
public class SortedProperties extends Properties {
/**
* Overrides, called by the store method.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public synchronized Enumeration keys() {
Enumeration keysEnum = super.keys();
Vector keyList = new Vector();
while(keysEnum.hasMoreElements()){
keyList.add(keysEnum.nextElement());
}
Collections.sort(keyList);
return keyList.elements();
}
}
| Java |
package il.yrtimid.osm.osmpoi.tagmatchers;
import il.yrtimid.osm.osmpoi.domain.Entity;
public class AndMatcher extends BinaryMatcher {
public AndMatcher(TagMatcher left, TagMatcher right) {
this.left = left;
this.right = right;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(java.lang.CharSequence, java.lang.CharSequence)
*/
@Override
public Boolean isMatch(CharSequence key, CharSequence value) {
return left.isMatch(key,value) && right.isMatch(key,value);
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(il.yrtimid.osm.osmpoi.domain.Entity)
*/
@Override
public Boolean isMatch(Entity entity) {
return left.isMatch(entity) && right.isMatch(entity);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.tagmatchers;
import java.util.ArrayList;
import java.util.List;
/**
* @author yrtimid
*
*/
public abstract class BinaryMatcher extends TagMatcher {
protected TagMatcher left;
protected TagMatcher right;
public TagMatcher getLeft() {
return left;
}
public TagMatcher getRight() {
return right;
}
/**
* Returns all sibling items of same operator. For ex: ((a|b)|(c&d)|e) will return a,b,(c&d),e
* @return
*/
public List<TagMatcher> getAllSiblings() {
List<TagMatcher> list = new ArrayList<TagMatcher>();
getAllSiblings(this, list);
return list;
}
private void getAllSiblings(BinaryMatcher matcher, List<TagMatcher> list) {
if (this.getClass().isInstance(matcher.left))
getAllSiblings((BinaryMatcher)matcher.left, list);
else
list.add(matcher.left);
if (this.getClass().isInstance(matcher.right))
getAllSiblings((BinaryMatcher)matcher.right, list);
else
list.add(matcher.right);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.tagmatchers;
import il.yrtimid.osm.osmpoi.domain.*;
import il.yrtimid.osm.osmpoi.domain.EntityType;
/**
* @author yrtimid
*
*/
public class AssociatedMatcher extends TagMatcher {
EntityType entityType;
Long id;
public AssociatedMatcher(EntityType type, Long id) {
this.entityType = type;
this.id = id;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(java.lang.CharSequence, java.lang.CharSequence)
*/
@Override
public Boolean isMatch(CharSequence key, CharSequence value) {
return false;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(il.yrtimid.osm.osmpoi.domain.Entity)
*/
@Override
public Boolean isMatch(Entity entity) {
switch (entity.getType()){
case Node:
break;
case Way:
if (this.entityType.equals(EntityType.Node)){
for(Node n : ((Way)entity).getNodes()){
if (n.getId() == id) return true;
}
}
break;
case Relation:
for(RelationMember m : ((Relation)entity).getMembers()){
if (this.entityType.equals(m.getMemberType()) && this.id == m.getMemberId()) return true;
}
break;
}
return false;
}
/**
* @return the entityType
*/
public EntityType getEntityType() {
return entityType;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
}
| Java |
package il.yrtimid.osm.osmpoi.tagmatchers;
import il.yrtimid.osm.osmpoi.domain.Entity;
public class OrMatcher extends BinaryMatcher {
public OrMatcher(TagMatcher left, TagMatcher right) {
this.left = left;
this.right = right;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(java.lang.CharSequence, java.lang.CharSequence)
*/
@Override
public Boolean isMatch(CharSequence key, CharSequence value) {
return left.isMatch(key, value) || right.isMatch(key, value);
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(il.yrtimid.osm.osmpoi.domain.Entity)
*/
@Override
public Boolean isMatch(Entity entity) {
return left.isMatch(entity) || right.isMatch(entity);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.tagmatchers;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.EntityType;
/**
* @author yrtimid
*
*/
public class IdMatcher extends TagMatcher {
EntityType entityType;
Long id;
public IdMatcher(EntityType type, Long id) {
this.entityType = type;
this.id = id;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(java.lang.CharSequence, java.lang.CharSequence)
*/
@Override
public Boolean isMatch(CharSequence key, CharSequence value) {
return false;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(il.yrtimid.osm.osmpoi.domain.Entity)
*/
@Override
public Boolean isMatch(Entity entity) {
return entity.getType() == entityType && entity.getId() == id;
}
/**
* @return the entityType
*/
public EntityType getEntityType() {
return entityType;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
}
| Java |
package il.yrtimid.osm.osmpoi.tagmatchers;
import il.yrtimid.osm.osmpoi.domain.Entity;
public class NotMatcher extends TagMatcher {
TagMatcher matcher;
public NotMatcher(TagMatcher matcher) {
this.matcher = matcher;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(java.lang.CharSequence, java.lang.CharSequence)
*/
@Override
public Boolean isMatch(CharSequence key, CharSequence value) {
return !matcher.isMatch(key, value);
}
public TagMatcher getMatcher(){
return matcher;
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(il.yrtimid.osm.osmpoi.domain.Entity)
*/
@Override
public Boolean isMatch(Entity entity) {
return !matcher.isMatch(entity);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.tagmatchers;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.EntityType;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.List;
/**
* Base class for all entity filters
*
* @author yrtimiD
*/
public abstract class TagMatcher {
public abstract Boolean isMatch(CharSequence key, CharSequence value);
public static TagMatcher parse(CharSequence expression) throws InvalidParameterException {
String e = expression.toString();
if (e.length() == 0)
return new KeyValueMatcher("*", "*");
//trim braces
if (e.startsWith(Character.toString(OPEN_BRACE)) && e.endsWith(Character.toString(CLOSE_BRACE))){
e = e.substring(1, e.length()-1);
}
char op = '&';
String[] parts = splitBy(e, op);// (X | Y) & Z will become "(X | Y)", "Z"
if (parts.length == 1){
op = '|';
parts = splitBy(e, op);// (X & Y) | Z will become "(X & Y)", "Z"
}
if (parts.length == 1){
op = '!';
parts = splitBy(e, op);// !(X & Y) will become "", "(X & Y)"
}
if (parts.length == 1){
op = '=';
parts = splitBy(e, op);// X=Y Z will become "X", "Y Z"
}
if (parts.length == 1) { //no &,|,=
if (!e.contains("*")) e = "*"+e+"*";
return new KeyValueMatcher("*", e);
}else if (parts.length == 2 && op == '='){
if (parts[0].toLowerCase().equals("node_id"))
return new IdMatcher(EntityType.Node, Long.parseLong(parts[1]));
else if (parts[0].toLowerCase().equals("way_id"))
return new IdMatcher(EntityType.Way, Long.parseLong(parts[1]));
else if (parts[0].toLowerCase().equals("relation_id"))
return new IdMatcher(EntityType.Relation, Long.parseLong(parts[1]));
else
return new KeyValueMatcher(parts[0], parts[1]);
} else if (parts.length == 2 && op == '!') {
return new NotMatcher(parse(parts[1]));
} else {
if ((op=='&') || (op=='|')) {
TagMatcher left = parse(parts[0]);
for (int i = 1; i < parts.length; i++) { //operator index
TagMatcher right = parse(parts[i]);
if (op == '&'){
left = new AndMatcher(left, right);
} else if (op=='|'){
left = new OrMatcher(left, right);
} else {
throw new IllegalArgumentException("something goes wrong while parsing '"+e+"'");
}
}
return left;
}
else {
throw new InvalidParameterException("Unknown operator "+parts[1]+" in '"+e+"'");
}
}
}
enum States
{
NORMAL_PROGRESS,
MATCHING_BRACE_SEARCHING,
FOUND_END_OF_PART
}
private static final char OPEN_BRACE = '(';
private static final char CLOSE_BRACE = ')';
public static String[] splitBy(String expression, char separator)
{
List<String> parts = new ArrayList<String>();
States state = States.NORMAL_PROGRESS;
int index = 0;
int braces = 0;
boolean canProgress = true;
boolean canAppend = true;
StringBuilder currentPart = new StringBuilder();
while (index < expression.length())
{
char c = expression.charAt(index);
canProgress = true;
canAppend = true;
switch (state)
{
case NORMAL_PROGRESS:
if (c == OPEN_BRACE)
{
state = States.MATCHING_BRACE_SEARCHING;
braces++;
}
else if (c == separator)
{
state = States.FOUND_END_OF_PART;
canProgress = false;
canAppend = false;
}
break;
case MATCHING_BRACE_SEARCHING:
if (c == OPEN_BRACE)
braces++;
if (c == CLOSE_BRACE)
braces--;
if (braces == 0)
state = States.NORMAL_PROGRESS;
break;
case FOUND_END_OF_PART:
parts.add(currentPart.toString().trim());
currentPart.delete(0, currentPart.length());
state = States.NORMAL_PROGRESS;
canAppend = false;
break;
default:
break;
}
if (canAppend)
currentPart.append(c);
if (canProgress)
index++;
}
parts.add(currentPart.toString().trim());
return parts.toArray(new String[parts.size()]);
}
public abstract Boolean isMatch(Entity entity);
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
return this.toString().equals(obj.toString());
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return this.toString().hashCode();
}
}
| Java |
package il.yrtimid.osm.osmpoi.tagmatchers;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.Tag;
public class KeyValueMatcher extends TagMatcher {
private String k;
private String v;
/**
* Creates new matcher which will match tags with exact name of the key and
* exact value '*' may be used to match any key or any value. Example: *=* -
* matches all nodes with at least one tag name=* - matches nodes which has
* name tag with any value *=test - matches nodes which has any tag with the
* "test" value
*
* @param key
* - '*' for any
* @param value
* - '*' for any
*/
public KeyValueMatcher(String key, String value) {
this.k = key.replace('%', '*');
this.v = value.replace('%', '*');
}
@Override
public Boolean isMatch(CharSequence key, CharSequence value) {
return (isMatchPattern(key, k) && isMatchPattern(value, v));
}
private Boolean isMatchPattern(CharSequence value, CharSequence pattern) {
String pat = pattern.toString();
if (pattern.equals("*"))
return true;
boolean isExactMatch = !pat.contains("*");
boolean isBegins = false, isEnds = false, isContains = false;
if (pat.startsWith("*")) {
isBegins = true;
pat = pat.substring(1);
}
if (pat.endsWith("*")) {
isEnds = true;
pat = pat.substring(0, pat.length() - 1);
}
if (isBegins && isEnds) {
isContains = true;
isBegins = false;
isEnds = false;
}
if (isExactMatch) {
return value.toString().equalsIgnoreCase(pat);
}
else {
if (isBegins)
return value.toString().toLowerCase().startsWith(pat.toLowerCase());
else if (isEnds)
return value.toString().toLowerCase().endsWith(pat.toLowerCase());
else if (isContains)
return value.toString().toLowerCase().contains(pat.toLowerCase());
}
return false;
}
public String getKey() {
return k;
}
public String getValue() {
return v;
}
public boolean isKeyExactMatch() {
return !(k.contains("*"));
}
public boolean isValueExactMatch() {
return !(v.contains("*"));
}
/*
* (non-Javadoc)
*
* @see
* il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher#isMatch(il.yrtimid.osm.osmpoi
* .domain.Entity)
*/
@Override
public Boolean isMatch(Entity entity) {
for (Tag t : entity.getTags()) {
if (isMatch(t.getKey(), t.getValue()))
return true;
}
return false;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "key:"+k+"=value:"+v;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.EntityType;
import il.yrtimid.osm.osmpoi.domain.Tag;
import il.yrtimid.osm.osmpoi.tagmatchers.KeyValueMatcher;
import il.yrtimid.osm.osmpoi.tagmatchers.TagMatcher;
/**
* @author yrtimid
*
*/
public class ImportSettings {
HashMap<EntityType, List<KeyValueMatcher>> tagsInclude = new HashMap<EntityType, List<KeyValueMatcher>>();// allowed tags by entity
HashMap<EntityType, List<KeyValueMatcher>> tagsExclude = new HashMap<EntityType, List<KeyValueMatcher>>();// forbidden tags by entity
HashMap<EntityType, HashSet<KeyValueMatcher>> addressTags = new HashMap<EntityType, HashSet<KeyValueMatcher>>();// matchers collection to check if entity may be used for address search
HashSet<String> excludedKeys = new HashSet<String>(); // these keys will not be imported
// boolean onlyWithTags = false; // if entity have no tags - it will be excluded
Boolean isBuildGrid = true;
Boolean isClearBeforeImport = true;
Boolean importAddresses = false;
Integer gridCellSize = Integer.MAX_VALUE;
public ImportSettings() {
excludedKeys.add("created_by");
excludedKeys.add("source");
tagsInclude.put(EntityType.Node, new ArrayList<KeyValueMatcher>());
tagsInclude.put(EntityType.Way, new ArrayList<KeyValueMatcher>());
tagsInclude.put(EntityType.Relation, new ArrayList<KeyValueMatcher>());
tagsExclude.put(EntityType.Node, new ArrayList<KeyValueMatcher>());
tagsExclude.put(EntityType.Way, new ArrayList<KeyValueMatcher>());
tagsExclude.put(EntityType.Relation, new ArrayList<KeyValueMatcher>());
addressTags.put(EntityType.Node, new HashSet<KeyValueMatcher>());
addressTags.put(EntityType.Way, new HashSet<KeyValueMatcher>());
addressTags.put(EntityType.Relation, new HashSet<KeyValueMatcher>());
addressTags.get(EntityType.Node).add(new KeyValueMatcher("addr:*","*"));
addressTags.get(EntityType.Node).add(new KeyValueMatcher("place","*"));
addressTags.get(EntityType.Way).add(new KeyValueMatcher("addr:*","*"));
addressTags.get(EntityType.Way).add(new KeyValueMatcher("highway","*"));
addressTags.get(EntityType.Way).add(new KeyValueMatcher("place","*"));
addressTags.get(EntityType.Relation).add(new KeyValueMatcher("addr:*","*"));
addressTags.get(EntityType.Relation).add(new KeyValueMatcher("highway","*"));
addressTags.get(EntityType.Relation).add(new KeyValueMatcher("place","*"));
}
/**
* Creates settings instance with default configuration
* @return
*/
public static ImportSettings getDefault(){
ImportSettings settings = new ImportSettings();
settings.setBuildGrid(true);
settings.setClearBeforeImport(true);
settings.setKey(EntityType.Node, "name*", true);
settings.setKey(EntityType.Node, "highway", false);
settings.setKey(EntityType.Node, "building",false);
settings.setKey(EntityType.Node, "barrier", false);
//settings.setKey(EntityType.Node, "*", false);//excluding * will exclude all items of this type
settings.setKey(EntityType.Way, "name*", true);
settings.setKey(EntityType.Way, "building",true);
settings.setKey(EntityType.Way, "highway",false);
//settings.setKey(EntityType.Way, "*", false);//excluding * will exclude all items of this type
//settings.setKey(EntityType.Relation, "name*", true);
settings.setKeyValue(EntityType.Relation, "type","associatedStreet", false);
settings.setKey(EntityType.Relation, "boundary",false);
settings.setKeyValue(EntityType.Relation, "type", "bridge", true);
settings.setKeyValue(EntityType.Relation, "type", "destination_sign", false);
settings.setKeyValue(EntityType.Relation, "type", "enforcement", false);
settings.setKeyValue(EntityType.Relation, "type", "multipolygon", false);
settings.setKeyValue(EntityType.Relation, "type", "public_transport", true);
settings.setKeyValue(EntityType.Relation, "type", "relatedStreet", false);
settings.setKeyValue(EntityType.Relation, "type", "associatedStreet", false);
settings.setKeyValue(EntityType.Relation, "type", "restriction", false);
settings.setKeyValue(EntityType.Relation, "type", "network", true);
settings.setKeyValue(EntityType.Relation, "type", "operators", true);
settings.setKeyValue(EntityType.Relation, "type", "health", true);
settings.setKey(EntityType.Relation, "landuse",false);
settings.setKey(EntityType.Relation, "natural",false);
settings.setKey(EntityType.Relation, "leisure",false);
settings.setKey(EntityType.Relation, "area",false);
settings.setKey(EntityType.Relation, "waterway",false);
settings.setKey(EntityType.Relation, "type", false);
//settings.setKey(EntityType.Relation, "*",false);//excluding * will exclude all items of this type
settings.setImportAddresses(false);
settings.setGridCellSize(50000);
return settings;
}
public boolean isImportNodes(){
return !tagsInclude.get(EntityType.Node).isEmpty();
}
public boolean isImportWays(){
return !tagsInclude.get(EntityType.Way).isEmpty();
}
public boolean isImportRelations(){
return !tagsInclude.get(EntityType.Relation).isEmpty();
}
public void setBuildGrid(boolean isCreateGrid){
this.isBuildGrid = isCreateGrid;
}
public boolean isBuildGrid(){
return this.isBuildGrid;
}
public void setClearBeforeImport(boolean isClearBeforeImport) {
this.isClearBeforeImport = isClearBeforeImport;
}
public boolean isClearBeforeImport() {
return isClearBeforeImport;
}
public Boolean isImportAddresses() {
return importAddresses;
}
public void reset(EntityType type){
tagsInclude.get(type).clear();
tagsExclude.get(type).clear();
}
/*
* Removes key both from include and exclude lists
*/
public void resetKey(EntityType type, String key){
KeyValueMatcher matcher = new KeyValueMatcher(key,"*");
tagsInclude.get(type).remove(matcher);
tagsExclude.get(type).remove(matcher);
}
/*
* Removes key-value both from include and exclude lists
*/
public void resetKeyValue(EntityType type, String key, String value){
KeyValueMatcher matcher = new KeyValueMatcher(key, value);
tagsInclude.get(type).remove(matcher);
tagsExclude.get(type).remove(matcher);
}
public void setKey(EntityType type, String key, Boolean include){
resetKey(type, key);
KeyValueMatcher matcher = new KeyValueMatcher(key,"*");
if (include){
tagsInclude.get(type).add(matcher);
}else{
tagsExclude.get(type).add(matcher);
}
}
public void setKeyValue(EntityType type, String key, String value, Boolean include){
resetKeyValue(type, key, value);
KeyValueMatcher matcher = new KeyValueMatcher(key, value);
if (include)
tagsInclude.get(type).add(matcher);
else
tagsExclude.get(type).add(matcher);
}
public void setImportAddresses(boolean importAddresses) {
this.importAddresses = importAddresses;
}
public int getGridCellSize() {
return gridCellSize;
}
public void setGridCellSize(int gridCellSize) {
this.gridCellSize = gridCellSize;
}
public void cleanTags(Entity entity){
Collection<Tag> tagsToRemove = new ArrayList<Tag>();
for (Tag t : entity.getTags()) {
if (excludedKeys.contains(t.getKey())) {
tagsToRemove.add(t);
}
}
for(Tag t:tagsToRemove){
entity.getTags().remove(t);
}
}
public Boolean isPoi(Entity entity){
Boolean include=false;
Boolean exclude=false;
for(TagMatcher matcher : tagsExclude.get(entity.getType())){
Boolean match = matcher.isMatch(entity);
if (match){
exclude = true;
break;
}
}
if (exclude)
return false;
for(TagMatcher matcher : tagsInclude.get(entity.getType())){
Boolean match = matcher.isMatch(entity);
if (match){
include = true;
break;
}
}
if (include)
return true;
return false;
}
public Boolean isAddress(Entity entity){
for(TagMatcher check:addressTags.get(entity.getType())){
if (check.isMatch(entity))
return true;
}
return false;
}
public void writeToProperties(Properties props){
props.setProperty("import.isBuildGrid", isBuildGrid.toString());
props.setProperty("import.gridCellSize", gridCellSize.toString());
props.setProperty("import.importAddresses", importAddresses.toString());
for(EntityType entityType : tagsInclude.keySet()){
List<KeyValueMatcher> tags = tagsInclude.get(entityType);
for(KeyValueMatcher tm : tags){
props.setProperty("import.include."+entityType+"."+tm.getKey(), tm.getValue());
}
}
for(EntityType entityType : tagsExclude.keySet()){
List<KeyValueMatcher> tags = tagsExclude.get(entityType);
for(KeyValueMatcher tm : tags){
props.setProperty("import.exclude."+entityType+"."+tm.getKey(), tm.getValue());
}
}
}
public static ImportSettings createFromProperties(Properties props){
ImportSettings settings = new ImportSettings();
settings.setBuildGrid(Boolean.parseBoolean(props.getProperty("import.isBuildGrid", "true")));
settings.setGridCellSize(Integer.parseInt(props.getProperty("import.gridCellSize", new Integer(Integer.MAX_VALUE).toString())));
settings.setImportAddresses(Boolean.parseBoolean(props.getProperty("import.importAddresses", "false")));
for(Object key : props.keySet()){
String[] tokens = key.toString().split("\\.");
if (tokens.length != 4 || !tokens[0].equals("import"))
continue;
EntityType entityType = EntityType.valueOf(tokens[2]);
String k = tokens[3];
if (tokens[1].equals("include")){
settings.setKeyValue(entityType, k, props.getProperty(key.toString()), true);
}else if (tokens[1].equals("exclude")){
settings.setKeyValue(entityType, k, props.getProperty(key.toString()), false);
}
}
return settings;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
/**
* @author yrtimid
*
*/
public class Pair<A, B> {
private A a;
private B b;
public Pair(A a, B b){
this.a = a;
this.b = b;
}
/**
* @return the a
*/
public A getA() {
return a;
}
/**
* @return the b
*/
public B getB() {
return b;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dal;
import java.sql.SQLException;
import il.yrtimid.osm.osmpoi.domain.Node;
import il.yrtimid.osm.osmpoi.domain.Way;
/**
* @author yrtimid
*
*/
public interface IDbCachedFiller extends IDbFiller{
public abstract void beginAdd();
public abstract void endAdd();
public abstract void addNodeIfBelongsToWay(Node node) throws SQLException;
public abstract void addNodeIfBelongsToRelation(Node node) throws SQLException;
public abstract void addWayIfBelongsToRelation(Way way) throws SQLException;
} | Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dal;
/**
* @author yrtimid
*
*/
public class Queries {
public static final String BOUNDS_TABLE = "bounds";
public static final String NODES_TABLE = "nodes";
public static final String NODES_TAGS_TABLE = "node_tags";
public static final String WAYS_TABLE = "ways";
public static final String WAY_TAGS_TABLE = "way_tags";
public static final String WAY_NODES_TABLE = "way_nodes";
public static final String RELATIONS_TABLE = "relations";
public static final String RELATION_TAGS_TABLE = "relation_tags";
public static final String MEMBERS_TABLE = "members";
public static final String GRID_TABLE = "grid";
public static final String INLINE_QUERIES_TABLE = "inline_queries";
public static final String INLINE_RESULTS_TABLE = "inline_results";
public static final String STARRED_TABLE = "starred";
public static final String SQL_CREATE_BOUNDS_TABLE = "CREATE TABLE IF NOT EXISTS bounds ("+
"top REAL NOT NULL," +
"bottom REAL NOT NULL," +
"left REAL NOT NULL," +
"right REAL NOT NULL" +
")";
public static final String SQL_CREATE_NODE_TABLE = "CREATE TABLE IF NOT EXISTS nodes ("
+" id INTEGER NOT NULL PRIMARY KEY,"
+" timestamp TEXT,"
+" lon REAL NOT NULL,"
+" lat REAL NOT NULL,"
+" grid_id INTEGER NOT NULL DEFAULT (0)"
+")";
public static final String SQL_CREATE_NODE_TAGS_TABLE = "CREATE TABLE IF NOT EXISTS node_tags ("
+" node_id INTEGER NOT NULL,"
+" k TEXT,"
+" v TEXT"
+")";
public static final String SQL_NODE_TAGS_IDX = "CREATE UNIQUE INDEX IF NOT EXISTS node_tags_node_id_k_idx ON node_tags(node_id,k)";
public static final String SQL_CREATE_WAYS_TABLE = "CREATE TABLE IF NOT EXISTS ways ("
+" id INTEGER NOT NULL PRIMARY KEY,"
+" timestamp TEXT"
+")";
public static final String SQL_CREATE_WAY_TAGS_TABLE = "CREATE TABLE IF NOT EXISTS way_tags ("
+" way_id INTEGER NOT NULL,"
+" k TEXT,"
+" v TEXT"
+")";
public static final String SQL_WAY_TAGS_IDX = "CREATE UNIQUE INDEX IF NOT EXISTS way_tags_way_id_k_idx ON way_tags(way_id,k)";
public static final String SQL_CREATE_WAY_NODES_TABLE = "CREATE TABLE IF NOT EXISTS way_nodes ("
+" way_id INTEGER NOT NULL,"
+" node_id INTEGER NOT NULL"
+")";
public static final String SQL_WAY_NODES_WAY_NODE_IDX = "CREATE UNIQUE INDEX IF NOT EXISTS way_nodes_way_id_node_id_idx ON way_nodes(way_id,node_id)";
public static final String SQL_WAY_NODES_WAY_IDX = "CREATE INDEX IF NOT EXISTS way_nodes_way_id_idx ON way_nodes(way_id ASC)";
public static final String SQL_WAY_NODES_NODE_IDX = "CREATE INDEX IF NOT EXISTS way_nodes_node_id_idx ON way_nodes(node_id ASC)";
public static final String SQL_CREATE_RELATIONS_TABLE = "CREATE TABLE IF NOT EXISTS relations ("
+" id INTEGER NOT NULL PRIMARY KEY,"
+" timestamp TEXT"
+")";
public static final String SQL_CREATE_RELATION_TAGS_TABLE = "CREATE TABLE IF NOT EXISTS relation_tags ("
+" relation_id INTEGER NOT NULL,"
+" k TEXT,"
+" v TEXT"
+")";
public static final String SQL_RELATION_TAGS_IDX = "CREATE UNIQUE INDEX IF NOT EXISTS relation_tags_rel_id_k_idx ON relation_tags(relation_id,k)";
public static final String SQL_CREATE_MEMBERS_TABLE = "CREATE TABLE IF NOT EXISTS members ("
+" relation_id INTEGER NOT NULL,"
+" type TEXT,"
+" ref INTEGER NOT NULL,"
+" role TEXT"
+")";
public static final String SQL_RELATION_MEMBERS_IDX = "CREATE UNIQUE INDEX IF NOT EXISTS relation_members_rel_id_type_ref_role_idx ON members(relation_id,type,ref,role)";
public static final String SQL_CREATE_GRID_TABLE = "CREATE TABLE IF NOT EXISTS grid ("
+" id INTEGER PRIMARY KEY AUTOINCREMENT,"
+" minLat REAL NOT NULL,"
+" minLon REAL NOT NULL,"
+" maxLat REAL NOT NULL,"
+" maxLon REAL NOT NULL"
+")";
public static final String SQL_CREATE_INLINE_QUERIES_TABLE = "CREATE TABLE IF NOT EXISTS inline_queries (id INTEGER PRIMARY KEY AUTOINCREMENT, query TEXT NOT NULL, [select] TEXT NOT NULL)";
public static final String SQL_CREATE_INLINE_RESULTS_TABLE = "CREATE TABLE IF NOT EXISTS inline_results (query_id INTEGER NOT NULL, value TEXT)";
public static final String SQL_CREATE_STARRED_TABLE = "CREATE TABLE IF NOT EXISTS starred (type TEXT NOT NULL, id INTEGER NOT NULL, title TEXT NOT NULL)";
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dal;
import il.yrtimid.osm.osmpoi.domain.Bound;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.Node;
import il.yrtimid.osm.osmpoi.domain.Relation;
import il.yrtimid.osm.osmpoi.domain.Way;
import java.sql.SQLException;
/**
* @author yrtimid
*
*/
public interface IDbFiller extends IDatabase{
public abstract void clearAll() throws Exception;
public abstract void initGrid() throws SQLException;
public abstract void addEntity(Entity entity) throws SQLException;
public abstract void addBound(Bound bound) throws SQLException;
public abstract void addNode(Node node) throws SQLException;
//public abstract void addNodes(Collection<Node> nodes);
public abstract void addNodeTags(Node node) throws SQLException;
//public abstract void addNodeTag(long nodeId, Tag tag);
//public abstract void addNodesTags(Collection<Node> nodes);
public abstract void addWay(Way way) throws SQLException;
//public abstract void addWayTag(long wayId, Tag tag);
public abstract void addWayTags(Way way) throws SQLException;
//public abstract void addWayNode(long wayId, int index, Node wayNode);
public abstract void addWayNodes(Way way) throws SQLException;
public abstract void addRelation(Relation rel) throws SQLException;
//public abstract void addRelationTag(long relId, Tag tag);
public abstract void addRelationTags(Relation rel) throws SQLException;
//public abstract void addRelationMember(long relId, int index, RelationMember mem);
public abstract void addRelationMembers(Relation rel) throws SQLException;
/**
* Splits large cells until no cells with node count greater than maxItems least
* @param maxItems
*/
public abstract void optimizeGrid(Integer maxItems) throws SQLException;
} | Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dal;
/**
* @author yrtimid
*
*/
public interface IDatabase {
void create() throws Exception;
void drop();
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
/**
* A data class representing a single OSM tag.
*
* @author Brett Henderson
*/
public class Tag implements Comparable<Tag>{
/**
* The key identifying the tag.
*/
private String key;
/**
* The value associated with the tag.
*/
private String value;
protected Tag(){}
/**
* Creates a new instance.
*
* @param key
* The key identifying the tag.
* @param value
* The value associated with the tag.
*/
public Tag(String key, String value) {
this.key = key;
this.value = value;
}
/**
* Compares this tag to the specified tag. The tag comparison is based on a
* comparison of key and value in that order.
*
* @param tag
* The tag to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered
* "bigger".
*/
public int compareTo(Tag tag) {
int keyResult;
keyResult = this.key.compareTo(tag.key);
if (keyResult != 0) {
return keyResult;
}
return this.value.compareTo(tag.value);
}
/**
* @return The key.
*/
public String getKey() {
return key;
}
/**
* @return The value.
*/
public String getValue() {
return value;
}
/**
* ${@inheritDoc}.
*/
@Override
public String toString() {
return "Tag('" + getKey() + "'='" + getValue() + "')";
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* Contains data common to all entity types. This is separated from the entity
* class to allow it to be instantiated before all the data required for a full
* entity is available.
*/
public class CommonEntityData {
protected long id;
protected long timestamp;
protected TagCollection tags;
protected CommonEntityData(){}
public CommonEntityData(long id) {
this(id, 0, new ArrayList<Tag>());
}
public CommonEntityData(long id, Date date) {
this(id, date.getTime(), new ArrayList<Tag>());
}
public CommonEntityData(long id, Date date, Collection<Tag> tags) {
this(id, date.getTime(), tags);
}
public CommonEntityData(long id, long timestamp) {
this(id, timestamp, new ArrayList<Tag>());
}
public CommonEntityData(long id, long timestamp, Collection<Tag> tags) {
this.id = id;
this.timestamp = timestamp;
this.tags = new TagCollection(tags);
}
/**
* Gets the identifier.
*
* @return The id.
*/
public long getId() {
return id;
}
/**
* Sets the identifier.
*
* @param id
* The identifier.
*/
public void setId(long id) {
this.id = id;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
/**
* Returns the attached tags. If the class is read-only, the collection will
* be read-only.
*
* @return The tags.
*/
public TagCollection getTags() {
return tags;
}
/**
* Compares the tags on this entity to the specified tags. The tag
* comparison is based on a comparison of key and value in that order.
*
* @param comparisonTags
* The tags to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered
* "bigger".
*/
protected int compareTags(Collection<Tag> comparisonTags) {
List<Tag> tags1;
List<Tag> tags2;
tags1 = new ArrayList<Tag>(tags);
tags2 = new ArrayList<Tag>(comparisonTags);
Collections.sort(tags1);
Collections.sort(tags2);
// The list with the most tags is considered bigger.
if (tags1.size() != tags2.size()) {
return tags1.size() - tags2.size();
}
// Check the individual tags.
for (int i = 0; i < tags1.size(); i++) {
int result = tags1.get(i).compareTo(tags2.get(i));
if (result != 0) {
return result;
}
}
// There are no differences.
return 0;
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import java.util.Collection;
/**
* A data class representing a single OSM node.
*
* @author Brett Henderson
*/
public class Node extends Entity implements Comparable<Node>{
protected double latitude;
protected double longitude;
protected Node(){
this(new CommonEntityData(), 0.0, 0.0);
}
/**
* Creates a new instance.
*
* @param entityData
* The common entity data.
* @param latitude
* The geographic latitude.
* @param longitude
* The geographic longitude.
*/
public Node(CommonEntityData entityData, double latitude, double longitude) {
super(entityData);
this.latitude = latitude;
this.longitude = longitude;
}
public Node(long nodeId){
this(new CommonEntityData(nodeId, -1), 0L, 0L);
}
/**
* {@inheritDoc}
*/
@Override
public EntityType getType() {
return EntityType.Node;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
if (o instanceof Node) {
return compareTo((Node) o) == 0;
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
/*
* As per the hashCode definition, this doesn't have to be unique it just has to return the
* same value for any two objects that compare equal. Using both id and version will provide
* a good distribution of values but is simple to calculate.
*/
return (int) getId();
}
/**
* Compares this node to the specified node. The node comparison is based on a comparison of id,
* version, latitude, longitude, timestamp and tags in that order.
*
* @param comparisonNode
* The node to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered "bigger".
*/
public int compareTo(Node comparisonNode) {
if (this.getId() < comparisonNode.getId()) {
return -1;
}
if (this.getId() > comparisonNode.getId()) {
return 1;
}
if (this.latitude < comparisonNode.latitude) {
return -1;
}
if (this.latitude > comparisonNode.latitude) {
return 1;
}
if (this.longitude < comparisonNode.longitude) {
return -1;
}
if (this.longitude > comparisonNode.longitude) {
return 1;
}
if (this.getTimestamp()<comparisonNode.getTimestamp()){
return -1;
}
if (this.getTimestamp()>comparisonNode.getTimestamp()){
return 1;
}
return compareTags(comparisonNode.getTags());
}
/**
* Gets the latitude.
*
* @return The latitude.
*/
public double getLatitude() {
return latitude;
}
/**
* Sets the latitude.
*
* @param latitude
* The latitude.
*/
public void setLatitude(double latitude) {
this.latitude = latitude;
}
/**
* Gets the longitude.
*
* @return The longitude.
*/
public double getLongitude() {
return longitude;
}
/**
* Sets the longitude.
*
* @param longitude
* The longitude.
*/
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public boolean hasTags(){
return this.getTags().size()>0;
}
/**
* ${@inheritDoc}.
*/
@Override
public String toString() {
String name = null;
Collection<Tag> tags = getTags();
for (Tag tag : tags) {
if (tag.getKey() != null && tag.getKey().equalsIgnoreCase("name")) {
name = tag.getValue();
break;
}
}
if (name != null) {
return "Node(id=" + getId() + ", #tags=" + getTags().size() + ", name='" + name + "')";
}
return "Node(id=" + getId() + ", #tags=" + getTags().size() + ")";
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.domain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
/**
* @author yrtimid
*
*/
public class TagCollection extends ArrayList<Tag> {
private static final long serialVersionUID = -3930512868581794286L;
/**
* Creates a new instance.
*/
public TagCollection() {
super();
}
/**
* Creates a new instance.
*
* @param tags
* The initial tags.
*/
public TagCollection(Collection<? extends Tag> tags) {
super(tags);
}
public Map<String, String> buildMap() {
Map<String, String> tagMap;
tagMap = new HashMap<String, String>(size());
for (Tag tag : this) {
tagMap.put(tag.getKey(), tag.getValue());
}
return tagMap;
}
static final Comparator<Tag> COMPARATOR = new Comparator<Tag>(){
@Override
public int compare(Tag object1, Tag object2) {
return object1.compareTo(object2);
}
};
public Collection<Tag> getSorted(){
ArrayList<Tag> copy = new ArrayList<Tag>(this);
Collections.sort(copy, COMPARATOR);
return copy;
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* A data class representing a single OSM way.
*
* @author Brett Henderson
*/
public class Way extends Entity implements Comparable<Way> {
private List<Node> nodes;
private List<WayNode> wayNodes;
protected Way() {
this(new CommonEntityData());
}
/**
* Creates a new instance.
*
* @param entityData
* The common entity data.
*/
public Way(CommonEntityData entityData) {
super(entityData);
this.nodes = new ArrayList<Node>();
this.wayNodes = new ArrayList<WayNode>();
}
public Way(long wayId){
this(new CommonEntityData(wayId));
}
/**
* Creates a new instance.
*
* @param entityData
* The common entity data.
* @param wayNodes
* The way nodes to apply to the object
*/
public Way(CommonEntityData entityData, List<Node> nodes) {
super(entityData);
this.nodes = new ArrayList<Node>(nodes);
this.wayNodes = new ArrayList<WayNode>();
}
/**
* {@inheritDoc}
*/
@Override
public EntityType getType() {
return EntityType.Way;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
if (o instanceof Way) {
return compareTo((Way) o) == 0;
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return (int) getId();
}
/**
* Compares this node list to the specified node list. The comparison is
* based on a direct comparison of the node ids.
*
* @param comparisonWayNodes
* The node list to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered
* "bigger".
*/
protected int compareNodes(List<Node> comparisonWayNodes) {
Iterator<Node> i;
Iterator<Node> j;
// The list with the most entities is considered bigger.
if (nodes.size() != comparisonWayNodes.size()) {
return nodes.size() - comparisonWayNodes.size();
}
// Check the individual way nodes.
i = nodes.iterator();
j = comparisonWayNodes.iterator();
while (i.hasNext()) {
int result = i.next().compareTo(j.next());
if (result != 0) {
return result;
}
}
// There are no differences.
return 0;
}
/**
* Compares this way to the specified way. The way comparison is based on a
* comparison of id, version, timestamp, wayNodeList and tags in that order.
*
* @param comparisonWay
* The way to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered
* "bigger".
*/
public int compareTo(Way comparisonWay) {
int wayNodeListResult;
if (this.getId() < comparisonWay.getId()) {
return -1;
}
if (this.getId() > comparisonWay.getId()) {
return 1;
}
if (this.getTimestamp()<comparisonWay.getTimestamp()) {
return -1;
}
if (this.getTimestamp()>comparisonWay.getTimestamp()) {
return 1;
}
wayNodeListResult = compareNodes(
comparisonWay.getNodes()
);
if (wayNodeListResult != 0) {
return wayNodeListResult;
}
return compareTags(comparisonWay.getTags());
}
public List<Node> getNodes() {
return nodes;
}
public List<WayNode> getWayNodes() {
return wayNodes;
}
/**
* Is this way closed? (A way is closed if the first node id equals the last node id.)
*
* @return True or false
*/
public boolean isClosed() {
return nodes.get(0).getId() == nodes.get(nodes.size() - 1).getId();
}
/**
* ${@inheritDoc}.
*/
@Override
public String toString() {
String name = null;
Collection<Tag> tags = getTags();
for (Tag tag : tags) {
if (tag.getKey() != null && tag.getKey().equalsIgnoreCase("name")) {
name = tag.getValue();
break;
}
}
if (name != null) {
return "Way(id=" + getId() + ", #tags=" + getTags().size() + ", name='" + name + "')";
}
return "Way(id=" + getId() + ", #tags=" + getTags().size() + ")";
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* A data class representing a single OSM relation.
*
* @author Brett Henderson
*/
public class Relation extends Entity implements Comparable<Relation>{
private List<RelationMember> members;
protected Relation(){
this(new CommonEntityData());
}
/**
* Creates a new instance.
*
* @param entityData
* The common entity data.
*/
public Relation(CommonEntityData entityData) {
super(entityData);
this.members = new ArrayList<RelationMember>();
}
/**
* Creates a new instance.
*
* @param entityData
* The common entity data.
* @param members
* The members to apply to the object.
*/
public Relation(CommonEntityData entityData, List<RelationMember> members) {
super(entityData);
this.members = new ArrayList<RelationMember>(members);
}
public Relation(long relationId){
this(new CommonEntityData(relationId, -1));
}
/**
* {@inheritDoc}
*/
@Override
public EntityType getType() {
return EntityType.Relation;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
if (o instanceof Relation) {
return compareTo((Relation) o) == 0;
} else {
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
/*
* As per the hashCode definition, this doesn't have to be unique it
* just has to return the same value for any two objects that compare
* equal. Using both id and version will provide a good distribution of
* values but is simple to calculate.
*/
return (int) getId();
}
/**
* Compares this member list to the specified member list. The bigger list
* is considered bigger, if that is equal then each relation member is
* compared.
*
* @param comparisonMemberList
* The member list to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered
* "bigger".
*/
protected int compareMemberList(Collection<RelationMember> comparisonMemberList) {
Iterator<RelationMember> i;
Iterator<RelationMember> j;
// The list with the most entities is considered bigger.
if (members.size() != comparisonMemberList.size()) {
return members.size() - comparisonMemberList.size();
}
// Check the individual node references.
i = members.iterator();
j = comparisonMemberList.iterator();
while (i.hasNext()) {
int result = i.next().compareTo(j.next());
if (result != 0) {
return result;
}
}
// There are no differences.
return 0;
}
/**
* Compares this relation to the specified relation. The relation comparison
* is based on a comparison of id, version, timestamp, and tags in that order.
*
* @param comparisonRelation
* The relation to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered
* "bigger".
*/
public int compareTo(Relation comparisonRelation) {
int memberListResult;
if (this.getId() < comparisonRelation.getId()) {
return -1;
}
if (this.getId() > comparisonRelation.getId()) {
return 1;
}
if (this.getTimestamp()<comparisonRelation.getTimestamp()) {
return -1;
}
if (this.getTimestamp()>comparisonRelation.getTimestamp()) {
return 1;
}
memberListResult = compareMemberList(
comparisonRelation.members
);
if (memberListResult != 0) {
return memberListResult;
}
return compareTags(comparisonRelation.getTags());
}
public List<RelationMember> getMembers() {
return members;
}
/**
* ${@inheritDoc}.
*/
@Override
public String toString() {
String type = null;
Collection<Tag> tags = getTags();
for (Tag tag : tags) {
if (tag.getKey() != null && tag.getKey().equalsIgnoreCase("type")) {
type = tag.getValue();
break;
}
}
if (type != null) {
return "Relation(id=" + getId() + ", #tags=" + getTags().size() + ", type='" + type + "')";
}
return "Relation(id=" + getId() + ", #tags=" + getTags().size() + ")";
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import java.security.InvalidParameterException;
/**
* A data class representing a single member within a relation entity.
*
* @author Brett Henderson
*/
public class RelationMember implements Comparable<RelationMember>{
private String memberRole;
private Entity member = null;
protected RelationMember(){}
public RelationMember(Entity member, String memberRole) {
this.memberRole = memberRole;
this.member = member;
}
public RelationMember(long memberId, EntityType memberType, String memberRole) {
this.memberRole = memberRole;
switch(memberType){
case Node:
this.member = new Node(memberId);
break;
case Way:
this.member = new Way(memberId);
break;
case Relation:
this.member = new Relation(memberId);
break;
default:
throw new InvalidParameterException("Unsupported member type: "+memberType.name());
}
}
/**
* Compares this relation member to the specified relation member. The
* relation member comparison is based on a comparison of member type, then
* member id, then role.
*
* @param relationMember
* The relation member to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered
* "bigger".
*/
public int compareTo(RelationMember relationMember) {
long result;
// Compare the member type.
result = this.getMemberType().compareTo(relationMember.getMemberType());
if (result > 0) {
return 1;
} else if (result < 0) {
return -1;
}
// Compare the member id.
result = this.getMemberId() - relationMember.getMemberId();
if (result > 0) {
return 1;
} else if (result < 0) {
return -1;
}
// Compare the member role.
result = this.memberRole.compareTo(relationMember.memberRole);
if (result > 0) {
return 1;
} else if (result < 0) {
return -1;
}
// No differences detected.
return 0;
}
/**
* Returns the id of the member entity.
*
* @return The member id.
*/
public long getMemberId() {
return member.getId();
}
/**
* Returns the type of the member entity.
*
* @return The member type.
*/
public EntityType getMemberType() {
return member.getType();
}
/**
* Returns the role that this member forms within the relation.
*
* @return The role.
*/
public String getMemberRole() {
return memberRole;
}
/**
* @param memberRole the memberRole to set
*/
public void setMemberRole(String memberRole) {
this.memberRole = memberRole;
}
/**
* @return the member
*/
public Entity getMember() {
return member;
}
/**
* @param member the member to set
*/
public void setMember(Entity member) {
this.member = member;
}
/**
* ${@inheritDoc}.
*/
@Override
public String toString() {
return "RelationMember(" + getMemberType() + " with id " + getMemberId() + " in the role '" + getMemberRole()
+ "')";
}
}
| Java |
package il.yrtimid.osm.osmpoi.domain;
public class WayNode extends Entity {
protected WayNode(){
this(new CommonEntityData());
}
/**
* Creates a new instance.
*
* @param entityData
* The common entity data.
*/
public WayNode(CommonEntityData entityData) {
super(entityData);
}
public WayNode(long nodeId) {
super(new CommonEntityData(nodeId));
}
@Override
public EntityType getType() {
return EntityType.NodeRef;
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import java.util.Collection;
/**
* A data class representing a single OSM entity. All top level data types
* inherit from this class.
*
* @author Brett Henderson
*/
public abstract class Entity{
protected CommonEntityData entityData;
protected Entity(){}
/**
* Creates a new instance.
*
* @param entityData
* The data to store in the entity. This instance is used directly and is not cloned.
*/
public Entity(CommonEntityData entityData) {
this.entityData = entityData;
}
/**
* Returns the specific data type represented by this entity.
*
* @return The entity type enum value.
*/
public abstract EntityType getType();
/**
* Gets the identifier.
*
* @return The id.
*/
public long getId() {
return entityData.getId();
}
/**
* Sets the identifier.
*
* @param id
* The identifier.
*/
public void setId(long id) {
entityData.setId(id);
}
/**
* Gets the timestamp in date form. This is the standard method for
* retrieving timestamp information.
*
* @return The timestamp.
*/
public long getTimestamp() {
return entityData.getTimestamp();
}
/**
* Sets the timestamp in date form. This is the standard method of updating a timestamp.
*
* @param timestamp
* The timestamp.
*/
public void setTimestamp(long timestamp) {
entityData.setTimestamp(timestamp);
}
/**
* Returns the attached tags. If the class is read-only, the collection will
* be read-only.
*
* @return The tags.
*/
public TagCollection getTags() {
return entityData.getTags();
}
/**
* Compares the tags on this entity to the specified tags. The tag
* comparison is based on a comparison of key and value in that order.
*
* @param comparisonTags
* The tags to compare to.
* @return 0 if equal, < 0 if considered "smaller", and > 0 if considered
* "bigger".
*/
protected int compareTags(Collection<Tag> comparisonTags) {
return entityData.compareTags(comparisonTags);
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
import java.util.Date;
/**
* A data class representing an OSM data bound element.
*
* @author Karl Newman
*/
public class Bound extends Entity {
private static final double MIN_LATITUDE = -90.0;
private static final double MAX_LATITUDE = 90.0;
private static final double MIN_LONGITUDE = -180.0;
private static final double MAX_LONGITUDE = 180.0;
private double right;
private double left;
private double top;
private double bottom;
private String origin;
/**
* Creates a new instance which covers the entire planet.
*
* @param origin
* The origin (source) of the data, typically a URI
*
*/
public Bound(String origin) {
this(MAX_LONGITUDE, MIN_LONGITUDE, MAX_LATITUDE, MIN_LATITUDE, origin);
}
/**
* Creates a new instance with the specified boundaries.
*
* @param right
* The longitude coordinate of the right (East) edge of the bound
* @param left
* The longitude coordinate of the left (West) edge of the bound
* @param top
* The latitude coordinate of the top (North) edge of the bound
* @param bottom
* The latitude coordinate of the bottom (South) edge of the bound
* @param origin
* The origin (source) of the data, typically a URI
*/
public Bound(double right, double left, double top, double bottom, String origin) {
super(new CommonEntityData(0, new Date())); // minimal underlying entity
// Check if any coordinates are out of bounds
if (Double.compare(right, MAX_LONGITUDE + 1.0d) > 0
|| Double.compare(right, MIN_LONGITUDE - 1.0d) < 0
|| Double.compare(left, MAX_LONGITUDE + 1.0d) > 0
|| Double.compare(left, MIN_LONGITUDE - 1.0d) < 0
|| Double.compare(top, MAX_LATITUDE + 1.0d) > 0
|| Double.compare(top, MIN_LATITUDE - 1.0d) < 0
|| Double.compare(bottom, MAX_LATITUDE + 1.0d) > 0
|| Double.compare(bottom, MIN_LATITUDE - 1.0d) < 0) {
throw new IllegalArgumentException("Bound coordinates outside of valid range");
}
if (Double.compare(top, bottom) < 0) {
throw new IllegalArgumentException("Bound top < bottom");
}
if (origin == null) {
throw new IllegalArgumentException("Bound origin is null");
}
this.right = right;
this.left = left;
this.top = top;
this.bottom = bottom;
this.origin = origin;
}
/**
* {@inheritDoc}
*/
@Override
public EntityType getType() {
return EntityType.Bound;
}
/**
* @return The right (East) bound longitude
*/
public double getRight() {
return right;
}
/**
* @return The left (West) bound longitude
*/
public double getLeft() {
return left;
}
/**
* @return The top (North) bound latitude
*/
public double getTop() {
return top;
}
/**
* @return The bottom (South) bound latitude
*/
public double getBottom() {
return bottom;
}
/**
* @return the origin
*/
public String getOrigin() {
return origin;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
/*
* As per the hashCode definition, this doesn't have to be unique it
* just has to return the same value for any two objects that compare
* equal. Using both id and version will provide a good distribution of
* values but is simple to calculate.
*/
return (int) getId();
}
/**
* ${@inheritDoc}.
*/
@Override
public String toString() {
return "Bound(top=" + getTop() + ", bottom=" + getBottom() + ", left=" + getLeft() + ", right=" + getRight()
+ ")";
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.domain;
/**
* An enum representing the different data types in the OSM data model.
*
* @author Brett Henderson
*/
public enum EntityType {
None,
/**
* Representation of the latitude/longitude bounding box of the entity stream.
*/
Bound,
/**
* Represents a geographical point.
*/
Node,
/**
* Represents a set of segments forming a path.
*/
Way,
/**
* Represents a relationship between multiple entities.
*/
Relation,
NodeRef
}
| Java |
package il.yrtimid.osm.osmpoi;
public interface ItemPipe<T> {
public void pushItem(T item);
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.xml.v0_6.impl;
import il.yrtimid.osm.osmpoi.domain.EntityType;
import java.util.HashMap;
import java.util.Map;
import org.openstreetmap.osmosis.core.OsmosisRuntimeException;
/**
* Parses the xml representation of a relation member type into an entity type
* object.
*
* @author Brett Henderson
*/
public class MemberTypeParser {
private static final Map<String, EntityType> MEMBER_TYPE_MAP = new HashMap<String, EntityType>();
static {
MEMBER_TYPE_MAP.put("node", EntityType.Node);
MEMBER_TYPE_MAP.put("way", EntityType.Way);
MEMBER_TYPE_MAP.put("relation", EntityType.Relation);
}
/**
* Parses the database representation of a relation member type into an
* entity type object.
*
* @param memberType
* The database value of member type.
* @return A strongly typed entity type.
*/
public EntityType parse(String memberType) {
if (MEMBER_TYPE_MAP.containsKey(memberType)) {
return MEMBER_TYPE_MAP.get(memberType);
} else {
throw new OsmosisRuntimeException("The member type " + memberType + " is not recognised.");
}
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.xml.v0_6.impl;
/**
* Defines some common constants shared between various xml processing classes.
*
* @author Brett Henderson
*/
public final class XmlConstants {
/**
* This class cannot be instantiated.
*/
private XmlConstants() {
}
/**
* Defines the version number to be stored in osm xml files. This number
* will also be applied to osmChange files.
*/
public static final String OSM_VERSION = "0.6";
/**
* The default URL for the production API.
*/
public static final String DEFAULT_URL = "http://www.openstreetmap.org/api/0.6";
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core.lifecycle;
/**
* Classes that hold heavyweight resources that can't wait for garbage
* collection should implement this interface. It provides a release method that
* should be called by all clients when the class is no longer required. This
* release method is guaranteed not to throw exceptions and should always be
* called within a finally clause.
*
* @author Brett Henderson
*/
public interface Releasable {
/**
* Performs resource cleanup tasks such as closing files, or database
* connections. This must be called after all processing is complete and may
* be called multiple times. Implementations must call release on any nested
* Releasable objects. It should be called within a finally block to ensure
* it is called in exception scenarios.
*/
void release();
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core.lifecycle;
/**
* Some class implementations persist information and require notification to
* complete all output prior to being released. In this case, clients of those
* classes should call the complete method.
*
* @author Brett Henderson
*/
public interface Completable extends Releasable {
/**
* Ensures that all information is fully persisted. This includes database
* commits, file buffer flushes, etc. Implementations must call complete on
* any nested Completable objects. Where the releasable method of a
* Releasable class should be called within a finally block, this method
* should typically be the final statement within the try block.
*/
void complete();
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core;
/**
* Constants shared across the Osmosis application.
*
* @author Brett Henderson
*/
public final class OsmosisConstants {
/**
* This class cannot be instantiated.
*/
private OsmosisConstants() {
}
/**
* Defines the version of the Osmosis application.
*/
public static final String VERSION = "0.39-70-g0d3a7b7";
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core.task.v0_6;
import il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6.Sink;
import org.openstreetmap.osmosis.core.task.common.Task;
/**
* Defines the interface for tasks producing OSM data types.
*
* @author Brett Henderson
*/
public interface Source extends Task {
/**
* Sets the osm sink to send data to.
*
* @param sink
* The sink for receiving all produced data.
*/
void setSink(Sink sink);
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core.task.v0_6;
/**
* Extends the basic Source interface with the Runnable capability. Runnable
* is not applied to the Source interface because tasks that act as filters
* do not require Runnable capability.
*
* @author Brett Henderson
*/
public interface RunnableSource extends Source, Runnable {
// This interface combines Source and Runnable but doesn't introduce
// methods of its own.
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core.task.v0_6;
import il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6.Sink;
/**
* Defines the interface for combining sink and source functionality. This is
* typically used by classes performing some form of translation on an input
* source before sending along to the output. This includes filtering tasks and
* modification tasks.
*
* @author Brett Henderson
*/
public interface SinkSource extends Sink, Source {
// Interface only combines functionality of its extended interfaces.
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core.task.common;
/**
* Defines the root of the interface inheritance hierarchy for all task types.
*
* @author Brett Henderson
*/
public interface Task {
// Interface only exists to provide a common hierarchy root for all task
// types.
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package org.openstreetmap.osmosis.core;
/**
* The root of the unchecked exception hierarchy for the application. All typed
* runtime exceptions subclass this exception.
*
* @author Brett Henderson
*/
public class OsmosisRuntimeException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new exception with <code>null</code> as its detail message.
*/
public OsmosisRuntimeException() {
super();
}
/**
* Constructs a new exception with the specified detail message. The
* cause is not initialized, and may subsequently be initialized by
* a call to {@link #initCause}.
*
* @param message the detail message.
*/
public OsmosisRuntimeException(String message) {
super(message);
}
/**
* Constructs a new exception with the specified cause and a detail
* message of <tt>(cause==null ? null : cause.toString())</tt> (which
* typically contains the class and detail message of <tt>cause</tt>).
*
* @param cause the cause.
*/
public OsmosisRuntimeException(Throwable cause) {
super(cause);
}
/**
* Constructs a new exception with the specified detail message and
* cause.
*
* @param message the detail message.
* @param cause the cause.
*/
public OsmosisRuntimeException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6;
import il.yrtimid.osm.osmpoi.domain.Entity;
/**
* @author yrtimid
*
*/
public class NullSink implements Sink {
/* (non-Javadoc)
* @see org.openstreetmap.osmosis.core.lifecycle.Completable#complete()
*/
@Override
public void complete() {
}
/* (non-Javadoc)
* @see org.openstreetmap.osmosis.core.lifecycle.Releasable#release()
*/
@Override
public void release() {
}
/* (non-Javadoc)
* @see org.openstreetmap.osmosis.core.task.v0_6.Sink#process(org.openstreetmap.osmosis.core.container.v0_6.EntityContainer)
*/
@Override
public void process(Entity entity) {
}
}
| Java |
// This software is released into the Public Domain. See copying.txt for details.
package il.yrtimid.osm.osmpoi.osmosis.core.task.v0_6;
import il.yrtimid.osm.osmpoi.domain.Entity;
import org.openstreetmap.osmosis.core.lifecycle.Completable;
import org.openstreetmap.osmosis.core.task.common.Task;
/**
* Defines the interface for tasks consuming OSM data types.
*
* @author Brett Henderson
*/
public interface Sink extends Task, Completable {
/**
* Process the entity.
*
* @param entityContainer
* The entity to be processed.
*/
void process(Entity entity);
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.db;
import il.yrtimid.osm.osmpoi.dal.IDatabase;
import il.yrtimid.osm.osmpoi.dal.Queries;
import java.io.File;
import java.sql.*;
/**
* @author yrtimid
*
*/
public class SqliteJDBCCreator extends SqliteJDBCDatabase implements IDatabase {
protected Connection conn;
/**
* @throws Exception
*
*/
public SqliteJDBCCreator(String filePath) throws Exception {
super(filePath);
this.conn = getConnection();
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.IDatabase#create(java.lang.String)
*/
@Override
public void create() throws Exception {
this.conn = getConnection();
createAllTables();
}
protected void execSQL(String query) throws SQLException{
Statement statement = null;
try {
statement = conn.createStatement();
statement.executeUpdate(query);
}finally{
if (statement!=null)
statement.close();
}
}
private void createAllTables() throws SQLException{
execSQL(Queries.SQL_CREATE_BOUNDS_TABLE);
execSQL(Queries.SQL_CREATE_NODE_TABLE);
execSQL(Queries.SQL_CREATE_NODE_TAGS_TABLE);
execSQL(Queries.SQL_NODE_TAGS_IDX);
execSQL(Queries.SQL_CREATE_WAYS_TABLE);
execSQL(Queries.SQL_CREATE_WAY_TAGS_TABLE);
execSQL(Queries.SQL_WAY_TAGS_IDX);
execSQL(Queries.SQL_CREATE_WAY_NODES_TABLE);
execSQL(Queries.SQL_WAY_NODES_WAY_NODE_IDX);
execSQL(Queries.SQL_WAY_NODES_WAY_IDX);
execSQL(Queries.SQL_WAY_NODES_NODE_IDX);
execSQL(Queries.SQL_CREATE_RELATIONS_TABLE);
execSQL(Queries.SQL_CREATE_RELATION_TAGS_TABLE);
execSQL(Queries.SQL_RELATION_TAGS_IDX);
execSQL(Queries.SQL_CREATE_MEMBERS_TABLE);
execSQL(Queries.SQL_RELATION_MEMBERS_IDX);
execSQL(Queries.SQL_CREATE_GRID_TABLE);
execSQL(Queries.SQL_CREATE_INLINE_QUERIES_TABLE);
execSQL(Queries.SQL_CREATE_INLINE_RESULTS_TABLE);
}
@Override
public void drop() {
new File(filePath).delete();
this.conn = null;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.db;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import il.yrtimid.osm.osmpoi.Pair;
import il.yrtimid.osm.osmpoi.dal.IDbFiller;
import il.yrtimid.osm.osmpoi.dal.Queries;
import il.yrtimid.osm.osmpoi.Log;
import il.yrtimid.osm.osmpoi.domain.Bound;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.Node;
import il.yrtimid.osm.osmpoi.domain.Relation;
import il.yrtimid.osm.osmpoi.domain.RelationMember;
import il.yrtimid.osm.osmpoi.domain.Tag;
import il.yrtimid.osm.osmpoi.domain.Way;
/**
* @author yrtimid
*
*/
public class SqliteJDBCFiller extends SqliteJDBCCreator implements IDbFiller {
public SqliteJDBCFiller(String filePath) throws Exception {
super(filePath);
}
@Override
public void clearAll() throws Exception {
drop();
//dropAllTables(db);
create();
}
@Override
public void initGrid() throws SQLException{
//db.execSQL("UPDATE "+NODES_TABLE+" SET grid_id=1");
execSQL("DROP TABLE IF EXISTS "+Queries.GRID_TABLE);
execSQL(Queries.SQL_CREATE_GRID_TABLE);
String sql_generate_grid = "INSERT INTO grid (minLat, minLon, maxLat, maxLon)"
+" SELECT min(lat) minLat, min(lon) minLon, max(lat) maxLat, max(lon) maxLon"
+" FROM nodes";
Log.d(sql_generate_grid);
execSQL(sql_generate_grid);
String updateNodesGrid = "UPDATE nodes SET grid_id = 1 WHERE grid_id <> 1";
Log.d(updateNodesGrid);
execSQL(updateNodesGrid);
}
@Override
public void addEntity(Entity entity) throws SQLException {
if (entity instanceof Node)
addNode((Node) entity);
else if (entity instanceof Way)
addWay((Way) entity);
else if (entity instanceof Relation)
addRelation((Relation) entity);
else if (entity instanceof Bound)
addBound((Bound)entity);
}
public void addBound(Bound bound) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT INTO "+Queries.BOUNDS_TABLE+" (top, bottom, left, right) VALUES(?,?,?,?)");
statement.setDouble(1, bound.getTop());
statement.setDouble(2, bound.getBottom());
statement.setDouble(3, bound.getLeft());
statement.setDouble(4, bound.getRight());
int res = statement.executeUpdate();
if (res != 1)
throw new SQLException("Bound was not inserted");
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void addNode(Node node) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT OR IGNORE INTO "+Queries.NODES_TABLE+" (id, timestamp, lat, lon, grid_id) VALUES(?,?,?,?,?)");
statement.setLong(1, node.getId());
statement.setLong(2, node.getTimestamp());
statement.setDouble(3, node.getLatitude());
statement.setDouble(4, node.getLongitude());
statement.setInt(5, 1);
statement.executeUpdate();
addNodeTags(node);
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void addNodeTags(Node node) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT OR IGNORE INTO "+Queries.NODES_TAGS_TABLE+" (node_id, k, v) VALUES(?,?,?)");
final long id = node.getId();
statement.setLong(1, id);
for(Tag tag:node.getTags()){
statement.setString(2, tag.getKey());
statement.setString(3, tag.getValue());
statement.executeUpdate();
}
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void addWay(Way way) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT OR IGNORE INTO "+Queries.WAYS_TABLE+" (id, timestamp) VALUES(?,?)");
statement.setLong(1, way.getId());
statement.setLong(2, way.getTimestamp());
statement.executeUpdate();
addWayTags(way);
addWayNodes(way);
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void addWayTags(Way way) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT OR IGNORE INTO "+Queries.WAY_TAGS_TABLE+" (way_id, k, v) VALUES(?,?,?)");
statement.setLong(1, way.getId());
for(Tag tag : way.getTags()){
statement.setString(2, tag.getKey());
statement.setString(3, tag.getValue());
statement.executeUpdate();
}
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void addWayNodes(Way way) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT OR IGNORE INTO "+Queries.WAY_NODES_TABLE+" (way_id, node_id) VALUES(?,?)");
statement.setLong(1, way.getId());
for(Node node : way.getNodes()){
statement.setLong(2, node.getId());
statement.executeUpdate();
}
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void addRelation(Relation rel) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT OR IGNORE INTO "+Queries.RELATIONS_TABLE+" (id, timestamp) VALUES(?,?)");
statement.setLong(1, rel.getId());
statement.setLong(2, rel.getTimestamp());
statement.executeUpdate();
addRelationTags(rel);
addRelationMembers(rel);
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void addRelationTags(Relation rel) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT OR IGNORE INTO "+Queries.RELATION_TAGS_TABLE+" (relation_id, k, v) VALUES(?,?,?)");
final long id = rel.getId();
statement.setLong(1, id);
for(Tag tag : rel.getTags()){
statement.setString(2, tag.getKey());
statement.setString(3, tag.getValue());
statement.executeUpdate();
}
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void addRelationMembers(Relation rel) throws SQLException {
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("INSERT OR IGNORE INTO "+Queries.MEMBERS_TABLE+" (relation_id, type, ref, role) VALUES(?,?,?,?)");
statement.setLong(1, rel.getId());
for(RelationMember mem : rel.getMembers()){
statement.setString(2, mem.getMemberType().name());
statement.setLong(3, mem.getMemberId());
statement.setString(4, mem.getMemberRole());
statement.executeUpdate();
}
}finally{
if (statement != null)
statement.close();
}
}
@Override
public void optimizeGrid(Integer maxItems) throws SQLException {
Collection<Pair<Integer,Integer>> cells = null;
conn.setAutoCommit(false);
do{
cells = getBigCells(maxItems);
Log.d("OptimizeGrid: "+cells.size()+" cells needs optimization for "+maxItems+" items");
for(Pair<Integer,Integer> cell : cells){
Log.d("OptimizeGrid: cell_id="+cell.getA()+", cell size="+cell.getB());
splitGridCell(cell.getA());
conn.commit();
}
}while(cells.size() > 0);
}
/**
* finds cells which have nodes count greater than minItems
* @param minItems
* @return
* @throws SQLException
*/
private Collection<Pair<Integer,Integer>> getBigCells(Integer minItems) throws SQLException{
Statement statement = null;
Collection<Pair<Integer,Integer>> gridIds = new ArrayList<Pair<Integer,Integer>>();
ResultSet cur = null;
try{
statement = conn.createStatement();
String sql = "SELECT grid_id, count(id) [count] FROM "+Queries.NODES_TABLE+" GROUP BY grid_id HAVING count(id)>"+minItems.toString();
cur = statement.executeQuery(sql);
while(cur.next()){
Integer id = cur.getInt("grid_id");
Integer count = cur.getInt("count");
gridIds.add(new Pair<Integer, Integer>(id, count));
}
}finally{
if (cur != null)
cur.close();
if (statement != null)
statement.close();
}
return gridIds;
}
/**
* Splits cell into 4 pieces and updates theirs nodes with the new split
* @param id ID of the cell to split
* @throws SQLException
*/
private void splitGridCell(Integer id) throws SQLException{
Statement statement = null;
PreparedStatement prepStatement = null;
ResultSet cur = null;
try {
statement = conn.createStatement();
Log.d("splitGridCell id:"+id);
//calc new cell size to be 1/2 of the old one
String getNewCellSizeSql = "SELECT round((maxLat-minLat)/2,7) dLat, round((maxLon-minLon)/2,7) dLon from "+Queries.GRID_TABLE+" WHERE id="+id.toString();
cur = statement.executeQuery(getNewCellSizeSql);
cur.next();
Double newCellSizeLat = cur.getDouble(1);
Double newCellSizeLon = cur.getDouble(2);
cur.close();
statement.close();
Log.d("newCellSizeLat="+newCellSizeLat+" newCellSizeLon="+newCellSizeLon);
String create4NewCellsSql;
create4NewCellsSql = "INSERT INTO grid (minLat, minLon, maxLat, maxLon) \n"
+" SELECT * FROM (\n"
+" SELECT minLat, minLon, minLat+%1$f, minLon+%2$f FROM grid where id = %3$d\n"
+" union all\n"
+" SELECT minLat+%1$f, minLon, maxLat, minLon+%2$f FROM grid where id = %3$d\n"
+" union all\n"
+" SELECT minLat, minLon+%2$f, minLat+%1$f, maxLon FROM grid where id = %3$d\n"
+" union all\n"
+" SELECT minLat+%1$f, minLon+%2$f, maxLat, maxLon FROM grid where id = %3$d\n"
+" )\n";
create4NewCellsSql = String.format(create4NewCellsSql, newCellSizeLat, newCellSizeLon, id);
Log.d(create4NewCellsSql);
prepStatement = conn.prepareStatement(create4NewCellsSql);
prepStatement.executeUpdate();
prepStatement.close();
//delete old cell
statement = conn.createStatement();
String deleteOldCellSql = "DELETE FROM "+Queries.GRID_TABLE+" WHERE id="+id.toString();
Log.d(deleteOldCellSql);
int deleteResult = statement.executeUpdate(deleteOldCellSql);
Log.d("deleted "+deleteResult+" cells");
statement.close();
//update nodes to use new cells
statement = conn.createStatement();
String updateNodesSql = "UPDATE nodes SET grid_id = (SELECT g.id FROM "+Queries.GRID_TABLE+" g WHERE lat>=minLat AND lat<=maxLat AND lon>=minLon AND lon<=maxLon limit 1) WHERE grid_id="+id.toString();
Log.d(updateNodesSql);
statement.executeUpdate(updateNodesSql);
}finally{
if (cur != null)
cur.close();
if (statement != null)
statement.close();
if (prepStatement != null)
prepStatement.close();
}
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.db;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import il.yrtimid.osm.osmpoi.dal.IDbCachedFiller;
import il.yrtimid.osm.osmpoi.dal.Queries;
import il.yrtimid.osm.osmpoi.domain.Entity;
import il.yrtimid.osm.osmpoi.domain.Node;
import il.yrtimid.osm.osmpoi.domain.Way;
/**
* @author yrtimid
*
*/
public class SqliteJDBCCachedFiller extends SqliteJDBCFiller implements IDbCachedFiller {
private static int MAX_UNCOMMITTED_ITEMS = 10000;
int uncommittedItems = 0;
/**
* @param filePath
* @throws Exception
*/
public SqliteJDBCCachedFiller(String filePath) throws Exception {
super(filePath);
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbCachedFiller#beginAdd()
*/
@Override
public void beginAdd() {
try {
conn.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbCachedFiller#endAdd()
*/
@Override
public void endAdd() {
try {
conn.commit();
conn.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.db.SqliteJDBCFiller#addEntity(il.yrtimid.osm.osmpoi.domain.Entity)
*/
@Override
public void addEntity(Entity entity) throws SQLException {
super.addEntity(entity);
uncommittedItems++;
if (uncommittedItems>=MAX_UNCOMMITTED_ITEMS){
try {
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
uncommittedItems = 0;
}
}
@Override
public void addNodeIfBelongsToWay(Node node) throws SQLException{
Statement statement = null;
ResultSet cur = null;
boolean exists = false;
try {
statement = conn.createStatement();
String sql = "SELECT way_id from "+Queries.WAY_NODES_TABLE+" WHERE node_id="+node.getId();
cur = statement.executeQuery(sql);
if (cur.next()){
long way_id = cur.getLong(1);
exists = true;
}
cur.close();
statement.close();
}finally{
if (cur != null)
cur.close();
if (statement != null)
statement.close();
}
if (exists)
addEntity(node);
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbCachedFiller#addNodeIfBelongsToRelation(il.yrtimid.osm.osmpoi.domain.Node)
*/
@Override
public void addNodeIfBelongsToRelation(Node node) throws SQLException{
Statement statement = null;
ResultSet cur = null;
boolean exists = false;
try {
statement = conn.createStatement();
String sql = "SELECT relation_id from "+Queries.MEMBERS_TABLE+" WHERE type='Node' AND ref="+node.getId();
cur = statement.executeQuery(sql);
if (cur.next()){
long way_id = cur.getLong(1);
exists = true;
}
cur.close();
statement.close();
}finally{
if (cur != null)
cur.close();
if (statement != null)
statement.close();
}
if (exists)
addEntity(node);
}
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dal.IDbCachedFiller#addWayIfBelongsToRelation(il.yrtimid.osm.osmpoi.domain.Way)
*/
@Override
public void addWayIfBelongsToRelation(Way way) throws SQLException{
Statement statement = null;
ResultSet cur = null;
boolean exists = false;
try {
statement = conn.createStatement();
String sql = "SELECT relation_id from "+Queries.MEMBERS_TABLE+" WHERE type='Way' AND ref="+way.getId();
cur = statement.executeQuery(sql);
if (cur.next()){
long way_id = cur.getLong(1);
exists = true;
}
cur.close();
statement.close();
}finally{
if (cur != null)
cur.close();
if (statement != null)
statement.close();
}
if (exists)
addEntity(way);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.db;
import il.yrtimid.osm.osmpoi.dal.Queries;
import il.yrtimid.osm.osmpoi.domain.GridCell;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author yrtimid
*
*/
public class SqliteJDBCGridReader extends SqliteJDBCDatabase {
/**
* @throws ClassNotFoundException
*
*/
public SqliteJDBCGridReader(String filePath) throws ClassNotFoundException {
super(filePath);
}
public Collection<GridCell> getGrid() throws SQLException{
Connection conn = getConnection();
Statement statement = null;
ResultSet cur = null;
Collection<GridCell> cells = new ArrayList<GridCell>();
try {
statement = conn.createStatement();
cur = statement.executeQuery("SELECT * FROM "+Queries.GRID_TABLE);
while(cur.next()){
Integer id = cur.getInt("id");
double minLat = cur.getDouble("minLat");
double maxLat = cur.getDouble("maxLat");
double minLon = cur.getDouble("minLon");
double maxLon = cur.getDouble("maxLon");
cells.add(new GridCell(id, minLat, minLon, maxLat, maxLon));
}
}finally{
if (cur != null)
cur.close();
if (statement != null)
statement.close();
if (conn != null)
conn.close();
}
return cells;
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* @author yrtimid
*
*/
public class SqliteJDBCDatabase {
String filePath;
/**
* @throws ClassNotFoundException
*
*/
public SqliteJDBCDatabase(String filePath) throws ClassNotFoundException {
this.filePath = filePath;
Class.forName("org.sqlite.JDBC");
}
protected Connection getConnection() throws SQLException{
return DriverManager.getConnection("jdbc:sqlite:" + filePath);
}
}
| Java |
package il.yrtimid.osm.osmpoi.dbcreator;
import il.yrtimid.osm.osmpoi.ImportSettings;
import il.yrtimid.osm.osmpoi.SortedProperties;
import il.yrtimid.osm.osmpoi.db.SqliteJDBCCachedFiller;
import il.yrtimid.osm.osmpoi.db.SqliteJDBCGridReader;
import il.yrtimid.osm.osmpoi.dbcreator.common.DbCreator;
import il.yrtimid.osm.osmpoi.domain.GridCell;
import il.yrtimid.osm.osmpoi.domain.Point;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Collection;
/**
*
*/
/**
* @author yrtimid
*
*/
public class DbCreatorConsole {
private static final String PROPERTIES_FILE_NAME = "dbcreator.properties";
private static ImportSettings settings = null;
private static final String ARGUMENT_CREATE = "--create";
private static final String ARGUMENT_SAVE_GRID = "--save-grid";
private static final String ARGUMENT_REBUILD_GRID = "--rebuild-grid";
/**
* @param args
*/
public static void main(String[] args) {
createSettings();
//////////////DEBUG/////////////////////
// args = new String[2];
// args[0] = "--create";
// args[1] = "israel_and_palestine.osm.pbf";
if (args.length == 2) {
if (ARGUMENT_CREATE.equals(args[0])) {
create(args[1]);
return;
} else if (ARGUMENT_SAVE_GRID.equals(args[0])) {
saveGrid(args[1]);
return;
} else if (ARGUMENT_REBUILD_GRID.equals(args[0])){
rebuildGrid(args[1]);
return;
}
}
printHelp();
}
private static void printHelp() {
System.out.println("Usage:");
System.out.println(ARGUMENT_CREATE + " <pbf file name>\tcreate new DB from PBF file");
System.out.println(ARGUMENT_SAVE_GRID + " <db file>\toutputs grid from DB in poly format (dev option)");
System.out.println(ARGUMENT_REBUILD_GRID + " <db file>\trebuilds grid (dev option)");
System.out.println("");
}
private static void createSettings() {
try {
File propsFile = new File(PROPERTIES_FILE_NAME);
SortedProperties props = new SortedProperties();
if (propsFile.exists()) {
props.load(new FileInputStream(propsFile));
settings = ImportSettings.createFromProperties(props);
} else {
settings = ImportSettings.getDefault();
settings.writeToProperties(props);
props.store(new FileOutputStream(propsFile), "OsmPoi-Db-Creator default settings");
System.out.println("New " + PROPERTIES_FILE_NAME + " file created with default settings");
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param dbFilePath path to the db file with grid
*/
private static void saveGrid(String dbFilePath) {
PrintStream stream = System.out;
try {
File dbFile = new File(dbFilePath);
if (dbFile.canRead()) {
stream.println(dbFile.getName().replace('.', '_'));
SqliteJDBCGridReader gridReader = new SqliteJDBCGridReader(dbFilePath);
Collection<GridCell> cells = gridReader.getGrid();
for(GridCell c : cells){
stream.println(c.getId());
for(int i=0;i<4;i++){
Point p = c.getVertex(i);
stream.println("\t"+p.getLongitude()+"\t"+p.getLatitude());
}
stream.println("END");
}
stream.println("END");
} else {
System.err.println("Can't read db file: " + dbFilePath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param sourceFilePath path to the *.pbf file to import from
*/
private static void create(String sourceFilePath) {
String poiDbName = "poi.db";
String addrDbName = "addr.db";
File poiDbFile = new File(poiDbName);
File addrDbFile = new File(addrDbName);
if (poiDbFile.exists()) {
System.out.println("Deleting old poi db");
poiDbFile.delete();
}
if (addrDbFile.exists()) {
System.out.println("Deleting old addr db");
addrDbFile.delete();
}
System.out.println("Processing file " + sourceFilePath);
System.out.println(new File(".").getAbsolutePath());
DbCreator creator;
try {
creator = new DbCreator(new SqliteJDBCCachedFiller(poiDbName), new SqliteJDBCCachedFiller(addrDbName), new ConsoleNotificationManager());
//creator.createEmptyDatabases();
creator.importToDB(sourceFilePath, settings);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done.");
}
private static void rebuildGrid(String dbFilePath) {
try {
File dbFile = new File(dbFilePath);
if (dbFile.canRead()) {
DbCreator creator = new DbCreator(new SqliteJDBCCachedFiller(dbFilePath), null, new ConsoleNotificationManager());
creator.rebuildGrid(settings);
} else {
System.err.println("Can't read db file: " + dbFilePath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.dbcreator;
import il.yrtimid.osm.osmpoi.dbcreator.common.*;
/**
* @author yrtimid
*
*/
public class ConsoleNotificationManager implements INotificationManager {
/* (non-Javadoc)
* @see il.yrtimid.osm.osmpoi.dbcreator.INotificationManager#notify(int, il.yrtimid.osm.osmpoi.dbcreator.Notification)
*/
@Override
public void notify(int id, Notification2 notification){
System.out.println(notification.title+": "+notification.text);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi;
/**
* @author yrtimid
* use setprop log.tag.OsmPoi VERBOSE to enable logging
*/
public class Log {
static final String TAG = "OsmPoi";
public static void i(String string) {
System.out.println(TAG+": "+string);
}
public static void w(String string) {
System.out.println(TAG+": "+string);
}
public static void e(String string) {
System.out.println(TAG+": "+string);
}
public static void d(String string) {
System.out.println(TAG+": "+string);
}
public static void v(String string) {
System.out.println(TAG+": "+string);
}
public static void wtf(String message, Throwable throwable) {
System.out.println(TAG+": "+message);
throwable.printStackTrace(System.out);
}
}
| Java |
/**
*
*/
package il.yrtimid.osm.osmpoi.domain;
/**
* @author yrtimid
*
*/
public class GridCell {
int id;
double minLat, minLon, maxLat, maxLon;
/**
* @param id
* @param minLat
* @param minLon
* @param maxLat
* @param maxLon
*/
public GridCell(int id, double minLat, double minLon, double maxLat, double maxLon) {
super();
this.id = id;
this.minLat = minLat;
this.minLon = minLon;
this.maxLat = maxLat;
this.maxLon = maxLon;
}
/**
*
* @param 0-based vertex index [0..3]
* @return
* @throws Exception
*/
public Point getVertex(int index) throws Exception{
switch(index){
case 0:
return new Point(minLat, minLon);
case 1:
return new Point(minLat, maxLon);
case 2:
return new Point(maxLat, maxLon);
case 3:
return new Point(maxLat, minLon);
default:
throw new Exception("Only index from 0 to 3 inclusive is supported");
}
}
/**
* @return the id
*/
public int getId() {
return id;
}
}
| Java |
package il.yrtimid.osm.osmpoi.domain;
/**
* @author yrtimid
*
*/
public class Point {
Double latitude;
Double longitude;
int radius;
public Point(Point point) {
this.latitude = point.latitude;
this.longitude = point.longitude;
}
public Point(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
public Double getLatitude() {
return latitude;
}
public Double getLongitude() {
return longitude;
}
/**
* @param latitude the latitude to set
*/
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
/**
* @param longitude the longitude to set
*/
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.