input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
@Override
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
try {
setBackground(null);
setForeground(null);
setFont(null);
setIcon(null);
setHorizontalAlignment(SwingConstants.LEADING);
super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
int r = table.convertRowIndexToModel(row);
int c = table.convertColumnIndexToModel(column);
String url = table.getModel().getValueAt(r, DatenDownload.DOWNLOAD_URL_NR).toString();
// Abos
boolean abo = !table.getModel().getValueAt(r, DatenDownload.DOWNLOAD_ABO_NR).equals("");
// Starts
Start s = ddaten.starterClass.getStart(url);
if (s != null) {
setColor(this, s, isSelected);
if (c == DatenDownload.DOWNLOAD_RESTZEIT_NR) {
if (s.restSekunden > 0) {
if (s.restSekunden < 60) {
this.setText("< 1 Min.");
} else {
this.setText(Long.toString(s.restSekunden / 60) + " Min.");
}
} else {
this.setText("");
}
} else if (c == DatenDownload.DOWNLOAD_PROGRESS_NR) {
int i = Integer.parseInt(s.datenDownload.arr[DatenDownload.DOWNLOAD_PROGRESS_NR]);
setHorizontalAlignment(SwingConstants.CENTER);
if (i == -1) {
// noch nicht gestartet
this.setText("");
} else if (i == DatenDownload.PROGRESS_WARTEN) {
this.setText("warten");
} else if (i == DatenDownload.PROGRESS_GESTARTET) {
this.setText("gestartet");
} else if (1 < i && i < DatenDownload.PROGRESS_FERTIG) {
////// return new ProgressPanel(s).progressPanel();
JProgressBar progressBar = new JProgressBar(0, 1000);
JPanel panel = new JPanel(new BorderLayout());
setColor(panel, s, isSelected);
setColor(progressBar, s, isSelected);
progressBar.setBorder(BorderFactory.createEmptyBorder());
progressBar.setStringPainted(true);
progressBar.setUI(new BasicProgressBarUI() {
@Override
protected Color getSelectionBackground() {
return UIManager.getDefaults().getColor("Table.foreground");
}
@Override
protected Color getSelectionForeground() {
return Color.white;
}
});
panel.add(progressBar);
panel.setBorder(BorderFactory.createEmptyBorder());
progressBar.setValue(i);
double d = i / 10.0;
progressBar.setString(Double.toString(d) + "%");
return panel;
} else if (i == DatenDownload.PROGRESS_FERTIG) {
if (s != null) {
if (s.status == Start.STATUS_ERR) {
this.setText("fehlerhaft");
} else {
this.setText("fertig");
}
} else {
this.setText("fertig");
}
}
}
} else {
if (c == DatenDownload.DOWNLOAD_PROGRESS_NR) {
this.setText("");
}
}
if (c == DatenDownload.DOWNLOAD_ABO_NR) {
setFont(new java.awt.Font("Dialog", Font.BOLD, 12));
if (abo) {
setForeground(GuiKonstanten.ABO_FOREGROUND);
} else {
setForeground(GuiKonstanten.DOWNLOAD_FOREGROUND);
setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/nein_12.png")));
setHorizontalAlignment(SwingConstants.CENTER);
}
}
if (c == DatenDownload.DOWNLOAD_PROGRAMM_RESTART_NR) {
boolean restart = ddaten.listeDownloads.getDownloadByUrl(url).isRestart();
setHorizontalAlignment(SwingConstants.CENTER);
if (restart) {
setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/ja_16.png")));
} else {
setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/nein_12.png")));
}
}
} catch (Exception ex) {
Log.fehlerMeldung(758200166, Log.FEHLER_ART_PROG, this.getClass().getName(), ex);
}
return this;
}
#location 99
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
try {
setBackground(null);
setForeground(null);
setFont(null);
setIcon(null);
setHorizontalAlignment(SwingConstants.LEADING);
super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
int r = table.convertRowIndexToModel(row);
int c = table.convertColumnIndexToModel(column);
String url = table.getModel().getValueAt(r, DatenDownload.DOWNLOAD_URL_NR).toString();
DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url);
// Abos
boolean abo = !table.getModel().getValueAt(r, DatenDownload.DOWNLOAD_ABO_NR).equals("");
// Starts
Start s = ddaten.starterClass.getStart(url);
if (s != null) {
setColor(this, s, isSelected);
}
if (c == DatenDownload.DOWNLOAD_RESTZEIT_NR) {
this.setText(download.getTextRestzeit(ddaten, s));
} else if (c == DatenDownload.DOWNLOAD_PROGRESS_NR) {
int i = Integer.parseInt(download.arr[DatenDownload.DOWNLOAD_PROGRESS_NR]);
setHorizontalAlignment(SwingConstants.CENTER);
if (s != null && 1 < i && i < DatenDownload.PROGRESS_FERTIG) {
JProgressBar progressBar = new JProgressBar(0, 1000);
JPanel panel = new JPanel(new BorderLayout());
if (s != null) {
setColor(panel, s, isSelected);
setColor(progressBar, s, isSelected);
}
progressBar.setBorder(BorderFactory.createEmptyBorder());
progressBar.setStringPainted(true);
progressBar.setUI(new BasicProgressBarUI() {
@Override
protected Color getSelectionBackground() {
return UIManager.getDefaults().getColor("Table.foreground");
}
@Override
protected Color getSelectionForeground() {
return Color.white;
}
});
panel.add(progressBar);
panel.setBorder(BorderFactory.createEmptyBorder());
progressBar.setValue(i);
double d = i / 10.0;
progressBar.setString(Double.toString(d) + "%");
return panel;
} else {
this.setText(download.getTextProgress(ddaten, s));
}
} else if (c == DatenDownload.DOWNLOAD_ABO_NR) {
setFont(new java.awt.Font("Dialog", Font.BOLD, 12));
if (abo) {
setForeground(GuiKonstanten.ABO_FOREGROUND);
} else {
setForeground(GuiKonstanten.DOWNLOAD_FOREGROUND);
setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/nein_12.png")));
setHorizontalAlignment(SwingConstants.CENTER);
}
} else if (c == DatenDownload.DOWNLOAD_PROGRAMM_RESTART_NR) {
boolean restart = download.isRestart();
setHorizontalAlignment(SwingConstants.CENTER);
if (restart) {
setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/ja_16.png")));
} else {
setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/nein_12.png")));
}
}
} catch (Exception ex) {
Log.fehlerMeldung(758200166, Log.FEHLER_ART_PROG, this.getClass().getName(), ex);
}
return this;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void ladenHttp(String filmWebsite, String thema, String alter) {
// erst die Nummer suchen
// >25420<4<165<23. Die b
// <http://www.kikaplus.net/clients/kika/mediathek/previewpic/1355302530-f80b463888fd4602d925b2ef2c861928 9.jpg<
final String MUSTER_BILD = "<http://www.";
seiteHttp = getUrlIo.getUri(nameSenderMReader, filmWebsite, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema);
String nummer, url, bild, urlFilm, titel;
nummer = seiteHttp.extract(">", "<");
bild = seiteHttp.extract(MUSTER_BILD, "<");
if (!bild.isEmpty()) {
bild = "http://www." + bild;
}
// die URL bauen:
// http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=10&id=25420&page=az
if (!nummer.isEmpty()) {
url = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=" + alter + "&id=" + nummer + "&page=az";
seiteHttp = getUrlIo.getUri(nameSenderMReader, url, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema);
final String MUSTER_URL = "var videofile = \"";
final String MUSTER_TITEL = "var videotitle = \"";
urlFilm = seiteHttp.extract(MUSTER_URL, "\"");
titel = seiteHttp.extract(MUSTER_TITEL, "\"");
if (!urlFilm.equals("")) {
meldung(urlFilm);
// DatenFilm(String ssender, String tthema, String filmWebsite, String ttitel, String uurl, String uurlRtmp,
// String datum, String zeit,
// long dauerSekunden, String description, String thumbnailUrl, String imageUrl, String[] keywords) {
DatenFilm film = null;
if ((film = istInFilmListe(nameSenderMReader, thema, titel)) != null) {
film.addUrlKlein(urlFilm, "");
} else {
// dann gibs ihn noch nicht
addFilm(new DatenFilm(nameSenderMReader, thema, "http://www.kika.de/fernsehen/mediathek/index.shtml", titel, urlFilm, ""/* urlRtmp */,
""/*datum*/, ""/*zeit*/,
0, "", bild, "", new String[]{""}));
}
} else {
Log.fehlerMeldung(-915263078, Log.FEHLER_ART_MREADER, "MediathekKika", "keine URL: " + filmWebsite);
}
}
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void addToListNormal() {
//<strong style="margin-left:10px;">Sesamstraße präsentiert: Eine Möhre für Zwei</strong><br />
//<a style="margin-left:20px;" href="?programm=168&id=14487&ag=5" title="Sendung vom 10.10.2012" class="overlay_link">42. Ordnung ist das halbe Chaos</a><br />
//<a style="margin-left:20px;" href="?programm=168&id=14485&ag=5" title="Sendung vom 10.10.2012" class="overlay_link">41. Über den Wolken</a><br />
final String ADRESSE = "http://kikaplus.net/clients/kika/kikaplus/";
final String MUSTER_URL = "<a style=\"margin-left:20px;\" href=\"";
final String MUSTER_THEMA = "<strong style=\"margin-left:10px;\">";
final String MUSTER_DATUM = "title=\"Sendung vom ";
listeThemen.clear();
seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER);
seite = getUrlIo.getUri(nameSenderMReader, ADRESSE, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite");
int pos = 0;
int pos1, pos2, stop, pDatum1, pDatum2, pTitel1, pTitel2;
String url, thema, datum, titel;
while ((pos = seite.indexOf(MUSTER_THEMA, pos)) != -1) {
try {
thema = "";
pos += MUSTER_THEMA.length();
stop = seite.indexOf(MUSTER_THEMA, pos);
pos1 = pos;
if ((pos2 = seite.indexOf("<", pos1)) != -1) {
thema = seite.substring(pos1, pos2);
}
while ((pos1 = seite.indexOf(MUSTER_URL, pos1)) != -1) {
titel = "";
datum = "";
if (stop != -1 && pos1 > stop) {
// dann schon das nächste Thema
break;
}
pos1 += MUSTER_URL.length();
if ((pos2 = seite.indexOf("\"", pos1)) != -1) {
url = seite.substring(pos1, pos2);
//if (!url.equals("")) {
url = StringEscapeUtils.unescapeXml(url);
if (!url.equals("") && !url.startsWith("http://") && !url.startsWith("/")) {
// Datum
if ((pDatum1 = seite.indexOf(MUSTER_DATUM, pos2)) != -1) {
pDatum1 += MUSTER_DATUM.length();
if ((pDatum2 = seite.indexOf("\"", pDatum1)) != -1) {
if (stop != -1 && pDatum1 < stop && pDatum2 < stop) {
// dann schon das nächste Thema
datum = seite.substring(pDatum1, pDatum2);
}
}
}
// Titel
if ((pTitel1 = seite.indexOf(">", pos2)) != -1) {
pTitel1 += 1;
if ((pTitel2 = seite.indexOf("<", pTitel1)) != -1) {
//if (stop != -1 && pTitel1 > stop && pTitel2 > stop) {
if (stop != -1 && pTitel1 < stop && pTitel2 < stop) {
titel = seite.substring(pTitel1, pTitel2);
}
}
}
// in die Liste eintragen
String[] add = new String[]{ADRESSE + url, thema, titel, datum};
listeThemen.addUrl(add);
}
}
}
} catch (Exception ex) {
Log.fehlerMeldung(-302025469, Log.FEHLER_ART_MREADER, "MediathekKiKA.addToList", ex, "");
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getPfadFlv() {
/////////////////////
if (!Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR].equals("")) {
return Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR];
}
final String PFAD_LINUX_FLV = "/usr/bin/flvstreamer";
final String PFAD_WINDOWS_FLV = "bin\\flvstreamer_win32_latest.exe";
String pfad = "";
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
pfad = GuiFunktionenProgramme.getPathJar() + PFAD_WINDOWS_FLV;
} else if (System.getProperty("os.name").toLowerCase().contains("linux")) {
pfad = PFAD_LINUX_FLV;
}
if (new File(pfad).exists()) {
return pfad;
} else {
return "";
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String getPfadFlv() {
if (Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR].equals("")) {
new DialogOk(null, true, new PanelProgrammPfade(), "Pfade Standardprogramme").setVisible(true);
}
return Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR];
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void starten() {
daten = new Daten(pfad);
Daten.nogui = true;
if (!userAgent.equals("")) {
Daten.setUserAgentManuel(userAgent);
}
// Infos schreiben
Log.startMeldungen(this.getClass().getName());
if (senderAllesLaden) {
Log.systemMeldung("Programmstart: alles laden");
} else {
Log.systemMeldung("Programmstart: nur update laden");
}
Log.systemMeldung("ImportUrl: " + importUrl);
Log.systemMeldung("Outputfile: " + output);
Log.systemMeldung("");
Log.systemMeldung("");
Daten.filmeLaden.addAdListener(new ListenerFilmeLaden() {
@Override
public void fertig(ListenerFilmeLadenEvent event) {
undTschuess(true /* exit */);
}
});
// laden was es schon gibt
//Daten.ioXmlFilmlisteLesen.filmlisteLesen(Daten.getBasisVerzeichnis() + Konstanten.XML_DATEI_FILME, false /* istUrl */, Daten.listeFilme);
new IoXmlFilmlisteLesen().standardFilmlisteLesen();
if (!senderLoeschen.isEmpty()) {
senderLoeschenUndExit();
}
// das eigentliche Suchen der Filme bei den Sendern starten
Daten.filmeLaden.filmeBeimSenderSuchen(Daten.listeFilme, senderAllesLaden, updateFilmliste);
}
#location 28
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void starten() {
daten = new Daten(pfad);
Daten.nogui = true;
if (!userAgent.equals("")) {
Daten.setUserAgentManuel(userAgent);
}
// Infos schreiben
Log.startMeldungen(this.getClass().getName());
if (senderAllesLaden) {
Log.systemMeldung("Programmstart: alles laden");
} else {
Log.systemMeldung("Programmstart: nur update laden");
}
Log.systemMeldung("ImportUrl: " + importUrl);
Log.systemMeldung("Outputfile: " + output);
Log.systemMeldung("");
Log.systemMeldung("");
Daten.filmeLaden.addAdListener(new ListenerFilmeLaden() {
@Override
public void fertig(ListenerFilmeLadenEvent event) {
undTschuess(true /* exit */);
}
});
// laden was es schon gibt
//Daten.ioXmlFilmlisteLesen.filmlisteLesen(Daten.getBasisVerzeichnis() + Konstanten.XML_DATEI_FILME, false /* istUrl */, Daten.listeFilme);
new IoXmlFilmlisteLesen().standardFilmlisteLesen();
if (!senderLoeschen.isEmpty()) {
senderLoeschenUndExit();
} else {
// das eigentliche Suchen der Filme bei den Sendern starten
Daten.filmeLaden.filmeBeimSenderSuchen(Daten.listeFilme, senderAllesLaden, updateFilmliste);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void metaDatenSchreiben() {
// FilmlisteMetaDaten
listeFilmeNeu.metaDaten = ListeFilme.newMetaDaten();
if (!Daten.filmeLaden.getStop() /* löschen */) {
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_DATUM_NR] = DatumZeit.getJetzt_ddMMyyyy_HHmm();
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_NUR_ZEIT_NR] = DatumZeit.getJetzt_HH_MM_SS();
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_NUR_DATUM_NR] = DatumZeit.getHeute_dd_MM_yyyy();
} else {
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_DATUM_NR] = "";
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_NUR_ZEIT_NR] = "";
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_NUR_DATUM_NR] = "";
}
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_ANZAHL_NR] = String.valueOf(listeFilmeNeu.size());
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_VERSION_NR] = Konstanten.VERSION;
try {
Date d = new Date(Main.class.getResource("Main.class").openConnection().getLastModified());
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_PRGRAMM_NR] = "compiled: " + new SimpleDateFormat("dd.MM.yyyy, HH:mm").format(d);
} catch (IOException ex) {
Log.fehlerMeldung("FilmeSuchen.metaDatenSchreiben", ex);
}
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
private void metaDatenSchreiben() {
// FilmlisteMetaDaten
listeFilmeNeu.metaDaten = ListeFilme.newMetaDaten();
if (!Daten.filmeLaden.getStop() /* löschen */) {
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_DATUM_NR] = DatumZeit.getJetzt_ddMMyyyy_HHmm();
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_NUR_ZEIT_NR] = DatumZeit.getJetzt_HH_MM_SS();
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_NUR_DATUM_NR] = DatumZeit.getHeute_dd_MM_yyyy();
} else {
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_DATUM_NR] = "";
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_NUR_ZEIT_NR] = "";
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_NUR_DATUM_NR] = "";
}
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_ANZAHL_NR] = String.valueOf(listeFilmeNeu.size());
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_VERSION_NR] = Konstanten.VERSION;
listeFilmeNeu.metaDaten[ListeFilme.FILMLISTE_PRGRAMM_NR] = Log.getCompileDate();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void downloadLoeschen(boolean dauerhaft) {
int rows[] = tabelle.getSelectedRows();
if (rows.length > 0) {
for (int i = rows.length - 1; i >= 0; --i) {
int delRow = tabelle.convertRowIndexToModel(rows[i]);
String url = tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString();
DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url);
if (dauerhaft) {
if (download.istAbo()) {
// ein Abo wird zusätzlich ins Logfile geschrieben
ddaten.erledigteAbos.zeileSchreiben(download.arr[DatenDownload.DOWNLOAD_THEMA_NR],
download.arr[DatenDownload.DOWNLOAD_TITEL_NR],
url);
}
ddaten.listeDownloads.delDownloadByUrl(url);
}
ddaten.starterClass.filmLoeschen(tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString());
((TModelDownload) tabelle.getModel()).removeRow(delRow);
}
setInfo();
} else {
new HinweisKeineAuswahl().zeigen();
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
private void downloadLoeschen(boolean dauerhaft) {
int rows[] = tabelle.getSelectedRows();
if (rows.length > 0) {
String[] urls = new String[rows.length];
for (int i = 0; i < rows.length; ++i) {
urls[i] = tabelle.getModel().getValueAt(tabelle.convertRowIndexToModel(rows[i]), DatenDownload.DOWNLOAD_URL_NR).toString();
}
for (int i = 0; i < urls.length; ++i) {
DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(urls[i]);
if (download == null) {
// wie kann das sein??
Log.debugMeldung("Gits ja gar nicht");
} else {
if (dauerhaft) {
if (download.istAbo()) {
// ein Abo wird zusätzlich ins Logfile geschrieben
ddaten.erledigteAbos.zeileSchreiben(download.arr[DatenDownload.DOWNLOAD_THEMA_NR],
download.arr[DatenDownload.DOWNLOAD_TITEL_NR], urls[i]);
}
ddaten.listeDownloads.delDownloadByUrl(urls[i]);
}// if (dauerhaft) {
ddaten.starterClass.filmLoeschen(urls[i]);
}
}
} else {
new HinweisKeineAuswahl().zeigen();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getMusterPfadVlc() {
final String PFAD_LINUX_VLC = "/usr/bin/vlc";
final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC";
String pfad = "";
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
pfad = getWindowsVlcPath();
} else if (System.getProperty("os.name").toLowerCase().contains("linux")) {
pfad = PFAD_LINUX_VLC;
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
pfad = PFAD_MAC_VLC;
}
if (new File(pfad).exists()) {
return pfad;
} else {
return "";
}
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String getMusterPfadVlc() {
final String PFAD_LINUX_VLC = "/usr/bin/vlc";
final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC";
final String PFAD_WIN_DEFAULT = "C:\\Programme\\VideoLAN\\VLC\\vlc.exe";
final String PFAD_WIN = "\\VideoLAN\\VLC\\vlc.exe";
String pfad;
switch (getOs()) {
case OS_LINUX:
pfad = PFAD_LINUX_VLC;
break;
case OS_MAC:
pfad = PFAD_MAC_VLC;
break;
case OS_WIN_32BIT:
case OS_WIN_64BIT:
case OS_UNKNOWN:
default:
if (System.getenv("ProgramFiles") != null) {
pfad = System.getenv("ProgramFiles") + PFAD_WIN;
} else if (System.getenv("ProgramFiles(x86)") != null) {
pfad = System.getenv("ProgramFiles(x86)") + PFAD_WIN;
} else {
pfad = PFAD_WIN_DEFAULT;
}
}
if (!new File(pfad).exists()) {
pfad = "";
}
return pfad;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void meldenFertig(String sender) {
//wird ausgeführt wenn Sender beendet ist
int MAX_SENDER = 25, MAX1 = 22, MAX2 = 15, MAX3 = 20, MAX4 = 30;
Log.systemMeldung("Fertig " + sender + ": " + DatumZeit.getJetzt_HH_MM_SS());
RunSender run = listeSenderLaufen.senderFertig(sender);
if (run != null) {
String zeile = "";
zeile += textLaenge(MAX_SENDER, "Sender: " + run.sender);
zeile += textLaenge(MAX1, " Laufzeit: " + run.getLaufzeitMinuten() + " Min.");
zeile += textLaenge(MAX2, " Seiten: " + GetUrl.getSeitenZaehler(run.sender));
zeile += textLaenge(MAX3, " Ladefehler: " + GetUrl.getSeitenZaehlerFehler(run.sender));
zeile += textLaenge(MAX3, " Fehlversuche: " + GetUrl.getSeitenZaehlerFehlerVersuche(run.sender));
zeile += textLaenge(MAX4, " Wartezeit Fehler[s]: " + GetUrl.getSeitenZaehlerWartezeitFehlerVersuche(run.sender));
String nameFilmliste[] = getMReaderNameSenderMreader(run.sender).getNameSenderFilmliste();
if (nameFilmliste.length == 1) {
zeile += textLaenge(MAX3, " Filme: " + listeFilmeNeu.countSender(nameFilmliste[0]));
fertigMeldung.add(zeile);
} else {
fertigMeldung.add(zeile);
for (int i = 0; i < nameFilmliste.length; i++) {
zeile = " --> Filme [" + nameFilmliste[i] + "]: " + listeFilmeNeu.countSender(nameFilmliste[i]);
fertigMeldung.add(zeile);
}
}
}
// wird einmal aufgerufen, wenn alle Sender fertig sind
if (listeSenderLaufen.listeFertig()) {
listeFilmeNeu.sort();
if (!allesLaden) {
// alte Filme eintragen
listeFilmeNeu.updateListe(listeFilmeAlt, true /* über den Index vergleichen */);
}
listeFilmeAlt = null; // brauchmer nicht mehr
metaDatenSchreiben();
stopZeit = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
int minuten;
try {
minuten = Math.round((stopZeit.getTime() - startZeit.getTime()) / (1000 * 60));
} catch (Exception ex) {
minuten = -1;
}
Log.systemMeldung("");
Log.systemMeldung("============================================================");
Log.systemMeldung("============================================================");
Log.systemMeldung("");
Log.systemMeldung(fertigMeldung.toArray(new String[0]));
Log.systemMeldung("");
Log.systemMeldung("============================================================");
Log.systemMeldung("");
Log.systemMeldung("Seiten geladen: " + GetUrl.getSeitenZaehler());
Log.systemMeldung("Summe geladen: " + GetUrl.getSumByte() / 1024 / 1024 + " MByte");
Log.systemMeldung(" --> Start: " + sdf.format(startZeit));
Log.systemMeldung(" --> Ende: " + sdf.format(stopZeit));
Log.systemMeldung(" --> Dauer[Min]: " + (minuten == 0 ? "<1" : minuten));
Log.systemMeldung("");
Log.systemMeldung("============================================================");
Log.systemMeldung("============================================================");
notifyFertig(new FilmListenerElement(sender, "", listeSenderLaufen.getMax(), listeSenderLaufen.getProgress()));
} else {
//nur ein Sender fertig
notifyProgress(new FilmListenerElement(sender, "", listeSenderLaufen.getMax(), listeSenderLaufen.getProgress()));
}
}
#location 53
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void meldenFertig(String sender) {
//wird ausgeführt wenn Sender beendet ist
int MAX_SENDER = 15, MAX1 = 24, MAX2 = 30;
Log.systemMeldung("Fertig " + sender + ": " + DatumZeit.getJetzt_HH_MM_SS());
RunSender run = listeSenderLaufen.senderFertig(sender);
if (run != null) {
// Zeile 1
String zeile = "==================================================================================================================";
fertigMeldung.add(zeile);
zeile = textLaenge(MAX_SENDER, run.sender);
zeile += textLaenge(MAX1, "Laufzeit[Min.]: " + run.getLaufzeitMinuten());
zeile += textLaenge(MAX1, " Seiten: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER, run.sender));
String nameFilmliste[] = getMReaderNameSenderMreader(run.sender).getNameSenderFilmliste();
if (nameFilmliste.length == 1) {
zeile += "Filme: " + listeFilmeNeu.countSender(nameFilmliste[0]);
} else {
for (int i = 0; i < nameFilmliste.length; i++) {
zeile += "Filme [" + nameFilmliste[i] + "]: " + listeFilmeNeu.countSender(nameFilmliste[i]) + " ";
}
}
fertigMeldung.add(zeile);
// Zeile 2
zeile = textLaenge(MAX_SENDER, "");
zeile += textLaenge(MAX1, " Ladefehler: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER_FEHlER, run.sender));
zeile += textLaenge(MAX1, "Fehlversuche: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER_FEHLERVERSUCHE, run.sender));
zeile += textLaenge(MAX2, "Wartezeit Fehler[s]: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER_WARTEZEIT_FEHLVERSUCHE, run.sender));
String groesse = (GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE, run.sender) == 0) ? "<1" : Long.toString(GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE, run.sender));
zeile += textLaenge(MAX1, "Daten[MByte]: " + groesse);
fertigMeldung.add(zeile);
}
// wird einmal aufgerufen, wenn alle Sender fertig sind
if (listeSenderLaufen.listeFertig()) {
listeFilmeNeu.sort();
if (!allesLaden) {
// alte Filme eintragen
listeFilmeNeu.updateListe(listeFilmeAlt, true /* über den Index vergleichen */);
}
listeFilmeAlt = null; // brauchmer nicht mehr
metaDatenSchreiben();
stopZeit = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
int minuten;
try {
minuten = Math.round((stopZeit.getTime() - startZeit.getTime()) / (1000 * 60));
} catch (Exception ex) {
minuten = -1;
}
Log.systemMeldung("");
Log.systemMeldung("==================================================================================================================");
Log.systemMeldung("Sender ===========================================================================================================");
Log.systemMeldung(fertigMeldung.toArray(new String[0]));
Log.systemMeldung("==================================================================================================================");
Log.systemMeldung("");
Log.systemMeldung(" Seiten geladen: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER));
String groesse = (GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE) == 0) ? "<1" : Long.toString(GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE, run.sender));
Log.systemMeldung("Summe geladen[MByte]: " + groesse);
Log.systemMeldung(" --> Start: " + sdf.format(startZeit));
Log.systemMeldung(" --> Ende: " + sdf.format(stopZeit));
Log.systemMeldung(" --> Dauer[Min]: " + (minuten == 0 ? "<1" : minuten));
Log.systemMeldung("");
Log.systemMeldung("==================================================================================================================");
Log.systemMeldung("==================================================================================================================");
notifyFertig(new FilmListenerElement(sender, "", listeSenderLaufen.getMax(), listeSenderLaufen.getProgress()));
} else {
//nur ein Sender fertig
notifyProgress(new FilmListenerElement(sender, "", listeSenderLaufen.getMax(), listeSenderLaufen.getProgress()));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void meldenFertig(String sender) {
//wird ausgeführt wenn Sender beendet ist
int MAX_SENDER = 15, MAX1 = 24, MAX2 = 30;
Log.systemMeldung("Fertig " + sender + ": " + DatumZeit.getJetzt_HH_MM_SS());
RunSender run = listeSenderLaufen.senderFertig(sender);
if (run != null) {
// Zeile 1
fertigMeldung.add("");
String zeile = "==================================================================================================================";
fertigMeldung.add(zeile);
zeile = textLaenge(MAX_SENDER, run.sender);
zeile += textLaenge(MAX1, "Laufzeit[Min.]: " + run.getLaufzeitMinuten());
zeile += textLaenge(MAX1, " Seiten: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER, run.sender));
String nameFilmliste[] = getMReaderNameSenderMreader(run.sender).getNameSenderFilmliste();
if (nameFilmliste.length == 1) {
zeile += "Filme: " + listeFilmeNeu.countSender(nameFilmliste[0]);
} else {
for (int i = 0; i < nameFilmliste.length; i++) {
zeile += "Filme [" + nameFilmliste[i] + "]: " + listeFilmeNeu.countSender(nameFilmliste[i]) + " ";
}
}
fertigMeldung.add(zeile);
// Zeile 2
zeile = textLaenge(MAX_SENDER, "");
zeile += textLaenge(MAX1, " Ladefehler: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER_FEHlER, run.sender));
zeile += textLaenge(MAX1, "Fehlversuche: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER_FEHLERVERSUCHE, run.sender));
zeile += textLaenge(MAX2, "Wartezeit Fehler[s]: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER_WARTEZEIT_FEHLVERSUCHE, run.sender));
String groesse = (GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE, run.sender) == 0) ? "<1" : Long.toString(GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE, run.sender));
zeile += textLaenge(MAX1, "Daten[MByte]: " + groesse);
fertigMeldung.add(zeile);
}
// wird einmal aufgerufen, wenn alle Sender fertig sind
if (listeSenderLaufen.listeFertig()) {
Log.progressEnde();
int anzFilme = listeFilmeNeu.size();
if (!allesLaden) {
// alte Filme eintragen
listeFilmeNeu.updateListe(listeFilmeAlt, true /* über den Index vergleichen */);
}
listeFilmeNeu.sort();
listeFilmeAlt = null; // brauchmer nicht mehr
// FilmlisteMetaDaten
listeFilmeNeu.metaDatenSchreiben(!Daten.filmeLaden.getStop() /* löschen */);
stopZeit = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
int sekunden;
try {
sekunden = Math.round((stopZeit.getTime() - startZeit.getTime()) / (1000));
} catch (Exception ex) {
sekunden = -1;
}
Log.systemMeldung("");
Log.systemMeldung("");
Log.systemMeldung("==================================================================================================================");
Log.systemMeldung("== Sender ======================================================================================================");
Log.systemMeldung("");
Iterator<String> it = fertigMeldung.iterator();
while (it.hasNext()) {
Log.systemMeldung(it.next());
}
Log.systemMeldung("");
Log.systemMeldung("==================================================================================================================");
Log.systemMeldung("");
Log.systemMeldung(" Filme geladen: " + anzFilme);
Log.systemMeldung(" Seiten geladen: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER));
String groesse = (GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE) == 0) ? "<1" : Long.toString(GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE));
Log.systemMeldung(" Summe geladen[MByte]: " + groesse);
if (sekunden <= 0) {
sekunden = 1;
}
long kb = (GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE) * 1024) / sekunden;
Log.systemMeldung(" -> Rate[kByte/s]: " + (kb == 0 ? "<1" : kb));
Log.systemMeldung(" -> Dauer[Min]: " + (sekunden / 60 == 0 ? "<1" : sekunden / 60));
Log.systemMeldung(" -> Start: " + sdf.format(startZeit));
Log.systemMeldung(" -> Ende: " + sdf.format(stopZeit));
Log.systemMeldung("");
Log.systemMeldung("==================================================================================================================");
Log.systemMeldung("==================================================================================================================");
notifyFertig(new ListenerFilmeLadenEvent(sender, "", listeSenderLaufen.getMax(), listeSenderLaufen.getProgress()));
} else {
//nur ein Sender fertig
notifyProgress(new ListenerFilmeLadenEvent(sender, "", listeSenderLaufen.getMax(), listeSenderLaufen.getProgress()));
}
}
#location 36
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void meldenFertig(String sender) {
//wird ausgeführt wenn Sender beendet ist
int MAX_SENDER = 15, MAX1 = 24, MAX2 = 30;
Log.systemMeldung("Fertig " + sender + ": " + DatumZeit.getJetzt_HH_MM_SS());
RunSender run = listeSenderLaufen.senderFertig(sender);
if (run != null) {
// Zeile 1
fertigMeldung.add("");
String zeile = "==================================================================================================================";
fertigMeldung.add(zeile);
zeile = textLaenge(MAX_SENDER, run.sender);
zeile += textLaenge(MAX1, "Laufzeit[Min.]: " + run.getLaufzeitMinuten());
zeile += textLaenge(MAX1, " Seiten: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER, run.sender));
String nameFilmliste[] = getMReaderNameSenderMreader(run.sender).getNameSenderFilmliste();
if (nameFilmliste.length == 1) {
zeile += "Filme: " + listeFilmeNeu.countSender(nameFilmliste[0]);
} else {
for (int i = 0; i < nameFilmliste.length; i++) {
zeile += "Filme [" + nameFilmliste[i] + "]: " + listeFilmeNeu.countSender(nameFilmliste[i]) + " ";
}
}
fertigMeldung.add(zeile);
// Zeile 2
zeile = textLaenge(MAX_SENDER, "");
zeile += textLaenge(MAX1, " Ladefehler: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER_FEHlER, run.sender));
zeile += textLaenge(MAX1, "Fehlversuche: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER_FEHLERVERSUCHE, run.sender));
zeile += textLaenge(MAX2, "Wartezeit Fehler[s]: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER_WARTEZEIT_FEHLVERSUCHE, run.sender));
String groesse = (GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE, run.sender) == 0) ? "<1" : Long.toString(GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE, run.sender));
zeile += textLaenge(MAX1, "Daten[MByte]: " + groesse);
fertigMeldung.add(zeile);
}
// wird einmal aufgerufen, wenn alle Sender fertig sind
if (listeSenderLaufen.listeFertig()) {
Log.progressEnde();
int anzFilme = listeFilmeNeu.size();
if (!senderAllesLaden || updateFilmliste) {
// alte Filme eintragen wenn angefordert oder nur ein update gesucht wurde
listeFilmeNeu.updateListe(listeFilmeAlt, true /* über den Index vergleichen */);
}
listeFilmeNeu.sort();
listeFilmeAlt = null; // brauchmer nicht mehr
// FilmlisteMetaDaten
listeFilmeNeu.metaDatenSchreiben(!Daten.filmeLaden.getStop() /* löschen */);
stopZeit = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
int sekunden;
try {
sekunden = Math.round((stopZeit.getTime() - startZeit.getTime()) / (1000));
} catch (Exception ex) {
sekunden = -1;
}
Log.systemMeldung("");
Log.systemMeldung("");
Log.systemMeldung("==================================================================================================================");
Log.systemMeldung("== Sender ======================================================================================================");
Log.systemMeldung("");
Iterator<String> it = fertigMeldung.iterator();
while (it.hasNext()) {
Log.systemMeldung(it.next());
}
Log.systemMeldung("");
Log.systemMeldung("==================================================================================================================");
Log.systemMeldung("");
Log.systemMeldung(" Filme geladen: " + anzFilme);
Log.systemMeldung(" Seiten geladen: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER));
String groesse = (GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE) == 0) ? "<1" : Long.toString(GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE));
Log.systemMeldung(" Summe geladen[MByte]: " + groesse);
if (sekunden <= 0) {
sekunden = 1;
}
long kb = (GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE) * 1024) / sekunden;
Log.systemMeldung(" -> Rate[kByte/s]: " + (kb == 0 ? "<1" : kb));
Log.systemMeldung(" -> Dauer[Min]: " + (sekunden / 60 == 0 ? "<1" : sekunden / 60));
Log.systemMeldung(" -> Start: " + sdf.format(startZeit));
Log.systemMeldung(" -> Ende: " + sdf.format(stopZeit));
Log.systemMeldung("");
Log.systemMeldung("==================================================================================================================");
Log.systemMeldung("==================================================================================================================");
notifyFertig(new ListenerFilmeLadenEvent(sender, "", listeSenderLaufen.getMax(), listeSenderLaufen.getProgress()));
} else {
//nur ein Sender fertig
notifyProgress(new ListenerFilmeLadenEvent(sender, "", listeSenderLaufen.getMax(), listeSenderLaufen.getProgress()));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getMusterPfadFlv() {
final String PFAD_LINUX_FLV = "/usr/bin/flvstreamer";
final String PFAD_WINDOWS_FLV = "bin\\flvstreamer_win32_latest.exe";
final String PFAD_MAC_FLV = "bin\\flvstreamer_macosx_intel_32bit_latest";
String pfad = "";
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
pfad = Funktionen.getPathJar() + PFAD_WINDOWS_FLV;
} else if (System.getProperty("os.name").toLowerCase().contains("linux")) {
pfad = PFAD_LINUX_FLV;
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
pfad = Funktionen.getPathJar() + PFAD_MAC_FLV;
}
if (new File(pfad).exists()) {
return pfad;
} else {
return "";
}
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String getMusterPfadFlv() {
final String PFAD_LINUX_FLV = "/usr/bin/flvstreamer";
final String PFAD_WINDOWS_FLV = "bin\\flvstreamer_win32_latest.exe";
final String PFAD_MAC_FLV = "bin\\flvstreamer_macosx_intel_32bit_latest";
String pfad;
switch (getOs()) {
case OS_LINUX:
pfad = PFAD_LINUX_FLV;
break;
case OS_MAC:
pfad = Funktionen.getPathJar() + PFAD_MAC_FLV;
break;
case OS_WIN_32BIT:
case OS_WIN_64BIT:
case OS_UNKNOWN:
default:
pfad = Funktionen.getPathJar() + PFAD_WINDOWS_FLV;
}
if (new File(pfad).exists()) {
return pfad;
} else {
return "";
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getMusterPfadFlv() {
final String PFAD_LINUX_FLV = "/usr/bin/flvstreamer";
final String PFAD_WINDOWS_FLV = "bin\\flvstreamer_win32_latest.exe";
final String PFAD_MAC_FLV = "bin\\flvstreamer_macosx_intel_32bit_latest";
String pfad = "";
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
pfad = Funktionen.getPathJar() + PFAD_WINDOWS_FLV;
} else if (System.getProperty("os.name").toLowerCase().contains("linux")) {
pfad = PFAD_LINUX_FLV;
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
pfad = Funktionen.getPathJar() + PFAD_MAC_FLV;
}
if (new File(pfad).exists()) {
return pfad;
} else {
return "";
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String getMusterPfadFlv() {
final String PFAD_LINUX_FLV = "/usr/bin/flvstreamer";
final String PFAD_WINDOWS_FLV = "bin\\flvstreamer_win32_latest.exe";
final String PFAD_MAC_FLV = "bin\\flvstreamer_macosx_intel_32bit_latest";
String pfad;
switch (getOs()) {
case OS_LINUX:
pfad = PFAD_LINUX_FLV;
break;
case OS_MAC:
pfad = Funktionen.getPathJar() + PFAD_MAC_FLV;
break;
case OS_WIN_32BIT:
case OS_WIN_64BIT:
case OS_UNKNOWN:
default:
pfad = Funktionen.getPathJar() + PFAD_WINDOWS_FLV;
}
if (new File(pfad).exists()) {
return pfad;
} else {
return "";
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void ladenHttp(String filmWebsite, String thema, String alter) {
// erst die Nummer suchen
// >25420<4<165<23. Die b
// <http://www.kikaplus.net/clients/kika/mediathek/previewpic/1355302530-f80b463888fd4602d925b2ef2c861928 9.jpg<
final String MUSTER_BILD = "<http://www.";
seiteHttp = getUrlIo.getUri(nameSenderMReader, filmWebsite, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema);
String nummer, url, bild, urlFilm, titel;
nummer = seiteHttp.extract(">", "<");
bild = seiteHttp.extract(MUSTER_BILD, "<");
if (!bild.isEmpty()) {
bild = "http://www." + bild;
}
// die URL bauen:
// http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=10&id=25420&page=az
if (!nummer.isEmpty()) {
url = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=" + alter + "&id=" + nummer + "&page=az";
seiteHttp = getUrlIo.getUri(nameSenderMReader, url, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema);
final String MUSTER_URL = "var videofile = \"";
final String MUSTER_TITEL = "var videotitle = \"";
urlFilm = seiteHttp.extract(MUSTER_URL, "\"");
titel = seiteHttp.extract(MUSTER_TITEL, "\"");
if (!urlFilm.equals("")) {
meldung(urlFilm);
// DatenFilm(String ssender, String tthema, String filmWebsite, String ttitel, String uurl, String uurlRtmp,
// String datum, String zeit,
// long dauerSekunden, String description, String thumbnailUrl, String imageUrl, String[] keywords) {
DatenFilm film = null;
if ((film = istInFilmListe(nameSenderMReader, thema, titel)) != null) {
film.addUrlKlein(urlFilm, "");
} else {
// dann gibs ihn noch nicht
addFilm(new DatenFilm(nameSenderMReader, thema, "http://www.kika.de/fernsehen/mediathek/index.shtml", titel, urlFilm, ""/* urlRtmp */,
""/*datum*/, ""/*zeit*/,
0, "", bild, "", new String[]{""}));
}
} else {
Log.fehlerMeldung(-915263078, Log.FEHLER_ART_MREADER, "MediathekKika", "keine URL: " + filmWebsite);
}
}
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void addToListNormal() {
//<strong style="margin-left:10px;">Sesamstraße präsentiert: Eine Möhre für Zwei</strong><br />
//<a style="margin-left:20px;" href="?programm=168&id=14487&ag=5" title="Sendung vom 10.10.2012" class="overlay_link">42. Ordnung ist das halbe Chaos</a><br />
//<a style="margin-left:20px;" href="?programm=168&id=14485&ag=5" title="Sendung vom 10.10.2012" class="overlay_link">41. Über den Wolken</a><br />
final String ADRESSE = "http://kikaplus.net/clients/kika/kikaplus/";
final String MUSTER_URL = "<a style=\"margin-left:20px;\" href=\"";
final String MUSTER_THEMA = "<strong style=\"margin-left:10px;\">";
final String MUSTER_DATUM = "title=\"Sendung vom ";
listeThemen.clear();
seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER);
seite = getUrlIo.getUri(nameSenderMReader, ADRESSE, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite");
int pos = 0;
int pos1, pos2, stop, pDatum1, pDatum2, pTitel1, pTitel2;
String url, thema, datum, titel;
while ((pos = seite.indexOf(MUSTER_THEMA, pos)) != -1) {
try {
thema = "";
pos += MUSTER_THEMA.length();
stop = seite.indexOf(MUSTER_THEMA, pos);
pos1 = pos;
if ((pos2 = seite.indexOf("<", pos1)) != -1) {
thema = seite.substring(pos1, pos2);
}
while ((pos1 = seite.indexOf(MUSTER_URL, pos1)) != -1) {
titel = "";
datum = "";
if (stop != -1 && pos1 > stop) {
// dann schon das nächste Thema
break;
}
pos1 += MUSTER_URL.length();
if ((pos2 = seite.indexOf("\"", pos1)) != -1) {
url = seite.substring(pos1, pos2);
//if (!url.equals("")) {
url = StringEscapeUtils.unescapeXml(url);
if (!url.equals("") && !url.startsWith("http://") && !url.startsWith("/")) {
// Datum
if ((pDatum1 = seite.indexOf(MUSTER_DATUM, pos2)) != -1) {
pDatum1 += MUSTER_DATUM.length();
if ((pDatum2 = seite.indexOf("\"", pDatum1)) != -1) {
if (stop != -1 && pDatum1 < stop && pDatum2 < stop) {
// dann schon das nächste Thema
datum = seite.substring(pDatum1, pDatum2);
}
}
}
// Titel
if ((pTitel1 = seite.indexOf(">", pos2)) != -1) {
pTitel1 += 1;
if ((pTitel2 = seite.indexOf("<", pTitel1)) != -1) {
//if (stop != -1 && pTitel1 > stop && pTitel2 > stop) {
if (stop != -1 && pTitel1 < stop && pTitel2 < stop) {
titel = seite.substring(pTitel1, pTitel2);
}
}
}
// in die Liste eintragen
String[] add = new String[]{ADRESSE + url, thema, titel, datum};
listeThemen.addUrl(add);
}
}
}
} catch (Exception ex) {
Log.fehlerMeldung(-302025469, Log.FEHLER_ART_MREADER, "MediathekKiKA.addToList", ex, "");
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void starten() {
daten = new Daten(pfad);
Daten.nogui = true;
if (!userAgent.equals("")) {
Daten.setUserAgentManuel(userAgent);
}
// Infos schreiben
Log.startMeldungen(this.getClass().getName());
if (senderAllesLaden) {
Log.systemMeldung("Programmstart: alles laden");
} else {
Log.systemMeldung("Programmstart: nur update laden");
}
Log.systemMeldung("ImportUrl: " + importUrl);
Log.systemMeldung("Outputfile: " + output);
Log.systemMeldung("");
Log.systemMeldung("");
Daten.filmeLaden.addAdListener(new ListenerFilmeLaden() {
@Override
public void fertig(ListenerFilmeLadenEvent event) {
undTschuess(true /* exit */);
}
});
// laden was es schon gibt
//Daten.ioXmlFilmlisteLesen.filmlisteLesen(Daten.getBasisVerzeichnis() + Konstanten.XML_DATEI_FILME, false /* istUrl */, Daten.listeFilme);
new IoXmlFilmlisteLesen().standardFilmlisteLesen();
if (!senderLoeschen.isEmpty()) {
senderLoeschenUndExit();
} else {
// das eigentliche Suchen der Filme bei den Sendern starten
Daten.filmeLaden.filmeBeimSenderSuchen(Daten.listeFilme, senderAllesLaden, updateFilmliste);
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void starten() {
daten = new Daten(pfad);
Daten.nogui = true;
if (!userAgent.equals("")) {
Daten.setUserAgentManuel(userAgent);
}
// Infos schreiben
Log.startMeldungen(this.getClass().getName());
if (senderAllesLaden) {
Log.systemMeldung("Programmstart: alles laden");
} else {
Log.systemMeldung("Programmstart: nur update laden");
}
Log.systemMeldung("ImportUrl: " + importUrl);
Log.systemMeldung("Outputfile: " + output);
Log.systemMeldung("");
Log.systemMeldung("");
Daten.filmeLaden.addAdListener(new ListenerFilmeLaden() {
@Override
public void fertig(ListenerFilmeLadenEvent event) {
undTschuess(true /* exit */);
}
});
// laden was es schon gibt
//Daten.ioXmlFilmlisteLesen.filmlisteLesen(Daten.getBasisVerzeichnis() + Konstanten.XML_DATEI_FILME, false /* istUrl */, Daten.listeFilme);
new IoXmlFilmlisteLesen().standardFilmlisteLesen();
// das eigentliche Suchen der Filme bei den Sendern starten
Daten.filmeLaden.filmeBeimSenderSuchen(Daten.listeFilme, senderAllesLaden, updateFilmliste);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void downloadLoeschen(boolean dauerhaft) {
int rows[] = jTable1.getSelectedRows();
if (rows.length > 0) {
for (int i = rows.length - 1; i >= 0; --i) {
int delRow = jTable1.convertRowIndexToModel(rows[i]);
String url = jTable1.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString();
DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url);
if (dauerhaft) {
if (download.istAbo()) {
// ein Abo wird zusätzlich ins Logfile geschrieben
ddaten.erledigteAbos.zeileSchreiben(download.arr[DatenDownload.DOWNLOAD_THEMA_NR],
download.arr[DatenDownload.DOWNLOAD_TITEL_NR],
url);
}
ddaten.listeDownloads.delDownloadByUrl(url);
}
ddaten.starterClass.filmLoeschen(jTable1.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString());
((TModelDownload) jTable1.getModel()).removeRow(delRow);
}
setInfo();
} else {
new HinweisKeineAuswahl().zeigen();
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
private void downloadLoeschen(boolean dauerhaft) {
int rows[] = tabelle.getSelectedRows();
if (rows.length > 0) {
for (int i = rows.length - 1; i >= 0; --i) {
int delRow = tabelle.convertRowIndexToModel(rows[i]);
String url = tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString();
DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url);
if (dauerhaft) {
if (download.istAbo()) {
// ein Abo wird zusätzlich ins Logfile geschrieben
ddaten.erledigteAbos.zeileSchreiben(download.arr[DatenDownload.DOWNLOAD_THEMA_NR],
download.arr[DatenDownload.DOWNLOAD_TITEL_NR],
url);
}
ddaten.listeDownloads.delDownloadByUrl(url);
}
ddaten.starterClass.filmLoeschen(tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString());
((TModelDownload) tabelle.getModel()).removeRow(delRow);
}
setInfo();
} else {
new HinweisKeineAuswahl().zeigen();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static synchronized void startMeldungen(String classname) {
Log.systemMeldung("###########################################################");
try {
//Version
Log.systemMeldung(Konstanten.PROGRAMMNAME + " " + Konstanten.VERSION);
Date d = new Date(Main.class.getResource("Main.class").openConnection().getLastModified());
Log.systemMeldung("Compiled: " + new SimpleDateFormat("dd.MM.yyyy, HH:mm").format(d));
} catch (IOException ex) {
}
Log.systemMeldung("Klassenname: " + classname);
Log.systemMeldung("");
Log.systemMeldung("Programmpfad: " + GuiFunktionenProgramme.getPathJar());
Log.systemMeldung("Verzeichnis Einstellungen: " + Daten.getBasisVerzeichnis());
Log.systemMeldung("Useragent: " + Daten.getUserAgent());
Log.systemMeldung("");
long totalMem = Runtime.getRuntime().totalMemory();
Log.systemMeldung("totalMemory: " + totalMem / (1024L * 1024L) + " MB");
long maxMem = Runtime.getRuntime().maxMemory();
Log.systemMeldung("maxMemory: " + maxMem / (1024L * 1024L) + " MB");
long freeMem = Runtime.getRuntime().freeMemory();
Log.systemMeldung("freeMemory: " + freeMem / (1024L * 1024L) + " MB");
Log.systemMeldung("###########################################################");
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
public static synchronized void startMeldungen(String classname) {
versionsMeldungen(classname);
Log.systemMeldung("Programmpfad: " + GuiFunktionenProgramme.getPathJar());
Log.systemMeldung("Verzeichnis Einstellungen: " + Daten.getBasisVerzeichnis());
Log.systemMeldung("Useragent: " + Daten.getUserAgent());
Log.systemMeldung("###########################################################");
Log.systemMeldung("");
Log.systemMeldung("");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getPfadScript() {
String pfadScript;
final String PFAD_LINUX_SCRIPT = "bin/flv.sh";
final String PFAD_WINDOWS_SCRIPT = "bin\\flv.bat";
if (System.getProperty("os.name").toLowerCase().contains("linux")) {
pfadScript = Funktionen.getPathJar() + PFAD_LINUX_SCRIPT;
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
pfadScript = Funktionen.getPathJar() + PFAD_LINUX_SCRIPT;
} else {
pfadScript = Funktionen.getPathJar() + PFAD_WINDOWS_SCRIPT;
}
return pfadScript;
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String getPfadScript() {
String pfadScript;
final String PFAD_LINUX_SCRIPT = "bin/flv.sh";
final String PFAD_WINDOWS_SCRIPT = "bin\\flv.bat";
switch (getOs()) {
case OS_LINUX:
pfadScript = Funktionen.getPathJar() + PFAD_LINUX_SCRIPT;
break;
case OS_MAC:
pfadScript = Funktionen.getPathJar() + PFAD_LINUX_SCRIPT;
break;
case OS_WIN_32BIT:
case OS_WIN_64BIT:
case OS_UNKNOWN:
default:
pfadScript = Funktionen.getPathJar() + PFAD_WINDOWS_SCRIPT;
}
return pfadScript;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public synchronized boolean zeileSchreiben(ArrayList<String[]> list) {
boolean ret = false;
String text;
String zeit = DatumZeit.getHeute_dd_MM_yyyy();
String thema, titel, url;
OutputStreamWriter writer = null;
File f = new File(Daten.getBasisVerzeichnis(true) + Konstanten.LOG_DATEI_DOWNLOAD_ABOS);
try {
writer = new OutputStreamWriter(new FileOutputStream(f, true));
for (String[] a : list) {
thema = a[0];
titel = a[1];
url = a[2];
listeErledigteAbos.add(url);
thema = GuiFunktionen.textLaenge(25, putzen(thema), false /* mitte */, false /*addVorne*/);
titel = GuiFunktionen.textLaenge(30, putzen(titel), false /* mitte */, false /*addVorne*/);
text = zeit + PAUSE + thema + PAUSE + titel + TRENNER + url + "\n";
writer.write(text);
ret = true;
}
// writer.close();
} catch (Exception ex) {
ret = false;
Log.fehlerMeldung(945258023, Log.FEHLER_ART_PROG, "LogDownload.zeileSchreiben-1", ex);
} finally {
try {
writer.close();
} catch (Exception ex) {
}
}
ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_LISTE_ERLEDIGTE_ABOS, ErledigteAbos.class.getSimpleName());
return ret;
}
#location 27
#vulnerability type NULL_DEREFERENCE | #fixed code
public synchronized boolean zeileSchreiben(ArrayList<String[]> list) {
boolean ret = false;
String text;
String zeit = DatumZeit.getHeute_dd_MM_yyyy();
String thema, titel, url;
try (OutputStreamWriter writer = new OutputStreamWriter(Files.newOutputStream(Daten.getDownloadAboFilePath()))) {
for (String[] a : list) {
thema = a[0];
titel = a[1];
url = a[2];
listeErledigteAbos.add(url);
thema = GuiFunktionen.textLaenge(25, putzen(thema), false /* mitte */, false /*addVorne*/);
titel = GuiFunktionen.textLaenge(30, putzen(titel), false /* mitte */, false /*addVorne*/);
text = zeit + PAUSE + thema + PAUSE + titel + TRENNER + url + "\n";
writer.write(text);
ret = true;
}
} catch (Exception ex) {
ret = false;
Log.fehlerMeldung(945258023, Log.FEHLER_ART_PROG, "LogDownload.zeileSchreiben-1", ex);
}
ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_LISTE_ERLEDIGTE_ABOS, ErledigteAbos.class.getSimpleName());
return ret;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private synchronized StringBuffer getUri(String sender, String addr, StringBuffer seite, String kodierung, int timeout, String meldung, int versuch, boolean lVersuch) {
int timeo = timeout;
boolean proxyB = false;
char[] zeichen = new char[1];
seite.setLength(0);
URLConnection conn;
int code = 0;
InputStream in = null;
InputStreamReader inReader = null;
Proxy proxy = null;
SocketAddress saddr = null;
// immer etwas bremsen
try {
long w = wartenBasis * faktorWarten;
this.wait(w);
} catch (Exception ex) {
Log.fehlerMeldung(976120379, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, sender);
}
try {
URL url = new URL(addr);
// conn = url.openConnection(Proxy.NO_PROXY);
conn = url.openConnection();
conn.setRequestProperty("User-Agent", Daten.getUserAgent());
if (timeout > 0) {
conn.setReadTimeout(timeout);
conn.setConnectTimeout(timeout);
}
if (conn instanceof HttpURLConnection) {
HttpURLConnection httpConnection = (HttpURLConnection) conn;
code = httpConnection.getResponseCode();
// if (code >= 400) {
// if (true) {
// // wenn möglich, einen Proxy einrichten
// Log.fehlerMeldung(236597125, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "---Proxy---");
// proxyB = true;
// saddr = new InetSocketAddress("localhost", 9050);
// proxy = new Proxy(Proxy.Type.SOCKS, saddr);
// conn = url.openConnection(proxy);
// conn.setRequestProperty("User-Agent", Daten.getUserAgent());
// if (timeout > 0) {
// conn.setReadTimeout(timeout);
// conn.setConnectTimeout(timeout);
// }
// } else {
// Log.fehlerMeldung(864123698, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "returncode >= 400");
// }
// }
} else {
Log.fehlerMeldung(949697315, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "keine HTTPcon");
}
in = conn.getInputStream();
inReader = new InputStreamReader(in, kodierung);
while (!Daten.filmeLaden.getStop() && inReader.read(zeichen) != -1) {
seite.append(zeichen);
incSeitenZaehler(LISTE_SUMME_BYTE, sender, 1);
}
} catch (IOException ex) {
if (lVersuch) {
String[] text;
if (meldung.equals("")) {
text = new String[]{sender + " - timout: " + timeo + " Versuche: " + versuch, addr /*, (proxyB ? "Porxy - " : "")*/};
} else {
text = new String[]{sender + " - timout: " + timeo + " Versuche: " + versuch, addr, meldung/*, (proxyB ? "Porxy - " : "")*/};
}
Log.fehlerMeldung(502739817, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, text);
}
} catch (Exception ex) {
Log.fehlerMeldung(973969801, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, "");
} finally {
try {
if (in != null) {
inReader.close();
}
} catch (IOException ex) {
}
}
return seite;
}
#location 72
#vulnerability type NULL_DEREFERENCE | #fixed code
private synchronized StringBuffer getUri(String sender, String addr, StringBuffer seite, String kodierung, int timeout, String meldung, int versuch, boolean lVersuch) {
int timeo = timeout;
boolean proxyB = false;
char[] zeichen = new char[1];
seite.setLength(0);
HttpURLConnection conn = null;
int code = 0;
InputStream in = null;
InputStreamReader inReader = null;
Proxy proxy = null;
SocketAddress saddr = null;
int ladeArt = LADE_ART_UNBEKANNT;
// immer etwas bremsen
try {
long w = wartenBasis * faktorWarten;
this.wait(w);
} catch (Exception ex) {
Log.fehlerMeldung(976120379, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, sender);
}
try {
// conn = url.openConnection(Proxy.NO_PROXY);
conn = (HttpURLConnection) new URL(addr).openConnection();
conn.setRequestProperty("User-Agent", Daten.getUserAgent());
conn.setRequestProperty("User-Agent", Daten.getUserAgent());
System.setProperty("http.maxConnections", "600");
System.setProperty("http.keepAlive", "false");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
if (timeout > 0) {
conn.setReadTimeout(timeout);
conn.setConnectTimeout(timeout);
}
// the encoding returned by the server
String encoding = conn.getContentEncoding();
// if (conn instanceof HttpURLConnection) {
// HttpURLConnection httpConnection = (HttpURLConnection) conn;
// code = httpConnection.getResponseCode();
// if (code >= 400) {
// if (true) {
// // wenn möglich, einen Proxy einrichten
// Log.fehlerMeldung(236597125, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "---Proxy---");
// proxyB = true;
// saddr = new InetSocketAddress("localhost", 9050);
// proxy = new Proxy(Proxy.Type.SOCKS, saddr);
// conn = url.openConnection(proxy);
// conn.setRequestProperty("User-Agent", Daten.getUserAgent());
// if (timeout > 0) {
// conn.setReadTimeout(timeout);
// conn.setConnectTimeout(timeout);
// }
// } else {
// Log.fehlerMeldung(864123698, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "returncode >= 400");
// }
// }
// } else {
// Log.fehlerMeldung(949697315, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "keine HTTPcon");
// }
//in = conn.getInputStream();
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
ladeArt = LADE_ART_GZIP;
in = new GZIPInputStream(conn.getInputStream());
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
ladeArt = LADE_ART_DEFLATE;
in = new InflaterInputStream(conn.getInputStream(), new Inflater(true));
} else {
ladeArt = LADE_ART_NIX;
in = conn.getInputStream();
}
inReader = new InputStreamReader(in, kodierung);
//// while (!Daten.filmeLaden.getStop() && inReader.read(zeichen) != -1) {
//// seite.append(zeichen);
//// incSeitenZaehler(LISTE_SUMME_BYTE, sender, 1);
//// }
char[] buff = new char[256];
int cnt;
while (!Daten.filmeLaden.getStop() && (cnt = inReader.read(buff)) > 0) {
seite.append(buff, 0, cnt);
incSeitenZaehler(LISTE_SUMME_BYTE, sender, cnt, ladeArt);
}
} catch (IOException ex) {
// consume error stream, otherwise, connection won't be reused
if (conn != null) {
try {
InputStream i = conn.getErrorStream();
if (i != null) {
i.close();
}
if (inReader != null) {
inReader.close();
}
} catch (Exception e) {
Log.fehlerMeldung(645105987, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", e, "");
}
}
if (lVersuch) {
String[] text;
if (meldung.equals("")) {
text = new String[]{sender + " - timout: " + timeo + " Versuche: " + versuch, addr /*, (proxyB ? "Porxy - " : "")*/};
} else {
text = new String[]{sender + " - timout: " + timeo + " Versuche: " + versuch, addr, meldung/*, (proxyB ? "Porxy - " : "")*/};
}
if (ex.getMessage().equals("Read timed out")) {
Log.fehlerMeldung(502739817, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri: TimeOut", text);
} else {
Log.fehlerMeldung(502739817, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, text);
}
}
} catch (Exception ex) {
Log.fehlerMeldung(973969801, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, "");
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ex) {
Log.fehlerMeldung(696321478, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, "");
}
}
return seite;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getCompileDate() {
String ret = "";
try {
Date d = new Date(Main.class.getResource("Main.class").openConnection().getLastModified());
ret = Konstanten.PROGRAMMNAME + " " + Konstanten.VERSION + " [Buildnummer: " + getBuildNr() + "] - Compiled: " + new SimpleDateFormat("dd.MM.yyyy, HH:mm").format(d);
} catch (Exception ex) {
Log.fehlerMeldung(569614756, "Log.getCompileDate: ", ex);
}
return ret;
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
public static String getCompileDate() {
// String ret = "";
// try {
// Date d = new Date(Main.class.getResource("Main.class").openConnection().getLastModified());
// ret = Konstanten.PROGRAMMNAME + " " + Konstanten.VERSION + " [Buildnummer: " + getBuildNr() + "] - Compiled: " + new SimpleDateFormat("dd.MM.yyyy, HH:mm").format(d);
// } catch (Exception ex) {
// Log.fehlerMeldung(569614756, "Log.getCompileDate: ", ex);
// }
// return ret;
final ResourceBundle rb;
String propToken = "BUILDDATE";
String msg = "";
try {
ResourceBundle.clearCache();
rb = ResourceBundle.getBundle("version");
msg = rb.getString(propToken);
} catch (Exception e) {
System.err.println(e.getMessage());
System.err.println("Token " + propToken + " not in Propertyfile!");
}
return Konstanten.PROGRAMMNAME + " " + Konstanten.VERSION + " [Buildnummer: " + getBuildNr() + "] - Compiled: " + msg;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void ladenHttp(String filmWebsite, String thema, String alter) {
// erst die Nummer suchen
// >25420<4<165<23. Die b
// <http://www.kikaplus.net/clients/kika/mediathek/previewpic/1355302530-f80b463888fd4602d925b2ef2c861928 9.jpg<
final String MUSTER_BILD = "<http://www.";
seiteHttp = getUrlIo.getUri(nameSenderMReader, filmWebsite, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema);
String nummer, url, bild, urlFilm, titel;
nummer = seiteHttp.extract(">", "<");
bild = seiteHttp.extract(MUSTER_BILD, "<");
if (!bild.isEmpty()) {
bild = "http://www." + bild;
}
// die URL bauen:
// http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=10&id=25420&page=az
if (!nummer.isEmpty()) {
url = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=" + alter + "&id=" + nummer + "&page=az";
seiteHttp = getUrlIo.getUri(nameSenderMReader, url, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema);
final String MUSTER_URL = "var videofile = \"";
final String MUSTER_TITEL = "var videotitle = \"";
urlFilm = seiteHttp.extract(MUSTER_URL, "\"");
titel = seiteHttp.extract(MUSTER_TITEL, "\"");
if (!urlFilm.equals("")) {
meldung(urlFilm);
// DatenFilm(String ssender, String tthema, String filmWebsite, String ttitel, String uurl, String uurlRtmp,
// String datum, String zeit,
// long dauerSekunden, String description, String thumbnailUrl, String imageUrl, String[] keywords) {
DatenFilm film = null;
if ((film = istInFilmListe(nameSenderMReader, thema, titel)) != null) {
film.addUrlKlein(urlFilm, "");
} else {
// dann gibs ihn noch nicht
addFilm(new DatenFilm(nameSenderMReader, thema, "http://www.kika.de/fernsehen/mediathek/index.shtml", titel, urlFilm, ""/* urlRtmp */,
""/*datum*/, ""/*zeit*/,
0, "", bild, "", new String[]{""}));
}
} else {
Log.fehlerMeldung(-915263078, Log.FEHLER_ART_MREADER, "MediathekKika", "keine URL: " + filmWebsite);
}
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void addToListNormal() {
//<strong style="margin-left:10px;">Sesamstraße präsentiert: Eine Möhre für Zwei</strong><br />
//<a style="margin-left:20px;" href="?programm=168&id=14487&ag=5" title="Sendung vom 10.10.2012" class="overlay_link">42. Ordnung ist das halbe Chaos</a><br />
//<a style="margin-left:20px;" href="?programm=168&id=14485&ag=5" title="Sendung vom 10.10.2012" class="overlay_link">41. Über den Wolken</a><br />
final String ADRESSE = "http://kikaplus.net/clients/kika/kikaplus/";
final String MUSTER_URL = "<a style=\"margin-left:20px;\" href=\"";
final String MUSTER_THEMA = "<strong style=\"margin-left:10px;\">";
final String MUSTER_DATUM = "title=\"Sendung vom ";
listeThemen.clear();
seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER);
seite = getUrlIo.getUri(nameSenderMReader, ADRESSE, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite");
int pos = 0;
int pos1, pos2, stop, pDatum1, pDatum2, pTitel1, pTitel2;
String url, thema, datum, titel;
while ((pos = seite.indexOf(MUSTER_THEMA, pos)) != -1) {
try {
thema = "";
pos += MUSTER_THEMA.length();
stop = seite.indexOf(MUSTER_THEMA, pos);
pos1 = pos;
if ((pos2 = seite.indexOf("<", pos1)) != -1) {
thema = seite.substring(pos1, pos2);
}
while ((pos1 = seite.indexOf(MUSTER_URL, pos1)) != -1) {
titel = "";
datum = "";
if (stop != -1 && pos1 > stop) {
// dann schon das nächste Thema
break;
}
pos1 += MUSTER_URL.length();
if ((pos2 = seite.indexOf("\"", pos1)) != -1) {
url = seite.substring(pos1, pos2);
//if (!url.equals("")) {
url = StringEscapeUtils.unescapeXml(url);
if (!url.equals("") && !url.startsWith("http://") && !url.startsWith("/")) {
// Datum
if ((pDatum1 = seite.indexOf(MUSTER_DATUM, pos2)) != -1) {
pDatum1 += MUSTER_DATUM.length();
if ((pDatum2 = seite.indexOf("\"", pDatum1)) != -1) {
if (stop != -1 && pDatum1 < stop && pDatum2 < stop) {
// dann schon das nächste Thema
datum = seite.substring(pDatum1, pDatum2);
}
}
}
// Titel
if ((pTitel1 = seite.indexOf(">", pos2)) != -1) {
pTitel1 += 1;
if ((pTitel2 = seite.indexOf("<", pTitel1)) != -1) {
//if (stop != -1 && pTitel1 > stop && pTitel2 > stop) {
if (stop != -1 && pTitel1 < stop && pTitel2 < stop) {
titel = seite.substring(pTitel1, pTitel2);
}
}
}
// in die Liste eintragen
String[] add = new String[]{ADRESSE + url, thema, titel, datum};
listeThemen.addUrl(add);
}
}
}
} catch (Exception ex) {
Log.fehlerMeldung(-302025469, Log.FEHLER_ART_MREADER, "MediathekKiKA.addToList", ex, "");
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void speichern() {
try {
FileOutputStream fstream = new FileOutputStream(datei);
DataOutputStream out = new DataOutputStream(fstream);
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(out));
for (String h : this) {
br.write(h + "\n");
}
br.flush();
out.close();
} catch (Exception e) {//Catch exception if any
Log.fehlerMeldung(978786563, Log.FEHLER_ART_PROG, History.class.getName(), e);
}
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
public void speichern() {
try (BufferedWriter br = new BufferedWriter(new OutputStreamWriter(new DataOutputStream(Files.newOutputStream(historyFilePath)))))
{
for (String h : this)
br.write(h + "\n");
br.flush();
} catch (Exception e) {//Catch exception if any
Log.fehlerMeldung(978786563, Log.FEHLER_ART_PROG, History.class.getName(), e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void updateSender(String nameSenderFilmliste, ListeFilme alteListe) {
// nur für den Mauskontext "Sender aktualisieren"
allesLaden = false;
initStart(alteListe);
MediathekReader reader = getMReaderNameSenderFilmliste(nameSenderFilmliste);
if (reader != null) {
new Thread(reader).start();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void updateSender(String nameSenderFilmliste, ListeFilme alteListe) {
// nur für den Mauskontext "Sender aktualisieren"
// allesLaden = false;
initStart(alteListe);
MediathekReader reader = getMReaderNameSenderFilmliste(nameSenderFilmliste);
if (reader != null) {
new Thread(reader).start();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static ListePset getStandardprogramme(DDaten ddaten) {
ListePset pSet;
InputStream datei;
if (System.getProperty("os.name").toLowerCase().contains("linux")) {
datei = new GetFile().getPsetVorlageLinux();
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
datei = new GetFile().getPsetVorlageMac();
} else {
datei = new GetFile().getPsetVorlageWindows();
}
// Standardgruppen laden
pSet = IoXmlLesen.importPset(datei, true);
return pSet;
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
public static ListePset getStandardprogramme(DDaten ddaten) {
ListePset pSet;
InputStream datei;
switch (getOs()) {
case OS_LINUX:
datei = new GetFile().getPsetVorlageLinux();
break;
case OS_MAC:
datei = new GetFile().getPsetVorlageMac();
break;
case OS_WIN_32BIT:
case OS_WIN_64BIT:
case OS_UNKNOWN:
default:
datei = new GetFile().getPsetVorlageWindows();
}
// Standardgruppen laden
pSet = IoXmlLesen.importPset(datei, true);
return pSet;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static boolean isLeopard() {
return isMac() && getOsVersion().startsWith("10.5");
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public static boolean isLeopard() {
return SystemInfo.isMacOSX() && SystemInfo.getOSVersion().startsWith("10.5");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void ladenHttp(String filmWebsite, String thema, String alter) {
// erst die Nummer suchen
// >25420<4<165<23. Die b
// <http://www.kikaplus.net/clients/kika/mediathek/previewpic/1355302530-f80b463888fd4602d925b2ef2c861928 9.jpg<
final String MUSTER_BILD = "<http://www.";
seiteHttp = getUrlIo.getUri(nameSenderMReader, filmWebsite, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema);
String nummer, url, bild, urlFilm, titel;
nummer = seiteHttp.extract(">", "<");
bild = seiteHttp.extract(MUSTER_BILD, "<");
if (!bild.isEmpty()) {
bild = "http://www." + bild;
}
// die URL bauen:
// http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=10&id=25420&page=az
if (!nummer.isEmpty()) {
url = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=" + alter + "&id=" + nummer + "&page=az";
seiteHttp = getUrlIo.getUri(nameSenderMReader, url, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema);
final String MUSTER_URL = "var videofile = \"";
final String MUSTER_TITEL = "var videotitle = \"";
urlFilm = seiteHttp.extract(MUSTER_URL, "\"");
titel = seiteHttp.extract(MUSTER_TITEL, "\"");
if (!urlFilm.equals("")) {
meldung(urlFilm);
// DatenFilm(String ssender, String tthema, String filmWebsite, String ttitel, String uurl, String uurlRtmp,
// String datum, String zeit,
// long dauerSekunden, String description, String thumbnailUrl, String imageUrl, String[] keywords) {
DatenFilm film = null;
if ((film = istInFilmListe(nameSenderMReader, thema, titel)) != null) {
film.addUrlKlein(urlFilm, "");
} else {
// dann gibs ihn noch nicht
addFilm(new DatenFilm(nameSenderMReader, thema, "http://www.kika.de/fernsehen/mediathek/index.shtml", titel, urlFilm, ""/* urlRtmp */,
""/*datum*/, ""/*zeit*/,
0, "", bild, "", new String[]{""}));
}
} else {
Log.fehlerMeldung(-915263078, Log.FEHLER_ART_MREADER, "MediathekKika", "keine URL: " + filmWebsite);
}
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void addToListNormal() {
//<strong style="margin-left:10px;">Sesamstraße präsentiert: Eine Möhre für Zwei</strong><br />
//<a style="margin-left:20px;" href="?programm=168&id=14487&ag=5" title="Sendung vom 10.10.2012" class="overlay_link">42. Ordnung ist das halbe Chaos</a><br />
//<a style="margin-left:20px;" href="?programm=168&id=14485&ag=5" title="Sendung vom 10.10.2012" class="overlay_link">41. Über den Wolken</a><br />
final String ADRESSE = "http://kikaplus.net/clients/kika/kikaplus/";
final String MUSTER_URL = "<a style=\"margin-left:20px;\" href=\"";
final String MUSTER_THEMA = "<strong style=\"margin-left:10px;\">";
final String MUSTER_DATUM = "title=\"Sendung vom ";
listeThemen.clear();
seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER);
seite = getUrlIo.getUri(nameSenderMReader, ADRESSE, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite");
int pos = 0;
int pos1, pos2, stop, pDatum1, pDatum2, pTitel1, pTitel2;
String url, thema, datum, titel;
while ((pos = seite.indexOf(MUSTER_THEMA, pos)) != -1) {
try {
thema = "";
pos += MUSTER_THEMA.length();
stop = seite.indexOf(MUSTER_THEMA, pos);
pos1 = pos;
if ((pos2 = seite.indexOf("<", pos1)) != -1) {
thema = seite.substring(pos1, pos2);
}
while ((pos1 = seite.indexOf(MUSTER_URL, pos1)) != -1) {
titel = "";
datum = "";
if (stop != -1 && pos1 > stop) {
// dann schon das nächste Thema
break;
}
pos1 += MUSTER_URL.length();
if ((pos2 = seite.indexOf("\"", pos1)) != -1) {
url = seite.substring(pos1, pos2);
//if (!url.equals("")) {
url = StringEscapeUtils.unescapeXml(url);
if (!url.equals("") && !url.startsWith("http://") && !url.startsWith("/")) {
// Datum
if ((pDatum1 = seite.indexOf(MUSTER_DATUM, pos2)) != -1) {
pDatum1 += MUSTER_DATUM.length();
if ((pDatum2 = seite.indexOf("\"", pDatum1)) != -1) {
if (stop != -1 && pDatum1 < stop && pDatum2 < stop) {
// dann schon das nächste Thema
datum = seite.substring(pDatum1, pDatum2);
}
}
}
// Titel
if ((pTitel1 = seite.indexOf(">", pos2)) != -1) {
pTitel1 += 1;
if ((pTitel2 = seite.indexOf("<", pTitel1)) != -1) {
//if (stop != -1 && pTitel1 > stop && pTitel2 > stop) {
if (stop != -1 && pTitel1 < stop && pTitel2 < stop) {
titel = seite.substring(pTitel1, pTitel2);
}
}
}
// in die Liste eintragen
String[] add = new String[]{ADRESSE + url, thema, titel, datum};
listeThemen.addUrl(add);
}
}
}
} catch (Exception ex) {
Log.fehlerMeldung(-302025469, Log.FEHLER_ART_MREADER, "MediathekKiKA.addToList", ex, "");
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public synchronized boolean zeileSchreiben(String thema, String titel, String url) {
boolean ret = false;
String text;
listeErledigteAbos.add(url);
File f = new File(Daten.getBasisVerzeichnis(true) + Konstanten.LOG_DATEI_DOWNLOAD_ABOS);
if (f != null) {
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(new FileOutputStream(f, true));
thema = GuiFunktionen.textLaenge(25, putzen(thema), false /* mitte */, false /*addVorne*/);
titel = GuiFunktionen.textLaenge(30, putzen(titel), false /* mitte */, false /*addVorne*/);
text = DatumZeit.getHeute_dd_MM_yyyy() + PAUSE + thema + PAUSE + titel + TRENNER + url + "\n";
writer.write(text);
writer.close();
ret = true;
} catch (Exception ex) {
Log.fehlerMeldung(945258023, Log.FEHLER_ART_PROG, "LogDownload.zeileSchreiben-1", ex);
} finally {
try {
writer.close();
} catch (Exception ex) {
}
}
}
ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_LISTE_ERLEDIGTE_ABOS, ErledigteAbos.class.getSimpleName());
return ret;
}
#location 14
#vulnerability type NULL_DEREFERENCE | #fixed code
public synchronized boolean zeileSchreiben(String thema, String titel, String url) {
boolean ret = false;
String text;
listeErledigteAbos.add(url);
//Automatic Resource Management
try (OutputStreamWriter writer = new OutputStreamWriter(Files.newOutputStream(Daten.getDownloadAboFilePath()))) {
thema = GuiFunktionen.textLaenge(25, putzen(thema), false /* mitte */, false /*addVorne*/);
titel = GuiFunktionen.textLaenge(30, putzen(titel), false /* mitte */, false /*addVorne*/);
text = DatumZeit.getHeute_dd_MM_yyyy() + PAUSE + thema + PAUSE + titel + TRENNER + url + "\n";
writer.write(text);
ret = true;
} catch (Exception ex) {
Log.fehlerMeldung(945258023, Log.FEHLER_ART_PROG, "LogDownload.zeileSchreiben-1", ex);
}
ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_LISTE_ERLEDIGTE_ABOS, ErledigteAbos.class.getSimpleName());
return ret;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void downloadLoeschen(boolean dauerhaft) {
int rows[] = jTable1.getSelectedRows();
if (rows.length > 0) {
for (int i = rows.length - 1; i >= 0; --i) {
int delRow = jTable1.convertRowIndexToModel(rows[i]);
String url = jTable1.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString();
DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url);
if (dauerhaft) {
if (download.istAbo()) {
// ein Abo wird zusätzlich ins Logfile geschrieben
ddaten.erledigteAbos.zeileSchreiben(download.arr[DatenDownload.DOWNLOAD_THEMA_NR],
download.arr[DatenDownload.DOWNLOAD_TITEL_NR],
url);
}
ddaten.listeDownloads.delDownloadByUrl(url);
}
ddaten.starterClass.filmLoeschen(jTable1.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString());
((TModelDownload) jTable1.getModel()).removeRow(delRow);
}
setInfo();
} else {
new HinweisKeineAuswahl().zeigen();
}
}
#location 17
#vulnerability type NULL_DEREFERENCE | #fixed code
private void downloadLoeschen(boolean dauerhaft) {
int rows[] = tabelle.getSelectedRows();
if (rows.length > 0) {
for (int i = rows.length - 1; i >= 0; --i) {
int delRow = tabelle.convertRowIndexToModel(rows[i]);
String url = tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString();
DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url);
if (dauerhaft) {
if (download.istAbo()) {
// ein Abo wird zusätzlich ins Logfile geschrieben
ddaten.erledigteAbos.zeileSchreiben(download.arr[DatenDownload.DOWNLOAD_THEMA_NR],
download.arr[DatenDownload.DOWNLOAD_TITEL_NR],
url);
}
ddaten.listeDownloads.delDownloadByUrl(url);
}
ddaten.starterClass.filmLoeschen(tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString());
((TModelDownload) tabelle.getModel()).removeRow(delRow);
}
setInfo();
} else {
new HinweisKeineAuswahl().zeigen();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static synchronized void versionsMeldungen(String classname) {
Log.systemMeldung("###########################################################");
long totalMem = Runtime.getRuntime().totalMemory();
Log.systemMeldung("totalMemory: " + totalMem / (1024L * 1024L) + " MB");
long maxMem = Runtime.getRuntime().maxMemory();
Log.systemMeldung("maxMemory: " + maxMem / (1024L * 1024L) + " MB");
long freeMem = Runtime.getRuntime().freeMemory();
Log.systemMeldung("freeMemory: " + freeMem / (1024L * 1024L) + " MB");
Log.systemMeldung("###########################################################");
try {
//Version
Log.systemMeldung(Konstanten.PROGRAMMNAME + " " + Konstanten.VERSION);
Date d = new Date(Main.class.getResource("Main.class").openConnection().getLastModified());
Log.systemMeldung("Compiled: " + new SimpleDateFormat("dd.MM.yyyy, HH:mm").format(d));
} catch (IOException ex) {
}
Log.systemMeldung("Klassenname: " + classname);
Log.systemMeldung("###########################################################");
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
public static synchronized void versionsMeldungen(String classname) {
Log.systemMeldung("###########################################################");
long totalMem = Runtime.getRuntime().totalMemory();
Log.systemMeldung("totalMemory: " + totalMem / (1024L * 1024L) + " MB");
long maxMem = Runtime.getRuntime().maxMemory();
Log.systemMeldung("maxMemory: " + maxMem / (1024L * 1024L) + " MB");
long freeMem = Runtime.getRuntime().freeMemory();
Log.systemMeldung("freeMemory: " + freeMem / (1024L * 1024L) + " MB");
Log.systemMeldung("###########################################################");
//Version
Log.systemMeldung(getCompileDate());
Log.systemMeldung("Klassenname: " + classname);
Log.systemMeldung("###########################################################");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getMusterPfadMplayer() {
final String PFAD_LINUX = "/usr/bin/mplayer";
final String PFAD_MAC = "/opt/local/bin/mplayer";
String pfad = "";
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
pfad = getWindowsMplayerPath();
} else if (System.getProperty("os.name").toLowerCase().contains("linux")) {
pfad = PFAD_LINUX;
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
pfad = PFAD_MAC;
}
if (new File(pfad).exists()) {
return pfad;
} else {
return "";
}
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String getMusterPfadMplayer() {
final String PFAD_LINUX = "/usr/bin/mplayer";
final String PFAD_MAC = "/opt/local/bin/mplayer";
final String PFAD_WIN_DEFAULT = "C:\\Program Files\\SMPlayer\\mplayer\\mplayer.exe";
final String PFAD_WIN = "\\SMPlayer\\mplayer\\mplayer.exe";
String pfad;
switch (getOs()) {
case OS_LINUX:
pfad = PFAD_LINUX;
break;
case OS_MAC:
pfad = PFAD_MAC;
break;
case OS_WIN_32BIT:
case OS_WIN_64BIT:
case OS_UNKNOWN:
default:
if (System.getenv("ProgramFiles") != null) {
pfad = System.getenv("ProgramFiles") + PFAD_WIN;
} else if (System.getenv("ProgramFiles(x86)") != null) {
pfad = System.getenv("ProgramFiles(x86)") + PFAD_WIN;
} else {
pfad = PFAD_WIN_DEFAULT;
}
}
if (!new File(pfad).exists()) {
pfad = "";
}
return pfad;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void addToListHttp() {
//http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age=3&page=all
//http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age=6&page=all
//http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age=10&page=all
final String ADRESSE_1 = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age=";
final String ADRESSE_2 = "&page=all";
final String MUSTER_START = "var programletterlist = {\"";
final String[] ALTER = {"3", "6", "10"};
// listeThemen.clear();
MVStringBuilder seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER);
meldungStart();
int pos1 = 0, pos2, start = 0, stop = 0;
String id = "", thema = "", url = "";
for (String alter : ALTER) {
seite = getUrlIo.getUri(nameSenderMReader, ADRESSE_1 + alter + ADRESSE_2, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite");
if ((start = seite.indexOf(MUSTER_START)) != -1) {
start += MUSTER_START.length();
pos1 = start;
if ((stop = seite.indexOf("}};", start)) != -1) {
while ((pos1 = seite.indexOf("\"", pos1)) != -1) {
thema = "";
id = "";
pos1 += 1;
if ((pos2 = seite.indexOf("\"", pos1)) != -1) {
id = seite.substring(pos1, pos2);
try {
// Testen auf Zehl
int z = Integer.parseInt(id);
} catch (Exception ex) {
continue;
}
++pos2;
if ((pos1 = seite.indexOf("\"", pos2)) != -1) {
++pos1;
if ((pos2 = seite.indexOf("\"", pos1)) != -1) {
thema = seite.substring(pos1, pos2);
}
}
// http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=program&id=165&age=10
url = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=program&id=" + id + "&age=" + alter;
ladenHttp(url, thema, alter);
}
}
}
}
}
}
#location 42
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void addToListNormal() {
//<strong style="margin-left:10px;">Sesamstraße präsentiert: Eine Möhre für Zwei</strong><br />
//<a style="margin-left:20px;" href="?programm=168&id=14487&ag=5" title="Sendung vom 10.10.2012" class="overlay_link">42. Ordnung ist das halbe Chaos</a><br />
//<a style="margin-left:20px;" href="?programm=168&id=14485&ag=5" title="Sendung vom 10.10.2012" class="overlay_link">41. Über den Wolken</a><br />
final String ADRESSE = "http://kikaplus.net/clients/kika/kikaplus/";
final String MUSTER_URL = "<a style=\"margin-left:20px;\" href=\"";
final String MUSTER_THEMA = "<strong style=\"margin-left:10px;\">";
final String MUSTER_DATUM = "title=\"Sendung vom ";
listeThemen.clear();
seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER);
seite = getUrlIo.getUri(nameSenderMReader, ADRESSE, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite");
int pos = 0;
int pos1, pos2, stop, pDatum1, pDatum2, pTitel1, pTitel2;
String url, thema, datum, titel;
while ((pos = seite.indexOf(MUSTER_THEMA, pos)) != -1) {
try {
thema = "";
pos += MUSTER_THEMA.length();
stop = seite.indexOf(MUSTER_THEMA, pos);
pos1 = pos;
if ((pos2 = seite.indexOf("<", pos1)) != -1) {
thema = seite.substring(pos1, pos2);
}
while ((pos1 = seite.indexOf(MUSTER_URL, pos1)) != -1) {
titel = "";
datum = "";
if (stop != -1 && pos1 > stop) {
// dann schon das nächste Thema
break;
}
pos1 += MUSTER_URL.length();
if ((pos2 = seite.indexOf("\"", pos1)) != -1) {
url = seite.substring(pos1, pos2);
//if (!url.equals("")) {
url = StringEscapeUtils.unescapeXml(url);
if (!url.equals("") && !url.startsWith("http://") && !url.startsWith("/")) {
// Datum
if ((pDatum1 = seite.indexOf(MUSTER_DATUM, pos2)) != -1) {
pDatum1 += MUSTER_DATUM.length();
if ((pDatum2 = seite.indexOf("\"", pDatum1)) != -1) {
if (stop != -1 && pDatum1 < stop && pDatum2 < stop) {
// dann schon das nächste Thema
datum = seite.substring(pDatum1, pDatum2);
}
}
}
// Titel
if ((pTitel1 = seite.indexOf(">", pos2)) != -1) {
pTitel1 += 1;
if ((pTitel2 = seite.indexOf("<", pTitel1)) != -1) {
//if (stop != -1 && pTitel1 > stop && pTitel2 > stop) {
if (stop != -1 && pTitel1 < stop && pTitel2 < stop) {
titel = seite.substring(pTitel1, pTitel2);
}
}
}
// in die Liste eintragen
String[] add = new String[]{ADRESSE + url, thema, titel, datum};
listeThemen.addUrl(add);
}
}
}
} catch (Exception ex) {
Log.fehlerMeldung(-302025469, Log.FEHLER_ART_MREADER, "MediathekKiKA.addToList", ex, "");
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getPfadScript() {
String pfadScript;
final String PFAD_LINUX_SCRIPT = "bin/flv.sh";
final String PFAD_WINDOWS_SCRIPT = "bin\\flv.bat";
if (System.getProperty("os.name").toLowerCase().contains("linux")) {
pfadScript = Funktionen.getPathJar() + PFAD_LINUX_SCRIPT;
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
pfadScript = Funktionen.getPathJar() + PFAD_LINUX_SCRIPT;
} else {
pfadScript = Funktionen.getPathJar() + PFAD_WINDOWS_SCRIPT;
}
return pfadScript;
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String getPfadScript() {
String pfadScript;
final String PFAD_LINUX_SCRIPT = "bin/flv.sh";
final String PFAD_WINDOWS_SCRIPT = "bin\\flv.bat";
switch (getOs()) {
case OS_LINUX:
pfadScript = Funktionen.getPathJar() + PFAD_LINUX_SCRIPT;
break;
case OS_MAC:
pfadScript = Funktionen.getPathJar() + PFAD_LINUX_SCRIPT;
break;
case OS_WIN_32BIT:
case OS_WIN_64BIT:
case OS_UNKNOWN:
default:
pfadScript = Funktionen.getPathJar() + PFAD_WINDOWS_SCRIPT;
}
return pfadScript;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void filmStartenWiederholenStoppen(boolean alle, boolean starten /* starten/wiederstarten oder stoppen */) {
// bezieht sich immer auf "alle" oder nur die markierten
// Film der noch keinen Starts hat wird gestartet
// Film dessen Start schon auf fertig/fehler steht wird wieder gestartet
// bei !starten wird der Film gestoppt
String[] urls;
// ==========================
// erst mal die URLs sammeln
if (alle) {
urls = new String[tabelle.getRowCount()];
for (int i = 0; i < tabelle.getRowCount(); ++i) {
urls[i] = tabelle.getModel().getValueAt(i, DatenDownload.DOWNLOAD_URL_NR).toString();
}
} else {
int[] rows = tabelle.getSelectedRows();
urls = new String[rows.length];
if (rows.length >= 0) {
for (int i = 0; i < rows.length; i++) {
int row = tabelle.convertRowIndexToModel(rows[i]);
urls[i] = tabelle.getModel().getValueAt(row, DatenDownload.DOWNLOAD_URL_NR).toString();
}
} else {
new HinweisKeineAuswahl().zeigen(parentComponent);
}
}
// ========================
// und jetzt abarbeiten
for (String url : urls) {
Start s = ddaten.starterClass.getStart(url);
DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url);
if (starten) {
// --------------
// starten
if (s != null) {
if (s.status > Start.STATUS_RUN) {
// wenn er noch läuft gibts nix
// wenn er schon fertig ist, erst mal fragen vor dem erneuten Starten
int a = JOptionPane.showConfirmDialog(parentComponent, "Film nochmal starten? ==> " + s.datenDownload.arr[DatenDownload.DOWNLOAD_TITEL_NR], "Fertiger Download", JOptionPane.YES_NO_OPTION);
if (a != JOptionPane.YES_OPTION) {
// weiter mit der nächsten URL
continue;
}
ddaten.starterClass.filmLoeschen(url);
if (s.datenDownload.istAbo()) {
// bei Abos Url auch aus dem Logfile löschen, der Film ist damit wieder auf "Anfang"
ddaten.erledigteAbos.urlAusLogfileLoeschen(url);
}
}
}
// jetzt noch starten/wiederstarten
// Start erstellen und zur Liste hinzufügen
download.starten(ddaten);
} else {
// ---------------
// stoppen
if (s != null) {
// wenn kein s -> dann gibts auch nichts zum stoppen oder wieder-starten
if (s.status <= Start.STATUS_RUN) {
// löschen -> nur wenn noch läuft, sonst gibts nichts mehr zum löschen
ddaten.starterClass.filmLoeschen(url);
if (s.datenDownload.istAbo()) {
// bei Abos Url auch aus dem Logfile löschen, der Film ist damit wieder auf "Anfang"
ddaten.erledigteAbos.urlAusLogfileLoeschen(url);
}
}
download.startMelden(DatenDownload.PROGRESS_NICHT_GESTARTET);
}
}
}
}
#location 53
#vulnerability type NULL_DEREFERENCE | #fixed code
private void filmStartenWiederholenStoppen(boolean alle, boolean starten /* starten/wiederstarten oder stoppen */) {
// bezieht sich immer auf "alle" oder nur die markierten
// Film der noch keinen Starts hat wird gestartet
// Film dessen Start schon auf fertig/fehler steht wird wieder gestartet
// bei !starten wird der Film gestoppt
String[] urls;
ArrayList<DatenDownload> arrayDownload = new ArrayList<DatenDownload>();
// ==========================
// erst mal die URLs sammeln
if (alle) {
urls = new String[tabelle.getRowCount()];
for (int i = 0; i < tabelle.getRowCount(); ++i) {
urls[i] = tabelle.getModel().getValueAt(i, DatenDownload.DOWNLOAD_URL_NR).toString();
}
} else {
int[] rows = tabelle.getSelectedRows();
urls = new String[rows.length];
if (rows.length >= 0) {
for (int i = 0; i < rows.length; i++) {
int row = tabelle.convertRowIndexToModel(rows[i]);
urls[i] = tabelle.getModel().getValueAt(row, DatenDownload.DOWNLOAD_URL_NR).toString();
}
} else {
new HinweisKeineAuswahl().zeigen(parentComponent);
}
}
// ========================
// und jetzt abarbeiten
for (String url : urls) {
Start s = ddaten.starterClass.getStart(url);
DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url);
if (starten) {
// --------------
// starten
if (s != null) {
if (s.status > Start.STATUS_RUN) {
// wenn er noch läuft gibts nix
// wenn er schon fertig ist, erst mal fragen vor dem erneuten Starten
int a = JOptionPane.showConfirmDialog(parentComponent, "Film nochmal starten? ==> " + s.datenDownload.arr[DatenDownload.DOWNLOAD_TITEL_NR], "Fertiger Download", JOptionPane.YES_NO_OPTION);
if (a != JOptionPane.YES_OPTION) {
// weiter mit der nächsten URL
continue;
}
ddaten.starterClass.filmLoeschen(url);
if (s.datenDownload.istAbo()) {
// bei Abos Url auch aus dem Logfile löschen, der Film ist damit wieder auf "Anfang"
ddaten.erledigteAbos.urlAusLogfileLoeschen(url);
}
}
}
arrayDownload.add(download);
} else {
// ---------------
// stoppen
if (s != null) {
// wenn kein s -> dann gibts auch nichts zum stoppen oder wieder-starten
if (s.status <= Start.STATUS_RUN) {
// löschen -> nur wenn noch läuft, sonst gibts nichts mehr zum löschen
ddaten.starterClass.filmLoeschen(url);
if (s.datenDownload.istAbo()) {
// bei Abos Url auch aus dem Logfile löschen, der Film ist damit wieder auf "Anfang"
ddaten.erledigteAbos.urlAusLogfileLoeschen(url);
}
}
arrayDownload.add(download);
}
}
}
if (starten) {
//alle Downloads starten/wiederstarten
DatenDownload.starten(ddaten, arrayDownload);
} else {
//oder alle Downloads stoppen
DatenDownload.statusMelden(arrayDownload, DatenDownload.PROGRESS_NICHT_GESTARTET);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static synchronized void startMeldungen(String classname) {
Log.systemMeldung("###########################################################");
try {
//Version
Log.systemMeldung(Konstanten.PROGRAMMNAME + " " + Konstanten.VERSION);
Date d = new Date(Main.class.getResource("Main.class").openConnection().getLastModified());
Log.systemMeldung("Compiled: " + new SimpleDateFormat("dd.MM.yyyy, HH:mm").format(d));
} catch (IOException ex) {
}
Log.systemMeldung("Klassenname: " + classname);
Log.systemMeldung("");
Log.systemMeldung("Programmpfad: " + GuiFunktionenProgramme.getPathJar());
Log.systemMeldung("Verzeichnis Einstellungen: " + Daten.getBasisVerzeichnis());
Log.systemMeldung("Useragent: " + Daten.getUserAgent());
Log.systemMeldung("");
long totalMem = Runtime.getRuntime().totalMemory();
Log.systemMeldung("totalMemory: " + totalMem / (1024L * 1024L) + " MB");
long maxMem = Runtime.getRuntime().maxMemory();
Log.systemMeldung("maxMemory: " + maxMem / (1024L * 1024L) + " MB");
long freeMem = Runtime.getRuntime().freeMemory();
Log.systemMeldung("freeMemory: " + freeMem / (1024L * 1024L) + " MB");
Log.systemMeldung("###########################################################");
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
public static synchronized void startMeldungen(String classname) {
versionsMeldungen(classname);
Log.systemMeldung("Programmpfad: " + GuiFunktionenProgramme.getPathJar());
Log.systemMeldung("Verzeichnis Einstellungen: " + Daten.getBasisVerzeichnis());
Log.systemMeldung("Useragent: " + Daten.getUserAgent());
Log.systemMeldung("###########################################################");
Log.systemMeldung("");
Log.systemMeldung("");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getCompileDate() {
String ret = "";
try {
Date d = new Date(Main.class.getResource("Main.class").openConnection().getLastModified());
ret = Konstanten.PROGRAMMNAME + " " + Konstanten.VERSION + " [Buildnummer: " + getBuildNr() + "] - Compiled: " + new SimpleDateFormat("dd.MM.yyyy, HH:mm").format(d);
} catch (Exception ex) {
Log.fehlerMeldung(569614756, "Log.getCompileDate: ", ex);
}
return ret;
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
public static String getCompileDate() {
// String ret = "";
// try {
// Date d = new Date(Main.class.getResource("Main.class").openConnection().getLastModified());
// ret = Konstanten.PROGRAMMNAME + " " + Konstanten.VERSION + " [Buildnummer: " + getBuildNr() + "] - Compiled: " + new SimpleDateFormat("dd.MM.yyyy, HH:mm").format(d);
// } catch (Exception ex) {
// Log.fehlerMeldung(569614756, "Log.getCompileDate: ", ex);
// }
// return ret;
final ResourceBundle rb;
String propToken = "BUILDDATE";
String msg = "";
try {
ResourceBundle.clearCache();
rb = ResourceBundle.getBundle("version");
msg = rb.getString(propToken);
} catch (Exception e) {
System.err.println(e.getMessage());
System.err.println("Token " + propToken + " not in Propertyfile!");
}
return Konstanten.PROGRAMMNAME + " " + Konstanten.VERSION + " [Buildnummer: " + getBuildNr() + "] - Compiled: " + msg;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void meldenFertig(String sender) {
//wird ausgeführt wenn Sender beendet ist
int MAX_SENDER = 15, MAX1 = 24, MAX2 = 30;
Log.systemMeldung("Fertig " + sender + ": " + DatumZeit.getJetzt_HH_MM_SS());
RunSender run = listeSenderLaufen.senderFertig(sender);
if (run != null) {
// Zeile 1
String zeile = "==================================================================================================================";
fertigMeldung.add(zeile);
zeile = textLaenge(MAX_SENDER, run.sender);
zeile += textLaenge(MAX1, "Laufzeit[Min.]: " + run.getLaufzeitMinuten());
zeile += textLaenge(MAX1, " Seiten: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER, run.sender));
String nameFilmliste[] = getMReaderNameSenderMreader(run.sender).getNameSenderFilmliste();
if (nameFilmliste.length == 1) {
zeile += "Filme: " + listeFilmeNeu.countSender(nameFilmliste[0]);
} else {
for (int i = 0; i < nameFilmliste.length; i++) {
zeile += "Filme [" + nameFilmliste[i] + "]: " + listeFilmeNeu.countSender(nameFilmliste[i]) + " ";
}
}
fertigMeldung.add(zeile);
// Zeile 2
zeile = textLaenge(MAX_SENDER, "");
zeile += textLaenge(MAX1, " Ladefehler: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER_FEHlER, run.sender));
zeile += textLaenge(MAX1, "Fehlversuche: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER_FEHLERVERSUCHE, run.sender));
zeile += textLaenge(MAX2, "Wartezeit Fehler[s]: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER_WARTEZEIT_FEHLVERSUCHE, run.sender));
String groesse = (GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE, run.sender) == 0) ? "<1" : Long.toString(GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE, run.sender));
zeile += textLaenge(MAX1, "Daten[MByte]: " + groesse);
fertigMeldung.add(zeile);
}
// wird einmal aufgerufen, wenn alle Sender fertig sind
if (listeSenderLaufen.listeFertig()) {
listeFilmeNeu.sort();
if (!allesLaden) {
// alte Filme eintragen
listeFilmeNeu.updateListe(listeFilmeAlt, true /* über den Index vergleichen */);
}
listeFilmeAlt = null; // brauchmer nicht mehr
metaDatenSchreiben();
stopZeit = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
int minuten;
try {
minuten = Math.round((stopZeit.getTime() - startZeit.getTime()) / (1000 * 60));
} catch (Exception ex) {
minuten = -1;
}
Log.systemMeldung("");
Log.systemMeldung("==================================================================================================================");
Log.systemMeldung("Sender ===========================================================================================================");
Log.systemMeldung(fertigMeldung.toArray(new String[0]));
Log.systemMeldung("==================================================================================================================");
Log.systemMeldung("");
Log.systemMeldung(" Seiten geladen: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER));
String groesse = (GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE) == 0) ? "<1" : Long.toString(GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE, run.sender));
Log.systemMeldung("Summe geladen[MByte]: " + groesse);
Log.systemMeldung(" --> Start: " + sdf.format(startZeit));
Log.systemMeldung(" --> Ende: " + sdf.format(stopZeit));
Log.systemMeldung(" --> Dauer[Min]: " + (minuten == 0 ? "<1" : minuten));
Log.systemMeldung("");
Log.systemMeldung("==================================================================================================================");
Log.systemMeldung("==================================================================================================================");
notifyFertig(new FilmListenerElement(sender, "", listeSenderLaufen.getMax(), listeSenderLaufen.getProgress()));
} else {
//nur ein Sender fertig
notifyProgress(new FilmListenerElement(sender, "", listeSenderLaufen.getMax(), listeSenderLaufen.getProgress()));
}
}
#location 56
#vulnerability type NULL_DEREFERENCE | #fixed code
public void meldenFertig(String sender) {
//wird ausgeführt wenn Sender beendet ist
int MAX_SENDER = 15, MAX1 = 24, MAX2 = 30;
Log.systemMeldung("Fertig " + sender + ": " + DatumZeit.getJetzt_HH_MM_SS());
RunSender run = listeSenderLaufen.senderFertig(sender);
if (run != null) {
// Zeile 1
String zeile = "==================================================================================================================";
fertigMeldung.add(zeile);
zeile = textLaenge(MAX_SENDER, run.sender);
zeile += textLaenge(MAX1, "Laufzeit[Min.]: " + run.getLaufzeitMinuten());
zeile += textLaenge(MAX1, " Seiten: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER, run.sender));
String nameFilmliste[] = getMReaderNameSenderMreader(run.sender).getNameSenderFilmliste();
if (nameFilmliste.length == 1) {
zeile += "Filme: " + listeFilmeNeu.countSender(nameFilmliste[0]);
} else {
for (int i = 0; i < nameFilmliste.length; i++) {
zeile += "Filme [" + nameFilmliste[i] + "]: " + listeFilmeNeu.countSender(nameFilmliste[i]) + " ";
}
}
fertigMeldung.add(zeile);
// Zeile 2
zeile = textLaenge(MAX_SENDER, "");
zeile += textLaenge(MAX1, " Ladefehler: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER_FEHlER, run.sender));
zeile += textLaenge(MAX1, "Fehlversuche: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER_FEHLERVERSUCHE, run.sender));
zeile += textLaenge(MAX2, "Wartezeit Fehler[s]: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER_WARTEZEIT_FEHLVERSUCHE, run.sender));
String groesse = (GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE, run.sender) == 0) ? "<1" : Long.toString(GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE, run.sender));
zeile += textLaenge(MAX1, "Daten[MByte]: " + groesse);
fertigMeldung.add(zeile);
}
// wird einmal aufgerufen, wenn alle Sender fertig sind
if (listeSenderLaufen.listeFertig()) {
listeFilmeNeu.sort();
if (!allesLaden) {
// alte Filme eintragen
listeFilmeNeu.updateListe(listeFilmeAlt, true /* über den Index vergleichen */);
}
listeFilmeAlt = null; // brauchmer nicht mehr
metaDatenSchreiben();
stopZeit = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
int minuten;
try {
minuten = Math.round((stopZeit.getTime() - startZeit.getTime()) / (1000 * 60));
} catch (Exception ex) {
minuten = -1;
}
Log.systemMeldung("");
Log.systemMeldung("==================================================================================================================");
Log.systemMeldung("Sender ===========================================================================================================");
Log.systemMeldung(fertigMeldung.toArray(new String[0]));
Log.systemMeldung("==================================================================================================================");
Log.systemMeldung("");
Log.systemMeldung(" Seiten geladen: " + GetUrl.getSeitenZaehler(GetUrl.LISTE_SEITEN_ZAEHLER));
String groesse = (GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE) == 0) ? "<1" : Long.toString(GetUrl.getSeitenZaehler(GetUrl.LISTE_SUMME_BYTE));
Log.systemMeldung("Summe geladen[MByte]: " + groesse);
Log.systemMeldung(" --> Start: " + sdf.format(startZeit));
Log.systemMeldung(" --> Ende: " + sdf.format(stopZeit));
Log.systemMeldung(" --> Dauer[Min]: " + (minuten == 0 ? "<1" : minuten));
Log.systemMeldung("");
Log.systemMeldung("==================================================================================================================");
Log.systemMeldung("==================================================================================================================");
notifyFertig(new FilmListenerElement(sender, "", listeSenderLaufen.getMax(), listeSenderLaufen.getProgress()));
} else {
//nur ein Sender fertig
notifyProgress(new FilmListenerElement(sender, "", listeSenderLaufen.getMax(), listeSenderLaufen.getProgress()));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static synchronized void versionsMeldungen(String classname) {
Log.systemMeldung("###########################################################");
long totalMem = Runtime.getRuntime().totalMemory();
Log.systemMeldung("totalMemory: " + totalMem / (1024L * 1024L) + " MB");
long maxMem = Runtime.getRuntime().maxMemory();
Log.systemMeldung("maxMemory: " + maxMem / (1024L * 1024L) + " MB");
long freeMem = Runtime.getRuntime().freeMemory();
Log.systemMeldung("freeMemory: " + freeMem / (1024L * 1024L) + " MB");
Log.systemMeldung("###########################################################");
try {
//Version
Log.systemMeldung(Konstanten.PROGRAMMNAME + " " + Konstanten.VERSION);
Date d = new Date(Main.class.getResource("Main.class").openConnection().getLastModified());
Log.systemMeldung("Compiled: " + new SimpleDateFormat("dd.MM.yyyy, HH:mm").format(d));
} catch (IOException ex) {
}
Log.systemMeldung("Klassenname: " + classname);
Log.systemMeldung("###########################################################");
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
public static synchronized void versionsMeldungen(String classname) {
Log.systemMeldung("###########################################################");
long totalMem = Runtime.getRuntime().totalMemory();
Log.systemMeldung("totalMemory: " + totalMem / (1024L * 1024L) + " MB");
long maxMem = Runtime.getRuntime().maxMemory();
Log.systemMeldung("maxMemory: " + maxMem / (1024L * 1024L) + " MB");
long freeMem = Runtime.getRuntime().freeMemory();
Log.systemMeldung("freeMemory: " + freeMem / (1024L * 1024L) + " MB");
Log.systemMeldung("###########################################################");
//Version
Log.systemMeldung(getCompileDate());
Log.systemMeldung("Klassenname: " + classname);
Log.systemMeldung("###########################################################");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private synchronized StringBuffer getUri(String sender, String addr, StringBuffer seite, String kodierung, int timeout, String meldung, int versuch, boolean lVersuch) {
int timeo = timeout;
boolean proxyB = false;
char[] zeichen = new char[1];
seite.setLength(0);
URLConnection conn;
int code = 0;
InputStream in = null;
InputStreamReader inReader = null;
Proxy proxy = null;
SocketAddress saddr = null;
// immer etwas bremsen
try {
long w = wartenBasis * faktorWarten;
this.wait(w);
} catch (Exception ex) {
Log.fehlerMeldung(976120379, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, sender);
}
try {
URL url = new URL(addr);
// conn = url.openConnection(Proxy.NO_PROXY);
conn = url.openConnection();
conn.setRequestProperty("User-Agent", Daten.getUserAgent());
if (timeout > 0) {
conn.setReadTimeout(timeout);
conn.setConnectTimeout(timeout);
}
if (conn instanceof HttpURLConnection) {
HttpURLConnection httpConnection = (HttpURLConnection) conn;
code = httpConnection.getResponseCode();
// if (code >= 400) {
// if (true) {
// // wenn möglich, einen Proxy einrichten
// Log.fehlerMeldung(236597125, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "---Proxy---");
// proxyB = true;
// saddr = new InetSocketAddress("localhost", 9050);
// proxy = new Proxy(Proxy.Type.SOCKS, saddr);
// conn = url.openConnection(proxy);
// conn.setRequestProperty("User-Agent", Daten.getUserAgent());
// if (timeout > 0) {
// conn.setReadTimeout(timeout);
// conn.setConnectTimeout(timeout);
// }
// } else {
// Log.fehlerMeldung(864123698, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "returncode >= 400");
// }
// }
} else {
Log.fehlerMeldung(949697315, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "keine HTTPcon");
}
in = conn.getInputStream();
inReader = new InputStreamReader(in, kodierung);
while (!Daten.filmeLaden.getStop() && inReader.read(zeichen) != -1) {
seite.append(zeichen);
incSeitenZaehler(LISTE_SUMME_BYTE, sender, 1);
}
} catch (IOException ex) {
if (lVersuch) {
String[] text;
if (meldung.equals("")) {
text = new String[]{sender + " - timout: " + timeo + " Versuche: " + versuch, addr /*, (proxyB ? "Porxy - " : "")*/};
} else {
text = new String[]{sender + " - timout: " + timeo + " Versuche: " + versuch, addr, meldung/*, (proxyB ? "Porxy - " : "")*/};
}
Log.fehlerMeldung(502739817, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, text);
}
} catch (Exception ex) {
Log.fehlerMeldung(973969801, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, "");
} finally {
try {
if (in != null) {
inReader.close();
}
} catch (IOException ex) {
}
}
return seite;
}
#location 72
#vulnerability type RESOURCE_LEAK | #fixed code
private synchronized StringBuffer getUri(String sender, String addr, StringBuffer seite, String kodierung, int timeout, String meldung, int versuch, boolean lVersuch) {
int timeo = timeout;
boolean proxyB = false;
char[] zeichen = new char[1];
seite.setLength(0);
HttpURLConnection conn = null;
int code = 0;
InputStream in = null;
InputStreamReader inReader = null;
Proxy proxy = null;
SocketAddress saddr = null;
int ladeArt = LADE_ART_UNBEKANNT;
// immer etwas bremsen
try {
long w = wartenBasis * faktorWarten;
this.wait(w);
} catch (Exception ex) {
Log.fehlerMeldung(976120379, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, sender);
}
try {
// conn = url.openConnection(Proxy.NO_PROXY);
conn = (HttpURLConnection) new URL(addr).openConnection();
conn.setRequestProperty("User-Agent", Daten.getUserAgent());
conn.setRequestProperty("User-Agent", Daten.getUserAgent());
System.setProperty("http.maxConnections", "600");
System.setProperty("http.keepAlive", "false");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
if (timeout > 0) {
conn.setReadTimeout(timeout);
conn.setConnectTimeout(timeout);
}
// the encoding returned by the server
String encoding = conn.getContentEncoding();
// if (conn instanceof HttpURLConnection) {
// HttpURLConnection httpConnection = (HttpURLConnection) conn;
// code = httpConnection.getResponseCode();
// if (code >= 400) {
// if (true) {
// // wenn möglich, einen Proxy einrichten
// Log.fehlerMeldung(236597125, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "---Proxy---");
// proxyB = true;
// saddr = new InetSocketAddress("localhost", 9050);
// proxy = new Proxy(Proxy.Type.SOCKS, saddr);
// conn = url.openConnection(proxy);
// conn.setRequestProperty("User-Agent", Daten.getUserAgent());
// if (timeout > 0) {
// conn.setReadTimeout(timeout);
// conn.setConnectTimeout(timeout);
// }
// } else {
// Log.fehlerMeldung(864123698, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "returncode >= 400");
// }
// }
// } else {
// Log.fehlerMeldung(949697315, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "keine HTTPcon");
// }
//in = conn.getInputStream();
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
ladeArt = LADE_ART_GZIP;
in = new GZIPInputStream(conn.getInputStream());
} else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
ladeArt = LADE_ART_DEFLATE;
in = new InflaterInputStream(conn.getInputStream(), new Inflater(true));
} else {
ladeArt = LADE_ART_NIX;
in = conn.getInputStream();
}
inReader = new InputStreamReader(in, kodierung);
//// while (!Daten.filmeLaden.getStop() && inReader.read(zeichen) != -1) {
//// seite.append(zeichen);
//// incSeitenZaehler(LISTE_SUMME_BYTE, sender, 1);
//// }
char[] buff = new char[256];
int cnt;
while (!Daten.filmeLaden.getStop() && (cnt = inReader.read(buff)) > 0) {
seite.append(buff, 0, cnt);
incSeitenZaehler(LISTE_SUMME_BYTE, sender, cnt, ladeArt);
}
} catch (IOException ex) {
// consume error stream, otherwise, connection won't be reused
if (conn != null) {
try {
InputStream i = conn.getErrorStream();
if (i != null) {
i.close();
}
if (inReader != null) {
inReader.close();
}
} catch (Exception e) {
Log.fehlerMeldung(645105987, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", e, "");
}
}
if (lVersuch) {
String[] text;
if (meldung.equals("")) {
text = new String[]{sender + " - timout: " + timeo + " Versuche: " + versuch, addr /*, (proxyB ? "Porxy - " : "")*/};
} else {
text = new String[]{sender + " - timout: " + timeo + " Versuche: " + versuch, addr, meldung/*, (proxyB ? "Porxy - " : "")*/};
}
if (ex.getMessage().equals("Read timed out")) {
Log.fehlerMeldung(502739817, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri: TimeOut", text);
} else {
Log.fehlerMeldung(502739817, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, text);
}
}
} catch (Exception ex) {
Log.fehlerMeldung(973969801, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, "");
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ex) {
Log.fehlerMeldung(696321478, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, "");
}
}
return seite;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void ladenHttp(String filmWebsite, String thema, String alter) {
// erst die Nummer suchen
// >25420<4<165<23. Die b
// <http://www.kikaplus.net/clients/kika/mediathek/previewpic/1355302530-f80b463888fd4602d925b2ef2c861928 9.jpg<
final String MUSTER_BILD = "<http://www.";
seiteHttp = getUrlIo.getUri(nameSenderMReader, filmWebsite, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema);
String nummer, url, bild, urlFilm, titel;
nummer = seiteHttp.extract(">", "<");
bild = seiteHttp.extract(MUSTER_BILD, "<");
if (!bild.isEmpty()) {
bild = "http://www." + bild;
}
// die URL bauen:
// http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=10&id=25420&page=az
if (!nummer.isEmpty()) {
url = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=" + alter + "&id=" + nummer + "&page=az";
seiteHttp = getUrlIo.getUri(nameSenderMReader, url, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema);
final String MUSTER_URL = "var videofile = \"";
final String MUSTER_TITEL = "var videotitle = \"";
urlFilm = seiteHttp.extract(MUSTER_URL, "\"");
titel = seiteHttp.extract(MUSTER_TITEL, "\"");
if (!urlFilm.equals("")) {
meldung(urlFilm);
// DatenFilm(String ssender, String tthema, String filmWebsite, String ttitel, String uurl, String uurlRtmp,
// String datum, String zeit,
// long dauerSekunden, String description, String thumbnailUrl, String imageUrl, String[] keywords) {
DatenFilm film = null;
if ((film = istInFilmListe(nameSenderMReader, thema, titel)) != null) {
film.addUrlKlein(urlFilm, "");
} else {
// dann gibs ihn noch nicht
addFilm(new DatenFilm(nameSenderMReader, thema, "http://www.kika.de/fernsehen/mediathek/index.shtml", titel, urlFilm, ""/* urlRtmp */,
""/*datum*/, ""/*zeit*/,
0, "", bild, "", new String[]{""}));
}
} else {
Log.fehlerMeldung(-915263078, Log.FEHLER_ART_MREADER, "MediathekKika", "keine URL: " + filmWebsite);
}
}
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void addToListNormal() {
//<strong style="margin-left:10px;">Sesamstraße präsentiert: Eine Möhre für Zwei</strong><br />
//<a style="margin-left:20px;" href="?programm=168&id=14487&ag=5" title="Sendung vom 10.10.2012" class="overlay_link">42. Ordnung ist das halbe Chaos</a><br />
//<a style="margin-left:20px;" href="?programm=168&id=14485&ag=5" title="Sendung vom 10.10.2012" class="overlay_link">41. Über den Wolken</a><br />
final String ADRESSE = "http://kikaplus.net/clients/kika/kikaplus/";
final String MUSTER_URL = "<a style=\"margin-left:20px;\" href=\"";
final String MUSTER_THEMA = "<strong style=\"margin-left:10px;\">";
final String MUSTER_DATUM = "title=\"Sendung vom ";
listeThemen.clear();
seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER);
seite = getUrlIo.getUri(nameSenderMReader, ADRESSE, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite");
int pos = 0;
int pos1, pos2, stop, pDatum1, pDatum2, pTitel1, pTitel2;
String url, thema, datum, titel;
while ((pos = seite.indexOf(MUSTER_THEMA, pos)) != -1) {
try {
thema = "";
pos += MUSTER_THEMA.length();
stop = seite.indexOf(MUSTER_THEMA, pos);
pos1 = pos;
if ((pos2 = seite.indexOf("<", pos1)) != -1) {
thema = seite.substring(pos1, pos2);
}
while ((pos1 = seite.indexOf(MUSTER_URL, pos1)) != -1) {
titel = "";
datum = "";
if (stop != -1 && pos1 > stop) {
// dann schon das nächste Thema
break;
}
pos1 += MUSTER_URL.length();
if ((pos2 = seite.indexOf("\"", pos1)) != -1) {
url = seite.substring(pos1, pos2);
//if (!url.equals("")) {
url = StringEscapeUtils.unescapeXml(url);
if (!url.equals("") && !url.startsWith("http://") && !url.startsWith("/")) {
// Datum
if ((pDatum1 = seite.indexOf(MUSTER_DATUM, pos2)) != -1) {
pDatum1 += MUSTER_DATUM.length();
if ((pDatum2 = seite.indexOf("\"", pDatum1)) != -1) {
if (stop != -1 && pDatum1 < stop && pDatum2 < stop) {
// dann schon das nächste Thema
datum = seite.substring(pDatum1, pDatum2);
}
}
}
// Titel
if ((pTitel1 = seite.indexOf(">", pos2)) != -1) {
pTitel1 += 1;
if ((pTitel2 = seite.indexOf("<", pTitel1)) != -1) {
//if (stop != -1 && pTitel1 > stop && pTitel2 > stop) {
if (stop != -1 && pTitel1 < stop && pTitel2 < stop) {
titel = seite.substring(pTitel1, pTitel2);
}
}
}
// in die Liste eintragen
String[] add = new String[]{ADRESSE + url, thema, titel, datum};
listeThemen.addUrl(add);
}
}
}
} catch (Exception ex) {
Log.fehlerMeldung(-302025469, Log.FEHLER_ART_MREADER, "MediathekKiKA.addToList", ex, "");
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public synchronized void abosSuchen() {
// in der Filmliste nach passenden Filmen suchen und
// in die Liste der Downloads eintragen
boolean gefunden = false;
DatenFilm film;
DatenAbo abo;
boolean checkBlack = !Boolean.parseBoolean(Daten.system[Konstanten.SYSTEM_BLACKLIST_AUSGESCHALTET_NR])
&& Boolean.parseBoolean(Daten.system[Konstanten.SYSTEM_BLACKLIST_AUCH_ABO_NR]);
ListIterator<DatenFilm> itFilm = Daten.listeFilme.listIterator();
while (itFilm.hasNext()) {
film = itFilm.next();
abo = ddaten.listeAbo.getAboFuerFilm(film);
if (abo == null) {
continue;
} else if (!abo.aboIstEingeschaltet()) {
continue;
} else if (ddaten.erledigteAbos.urlPruefen(film.arr[DatenFilm.FILM_URL_NR])) {
// ist schon im Logfile, weiter
continue;
} else if (checkListe(film.arr[DatenFilm.FILM_URL_NR])) {
// haben wir schon in der Downloadliste
continue;
} else if (checkBlack && !ddaten.listeBlacklist.checkBlackOkFilme_Downloads(film)) {
// wenn Blacklist auch für Abos, dann ers mal da schauen
continue;
} else {
//diesen Film in die Downloadliste eintragen
abo.arr[DatenAbo.ABO_DOWN_DATUM_NR] = new SimpleDateFormat("dd.MM.yyyy").format(new Date());
//wenn nicht doppelt, dann in die Liste schreiben
DatenPset pSet = ddaten.listePset.getPsetAbo(abo.arr[DatenAbo.ABO_PSET_NR]);
if (!abo.arr[DatenAbo.ABO_PSET_NR].equals(pSet.arr[DatenPset.PROGRAMMSET_NAME_NR])) {
// abo ändern
abo.arr[DatenAbo.ABO_PSET_NR] = pSet.arr[DatenPset.PROGRAMMSET_NAME_NR];
}
if (pSet != null) {
add(new DatenDownload(pSet, film, Start.QUELLE_ABO, abo, "", ""));
gefunden = true;
}
}
} //while
if (gefunden) {
listeNummerieren();
}
}
#location 31
#vulnerability type NULL_DEREFERENCE | #fixed code
public synchronized void abosSuchen() {
// in der Filmliste nach passenden Filmen suchen und
// in die Liste der Downloads eintragen
boolean gefunden = false;
DatenFilm film;
DatenAbo abo;
boolean checkBlack = !Boolean.parseBoolean(Daten.system[Konstanten.SYSTEM_BLACKLIST_AUSGESCHALTET_NR])
&& Boolean.parseBoolean(Daten.system[Konstanten.SYSTEM_BLACKLIST_AUCH_ABO_NR]);
ListIterator<DatenFilm> itFilm = Daten.listeFilme.listIterator();
while (itFilm.hasNext()) {
film = itFilm.next();
abo = ddaten.listeAbo.getAboFuerFilm(film);
if (abo == null) {
continue;
} else if (!abo.aboIstEingeschaltet()) {
continue;
} else if (ddaten.erledigteAbos.urlPruefen(film.arr[DatenFilm.FILM_URL_NR])) {
// ist schon im Logfile, weiter
continue;
} else if (checkListe(film.arr[DatenFilm.FILM_URL_NR])) {
// haben wir schon in der Downloadliste
continue;
} else if (checkBlack) {
if (!ddaten.listeBlacklist.checkBlackOkFilme_Downloads(film)) { // wenn Blacklist auch für Abos, dann ers mal da schauen
continue;
}
} else {
//diesen Film in die Downloadliste eintragen
abo.arr[DatenAbo.ABO_DOWN_DATUM_NR] = new SimpleDateFormat("dd.MM.yyyy").format(new Date());
//wenn nicht doppelt, dann in die Liste schreiben
DatenPset pSet = ddaten.listePset.getPsetAbo(abo.arr[DatenAbo.ABO_PSET_NR]);
if (pSet != null) {
if (!abo.arr[DatenAbo.ABO_PSET_NR].equals(pSet.arr[DatenPset.PROGRAMMSET_NAME_NR])) {
abo.arr[DatenAbo.ABO_PSET_NR] = pSet.arr[DatenPset.PROGRAMMSET_NAME_NR];
}
add(new DatenDownload(pSet, film, Start.QUELLE_ABO, abo, "", ""));
gefunden = true;
}
}
} //while
if (gefunden) {
listeNummerieren();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void speichern() {
try {
FileOutputStream fstream = new FileOutputStream(datei);
DataOutputStream out = new DataOutputStream(fstream);
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(out));
for (String h : this) {
br.write(h + "\n");
}
br.flush();
out.close();
} catch (Exception e) {//Catch exception if any
Log.fehlerMeldung(978786563, Log.FEHLER_ART_PROG, History.class.getName(), e);
}
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
public void speichern() {
try (BufferedWriter br = new BufferedWriter(new OutputStreamWriter(new DataOutputStream(Files.newOutputStream(historyFilePath)))))
{
for (String h : this)
br.write(h + "\n");
br.flush();
} catch (Exception e) {//Catch exception if any
Log.fehlerMeldung(978786563, Log.FEHLER_ART_PROG, History.class.getName(), e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void ladenHttp(String filmWebsite, String thema, String alter) {
// erst die Nummer suchen
// >25420<4<165<23. Die b
// <http://www.kikaplus.net/clients/kika/mediathek/previewpic/1355302530-f80b463888fd4602d925b2ef2c861928 9.jpg<
final String MUSTER_BILD = "<http://www.";
seiteHttp = getUrlIo.getUri(nameSenderMReader, filmWebsite, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema);
String nummer, url, bild, urlFilm, titel;
nummer = seiteHttp.extract(">", "<");
bild = seiteHttp.extract(MUSTER_BILD, "<");
if (!bild.isEmpty()) {
bild = "http://www." + bild;
}
// die URL bauen:
// http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=10&id=25420&page=az
if (!nummer.isEmpty()) {
url = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=" + alter + "&id=" + nummer + "&page=az";
seiteHttp = getUrlIo.getUri(nameSenderMReader, url, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema);
final String MUSTER_URL = "var videofile = \"";
final String MUSTER_TITEL = "var videotitle = \"";
urlFilm = seiteHttp.extract(MUSTER_URL, "\"");
titel = seiteHttp.extract(MUSTER_TITEL, "\"");
if (!urlFilm.equals("")) {
meldung(urlFilm);
// DatenFilm(String ssender, String tthema, String filmWebsite, String ttitel, String uurl, String uurlRtmp,
// String datum, String zeit,
// long dauerSekunden, String description, String thumbnailUrl, String imageUrl, String[] keywords) {
DatenFilm film = null;
if ((film = istInFilmListe(nameSenderMReader, thema, titel)) != null) {
film.addUrlKlein(urlFilm, "");
} else {
// dann gibs ihn noch nicht
addFilm(new DatenFilm(nameSenderMReader, thema, "http://www.kika.de/fernsehen/mediathek/index.shtml", titel, urlFilm, ""/* urlRtmp */,
""/*datum*/, ""/*zeit*/,
0, "", bild, "", new String[]{""}));
}
} else {
Log.fehlerMeldung(-915263078, Log.FEHLER_ART_MREADER, "MediathekKika", "keine URL: " + filmWebsite);
}
}
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void addToListNormal() {
//<strong style="margin-left:10px;">Sesamstraße präsentiert: Eine Möhre für Zwei</strong><br />
//<a style="margin-left:20px;" href="?programm=168&id=14487&ag=5" title="Sendung vom 10.10.2012" class="overlay_link">42. Ordnung ist das halbe Chaos</a><br />
//<a style="margin-left:20px;" href="?programm=168&id=14485&ag=5" title="Sendung vom 10.10.2012" class="overlay_link">41. Über den Wolken</a><br />
final String ADRESSE = "http://kikaplus.net/clients/kika/kikaplus/";
final String MUSTER_URL = "<a style=\"margin-left:20px;\" href=\"";
final String MUSTER_THEMA = "<strong style=\"margin-left:10px;\">";
final String MUSTER_DATUM = "title=\"Sendung vom ";
listeThemen.clear();
seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER);
seite = getUrlIo.getUri(nameSenderMReader, ADRESSE, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite");
int pos = 0;
int pos1, pos2, stop, pDatum1, pDatum2, pTitel1, pTitel2;
String url, thema, datum, titel;
while ((pos = seite.indexOf(MUSTER_THEMA, pos)) != -1) {
try {
thema = "";
pos += MUSTER_THEMA.length();
stop = seite.indexOf(MUSTER_THEMA, pos);
pos1 = pos;
if ((pos2 = seite.indexOf("<", pos1)) != -1) {
thema = seite.substring(pos1, pos2);
}
while ((pos1 = seite.indexOf(MUSTER_URL, pos1)) != -1) {
titel = "";
datum = "";
if (stop != -1 && pos1 > stop) {
// dann schon das nächste Thema
break;
}
pos1 += MUSTER_URL.length();
if ((pos2 = seite.indexOf("\"", pos1)) != -1) {
url = seite.substring(pos1, pos2);
//if (!url.equals("")) {
url = StringEscapeUtils.unescapeXml(url);
if (!url.equals("") && !url.startsWith("http://") && !url.startsWith("/")) {
// Datum
if ((pDatum1 = seite.indexOf(MUSTER_DATUM, pos2)) != -1) {
pDatum1 += MUSTER_DATUM.length();
if ((pDatum2 = seite.indexOf("\"", pDatum1)) != -1) {
if (stop != -1 && pDatum1 < stop && pDatum2 < stop) {
// dann schon das nächste Thema
datum = seite.substring(pDatum1, pDatum2);
}
}
}
// Titel
if ((pTitel1 = seite.indexOf(">", pos2)) != -1) {
pTitel1 += 1;
if ((pTitel2 = seite.indexOf("<", pTitel1)) != -1) {
//if (stop != -1 && pTitel1 > stop && pTitel2 > stop) {
if (stop != -1 && pTitel1 < stop && pTitel2 < stop) {
titel = seite.substring(pTitel1, pTitel2);
}
}
}
// in die Liste eintragen
String[] add = new String[]{ADRESSE + url, thema, titel, datum};
listeThemen.addUrl(add);
}
}
}
} catch (Exception ex) {
Log.fehlerMeldung(-302025469, Log.FEHLER_ART_MREADER, "MediathekKiKA.addToList", ex, "");
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void aktFilmSetzen() {
if (this.isShowing()) {
DatenFilm aktFilm = null;
int selectedTableRow = tabelle.getSelectedRow();
if (selectedTableRow >= 0) {
int selectedModelRow = tabelle.convertRowIndexToModel(selectedTableRow);
DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(tabelle.getModel().getValueAt(selectedModelRow, DatenDownload.DOWNLOAD_URL_NR).toString());
if (download.film == null) {
// geladener Einmaldownload nach Programmstart
download.film = Daten.listeFilme.getFilmByUrl(tabelle.getModel().getValueAt(selectedModelRow, DatenDownload.DOWNLOAD_URL_NR).toString());
} else {
aktFilm = download.film;
}
}
filmInfoHud.updateCurrentFilm(aktFilm);
// Beschreibung setzen
panelBeschreibung.setAktFilm(aktFilm);
}
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
private void aktFilmSetzen() {
if (this.isShowing()) {
DatenFilm aktFilm = null;
int selectedTableRow = tabelle.getSelectedRow();
if (selectedTableRow >= 0) {
int selectedModelRow = tabelle.convertRowIndexToModel(selectedTableRow);
DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(tabelle.getModel().getValueAt(selectedModelRow, DatenDownload.DOWNLOAD_URL_NR).toString());
if (download != null) {
// wenn beim Löschen aufgerufen, ist der Download schon weg
if (download.film == null) {
// geladener Einmaldownload nach Programmstart
download.film = Daten.listeFilme.getFilmByUrl(tabelle.getModel().getValueAt(selectedModelRow, DatenDownload.DOWNLOAD_URL_NR).toString());
} else {
aktFilm = download.film;
}
}
}
filmInfoHud.updateCurrentFilm(aktFilm);
// Beschreibung setzen
panelBeschreibung.setAktFilm(aktFilm);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getMusterPfadVlc() {
final String PFAD_LINUX_VLC = "/usr/bin/vlc";
final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC";
String pfad = "";
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
pfad = getWindowsVlcPath();
} else if (System.getProperty("os.name").toLowerCase().contains("linux")) {
pfad = PFAD_LINUX_VLC;
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
pfad = PFAD_MAC_VLC;
}
if (new File(pfad).exists()) {
return pfad;
} else {
return "";
}
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String getMusterPfadVlc() {
final String PFAD_LINUX_VLC = "/usr/bin/vlc";
final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC";
final String PFAD_WIN_DEFAULT = "C:\\Programme\\VideoLAN\\VLC\\vlc.exe";
final String PFAD_WIN = "\\VideoLAN\\VLC\\vlc.exe";
String pfad;
switch (getOs()) {
case OS_LINUX:
pfad = PFAD_LINUX_VLC;
break;
case OS_MAC:
pfad = PFAD_MAC_VLC;
break;
case OS_WIN_32BIT:
case OS_WIN_64BIT:
case OS_UNKNOWN:
default:
if (System.getenv("ProgramFiles") != null) {
pfad = System.getenv("ProgramFiles") + PFAD_WIN;
} else if (System.getenv("ProgramFiles(x86)") != null) {
pfad = System.getenv("ProgramFiles(x86)") + PFAD_WIN;
} else {
pfad = PFAD_WIN_DEFAULT;
}
}
if (!new File(pfad).exists()) {
pfad = "";
}
return pfad;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void playerStarten(DatenPset pSet) {
// Url mit Prognr. starten
if (tabelle.getSelectedRow() == -1) {
new HinweisKeineAuswahl().zeigen(parentComponent);
} else if (pSet.istSpeichern()) {
// wenn das pSet zum Speichern (über die Button) gewählt wurde,
// weiter mit dem Dialog "Speichern"
filmSpeichern_(pSet);
} else {
String url = "";
DatenFilm ersterFilm = new DatenFilm();
int selectedTableRows[] = tabelle.getSelectedRows();
for (int l = selectedTableRows.length - 1; l >= 0; --l) {
int selectedModelRow = tabelle.convertRowIndexToModel(selectedTableRows[l]);
ersterFilm = DDaten.listeFilmeNachBlackList.getFilmByUrl(tabelle.getModel().getValueAt(selectedModelRow, DatenFilm.FILM_URL_NR).toString());
// jede neue URL davorsetzen
url = ersterFilm.arr[DatenFilm.FILM_URL_NR] + " " + url;
// und in die History eintragen
//ddaten.history.add(ersterFilm.getUrlOrg()); wird in StartetClass gemacht
}
ersterFilm.arr[DatenFilm.FILM_URL_NR] = url.trim();
ddaten.starterClass.urlStarten(pSet, ersterFilm);
}
}
#location 17
#vulnerability type NULL_DEREFERENCE | #fixed code
private void playerStarten(DatenPset pSet) {
// Url mit Prognr. starten
if (tabelle.getSelectedRow() == -1) {
new HinweisKeineAuswahl().zeigen(parentComponent);
} else if (pSet.istSpeichern()) {
// wenn das pSet zum Speichern (über die Button) gewählt wurde,
// weiter mit dem Dialog "Speichern"
filmSpeichern_(pSet);
} else {
// mit dem flvstreamer immer nur einen Filme starten
int selectedModelRow = tabelle.convertRowIndexToModel(tabelle.getSelectedRow());
DatenFilm datenFilm = DDaten.listeFilmeNachBlackList.getFilmByUrl(tabelle.getModel().getValueAt(selectedModelRow, DatenFilm.FILM_URL_NR).toString());
ddaten.starterClass.urlStarten(pSet, datenFilm);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void laden() {
clear();
File file = new File(datei);
if (!file.exists()) {
return;
}
try {
FileInputStream fstream = new FileInputStream(datei);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
super.add(strLine);
}
//Close the input stream
in.close();
ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_LISTE_HISTORY_GEAENDERT, History.class.getSimpleName());
} catch (Exception e) {//Catch exception if any
System.err.println("Fehler: " + e);
Log.fehlerMeldung(303049876, Log.FEHLER_ART_PROG, History.class.getName(), e);
}
}
#location 18
#vulnerability type RESOURCE_LEAK | #fixed code
public void laden() {
clear();
if (Files.notExists(historyFilePath))
return;
try (BufferedReader br = new BufferedReader(new InputStreamReader(new DataInputStream(Files.newInputStream(historyFilePath))))) {
String strLine;
while ((strLine = br.readLine()) != null) {
super.add(strLine);
}
ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_LISTE_HISTORY_GEAENDERT, History.class.getSimpleName());
} catch (Exception e) {
System.err.println("Fehler: " + e);
Log.fehlerMeldung(303049876, Log.FEHLER_ART_PROG, History.class.getName(), e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public boolean filmlisteIstAelter() {
// Filmliste ist älter als: FilmeLaden.ALTER_FILMLISTE_SEKUNDEN_FUER_AUTOUPDATE
int ret = -1;
Date jetzt = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy, HH:mm");
String date = metaDaten[ListeFilme.FILMLISTE_DATUM_NR];
Date filmDate = null;
try {
filmDate = sdf.parse(date);
} catch (ParseException ex) {
}
if (jetzt != null && filmDate != null) {
ret = Math.round((jetzt.getTime() - filmDate.getTime()) / (1000));
ret = Math.abs(ret);
}
if (ret != -1) {
Log.systemMeldung("Die Filmliste ist " + ret / 60 + " Minuten alt");
}
if (ret > FilmeLaden.ALTER_FILMLISTE_SEKUNDEN_FUER_AUTOUPDATE) {
return true;
} else if (ret == -1) {
return true;
}
return false;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public boolean filmlisteIstAelter() {
return filmlisteIstAelter(FilmeLaden.ALTER_FILMLISTE_SEKUNDEN_FUER_AUTOUPDATE);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getMusterPfadFlv() {
final String PFAD_LINUX_FLV = "/usr/bin/flvstreamer";
final String PFAD_WINDOWS_FLV = "bin\\flvstreamer_win32_latest.exe";
final String PFAD_MAC_FLV = "bin\\flvstreamer_macosx_intel_32bit_latest";
String pfad = "";
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
pfad = Funktionen.getPathJar() + PFAD_WINDOWS_FLV;
} else if (System.getProperty("os.name").toLowerCase().contains("linux")) {
pfad = PFAD_LINUX_FLV;
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
pfad = Funktionen.getPathJar() + PFAD_MAC_FLV;
}
if (new File(pfad).exists()) {
return pfad;
} else {
return "";
}
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String getMusterPfadFlv() {
final String PFAD_LINUX_FLV = "/usr/bin/flvstreamer";
final String PFAD_WINDOWS_FLV = "bin\\flvstreamer_win32_latest.exe";
final String PFAD_MAC_FLV = "bin\\flvstreamer_macosx_intel_32bit_latest";
String pfad;
switch (getOs()) {
case OS_LINUX:
pfad = PFAD_LINUX_FLV;
break;
case OS_MAC:
pfad = Funktionen.getPathJar() + PFAD_MAC_FLV;
break;
case OS_WIN_32BIT:
case OS_WIN_64BIT:
case OS_UNKNOWN:
default:
pfad = Funktionen.getPathJar() + PFAD_WINDOWS_FLV;
}
if (new File(pfad).exists()) {
return pfad;
} else {
return "";
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getPfadVlc() {
///////////////////////
if (!Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR].equals("")) {
return Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR];
}
final String PFAD_LINUX_VLC = "/usr/bin/vlc";
final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC";
String pfad = "";
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
pfad = getWindowsVlcPath();
} else if (System.getProperty("os.name").toLowerCase().contains("linux")) {
pfad = PFAD_LINUX_VLC;
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
pfad = PFAD_MAC_VLC;
}
if (new File(pfad).exists()) {
return pfad;
} else {
return "";
}
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String getPfadVlc() {
if (Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR].equals("")) {
new DialogOk(null, true, new PanelProgrammPfade(), "Pfade Standardprogramme").setVisible(true);
}
return Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR];
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static ListePset getStandardprogramme(DDaten ddaten) {
ListePset pSet;
InputStream datei;
if (System.getProperty("os.name").toLowerCase().contains("linux")) {
datei = new GetFile().getPsetVorlageLinux();
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
datei = new GetFile().getPsetVorlageMac();
} else {
datei = new GetFile().getPsetVorlageWindows();
}
// Standardgruppen laden
pSet = IoXmlLesen.importPset(datei, true);
return pSet;
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
public static ListePset getStandardprogramme(DDaten ddaten) {
ListePset pSet;
InputStream datei;
switch (getOs()) {
case OS_LINUX:
datei = new GetFile().getPsetVorlageLinux();
break;
case OS_MAC:
datei = new GetFile().getPsetVorlageMac();
break;
case OS_WIN_32BIT:
case OS_WIN_64BIT:
case OS_UNKNOWN:
default:
datei = new GetFile().getPsetVorlageWindows();
}
// Standardgruppen laden
pSet = IoXmlLesen.importPset(datei, true);
return pSet;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getMusterPfadVlc() {
final String PFAD_LINUX_VLC = "/usr/bin/vlc";
final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC";
String pfad = "";
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
pfad = getWindowsVlcPath();
} else if (System.getProperty("os.name").toLowerCase().contains("linux")) {
pfad = PFAD_LINUX_VLC;
} else if (System.getProperty("os.name").toLowerCase().contains("mac")) {
pfad = PFAD_MAC_VLC;
}
if (new File(pfad).exists()) {
return pfad;
} else {
return "";
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String getMusterPfadVlc() {
final String PFAD_LINUX_VLC = "/usr/bin/vlc";
final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC";
final String PFAD_WIN_DEFAULT = "C:\\Programme\\VideoLAN\\VLC\\vlc.exe";
final String PFAD_WIN = "\\VideoLAN\\VLC\\vlc.exe";
String pfad;
switch (getOs()) {
case OS_LINUX:
pfad = PFAD_LINUX_VLC;
break;
case OS_MAC:
pfad = PFAD_MAC_VLC;
break;
case OS_WIN_32BIT:
case OS_WIN_64BIT:
case OS_UNKNOWN:
default:
if (System.getenv("ProgramFiles") != null) {
pfad = System.getenv("ProgramFiles") + PFAD_WIN;
} else if (System.getenv("ProgramFiles(x86)") != null) {
pfad = System.getenv("ProgramFiles(x86)") + PFAD_WIN;
} else {
pfad = PFAD_WIN_DEFAULT;
}
}
if (!new File(pfad).exists()) {
pfad = "";
}
return pfad;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void stopContainer(String containerId) {
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
ContainerStatus containerStatus = task.status().containerStatus();
if (containerStatus != null && containerStatus.containerId().equals(containerId)) {
String serviceId = task.serviceId();
Service.Criteria criteria = Service.Criteria.builder()
.serviceId(serviceId)
.build();
List<Service> services = dockerClient.listServices(criteria);
if (!CollectionUtils.isEmpty(services)) {
dockerClient.removeService(serviceId);
}
}
}
} catch (DockerException | InterruptedException e) {
logger.warn(nodeId + " Error while stopping the container", e);
ga.trackException(e);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
public void stopContainer(String containerId) {
try {
SwarmUtilities.stopServiceByContainerId(containerId);
} catch (DockerException | InterruptedException e) {
logger.warn(nodeId + " Error while stopping the container", e);
ga.trackException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private String getContainerId(String containerName) {
List<Container> containerList = null;
try {
containerList = dockerClient.listContainers(DockerClient.ListContainersParam.allContainers());
} catch (DockerException | InterruptedException e) {
logger.log(Level.FINE, nodeId + " Error while getting containerId", e);
ga.trackException(e);
}
for (Container container : containerList) {
if (containerName.equalsIgnoreCase(container.names().get(0))) {
return container.id();
}
}
return null;
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
private String getContainerId(String containerName) {
final String containerNameSearch = containerName.contains("/") ?
containerName : String.format("/%s", containerName);
List<Container> containerList = null;
try {
containerList = dockerClient.listContainers(DockerClient.ListContainersParam.allContainers());
} catch (DockerException | InterruptedException e) {
logger.log(Level.FINE, nodeId + " Error while getting containerId", e);
ga.trackException(e);
}
return containerList.stream()
.filter(container -> containerNameSearch.equalsIgnoreCase(container.names().get(0)))
.findFirst().get().id();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void executeCommand(String containerId, String[] command, boolean waitForExecution) {
String swarmNodeIp = null;
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
if (task.status().containerStatus().containerId().equals(containerId)) {
List<Node> nodes = dockerClient.listNodes();
for (Node node :nodes) {
if (node.id().equals(task.nodeId())) {
swarmNodeIp = node.status().addr();
}
}
}
}
} catch (DockerException | InterruptedException | NullPointerException e) {
logger.debug(nodeId + " Error while executing the command", e);
ga.trackException(e);
}
if (swarmNodeIp != null) {
execCommandOnRemote(swarmNodeIp, containerId, command);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
public void executeCommand(String containerId, String[] command, boolean waitForExecution) {
String swarmNodeIp = null;
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
ContainerStatus containerStatus = task.status().containerStatus();
if (containerStatus != null && containerStatus.containerId().equals(containerId)) {
List<Node> nodes = dockerClient.listNodes();
for (Node node :nodes) {
if (node.id().equals(task.nodeId())) {
swarmNodeIp = node.status().addr();
execCommandOnRemote(swarmNodeIp, containerId, command);
}
}
}
}
} catch (DockerException | InterruptedException | NullPointerException e) {
logger.debug(nodeId + " Error while executing the command", e);
ga.trackException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void pollerThreadTearsDownNodeAfterTestIsCompleted() throws IOException {
// Supported desired capability for the test session
Map<String, Object> requestedCapability = getCapabilitySupportedByDockerSelenium();
// Start poller thread
proxy.startPolling();
// Mock the poller HttpClient to avoid exceptions due to failed connections
proxy.getDockerSeleniumNodePollerThread().setClient(getMockedClient());
// Get a test session
TestSession newSession = proxy.getNewSession(requestedCapability);
Assert.assertNotNull(newSession);
// The node should be busy since there is a session in it
Assert.assertTrue(proxy.isBusy());
// We release the session, the node should be free
newSession.getSlot().doFinishRelease();
// After running one test, the node shouldn't be busy and also down
Assert.assertFalse(proxy.isBusy());
long sleepTime = proxy.getDockerSeleniumNodePollerThread().getSleepTimeBetweenChecks();
await().atMost(sleepTime + 2000, MILLISECONDS).untilCall(to(proxy).isDown(), equalTo(true));
}
#location 21
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void pollerThreadTearsDownNodeAfterTestIsCompleted() throws IOException {
// Supported desired capability for the test session
Map<String, Object> requestedCapability = getCapabilitySupportedByDockerSelenium();
// Start poller thread
proxy.startPolling();
// Mock the poller HttpClient to avoid exceptions due to failed connections
proxy.getDockerSeleniumNodePollerThread().setClient(getMockedClient());
// Get a test session
TestSession newSession = proxy.getNewSession(requestedCapability);
Assert.assertNotNull(newSession);
// The node should be busy since there is a session in it
Assert.assertTrue(proxy.isBusy());
// We release the session, the node should be free
WebDriverRequest request = mock(WebDriverRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getMethod()).thenReturn("DELETE");
when(request.getRequestType()).thenReturn(RequestType.STOP_SESSION);
newSession.getSlot().doFinishRelease();
proxy.afterCommand(newSession, request, response);
// After running one test, the node shouldn't be busy and also down
Assert.assertFalse(proxy.isBusy());
long sleepTime = proxy.getDockerSeleniumNodePollerThread().getSleepTimeBetweenChecks();
await().atMost(sleepTime + 2000, MILLISECONDS).untilCall(to(proxy).isDown(), equalTo(true));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public String getLatestDownloadedImage(String imageName) {
List<Image> images;
try {
images = dockerClient.listImages(DockerClient.ListImagesParam.byName(imageName));
if (images.isEmpty()) {
logger.error(nodeId + " A downloaded docker-selenium image was not found!");
return imageName;
}
for (int i = images.size() - 1; i >= 0; i--) {
if (images.get(i).repoTags() == null) {
images.remove(i);
}
}
images.sort((o1, o2) -> o2.created().compareTo(o1.created()));
return images.get(0).repoTags().get(0);
} catch (DockerException | InterruptedException e) {
logger.warn(nodeId + " Error while executing the command", e);
ga.trackException(e);
}
return imageName;
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
public String getLatestDownloadedImage(String imageName) {
// TODO: verify this is handled by docker
return imageName;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void stopContainer(String containerId) {
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
if (task.status().containerStatus().containerId().equals(containerId)) {
String serviceId = task.serviceId();
dockerClient.removeService(serviceId);
}
}
} catch (DockerException | InterruptedException e) {
logger.warn(nodeId + " Error while stopping the container", e);
ga.trackException(e);
}
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
public void stopContainer(String containerId) {
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
ContainerStatus containerStatus = task.status().containerStatus();
if (containerStatus != null && containerStatus.containerId().equals(containerId)) {
String serviceId = task.serviceId();
List<Service> services = dockerClient.listServices();
if (services.stream().anyMatch(service -> service.id().equals(serviceId))) {
dockerClient.removeService(serviceId);
}
}
}
} catch (DockerException | InterruptedException e) {
logger.warn(nodeId + " Error while stopping the container", e);
ga.trackException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private String getContainerId(String zaleniumContainerName, URL remoteUrl) {
try {
List<Task> tasks = dockerClient.listTasks();
logger.debug("---------------Size of tasks list : {} ---------------", tasks.size());
for (Task task : tasks) {
logger.debug("--------------- Task : {} ---------------", task);
for (NetworkAttachment networkAttachment : task.networkAttachments()) {
for (String address : networkAttachment.addresses()) {
if (address.startsWith(remoteUrl.getHost())) {
return task.status().containerStatus().containerId();
}
}
}
}
} catch (DockerException | InterruptedException e) {
e.printStackTrace();
}
return null;
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
private String getContainerId(String zaleniumContainerName, URL remoteUrl) {
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
List<NetworkAttachment> networkAttachments = task.networkAttachments();
if (networkAttachments != null) {
for (NetworkAttachment networkAttachment : task.networkAttachments()) {
for (String address : networkAttachment.addresses()) {
if (address.startsWith(remoteUrl.getHost())) {
return task.status().containerStatus().containerId();
}
}
}
}
}
} catch (DockerException | InterruptedException e) {
e.printStackTrace();
}
return null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void executeCommand(String containerId, String[] command, boolean waitForExecution) {
try {
List<Task> tasks = dockerClient.listTasks();
pullSwarmExecImage();
for (Task task : CollectionUtils.emptyIfNull(tasks)) {
ContainerStatus containerStatus = task.status().containerStatus();
if (containerStatus != null && containerStatus.containerId().equals(containerId)) {
startSwarmExecContainer(task, command, containerId);
return;
}
}
} catch (DockerException | InterruptedException e) {
logger.warn("Error while executing comman on container {}", containerId);
ga.trackException(e);
}
logger.warn("Couldn't execute command on container {}", containerId);
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
public void executeCommand(String containerId, String[] command, boolean waitForExecution) {
try {
Task task = SwarmUtilities.getTaskByContainerId(containerId);
if (task != null) {
pullSwarmExecImage();
startSwarmExecContainer(task, command, containerId);
} else {
logger.warn("Couldn't execute command on container {}", containerId);
}
} catch (DockerException | InterruptedException e) {
logger.warn("Error while executing comman on container {}", containerId);
ga.trackException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@VisibleForTesting
void copyVideos(final String containerId) {
if (testInformation == null || StringUtils.isEmpty(containerId)) {
// No tests run or container has been removed, nothing to copy and nothing to update.
return;
}
String currentName = configureThreadName();
boolean videoWasCopied = false;
TarArchiveInputStream tarStream = new TarArchiveInputStream(containerClient.copyFiles(containerId, "/videos/"));
try {
TarArchiveEntry entry;
while ((entry = tarStream.getNextTarEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
String fileExtension = entry.getName().substring(entry.getName().lastIndexOf('.'));
testInformation.setFileExtension(fileExtension);
Path videoFile = Paths.get(String.format("%s/%s", testInformation.getVideoFolderPath(),
testInformation.getFileName()));
if (!Files.exists(videoFile.getParent())) {
Files.createDirectories(videoFile.getParent());
}
Files.copy(tarStream, videoFile);
CommonProxyUtilities.setFilePermissions(videoFile);
videoWasCopied = true;
LOGGER.debug("Video file copied to: {}/{}", testInformation.getVideoFolderPath(), testInformation.getFileName());
}
} catch (IOException e) {
// This error happens in k8s, but the file is ok, nevertheless the size is not accurate
boolean isPipeClosed = e.getMessage().toLowerCase().contains("pipe closed");
if (ContainerFactory.getIsKubernetes().get() && isPipeClosed) {
LOGGER.debug("Video file copied to: {}/{}", testInformation.getVideoFolderPath(), testInformation.getFileName());
} else {
LOGGER.warn("Error while copying the video", e);
}
ga.trackException(e);
} finally {
if (!videoWasCopied) {
testInformation.setVideoRecorded(false);
}
}
setThreadName(currentName);
}
#location 39
#vulnerability type RESOURCE_LEAK | #fixed code
@VisibleForTesting
void copyVideos(final String containerId) {
if (testInformation == null || StringUtils.isEmpty(containerId)) {
// No tests run or container has been removed, nothing to copy and nothing to update.
return;
}
String currentName = configureThreadName();
boolean videoWasCopied = false;
InputStreamGroupIterator tarStream = containerClient.copyFiles(containerId, "/videos/");
try {
InputStreamDescriptor entry;
while ((entry = tarStream.next()) != null) {
String fileExtension = entry.name().substring(entry.name().lastIndexOf('.'));
testInformation.setFileExtension(fileExtension);
Path videoFile = Paths.get(String.format("%s/%s", testInformation.getVideoFolderPath(),
testInformation.getFileName()));
if (!Files.exists(videoFile.getParent())) {
Files.createDirectories(videoFile.getParent());
}
Files.copy(entry.get(), videoFile);
CommonProxyUtilities.setFilePermissions(videoFile);
videoWasCopied = true;
LOGGER.debug("Video file copied to: {}/{}", testInformation.getVideoFolderPath(), testInformation.getFileName());
}
} catch (IOException e) {
// This error happens in k8s, but the file is ok, nevertheless the size is not accurate
boolean isPipeClosed = e.getMessage().toLowerCase().contains("pipe closed");
if (ContainerFactory.getIsKubernetes().get() && isPipeClosed) {
LOGGER.debug("Video file copied to: {}/{}", testInformation.getVideoFolderPath(), testInformation.getFileName());
} else {
LOGGER.warn("Error while copying the video", e);
}
ga.trackException(e);
} finally {
if (!videoWasCopied) {
testInformation.setVideoRecorded(false);
}
}
setThreadName(currentName);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public boolean isTerminated(ContainerCreationStatus container) {
List<String> termStates = Arrays.asList("complete", "failed", "shutdown", "rejected", "orphaned", "removed");
String containerId = container.getContainerId();
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
TaskStatus taskStatus = task.status();
String state = taskStatus.state();
if (termStates.contains(state)) {
return taskStatus.containerStatus().containerId().equals(containerId);
}
}
return false;
} catch (DockerException | InterruptedException e) {
logger.warn("Failed to fetch container status [" + container + "].", e);
return false;
}
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public boolean isTerminated(ContainerCreationStatus container) {
List<String> termStates = Arrays.asList("complete", "failed", "shutdown", "rejected", "orphaned", "removed");
String containerId = container.getContainerId();
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
TaskStatus taskStatus = task.status();
ContainerStatus containerStatus = taskStatus.containerStatus();
if (containerStatus != null && containerStatus.containerId().equals(containerId)) {
String state = taskStatus.state();
return termStates.contains(state);
}
}
return false;
} catch (DockerException | InterruptedException e) {
logger.warn("Failed to fetch container status [" + container + "].", e);
return false;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public String getContainerIp(String containerName) {
String containerId = this.getContainerId(containerName);
if (containerId == null) {
logger.warn("Failed to get id of container: {} ", containerName);
return null;
}
try {
List<Task> tasks = dockerClient.listTasks();
String swarmOverlayNetwork = ZaleniumConfiguration.getSwarmOverlayNetwork();
for (Task task : tasks) {
ContainerStatus containerStatus = task.status().containerStatus();
if (containerStatus != null) {
if (containerStatus.containerId().equals(containerId)) {
for (NetworkAttachment networkAttachment : CollectionUtils.emptyIfNull(task.networkAttachments())) {
if (networkAttachment.network().spec().name().equals(swarmOverlayNetwork)) {
String cidrSuffix = "/\\d+$";
return networkAttachment.addresses().get(0).replaceAll(cidrSuffix, "");
}
}
}
}
}
} catch (DockerException | InterruptedException e) {
logger.debug(nodeId + " Error while getting the container IP.", e);
ga.trackException(e);
}
logger.warn("Failed to get ip of container: {}", containerName);
return null;
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public String getContainerIp(String containerName) {
String containerId = this.getContainerId(containerName);
if (containerId == null) {
logger.warn("Failed to get id of container: {} ", containerName);
return null;
}
try {
String swarmOverlayNetwork = ZaleniumConfiguration.getSwarmOverlayNetwork();
Task task = SwarmUtilities.getTaskByContainerId(containerId);
if (task != null) {
for (NetworkAttachment networkAttachment : CollectionUtils.emptyIfNull(task.networkAttachments())) {
if (networkAttachment.network().spec().name().equals(swarmOverlayNetwork)) {
String cidrSuffix = "/\\d+$";
return networkAttachment.addresses().get(0).replaceAll(cidrSuffix, "");
}
}
}
} catch (DockerException | InterruptedException e) {
logger.debug(nodeId + " Error while getting the container IP.", e);
ga.trackException(e);
}
logger.warn("Failed to get ip of container: {}", containerName);
return null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@VisibleForTesting
void copyLogs(final String containerId) {
if (SwarmUtilities.isSwarmActive()) {
// Disabling logs in swarm mode
return;
}
if (testInformation == null || StringUtils.isEmpty(containerId)) {
// No tests run or container has been removed, nothing to copy and nothing to update.
return;
}
String currentName = configureThreadName();
TarArchiveInputStream tarStream = new TarArchiveInputStream(containerClient.copyFiles(containerId, "/var/log/cont/"));
try {
TarArchiveEntry entry;
while ((entry = tarStream.getNextTarEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
if (!Files.exists(Paths.get(testInformation.getLogsFolderPath()))) {
Path directories = Files.createDirectories(Paths.get(testInformation.getLogsFolderPath()));
CommonProxyUtilities.setFilePermissions(directories);
CommonProxyUtilities.setFilePermissions(directories.getParent());
}
String fileName = entry.getName().replace("cont/", "");
Path logFile = Paths.get(String.format("%s/%s", testInformation.getLogsFolderPath(), fileName));
Files.copy(tarStream, logFile);
CommonProxyUtilities.setFilePermissions(logFile);
}
LOGGER.debug("Logs copied to: {}", testInformation.getLogsFolderPath());
} catch (IOException | NullPointerException e) {
// This error happens in k8s, but the file is ok, nevertheless the size is not accurate
String exceptionMessage = Optional.ofNullable(e.getMessage()).orElse("");
boolean isPipeClosed = exceptionMessage.toLowerCase().contains("pipe closed");
if (ContainerFactory.getIsKubernetes().get() && isPipeClosed) {
LOGGER.debug("Logs copied to: {}", testInformation.getLogsFolderPath());
} else {
LOGGER.debug("Error while copying the logs", e);
}
ga.trackException(e);
}
setThreadName(currentName);
}
#location 30
#vulnerability type RESOURCE_LEAK | #fixed code
@VisibleForTesting
void copyLogs(final String containerId) {
if (SwarmUtilities.isSwarmActive()) {
// Disabling logs in swarm mode
return;
}
if (testInformation == null || StringUtils.isEmpty(containerId)) {
// No tests run or container has been removed, nothing to copy and nothing to update.
return;
}
String currentName = configureThreadName();
InputStreamGroupIterator tarStream = containerClient.copyFiles(containerId, "/var/log/cont/");
try {
InputStreamDescriptor entry;
while ((entry = tarStream.next()) != null) {
if (!Files.exists(Paths.get(testInformation.getLogsFolderPath()))) {
Path directories = Files.createDirectories(Paths.get(testInformation.getLogsFolderPath()));
CommonProxyUtilities.setFilePermissions(directories);
CommonProxyUtilities.setFilePermissions(directories.getParent());
}
String fileName = entry.name().replace("cont/", "");
Path logFile = Paths.get(String.format("%s/%s", testInformation.getLogsFolderPath(), fileName));
Files.copy(entry.get(), logFile);
CommonProxyUtilities.setFilePermissions(logFile);
}
LOGGER.debug("Logs copied to: {}", testInformation.getLogsFolderPath());
} catch (IOException | NullPointerException e) {
// This error happens in k8s, but the file is ok, nevertheless the size is not accurate
String exceptionMessage = Optional.ofNullable(e.getMessage()).orElse("");
boolean isPipeClosed = exceptionMessage.toLowerCase().contains("pipe closed");
if (ContainerFactory.getIsKubernetes().get() && isPipeClosed) {
LOGGER.debug("Logs copied to: {}", testInformation.getLogsFolderPath());
} else {
LOGGER.debug("Error while copying the logs", e);
}
ga.trackException(e);
}
setThreadName(currentName);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public boolean isTerminated(ContainerCreationStatus container) {
List<String> termStates = Arrays.asList("complete", "failed", "shutdown", "rejected", "orphaned", "removed");
String containerId = container.getContainerId();
try {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
TaskStatus taskStatus = task.status();
ContainerStatus containerStatus = taskStatus.containerStatus();
if (containerStatus != null && containerStatus.containerId().equals(containerId)) {
String state = taskStatus.state();
return termStates.contains(state);
}
}
return false;
} catch (DockerException | InterruptedException e) {
logger.warn("Failed to fetch container status [" + container + "].", e);
return false;
}
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public boolean isTerminated(ContainerCreationStatus container) {
try {
List<String> termStates = Arrays.asList("complete", "failed", "shutdown", "rejected", "orphaned", "removed");
String containerId = container.getContainerId();
List<Task> tasks = dockerClient.listTasks();
boolean containerExists = tasks.stream().anyMatch(task -> {
ContainerStatus containerStatus = task.status().containerStatus();
return containerStatus != null && containerStatus.containerId().equals(containerId);
});
if (!containerExists) {
logger.info("Container {} has no task - terminal.", container);
return true;
} else {
return tasks.stream().anyMatch(task -> {
ContainerStatus containerStatus = task.status().containerStatus();
boolean hasTerminalState = termStates.contains(task.status().state());
boolean isContainer = containerStatus != null && containerStatus.containerId().equals(containerId);
boolean isTerminated = isContainer && hasTerminalState;
if (isTerminated) {
logger.info("Container {} is {} - terminal.", container, task.status().state());
}
return isTerminated;
});
}
} catch (DockerException | InterruptedException e) {
logger.warn("Failed to fetch container status [" + container + "].", e);
return false;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private ContainerCreationStatus getContainerCreationStatus (String serviceId, String nodePort) throws DockerException, InterruptedException {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
if (task.serviceId().equals(serviceId)) {
ContainerStatus containerStatus = task.status().containerStatus();
String containerId = containerStatus.containerId();
String containerName = containerStatus.containerId();
return new ContainerCreationStatus(true, containerName, containerId, nodePort);
}
}
return null;
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
private ContainerCreationStatus getContainerCreationStatus (String serviceId, String nodePort) throws DockerException, InterruptedException {
List<Task> tasks = dockerClient.listTasks();
for (Task task : tasks) {
if (task.serviceId().equals(serviceId)) {
ContainerStatus containerStatus = task.status().containerStatus();
if (containerStatus != null) {
String containerId = containerStatus.containerId();
String containerName = containerStatus.containerId();
return new ContainerCreationStatus(true, containerName, containerId, nodePort);
}
}
}
return null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@VisibleForTesting
void copyVideos(final String containerId) {
if (testInformation == null || StringUtils.isEmpty(containerId)) {
// No tests run or container has been removed, nothing to copy and nothing to update.
return;
}
String currentName = configureThreadName();
boolean videoWasCopied = false;
TarArchiveInputStream tarStream = new TarArchiveInputStream(containerClient.copyFiles(containerId, "/videos/"));
try {
TarArchiveEntry entry;
while ((entry = tarStream.getNextTarEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
String fileExtension = entry.getName().substring(entry.getName().lastIndexOf('.'));
testInformation.setFileExtension(fileExtension);
Path videoFile = Paths.get(String.format("%s/%s", testInformation.getVideoFolderPath(),
testInformation.getFileName()));
if (!Files.exists(videoFile.getParent())) {
Files.createDirectories(videoFile.getParent());
}
Files.copy(tarStream, videoFile);
CommonProxyUtilities.setFilePermissions(videoFile);
videoWasCopied = true;
LOGGER.debug("Video file copied to: {}/{}", testInformation.getVideoFolderPath(), testInformation.getFileName());
}
} catch (IOException e) {
// This error happens in k8s, but the file is ok, nevertheless the size is not accurate
boolean isPipeClosed = e.getMessage().toLowerCase().contains("pipe closed");
if (ContainerFactory.getIsKubernetes().get() && isPipeClosed) {
LOGGER.debug("Video file copied to: {}/{}", testInformation.getVideoFolderPath(), testInformation.getFileName());
} else {
LOGGER.warn("Error while copying the video", e);
}
ga.trackException(e);
} finally {
if (!videoWasCopied) {
testInformation.setVideoRecorded(false);
}
}
setThreadName(currentName);
}
#location 38
#vulnerability type RESOURCE_LEAK | #fixed code
@VisibleForTesting
void copyVideos(final String containerId) {
if (testInformation == null || StringUtils.isEmpty(containerId)) {
// No tests run or container has been removed, nothing to copy and nothing to update.
return;
}
String currentName = configureThreadName();
boolean videoWasCopied = false;
InputStreamGroupIterator tarStream = containerClient.copyFiles(containerId, "/videos/");
try {
InputStreamDescriptor entry;
while ((entry = tarStream.next()) != null) {
String fileExtension = entry.name().substring(entry.name().lastIndexOf('.'));
testInformation.setFileExtension(fileExtension);
Path videoFile = Paths.get(String.format("%s/%s", testInformation.getVideoFolderPath(),
testInformation.getFileName()));
if (!Files.exists(videoFile.getParent())) {
Files.createDirectories(videoFile.getParent());
}
Files.copy(entry.get(), videoFile);
CommonProxyUtilities.setFilePermissions(videoFile);
videoWasCopied = true;
LOGGER.debug("Video file copied to: {}/{}", testInformation.getVideoFolderPath(), testInformation.getFileName());
}
} catch (IOException e) {
// This error happens in k8s, but the file is ok, nevertheless the size is not accurate
boolean isPipeClosed = e.getMessage().toLowerCase().contains("pipe closed");
if (ContainerFactory.getIsKubernetes().get() && isPipeClosed) {
LOGGER.debug("Video file copied to: {}/{}", testInformation.getVideoFolderPath(), testInformation.getFileName());
} else {
LOGGER.warn("Error while copying the video", e);
}
ga.trackException(e);
} finally {
if (!videoWasCopied) {
testInformation.setVideoRecorded(false);
}
}
setThreadName(currentName);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public String getContainerIp(String containerName) {
String containerId = this.getContainerId(containerName);
if (containerId == null) {
return null;
}
try {
ContainerInfo containerInfo = dockerClient.inspectContainer(containerId);
if (containerInfo.networkSettings().ipAddress().trim().isEmpty()) {
ImmutableMap<String, AttachedNetwork> networks = containerInfo.networkSettings().networks();
return networks.entrySet().stream().findFirst().get().getValue().ipAddress();
}
return containerInfo.networkSettings().ipAddress();
} catch (DockerException | InterruptedException e) {
logger.debug(nodeId + " Error while getting the container IP.", e);
ga.trackException(e);
}
return null;
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public String getContainerIp(String containerName) {
String containerId = this.getContainerId(containerName);
if (containerId == null) {
return null;
}
try {
List<Task> tasks = dockerClient.listTasks();
String swarmOverlayNetwork = ZaleniumConfiguration.getSwarmOverlayNetwork();
for (Task task : tasks) {
ContainerStatus containerStatus = task.status().containerStatus();
if (containerStatus != null) {
if (containerStatus.containerId().equals(containerId)) {
for (NetworkAttachment networkAttachment : task.networkAttachments()) {
if (networkAttachment.network().spec().name().equals(swarmOverlayNetwork)) {
String cidrSuffix = "/\\d+$";
return networkAttachment.addresses().get(0).replaceAll(cidrSuffix, "");
}
}
}
}
}
} catch (DockerException | InterruptedException e) {
logger.debug(nodeId + " Error while getting the container IP.", e);
ga.trackException(e);
}
return null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void loadMountedFolder(String zaleniumContainerName) {
if (this.mountedFolder == null) {
String containerId = getContainerId(String.format("/%s", zaleniumContainerName));
ContainerInfo containerInfo = null;
try {
containerInfo = dockerClient.inspectContainer(containerId);
} catch (DockerException | InterruptedException e) {
logger.log(Level.WARNING, nodeId + " Error while getting mounted folders.", e);
ga.trackException(e);
}
for (ContainerMount containerMount : containerInfo.mounts()) {
if ("/tmp/mounted".equalsIgnoreCase(containerMount.destination())) {
this.mountedFolder = containerMount;
}
}
}
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
private void loadMountedFolder(String zaleniumContainerName) {
if (this.mountedFolder == null) {
String containerId = getContainerId(String.format("/%s", zaleniumContainerName));
if (containerId == null) {
return;
}
ContainerInfo containerInfo = null;
try {
containerInfo = dockerClient.inspectContainer(containerId);
} catch (DockerException | InterruptedException e) {
logger.log(Level.WARNING, nodeId + " Error while getting mounted folders.", e);
ga.trackException(e);
}
for (ContainerMount containerMount : containerInfo.mounts()) {
if ("/tmp/mounted".equalsIgnoreCase(containerMount.destination())) {
this.mountedFolder = containerMount;
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void swapRecordingHistograms() {
final AtomicHistogram tempHistogram = intervalRawDataHistogram;
intervalRawDataHistogram = currentRecordingHistogram;
currentRecordingHistogram = tempHistogram;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void trackRecordingInterval() {
long now = TimeServices.nanoTime();
intervalEstimator.recordInterval(now);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public <T> List<T> fetch(final JsonObject criteria, final String pojo) {
return this.reader.fetch(criteria, JqFlow.create(this.analyzer, pojo));
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public <T> List<T> fetch(final JsonObject criteria, final String pojo) {
return this.reader.fetch(JqFlow.create(this.analyzer, pojo).inputQrJ(criteria));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static Future<TermStatus> runAsync(final CommandLine parsed, final List<CommandAtom> commands,
final Function<Commander, Commander> binder) {
/*
* Found command inner run method
*/
final CommandAtom command = commands.stream()
.filter(each -> parsed.hasOption(each.getName()) || parsed.hasOption(each.getSimple()))
.findAny().orElse(null);
if (Objects.isNull(command) || !command.valid()) {
/*
* Internal error
*/
if (Objects.nonNull(command)) {
Sl.failWarn(" Plugin null -> name = {0},{1}, type = {2}",
command.getSimple(), command.getName(), command.getType());
}
throw new CommandMissingException(ConsoleInteract.class, Ut.fromJoin(parsed.getArgs()));
} else {
final Options options = new Options();
commands.stream().map(CommandAtom::option).forEach(options::addOption);
/*
* Create CommandArgs
*/
final List<String> inputArgs = parsed.getArgList();
final List<String> inputNames = command.getOptionNames();
final CommandInput commandInput = CommandInput.create(inputNames, inputArgs);
commandInput.bind(options);
/*
* Commander
*/
final Commander commander;
if (CommandType.SYSTEM == command.getType()) {
/*
* Sub-System call
*/
commander = Ut.instance(ConsoleCommander.class);
} else {
/*
* Plugin processing
* instance instead of single for shared usage
*/
commander = Ut.instance(command.getPlugin());
}
/*
* binder processing
*/
Sl.welcomeCommand(command);
return binder.apply(commander.bind(command)).executeAsync(commandInput);
}
}
#location 48
#vulnerability type NULL_DEREFERENCE | #fixed code
static Future<TermStatus> runAsync(final CommandLine parsed, final List<CommandAtom> commands,
final Function<Commander, Commander> binder) {
/*
* Found command inner run method, double check for CommandAtom
*/
final List<String> args = parsed.getArgList();
return findAsync(args.get(Values.IDX), commands).compose(command -> {
/*
* Create CommandArgs
*/
final CommandInput input = getInput(parsed).bind(command);
/*
* Commander
*/
final Commander commander;
if (CommandType.SYSTEM == command.getType()) {
/*
* Sub-System call
*/
commander = Ut.instance(ConsoleCommander.class);
} else {
/*
* Plugin processing
* instance instead of single for shared usage
*/
commander = Ut.instance(command.getPlugin());
}
/*
* binder processing
*/
Sl.welcomeCommand(command);
return binder.apply(commander.bind(command)).executeAsync(input);
});
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
<T> Integer count(final JsonObject filters) {
final DSLContext context = JooqInfix.getDSL();
return null == filters ? context.fetchCount(this.vertxDAO.getTable()) :
context.fetchCount(this.vertxDAO.getTable(), JooqCond.transform(filters, this.analyzer::column));
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
<T> Future<T> fetchOneAsync(final String field, final Object value) {
return JqTool.future(this.vertxDAO.fetchOneAsync(this.analyzer.column(field), value));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private Resolver<T> getResolver(final RoutingContext context,
final Epsilon<T> income) {
/* 1.Read the resolver first **/
final Annotation annotation = income.getAnnotation();
final Class<?> resolverCls = Ut.invoke(annotation, "resolver");
final String header = context.request().getHeader(HttpHeaders.CONTENT_TYPE);
/* 2.Check configured in default **/
if (UnsetResolver.class == resolverCls) {
/* 3. Old path **/
final JsonObject content = NODE.read();
// LOGGER.info("[ RESOLVER ] Resolvers = {0}", content.encodePrettily());
final String resolver;
if (null == header) {
resolver = content.getString("default");
} else {
final MediaType type = MediaType.valueOf(header);
final JsonObject resolverMap = content.getJsonObject(type.getType());
resolver = resolverMap.getString(type.getSubtype());
}
LOGGER.info(Info.RESOLVER, resolver, header, context.request().absoluteURI());
return Ut.singleton(resolver);
} else {
LOGGER.info(Info.RESOLVER_CONFIG, resolverCls, header);
return Ut.singleton(resolverCls);
}
}
#location 24
#vulnerability type NULL_DEREFERENCE | #fixed code
private Resolver<T> getResolver(final RoutingContext context,
final Epsilon<T> income) {
/* 1.Read the resolver first **/
final Annotation annotation = income.getAnnotation();
final Class<?> resolverCls = Ut.invoke(annotation, "resolver");
final String header = context.request().getHeader(HttpHeaders.CONTENT_TYPE);
/* 2.Check configured in default **/
if (UnsetResolver.class == resolverCls) {
/* 3. Old path **/
final JsonObject content = NODE.read();
// LOGGER.info("[ RESOLVER ] Resolvers = {0}", content.encodePrettily());
final String resolver;
if (null == header) {
resolver = content.getString("default");
} else {
final MediaType type = MediaType.valueOf(header);
final JsonObject resolverMap = content.getJsonObject(type.getType());
resolver = resolverMap.getString(type.getSubtype());
}
LOGGER.info(Info.RESOLVER, resolver, header, context.request().absoluteURI());
return Ut.singleton(resolver);
} else {
LOGGER.info(Info.RESOLVER_CONFIG, resolverCls, header);
/*
* Split workflow
* Resolver or Solve
*/
if (Ut.isImplement(resolverCls, Resolver.class)) {
/*
* Resolver Directly
*/
return Ut.singleton(resolverCls);
} else {
/*
* Solve component, contract to set Solve<T> here.
*/
final Resolver<T> resolver = Ut.singleton(SolveResolver.class);
Ut.contract(resolver, Solve.class, Ut.singleton(resolverCls));
return resolver;
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public <T> Future<List<T>> fetchAsync(final JsonObject criteria, final String pojo) {
return this.reader.fetchAsync(criteria, JqFlow.create(this.analyzer, pojo));
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public <T> Future<List<T>> fetchAsync(final JsonObject criteria, final String pojo) {
return JqFlow.create(this.analyzer, pojo).inputQrJAsync(criteria).compose(this.reader::fetchAsync);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
<T> Integer count(final JsonObject filters) {
final DSLContext context = JooqInfix.getDSL();
return null == filters ? context.fetchCount(this.vertxDAO.getTable()) :
context.fetchCount(this.vertxDAO.getTable(), JooqCond.transform(filters, this.analyzer::column));
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
<T> Future<T> fetchOneAsync(final String field, final Object value) {
return JqTool.future(this.vertxDAO.fetchOneAsync(this.analyzer.column(field), value));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public String unique(final CacheMeta meta) {
final Class<?> entityCls = meta.type();
final TreeMap<String, String> treeMap = new TreeMap<>();
treeMap.put(meta.primaryString(), this.id);
return CacheTool.keyId(entityCls.getName(), treeMap);
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public String unique(final CacheMeta meta) {
final TreeMap<String, String> treeMap = new TreeMap<>();
treeMap.put(meta.primaryString(), this.id);
return CacheTool.keyId(meta.typeName(), treeMap);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void onData(final Cell cell) {
final DyeCell dye;
if (CellType.NUMERIC == cell.getCellType()) {
/*
* Buf for date exporting here
*/
final double cellValue = cell.getNumericCellValue();
if (DateUtil.isValidExcelDate(cellValue)) {
final Date value = DateUtil.getJavaDate(cellValue, TimeZone.getDefault());
final LocalDateTime datetime = Ut.toDateTime(value);
final LocalTime time = datetime.toLocalTime();
if (LocalTime.MIN == time) {
/*
* LocalDate
*/
dye = this.onDataValue("DATA-DATE").dateFormat(false);
} else {
/*
* LocalDateTime
*/
dye = this.onDataValue("DATA-DATETIME").dateFormat(true);
}
} else {
/*
* Number
*/
dye = this.onDataValue("DATA-VALUE");
}
} else {
/*
* Other
*/
dye = this.onDataValue("DATA-VALUE");
}
cell.setCellStyle(dye.build());
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
void onTable(final Cell cell) {
final DyeCell dyeCell = Fn.pool(this.stylePool, "TABLE",
() -> DyeCell.create(this.workbook)
.color("FFFFFF", "3EB7FF")
.align(HorizontalAlignment.CENTER)
.border(BorderStyle.THIN)
.font(13, false));
cell.setCellStyle(dyeCell.build());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
<T> T fetchOne(final JsonObject filters) {
final Condition condition = JooqCond.transform(filters, Operator.AND, this.analyzer::column);
final DSLContext context = JooqInfix.getDSL();
return this.toResult(context.selectFrom(this.vertxDAO.getTable()).where(condition).fetchOne(this.vertxDAO.mapper()));
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
<T> Future<JsonObject> searchAsync(final JsonObject params, final JqFlow workflow) {
return this.search.searchAsync(params, workflow);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Future<JsonArray> groupAsync(final String sigma) {
/*
* Build condition of `sigma`
*/
final JsonObject condition = new JsonObject();
condition.put(KeField.SIGMA, sigma);
/*
* Permission Groups processing
*/
return Ux.Jooq.on(SPermissionDao.class)
.countByAsync(condition, "group", "identifier");
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Future<JsonArray> groupAsync(final String sigma) {
/*
* Build condition of `sigma`
*/
final JsonObject condition = new JsonObject();
condition.put(KeField.SIGMA, sigma);
/*
* Permission Groups processing
*「Upgrade」
* Old method because `GROUP` is in S_PERMISSION
* return Ux.Jooq.on(SPermissionDao.class).countByAsync(condition, "group", "identifier");
* New version: S_PERM_SET processing
*/
return Ux.Jooq.on(SPermSetDao.class).fetchJAsync(condition);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Address(Addr.Authority.PERMISSION_BY_ROLE)
public Future<JsonArray> fetchAsync(final String roleId) {
if (Ut.notNil(roleId)) {
return Ux.Jooq.on(RRolePermDao.class)
.fetchAsync(KeField.ROLE_ID, roleId)
.compose(Ux::fnJArray);
} else return Ux.futureJArray();
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Address(Addr.Authority.PERMISSION_BY_ROLE)
public Future<JsonArray> fetchAsync(final String roleId) {
return Fn.getEmpty(Ux.futureJArray(), () -> Ux.Jooq.on(RRolePermDao.class)
.fetchAsync(KeField.ROLE_ID, roleId)
.compose(Ux::fnJArray), roleId);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
L1Cache cacheL1() {
L1Cache cache = null;
final Class<?> componentCls = this.l1Config.getComponent();
if (Objects.nonNull(componentCls) && Ut.isImplement(componentCls, L1Cache.class)) {
/*
* L1 cache here
*/
final Class<?> cacheClass = this.l1Config.getComponent();
cache = Fn.poolThread(POOL_L1, () -> Ut.instance(cacheClass));
cache.bind(this.vertx).bind(this.l1Config.copy());
}
return cache;
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
L1Cache cacheL1() {
L1Cache cache = null;
final Class<?> componentCls = this.l1Config.getComponent();
if (Objects.nonNull(componentCls) && Ut.isImplement(componentCls, L1Cache.class)) {
/*
* L1 cache here
*/
final Class<?> cacheClass = this.l1Config.getComponent();
cache = Fn.poolThread(POOL_L1, () -> {
final L1Cache created = Ut.instance(cacheClass);
return created.bind(this.vertx).bind(this.l1Config.copy());
});
}
return cache;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Future<JsonArray> syncPerm(final JsonArray permissions, final String group, final String sigma) {
/*
* Fetch all permissions from database and calculated removed list
*/
final JsonObject condition = new JsonObject();
condition.put(KeField.GROUP, group);
condition.put(KeField.SIGMA, sigma);
final UxJooq permDao = Ux.Jooq.on(SPermissionDao.class);
return permDao.<SPermission>fetchAndAsync(condition).compose(existing -> {
/*
* Process filter to get removed
*/
final List<SPermission> saved = Ux.fromJson(permissions, SPermission.class);
final Set<String> keeped = saved.stream().map(SPermission::getKey).collect(Collectors.toSet());
final List<String> removedKeys = existing.stream()
.filter(item -> !keeped.contains(item.getKey()))
.map(SPermission::getKey).collect(Collectors.toList());
return this.removeAsync(removedKeys, sigma).compose(nil -> {
/*
* Save Action for SPermission by `key` only
*/
final List<Future<SPermission>> futures = new ArrayList<>();
Ut.itList(saved).map(permission -> permDao.<SPermission>fetchByIdAsync(permission.getKey())
.compose(queired -> {
if (Objects.isNull(queired)) {
/*
* Insert entity object into database
*/
return permDao.insertAsync(permission);
} else {
/*
* Update the `key` hitted object into database
*/
return permDao.updateAsync(permission.getKey(), permission);
}
})).forEach(futures::add);
return Ux.thenCombineT(futures).compose(Ux::futureA);
});
});
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Future<JsonArray> syncPerm(final JsonArray permissions, final String group, final String sigma) {
/*
* 1. permissions ->
* -- ADD = List
* -- UPDATE = List
* -- DELETE = List
*/
final Set<String> permCodes = Ut.mapString(permissions, KeField.CODE);
final JsonObject condition = new JsonObject();
condition.put(KeField.SIGMA, sigma);
return null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Future<JsonObject> fetchModule(final String appId, final String entry) {
final JsonObject filters = new JsonObject()
.put("", Boolean.TRUE)
.put("entry", entry)
.put("appId", appId);
return Ux.Jooq.on(XModuleDao.class)
.fetchOneAsync(filters)
.compose(Ux::fnJObject)
/* Metadata field usage */
.compose(Ke.mount(KeField.METADATA));
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Future<JsonObject> fetchModule(final String appId, final String entry) {
final JsonObject filters = new JsonObject()
.put("", Boolean.TRUE)
.put("entry", entry)
.put("appId", appId);
/*
* Cache Module for future usage
*/
return AcCache.getModule(filters, () -> Ux.Jooq.on(XModuleDao.class)
.fetchOneAsync(filters)
.compose(Ux::fnJObject)
/* Metadata field usage */
.compose(Ke.mount(KeField.METADATA)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void mount(final Router router) {
final Class<?> clazz = ZeroAmbient.getPlugin(KEY_ROUTER);
if (Values.ZERO == LOG_FLAG_START.getAndIncrement()) {
LOGGER.info(Info.DY_DETECT, NAME);
}
if (null != clazz && Ut.isImplement(clazz, PlugRouter.class)) {
final JsonObject config = uniform.read();
final JsonObject routerConfig = Fn.getNull(new JsonObject(), () -> config.getJsonObject(KEY_ROUTER), config);
if (Values.ONE == LOG_FLAG_END.getAndIncrement()) {
LOGGER.info(Info.DY_FOUND, NAME, clazz.getName(), routerConfig.encode());
}
// Mount dynamic router
final PlugRouter plugRouter = Fn.poolThread(Pool.PLUGS,
() -> Ut.instance(clazz));
plugRouter.bind(vertxRef);
plugRouter.mount(router, routerConfig);
} else {
if (Values.ONE == LOG_FLAG_END.getAndIncrement()) {
LOGGER.info(Info.DY_SKIP, NAME,
Fn.getNull(null, () -> null == clazz ? null : clazz.getName(), clazz));
}
}
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void mount(final Router router) {
final Class<?> clazz = ZeroAmbient.getPlugin(PlugRouter.KEY_ROUTER);
if (Values.ZERO == LOG_FLAG_START.getAndIncrement()) {
LOGGER.info(Info.DY_DETECT, NAME);
}
if (null != clazz && Ut.isImplement(clazz, PlugRouter.class)) {
final JsonObject routerConfig = PlugRouter.config();
if (Values.ONE == LOG_FLAG_END.getAndIncrement()) {
LOGGER.info(Info.DY_FOUND, NAME, clazz.getName(), routerConfig.encode());
}
// Mount dynamic router
final PlugRouter plugRouter = Fn.poolThread(Pool.PLUGS,
() -> Ut.instance(clazz));
plugRouter.bind(this.vertxRef);
plugRouter.mount(router, routerConfig);
} else {
if (Values.ONE == LOG_FLAG_END.getAndIncrement()) {
LOGGER.info(Info.DY_SKIP, NAME,
Fn.getNull(null, () -> null == clazz ? null : clazz.getName(), clazz));
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void onData(final Cell cell) {
final DyeCell dyeCell = Fn.pool(this.stylePool, "DATA",
() -> DyeCell.create(this.workbook)
.border(BorderStyle.THIN)
.align(null, VerticalAlignment.TOP)
.font(13, false));
cell.setCellStyle(dyeCell.build());
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
void onTable(final Cell cell) {
final DyeCell dyeCell = Fn.pool(this.stylePool, "TABLE",
() -> DyeCell.create(this.workbook)
.color("FFFFFF", "3EB7FF")
.align(HorizontalAlignment.CENTER)
.border(BorderStyle.THIN)
.font(13, false));
cell.setCellStyle(dyeCell.build());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static Object invokeSingle(final Object proxy,
final Method method,
final Envelop envelop) {
final Class<?> argType = method.getParameterTypes()[Values.IDX];
// One type dynamic here
final Object reference = Objects.nonNull(envelop) ? envelop.data() : new JsonObject();
// Non Direct
Object parameters = reference;
if (JsonObject.class == reference.getClass()) {
final JsonObject json = (JsonObject) reference;
if (isInterface(json)) {
// Proxy mode
if (Values.ONE == json.fieldNames().size()) {
// New Mode for direct type
parameters = json.getValue("0");
}
}
}
final Object arguments = ZeroSerializer.getValue(argType, Ut.toString(parameters));
return Ut.invoke(proxy, method.getName(), arguments);
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
static Object invokeSingle(final Object proxy,
final Method method,
final Envelop envelop) {
final Class<?> argType = method.getParameterTypes()[Values.IDX];
// Append single argument
final Object analyzed = TypedArgument.analyze(envelop, argType);
if (Objects.isNull(analyzed)) {
// One type dynamic here
final Object reference = Objects.nonNull(envelop) ? envelop.data() : new JsonObject();
// Non Direct
Object parameters = reference;
if (JsonObject.class == reference.getClass()) {
final JsonObject json = (JsonObject) reference;
if (isInterface(json)) {
// Proxy mode
if (Values.ONE == json.fieldNames().size()) {
// New Mode for direct type
parameters = json.getValue("0");
}
}
}
final Object arguments = ZeroSerializer.getValue(argType, Ut.toString(parameters));
return Ut.invoke(proxy, method.getName(), arguments);
} else {
/*
* XHeader
* User
* Session
* These three argument types could be single
*/
return Ut.invoke(proxy, method.getName(), analyzed);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void onData(final Cell cell) {
final DyeCell dye;
if (CellType.NUMERIC == cell.getCellType()) {
/*
* Buf for date exporting here
*/
final double cellValue = cell.getNumericCellValue();
if (DateUtil.isValidExcelDate(cellValue)) {
final Date value = DateUtil.getJavaDate(cellValue, TimeZone.getDefault());
final LocalDateTime datetime = Ut.toDateTime(value);
final LocalTime time = datetime.toLocalTime();
if (LocalTime.MIN == time) {
/*
* LocalDate
*/
dye = this.onDataValue("DATA-DATE").dateFormat(false);
} else {
/*
* LocalDateTime
*/
dye = this.onDataValue("DATA-DATETIME").dateFormat(true);
}
} else {
/*
* Number
*/
dye = this.onDataValue("DATA-VALUE");
}
} else {
/*
* Other
*/
dye = this.onDataValue("DATA-VALUE");
}
cell.setCellStyle(dye.build());
}
#location 21
#vulnerability type NULL_DEREFERENCE | #fixed code
void onTable(final Cell cell) {
final DyeCell dyeCell = Fn.pool(this.stylePool, "TABLE",
() -> DyeCell.create(this.workbook)
.color("FFFFFF", "3EB7FF")
.align(HorizontalAlignment.CENTER)
.border(BorderStyle.THIN)
.font(13, false));
cell.setCellStyle(dyeCell.build());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void mountSession(final Router router) {
if (ZeroHeart.isSession()) {
/*
* Session Global for Authorization, replace old mode with
* SessionClient, this client will get SessionStore
* by configuration information instead of create it directly.
*/
final SessionClient client = SessionInfix.getOrCreate(this.vertx);
router.route().order(Orders.SESSION).handler(client.getHandler());
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
private void mountSession(final Router router) {
if (ZeroHeart.isSession()) {
/*
* Session Global for Authorization, replace old mode with
* SessionClient, this client will get SessionStore
* by configuration information instead of create it directly.
*/
final SessionClient client = SessionInfix.getOrCreate(this.vertx);
router.route().order(Orders.SESSION).handler(client.getHandler());
} else {
/*
* Default Session Handler here for public domain
* If enabled session extension, you should provide other session store
*/
final SessionStore store;
if (this.vertx.isClustered()) {
/*
* Cluster environment
*/
store = ClusteredSessionStore.create(this.vertx);
} else {
/*
* Single Node environment
*/
store = LocalSessionStore.create(this.vertx);
}
router.route().order(Orders.SESSION).handler(SessionHandler.create(store));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void register(JsonProvider jsonProvider) {
this.registeredJsonProvider = Objects.requireNonNull(jsonProvider);
logger.debug(() -> "Set json provider to " + jsonProvider.getClass().getName());
}
#location 3
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
public void register(JsonProvider jsonProvider) {
this.registeredJsonProvider = Objects.requireNonNull(jsonProvider);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testParse_Map1() {
BEParser parser = new BEParser("d4:spaml1:a1:bee");
assertEquals(BEType.MAP, parser.readType());
Map<String, Object> expected = new HashMap<>();
expected.put("spam", Arrays.asList("a", "b"));
assertEquals(expected, parser.readMap());
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testParse_Map1() {
BEParser parser = new BEParser("d4:spaml1:a1:bee".getBytes());
assertEquals(BEType.MAP, parser.readType());
byte[][] expected = new byte[][] {"a".getBytes(charset), "b".getBytes(charset)};
Map<String, Object> map = parser.readMap();
Object o = map.get("spam");
assertNotNull(o);
assertTrue(o instanceof List);
List<?> actual = (List<?>) o;
assertArrayEquals(expected, actual.toArray());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = Exception.class)
public void testParse_Integer_Exception_ZeroLength() {
BEParser parser = new BEParser("ie");
assertEquals(BEType.INTEGER, parser.readType());
parser.readInteger();
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = Exception.class)
public void testParse_Integer_Exception_ZeroLength() {
BEParser parser = new BEParser("ie".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
parser.readInteger();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testParse_String2() {
BEParser parser = new BEParser("11:!@#$%^&*()_");
assertEquals(BEType.STRING, parser.readType());
assertEquals("!@#$%^&*()_", parser.readString());
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testParse_String2() {
BEParser parser = new BEParser("11:!@#$%^&*()_".getBytes());
assertEquals(BEType.STRING, parser.readType());
assertEquals("!@#$%^&*()_", parser.readString(charset));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = Exception.class)
public void testParse_String_Exception_EmptyString() {
new BEParser("");
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = Exception.class)
public void testParse_String_Exception_EmptyString() {
new BEParser("".getBytes());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testParse_String1() {
BEParser parser = new BEParser("1:s");
assertEquals(BEType.STRING, parser.readType());
assertEquals("s", parser.readString());
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testParse_String1() {
BEParser parser = new BEParser("1:s".getBytes());
assertEquals(BEType.STRING, parser.readType());
assertEquals("s", parser.readString(charset));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testParse_Integer_Negative() {
BEParser parser = new BEParser("i-1e");
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ONE.negate(), parser.readInteger());
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testParse_Integer_Negative() {
BEParser parser = new BEParser("i-1e".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ONE.negate(), parser.readInteger());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testParse_String2() {
BEParser parser = new BEParser("11:!@#$%^&*()_");
assertEquals(BEType.STRING, parser.readType());
assertEquals("!@#$%^&*()_", parser.readString());
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testParse_String2() {
BEParser parser = new BEParser("11:!@#$%^&*()_".getBytes());
assertEquals(BEType.STRING, parser.readType());
assertEquals("!@#$%^&*()_", parser.readString(charset));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testParse_Integer_Negative() {
BEParser parser = new BEParser("i-1e");
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ONE.negate(), parser.readInteger());
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testParse_Integer_Negative() {
BEParser parser = new BEParser("i-1e".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
assertEquals(BigInteger.ONE.negate(), parser.readInteger());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = Exception.class)
public void testParse_Integer_Exception_UnexpectedTokens() {
BEParser parser = new BEParser("i-1-e");
assertEquals(BEType.INTEGER, parser.readType());
parser.readInteger();
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = Exception.class)
public void testParse_Integer_Exception_UnexpectedTokens() {
BEParser parser = new BEParser("i-1-e".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
parser.readInteger();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = Exception.class)
public void testParse_Integer_Exception_ZeroLength() {
BEParser parser = new BEParser("ie");
assertEquals(BEType.INTEGER, parser.readType());
parser.readInteger();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = Exception.class)
public void testParse_Integer_Exception_ZeroLength() {
BEParser parser = new BEParser("ie".getBytes());
assertEquals(BEType.INTEGER, parser.readType());
parser.readInteger();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testDescriptors_WriteMultiFile() {
String torrentName = "xyz-torrent";
File torrentDirectory = new File(rootDirectory, torrentName);
String extension = "-multi.bin";
String fileName1 = 1 + extension,
fileName2 = 2 + extension,
fileName3 = 3 + extension,
fileName4 = 4 + extension,
fileName5 = 5 + extension,
fileName6 = 6 + extension;
long chunkSize = 16;
long torrentSize = chunkSize * 6;
long fileSize1 = 25,
fileSize2 = 18,
fileSize3 = 5,
fileSize4 = 31,
fileSize5 = 16,
fileSize6 = 1;
// sanity check
assertEquals(torrentSize, fileSize1 + fileSize2 + fileSize3 + fileSize4 + fileSize5 + fileSize6);
byte[] chunk0Hash = CryptoUtil.getSha1Digest(Arrays.copyOfRange(MULTI_FILE_1, 0, 16));
byte[] chunk1 = new byte[(int) chunkSize];
System.arraycopy(MULTI_FILE_1, 16, chunk1, 0, 9);
System.arraycopy(MULTI_FILE_2, 0, chunk1, 9, 7);
byte[] chunk1Hash = CryptoUtil.getSha1Digest(chunk1);
byte[] chunk2 = new byte[(int) chunkSize];
System.arraycopy(MULTI_FILE_2, 7, chunk2, 0, 11);
System.arraycopy(MULTI_FILE_3, 0, chunk2, 11, 5);
byte[] chunk2Hash = CryptoUtil.getSha1Digest(chunk2);
byte[] chunk3 = new byte[(int) chunkSize];
System.arraycopy(MULTI_FILE_4, 0, chunk3, 0, 16);
byte[] chunk3Hash = CryptoUtil.getSha1Digest(chunk3);
byte[] chunk4 = new byte[(int) chunkSize];
System.arraycopy(MULTI_FILE_4, 16, chunk4, 0, 15);
System.arraycopy(MULTI_FILE_5, 0, chunk4, 15, 1);
byte[] chunk4Hash = CryptoUtil.getSha1Digest(chunk4);
byte[] chunk5 = new byte[(int) chunkSize];
System.arraycopy(MULTI_FILE_5, 1, chunk5, 0, 15);
System.arraycopy(MULTI_FILE_6, 0, chunk5, 15, 1);
byte[] chunk5Hash = CryptoUtil.getSha1Digest(chunk5);
Torrent torrent = mockTorrent(torrentName, torrentSize, chunkSize,
new byte[][] {chunk0Hash, chunk1Hash, chunk2Hash, chunk3Hash, chunk4Hash, chunk5Hash},
mockTorrentFile(fileSize1, fileName1), mockTorrentFile(fileSize2, fileName2),
mockTorrentFile(fileSize3, fileName3), mockTorrentFile(fileSize4, fileName4),
mockTorrentFile(fileSize5, fileName5), mockTorrentFile(fileSize6, fileName6));
IDataDescriptor descriptor = new DataDescriptor(dataAccessFactory, configurationService, torrent);
List<IChunkDescriptor> chunks = descriptor.getChunkDescriptors();
assertEquals(6, chunks.size());
chunks.get(0).writeBlock(sequence(8), 0);
chunks.get(0).writeBlock(sequence(8), 8);
assertTrue(chunks.get(0).verify());
chunks.get(1).writeBlock(sequence(4), 0);
chunks.get(1).writeBlock(sequence(4), 4);
chunks.get(1).writeBlock(sequence(4), 8);
chunks.get(1).writeBlock(sequence(4), 12);
assertTrue(chunks.get(1).verify());
// reverse order
chunks.get(2).writeBlock(sequence(11), 5);
chunks.get(2).writeBlock(sequence(3), 2);
chunks.get(2).writeBlock(sequence(2), 0);
assertFalse(chunks.get(2).verify());
chunks.get(2).writeBlock(new byte[]{1,2,1,2,3,1,2,3}, 0);
assertTrue(chunks.get(2).verify());
// "random" order
chunks.get(3).writeBlock(sequence(4), 4);
chunks.get(3).writeBlock(sequence(4), 0);
chunks.get(3).writeBlock(sequence(4), 12);
chunks.get(3).writeBlock(sequence(4), 8);
assertTrue(chunks.get(3).verify());
// block size same as chunk size
chunks.get(4).writeBlock(sequence(16), 0);
assertTrue(chunks.get(4).verify());
// 1-byte blocks
chunks.get(5).writeBlock(sequence(1), 0);
chunks.get(5).writeBlock(sequence(1), 15);
chunks.get(5).writeBlock(sequence(14), 1);
assertFalse(chunks.get(5).verify());
chunks.get(5).writeBlock(new byte[]{1,1,2,3,4,5,6,7,8,9,1,2,3,4,5,1}, 0);
assertTrue(chunks.get(5).verify());
byte[] file1 = readBytesFromFile(new File(torrentDirectory, fileName1), (int) fileSize1);
assertArrayEquals(MULTI_FILE_1, file1);
byte[] file2 = readBytesFromFile(new File(torrentDirectory, fileName2), (int) fileSize2);
assertArrayEquals(MULTI_FILE_2, file2);
byte[] file3 = readBytesFromFile(new File(torrentDirectory, fileName3), (int) fileSize3);
assertArrayEquals(MULTI_FILE_3, file3);
byte[] file4 = readBytesFromFile(new File(torrentDirectory, fileName4), (int) fileSize4);
assertArrayEquals(MULTI_FILE_4, file4);
byte[] file5 = readBytesFromFile(new File(torrentDirectory, fileName5), (int) fileSize5);
assertArrayEquals(MULTI_FILE_5, file5);
byte[] file6 = readBytesFromFile(new File(torrentDirectory, fileName6), (int) fileSize6);
assertArrayEquals(MULTI_FILE_6, file6);
}
#location 62
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testDescriptors_WriteMultiFile() {
String torrentName = "xyz-torrent";
File torrentDirectory = new File(rootDirectory, torrentName);
String extension = "-multi.bin";
String fileName1 = 1 + extension,
fileName2 = 2 + extension,
fileName3 = 3 + extension,
fileName4 = 4 + extension,
fileName5 = 5 + extension,
fileName6 = 6 + extension;
IDataDescriptor descriptor = createDataDescriptor_MultiFile(fileName1, fileName2, fileName3, fileName4,
fileName5, fileName6, torrentDirectory);
List<IChunkDescriptor> chunks = descriptor.getChunkDescriptors();
chunks.get(0).writeBlock(sequence(8), 0);
chunks.get(0).writeBlock(sequence(8), 8);
assertTrue(chunks.get(0).verify());
chunks.get(1).writeBlock(sequence(4), 0);
chunks.get(1).writeBlock(sequence(4), 4);
chunks.get(1).writeBlock(sequence(4), 8);
chunks.get(1).writeBlock(sequence(4), 12);
assertTrue(chunks.get(1).verify());
// reverse order
chunks.get(2).writeBlock(sequence(11), 5);
chunks.get(2).writeBlock(sequence(3), 2);
chunks.get(2).writeBlock(sequence(2), 0);
assertFalse(chunks.get(2).verify());
chunks.get(2).writeBlock(new byte[]{1,2,1,2,3,1,2,3}, 0);
assertTrue(chunks.get(2).verify());
// "random" order
chunks.get(3).writeBlock(sequence(4), 4);
chunks.get(3).writeBlock(sequence(4), 0);
chunks.get(3).writeBlock(sequence(4), 12);
chunks.get(3).writeBlock(sequence(4), 8);
assertTrue(chunks.get(3).verify());
// block size same as chunk size
chunks.get(4).writeBlock(sequence(16), 0);
assertTrue(chunks.get(4).verify());
// 1-byte blocks
chunks.get(5).writeBlock(sequence(1), 0);
chunks.get(5).writeBlock(sequence(1), 15);
chunks.get(5).writeBlock(sequence(14), 1);
assertFalse(chunks.get(5).verify());
chunks.get(5).writeBlock(new byte[]{1,1,2,3,4,5,6,7,8,9,1,2,3,4,5,1}, 0);
assertTrue(chunks.get(5).verify());
assertFileHasContents(new File(torrentDirectory, fileName1), MULTI_FILE_1);
assertFileHasContents(new File(torrentDirectory, fileName2), MULTI_FILE_2);
assertFileHasContents(new File(torrentDirectory, fileName3), MULTI_FILE_3);
assertFileHasContents(new File(torrentDirectory, fileName4), MULTI_FILE_4);
assertFileHasContents(new File(torrentDirectory, fileName5), MULTI_FILE_5);
assertFileHasContents(new File(torrentDirectory, fileName6), MULTI_FILE_6);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testParse_Map1() {
BEParser parser = new BEParser("d4:spaml1:a1:bee");
assertEquals(BEType.MAP, parser.readType());
Map<String, Object> expected = new HashMap<>();
expected.put("spam", Arrays.asList("a", "b"));
assertEquals(expected, parser.readMap());
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testParse_Map1() {
BEParser parser = new BEParser("d4:spaml1:a1:bee".getBytes());
assertEquals(BEType.MAP, parser.readType());
byte[][] expected = new byte[][] {"a".getBytes(charset), "b".getBytes(charset)};
Map<String, Object> map = parser.readMap();
Object o = map.get("spam");
assertNotNull(o);
assertTrue(o instanceof List);
List<?> actual = (List<?>) o;
assertArrayEquals(expected, actual.toArray());
} | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.