code
stringlengths
3
1.18M
language
stringclasses
1 value
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.net; import android.util.Xml; import java.io.IOException; import java.io.InputStream; import java.net.ContentHandler; import java.net.HttpURLConnection; import java.net.URLConnection; /** * Reads an XML response from an {@link HttpURLConnection}. * * @param <T> */ abstract class XmlContentHandler<T> extends ContentHandler { protected final void parse(URLConnection connection, org.xml.sax.ContentHandler handler) throws IOException { InputStream input = connection.getInputStream(); try { // The server sends UTF-8 instead of the HTTP default (ISO-8859-1). Xml.Encoding encoding = Xml.Encoding.UTF_8; Xml.parse(input, encoding, handler); } catch (Exception e) { IOException ioe = new IOException("Invalid XML"); ioe.initCause(e); throw ioe; } finally { input.close(); } } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.net; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.IOException; import java.io.InputStream; import java.net.ContentHandler; import java.net.URLConnection; final class BitmapContentHandler extends ContentHandler { private static final int TIMEOUT = 2000; @Override public Bitmap getContent(URLConnection connection) throws IOException { // In some versions of VLC, album art requests can take a long time // to return if there is no album art available for the current track. // Set a short timeout to prevent a backlog of requests in this queue. connection.setConnectTimeout(TIMEOUT); connection.setReadTimeout(TIMEOUT); InputStream input = connection.getInputStream(); try { input = new BlockingFilterInputStream(input); Bitmap bitmap = BitmapFactory.decodeStream(input); if (bitmap == null) { throw new IOException("Decoding failed"); } return bitmap; } finally { input.close(); } } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.loader; import org.peterbaldwin.vlcremote.model.Directory; import org.peterbaldwin.vlcremote.model.Remote; import org.peterbaldwin.vlcremote.net.MediaServer; import android.content.Context; public class DirectoryLoader extends ModelLoader<Remote<Directory>> { private final MediaServer mMediaServer; private final String mDir; public DirectoryLoader(Context context, MediaServer mediaServer, String dir) { super(context); mMediaServer = mediaServer; mDir = dir; } @Override public Remote<Directory> loadInBackground() { return mMediaServer.browse(mDir).load(); } }
Java
package org.peterbaldwin.vlcremote.loader; import org.peterbaldwin.client.android.vlcremote.R; import org.peterbaldwin.vlcremote.net.MediaServer; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import java.io.IOException; public class ImageLoader extends ModelLoader<Drawable> { private final MediaServer mMediaServer; private final Uri mUri; public ImageLoader(Context context, MediaServer mediaServer, Uri uri) { super(context); mMediaServer = mediaServer; mUri = uri; } @Override public Drawable loadInBackground() { Resources res = getContext().getResources(); if (mUri != null && "http".equals(mUri.getScheme())) { try { return new BitmapDrawable(res, mMediaServer.image(mUri).read()); } catch (IOException e) { return res.getDrawable(R.drawable.albumart_mp_unknown); } } else { return res.getDrawable(R.drawable.albumart_mp_unknown); } } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.loader; import android.content.Context; import android.support.v4.content.AsyncTaskLoader; abstract class ModelLoader<D> extends AsyncTaskLoader<D> { private D mModel; protected ModelLoader(Context context) { super(context); } @Override protected void onStartLoading() { if (mModel != null) { deliverResult(mModel); } else { forceLoad(); } } @Override public void deliverResult(D model) { if (!isReset()) { super.deliverResult(model); mModel = model; } } @Override protected void onStopLoading() { cancelLoad(); } @Override protected void onReset() { super.onReset(); cancelLoad(); mModel = null; } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.loader; import org.peterbaldwin.vlcremote.model.Playlist; import org.peterbaldwin.vlcremote.model.Remote; import org.peterbaldwin.vlcremote.net.MediaServer; import android.content.Context; public class PlaylistLoader extends ModelLoader<Remote<Playlist>> { private final MediaServer mMediaServer; private final String mSearch; public PlaylistLoader(Context context, MediaServer mediaServer, String search) { super(context); mMediaServer = mediaServer; mSearch = search; } @Override public Remote<Playlist> loadInBackground() { return mMediaServer.playlist(mSearch).load(); } }
Java
package org.peterbaldwin.vlcremote.loader; import org.peterbaldwin.client.android.vlcremote.R; import org.peterbaldwin.vlcremote.net.MediaServer; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import java.io.IOException; public class ArtLoader extends ModelLoader<Drawable> { private final MediaServer mMediaServer; public ArtLoader(Context context, MediaServer mediaServer) { super(context); mMediaServer = mediaServer; } @Override public Drawable loadInBackground() { Resources res = getContext().getResources(); try { return new BitmapDrawable(res, mMediaServer.art().read()); } catch (IOException e) { return res.getDrawable(R.drawable.albumart_mp_unknown); } } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Modifications: * 1. Changed package name * 2. Don't send change notifications unless something actually changed. */ package org.peterbaldwin.vlcremote.preference; import org.peterbaldwin.client.android.vlcremote.R; import android.content.Context; import android.preference.PreferenceCategory; import android.util.AttributeSet; import android.view.View; public class ProgressCategory extends PreferenceCategory { private boolean mProgress = false; public ProgressCategory(Context context, AttributeSet attrs) { super(context, attrs); setLayoutResource(R.layout.preference_progress_category); } @Override public void onBindView(View view) { super.onBindView(view); View textView = view.findViewById(R.id.scanning_text); View progressBar = view.findViewById(R.id.scanning_progress); int visibility = mProgress ? View.VISIBLE : View.INVISIBLE; textView.setVisibility(visibility); progressBar.setVisibility(visibility); } /** * Turn on/off the progress indicator and text on the right. * * @param progressOn whether or not the progress should be displayed */ public void setProgress(boolean progressOn) { if (mProgress != progressOn) { mProgress = progressOn; notifyChanged(); } } }
Java
/*- * Copyright (C) 2009 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.sweep; import java.io.IOException; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; final class Worker extends Thread { public interface Manager { /** * Retrieves and removes the next IP address, or returns {@code null} if * there are not more addresses to scan. */ byte[] pollIpAddress(); } public interface Callback { /** * Indicates that an address is reachable. */ void onReachable(InetAddress address, int port, String hostname, int responseCode); /** * Indicates that an address is unreachable. */ void onUnreachable(byte[] ipAddress, int port, IOException e); } private final int mPort; private final String mPath; private Manager mManager; private Callback mCallback; public Worker(int port, String path) { mPort = port; mPath = path; } public void setManager(Manager manager) { mManager = manager; } public void setCallback(Callback callback) { mCallback = callback; } private static URL createUrl(String scheme, String host, int port, String path) { try { return new URL("http", host, port, path); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } } @Override public void run() { // Note: InetAddress#isReachable(int) always returns false for Windows // hosts because applications do not have permission to perform ICMP // echo requests. for (;;) { byte[] ipAddress = mManager.pollIpAddress(); if (ipAddress == null) { break; } try { InetAddress address = InetAddress.getByAddress(ipAddress); String hostAddress = address.getHostAddress(); URL url = createUrl("http", hostAddress, mPort, mPath); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(1000); try { int responseCode = connection.getResponseCode(); String hostname = address.getHostName(); mCallback.onReachable(address, mPort, hostname, responseCode); } finally { connection.disconnect(); } } catch (IOException e) { mCallback.onUnreachable(ipAddress, mPort, e); } } } }
Java
/*- * Copyright (C) 2009 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.sweep; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.os.Process; import android.util.Log; import java.io.IOException; import java.net.InetAddress; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; public final class PortSweeper { public interface Callback { void onHostFound(String hostname, int responseCode); void onProgress(int progress, int max); } private static final String TAG = "Scanner"; private static final int HANDLE_SCAN = 1; private static final int HANDLE_START = 1; private static final int HANDLE_REACHABLE = 2; private static final int HANDLE_UNREACHABLE = 3; private static final int HANDLE_COMPLETE = 4; private final Queue<byte[]> mAddressQueue; /** * Queue for scan requests. */ private final Handler mScanHandler; /** * Processes scan requests. * <p> * No real work is done on this thread; it just waits for the workers to * finish using {@link Thread#join()}. */ private final HandlerThread mScanThread; /** * Dispatches callbacks on the main thread. */ private final Handler mCallbackHandler; /** * Provides work for worker threads. */ private final Worker.Manager mWorkerManager; /** * Handles results from worker threads. */ private final Worker.Callback mWorkerCallback; /** * The port to scan. */ private final int mPort; /** * The HTTP path to scan. */ private final String mPath; /** * The number of workers to allocate. */ private final int mWorkerCount; /** * Callback for port sweep progress and results. */ private Callback mCallback; /** * The current progress. */ private int mProgress; /** * The maximum progress. */ private int mMax; /** * Indicates that the sweep is complete. */ private boolean mComplete; public PortSweeper(int port, String file, int threadCount, Callback callback, Looper looper) { mPort = port; mPath = file; mWorkerCount = threadCount; mCallback = callback; mAddressQueue = new ConcurrentLinkedQueue<byte[]>(); mWorkerManager = new MyWorkerManager(); mWorkerCallback = new MyWorkerCallback(); mScanThread = new HandlerThread("Scanner", Process.THREAD_PRIORITY_BACKGROUND); mScanThread.start(); Handler.Callback callbackHandlerCallback = new MyCallbackHandlerCallback(); mCallbackHandler = new Handler(looper, callbackHandlerCallback); Handler.Callback scanHandlerCallback = new MyScanHandlerCallback(); mScanHandler = new Handler(mScanThread.getLooper(), scanHandlerCallback); } public void setCallback(Callback callback) { mCallback = callback; if (mCallback != null) { // Replay progress for new callback receiver mCallback.onProgress(0, mMax); mCallback.onProgress(mProgress, mMax); } } public void sweep(byte[] ipAddress) { abort(); // Schedule a new sweep. The new sweep will not start until all previous // sweeps have been fully aborted. mScanHandler.obtainMessage(HANDLE_SCAN, ipAddress).sendToTarget(); } public void abort() { // Clear pending jobs mScanHandler.removeMessages(HANDLE_SCAN); // Abort the job in progress mAddressQueue.clear(); } public void destory() { abort(); Looper looper = mScanThread.getLooper(); looper.quit(); } /** * Scans all local IP addresses using a pool of worker threads and waits for * the all of the workers to finish scanning before returning. */ private void handleScan(byte[] interfaceAddress) { Worker[] workers = new Worker[mWorkerCount]; for (int i = 0; i < workers.length; i++) { Worker worker = workers[i] = new Worker(mPort, mPath); worker.setPriority(Thread.MIN_PRIORITY); worker.setManager(mWorkerManager); worker.setCallback(mWorkerCallback); } int count = 0; // Scan outwards from the interface IP address for best results // with DHCP servers that allocate addresses sequentially. byte start = interfaceAddress[interfaceAddress.length - 1]; for (int delta = 1; delta < 128; delta++) { for (int sign = -1; sign <= 1; sign += 2) { int b = (256 + start + sign * delta) % 256; if (b != 0) { byte[] ipAddress = interfaceAddress.clone(); ipAddress[ipAddress.length - 1] = (byte) b; mAddressQueue.add(ipAddress); count += 1; } else { // Skip broadcast address } } } mCallbackHandler.obtainMessage(HANDLE_START, 0, count).sendToTarget(); for (int i = 0; i < workers.length; i++) { Worker worker = workers[i]; worker.start(); } try { for (int i = 0; i < workers.length; i++) { Worker worker = workers[i]; worker.join(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { mCallbackHandler.sendEmptyMessage(HANDLE_COMPLETE); } } private class MyScanHandlerCallback implements Handler.Callback { /** {@inheritDoc} */ public boolean handleMessage(Message msg) { switch (msg.what) { case HANDLE_SCAN: byte[] interfaceAddress = (byte[]) msg.obj; handleScan(interfaceAddress); return true; default: return false; } } } private class MyWorkerManager implements Worker.Manager { /** {@inheritDoc} */ public byte[] pollIpAddress() { return mAddressQueue.poll(); } } private class MyWorkerCallback implements Worker.Callback { /** {@inheritDoc} */ public void onReachable(InetAddress address, int port, String hostname, int responseCode) { Message m = mCallbackHandler.obtainMessage(HANDLE_REACHABLE); m.obj = hostname; m.arg1 = responseCode; m.sendToTarget(); } /** {@inheritDoc} */ public void onUnreachable(byte[] ipAddress, int port, IOException e) { Message m = mCallbackHandler.obtainMessage(HANDLE_UNREACHABLE); m.obj = e; m.sendToTarget(); } } private class MyCallbackHandlerCallback implements Handler.Callback { /** {@inheritDoc} */ public boolean handleMessage(Message msg) { if (mComplete && msg.what != HANDLE_START) { Log.w(TAG, "unexpected callback"); return true; } try { switch (msg.what) { case HANDLE_START: mComplete = false; mProgress = msg.arg1; mMax = msg.arg2; return true; case HANDLE_REACHABLE: String hostname = (String) msg.obj; int responseCode = msg.arg1; Log.d(TAG, "found: " + hostname); mCallback.onHostFound(hostname, responseCode); mProgress++; return true; case HANDLE_UNREACHABLE: IOException e = (IOException) msg.obj; Log.d(TAG, "unreachable", e); mProgress++; return true; case HANDLE_COMPLETE: mComplete = true; mProgress = mMax; return true; default: return false; } } finally { mProgress = Math.min(mProgress, mMax); mCallback.onProgress(mProgress, mMax); } } } }
Java
package org.peterbaldwin.vlcremote.widget; import org.peterbaldwin.client.android.vlcremote.R; import org.peterbaldwin.vlcremote.model.PlaylistItem; import org.peterbaldwin.vlcremote.model.Track; import android.content.Context; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public final class PlaylistAdapter extends BaseAdapter { private List<PlaylistItem> mItems; /** {@inheritDoc} */ public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { Context context = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(context); view = inflater.inflate(R.layout.playlist_list_item, parent, false); } TextView text1 = (TextView) view.findViewById(android.R.id.text1); TextView text2 = (TextView) view.findViewById(android.R.id.text2); View icon = view.findViewById(android.R.id.icon); PlaylistItem item = getItem(position); if (item instanceof Track) { Track track = (Track) item; if (!TextUtils.isEmpty(track.getTitle())) { text1.setText(track.getTitle()); text2.setText(track.getArtist()); } else { text1.setText(item.getName()); text2.setText(""); } icon.setVisibility(track.isCurrent() ? View.VISIBLE : View.GONE); } else { text1.setText(item.getName()); text2.setText(""); icon.setVisibility(View.GONE); } return view; } /** {@inheritDoc} */ public int getCount() { return mItems != null ? mItems.size() : 0; } /** {@inheritDoc} */ public PlaylistItem getItem(int position) { return mItems.get(position); } @Override public boolean hasStableIds() { return true; } /** {@inheritDoc} */ public long getItemId(int position) { if (position < getCount()) { PlaylistItem item = getItem(position); return item.getId(); } else { return AdapterView.INVALID_ROW_ID; } } public void setItems(List<PlaylistItem> items) { mItems = items; if (mItems != null) { notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } } public List<PlaylistItem> getItems() { int count = getCount(); List<PlaylistItem> items = new ArrayList<PlaylistItem>(count); for (int position = 0; position < count; position++) { PlaylistItem item = getItem(position); items.add(item); } return items; } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.widget; import org.peterbaldwin.client.android.vlcremote.R; import org.peterbaldwin.vlcremote.model.Directory; import org.peterbaldwin.vlcremote.model.File; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.SectionIndexer; import java.util.ArrayList; import java.util.List; public class DirectoryAdapter extends ArrayAdapter<File> implements SectionIndexer { private Object[] mSections = new Object[0]; private Integer[] mPositionForSection = new Integer[0]; private Integer[] mSectionForPosition = new Integer[0]; public DirectoryAdapter(Context context) { super(context, R.layout.file_list_item, android.R.id.text1); } /** {@inheritDoc} */ public int getPositionForSection(int section) { if (section < 0) { section = 0; } if (section >= mPositionForSection.length) { section = mPositionForSection.length - 1; } return mPositionForSection[section]; } /** {@inheritDoc} */ public int getSectionForPosition(int position) { if (position < 0) { position = 0; } if (position >= mSectionForPosition.length) { position = mSectionForPosition.length - 1; } return mSectionForPosition[position]; } /** {@inheritDoc} */ public Object[] getSections() { return mSections; } @Override public void add(File object) { throw new UnsupportedOperationException(); } @Override public void clear() { super.clear(); mSections = new Object[0]; mPositionForSection = new Integer[0]; mSectionForPosition = new Integer[0]; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); File file = getItem(position); ImageView icon = (ImageView) v.findViewById(android.R.id.icon); if (file.isDirectory()) { String name = file.getName(); if ("..".equals(name)) { icon.setImageResource(R.drawable.ic_up); } else { icon.setImageResource(R.drawable.ic_directory); } } else { String contentType = file.getMimeType(); if (contentType != null) { contentType = contentType.toLowerCase(); if (contentType.startsWith("audio/")) { icon.setImageResource(R.drawable.ic_mime_audio); } else if (contentType.startsWith("image/")) { icon.setImageResource(R.drawable.ic_mime_image); } else if (contentType.startsWith("video/")) { icon.setImageResource(R.drawable.ic_mime_video); } else { icon.setImageResource(R.drawable.ic_file); } } else { icon.setImageResource(R.drawable.ic_file); } } return v; } private String getSection(File file) { String name = file.getName(); if (name.equals("..")) { Context context = getContext(); return context.getString(R.string.section_parent); } else if (name.length() > 0) { char c = name.charAt(0); c = Character.toUpperCase(c); return String.valueOf(c); } else { // This shouldn't happen return ""; } } public void setDirectory(Directory items) { super.clear(); if (items != null) { int count = items.size(); // Space for every letter and digit, plus a couple symbols int capacity = 48; Integer lastSection = null; List<String> sections = new ArrayList<String>(capacity); List<Integer> positionForSection = new ArrayList<Integer>(capacity); List<Integer> sectionForPosition = new ArrayList<Integer>(count); for (int position = 0; position < count; position++) { File file = items.get(position); String section = getSection(file); if (!sections.contains(section)) { lastSection = Integer.valueOf(sections.size()); sections.add(section); positionForSection.add(Integer.valueOf(position)); } sectionForPosition.add(lastSection); super.add(file); } mSections = sections.toArray(); mPositionForSection = toArray(positionForSection); mSectionForPosition = toArray(sectionForPosition); } else { mSections = new Object[0]; mPositionForSection = new Integer[0]; mSectionForPosition = new Integer[0]; } } private static Integer[] toArray(List<Integer> list) { return list.toArray(new Integer[list.size()]); } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.widget; import org.peterbaldwin.client.android.vlcremote.R; import android.content.Context; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Toast; /** * Displays the current volume level as a {@link Toast}. */ public class VolumePanel { private final Toast mToast; private final View mView; private final ImageView mIcon; private final ProgressBar mProgress; public VolumePanel(Context context) { mToast = new Toast(context); LayoutInflater inflater = LayoutInflater.from(context); mView = inflater.inflate(R.layout.volume_adjust, null); mIcon = (ImageView) mView.findViewById(android.R.id.icon); mProgress = (ProgressBar) mView.findViewById(android.R.id.progress); } public void onVolumeChanged(int level) { mIcon.setImageResource(level == 0 ? R.drawable.ic_volume_off_small : R.drawable.ic_volume_small); mProgress.setProgress(level); mToast.setView(mView); mToast.setDuration(Toast.LENGTH_LONG); mToast.setGravity(Gravity.TOP, 0, 0); mToast.show(); } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.fragment; import org.peterbaldwin.client.android.vlcremote.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.View; import android.widget.AdapterView; public final class HotkeyDialog extends DialogFragment implements AdapterView.OnItemClickListener { private String[] mCodes; private HotkeyListener mHotkeyListener; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCodes = getResources().getStringArray(R.array.hotkey_codes); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Context context = getActivity(); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setItems(R.array.hotkey_labels, null); builder.setNeutralButton(R.string.close, null); AlertDialog dialog = builder.create(); // Handle ListView item clicks directly so that dialog is not dismissed dialog.getListView().setOnItemClickListener(this); return dialog; } public void setHotkeyListener(HotkeyListener hotkeyListener) { mHotkeyListener = hotkeyListener; } /** {@inheritDoc} */ public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (mHotkeyListener != null) { mHotkeyListener.onHotkey(mCodes[position]); } } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.fragment; import org.peterbaldwin.client.android.vlcremote.R; import org.peterbaldwin.vlcremote.intent.Intents; import org.peterbaldwin.vlcremote.loader.PlaylistLoader; import org.peterbaldwin.vlcremote.model.Playlist; import org.peterbaldwin.vlcremote.model.PlaylistItem; import org.peterbaldwin.vlcremote.model.Remote; import org.peterbaldwin.vlcremote.model.Status; import org.peterbaldwin.vlcremote.model.Track; import org.peterbaldwin.vlcremote.net.MediaServer; import org.peterbaldwin.vlcremote.widget.PlaylistAdapter; import android.app.Activity; import android.app.SearchManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.text.TextUtils; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class PlaylistFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Remote<Playlist>> { private static final int LOADER_PLAYLIST = 1; private Context mContext; private MediaServer mMediaServer; private TextView mEmptyView; private PlaylistAdapter mAdapter; private BroadcastReceiver mStatusReceiver; private String mCurrent; @Override public void onAttach(Activity activity) { super.onAttach(activity); mContext = activity; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.playlist, container, false); mAdapter = new PlaylistAdapter(); setListAdapter(mAdapter); mEmptyView = (TextView) view.findViewById(android.R.id.empty); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); registerForContextMenu(getListView()); if (mMediaServer != null) { getLoaderManager().initLoader(LOADER_PLAYLIST, null, this); } } @Override public void onResume() { super.onResume(); mStatusReceiver = new StatusReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(Intents.ACTION_STATUS); getActivity().registerReceiver(mStatusReceiver, filter); } @Override public void onPause() { getActivity().unregisterReceiver(mStatusReceiver); mStatusReceiver = null; super.onPause(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.playlist_options, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_refresh: reload(); return true; case R.id.menu_clear_playlist: mMediaServer.status().command.playback.empty(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (menuInfo instanceof AdapterContextMenuInfo) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; PlaylistItem item = mAdapter.getItem(info.position); MenuInflater inflater = getActivity().getMenuInflater(); inflater.inflate(R.menu.playlist_context, menu); MenuItem searchItem = menu.findItem(R.id.playlist_context_search); searchItem.setVisible(isSearchable(item)); } } private boolean isSearchable(PlaylistItem item) { if (item instanceof Track) { Track track = (Track) item; boolean hasTitle = !TextUtils.isEmpty(track.getTitle()); boolean hasArtist = !TextUtils.isEmpty(track.getArtist()); return hasTitle && hasArtist; } else { return false; } } @Override public boolean onContextItemSelected(MenuItem menuItem) { ContextMenuInfo menuInfo = menuItem.getMenuInfo(); if (menuInfo instanceof AdapterContextMenuInfo) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; if (info.position < mAdapter.getCount()) { PlaylistItem item = mAdapter.getItem(info.position); switch (menuItem.getItemId()) { case R.id.playlist_context_play: selectItem(item); return true; case R.id.playlist_context_dequeue: removeItem(item); return true; case R.id.playlist_context_search: searchForItem(item); return true; } } } return super.onContextItemSelected(menuItem); } public void setMediaServer(MediaServer mediaServer) { mMediaServer = mediaServer; reload(); } private void removeItem(PlaylistItem item) { int id = item.getId(); // TODO: Register observer and notify observers when playlist item is // deleted mMediaServer.status().command.playback.delete(id); } private void searchForItem(PlaylistItem item) { if (item instanceof Track) { Track track = (Track) item; String title = track.getTitle(); String artist = track.getArtist(); String query = artist + " " + title; Intent intent = new Intent(MediaStore.INTENT_ACTION_MEDIA_SEARCH); intent.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist); intent.putExtra(MediaStore.EXTRA_MEDIA_TITLE, title); intent.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, "audio/*"); intent.putExtra(SearchManager.QUERY, query); String chooserTitle = getString(R.string.mediasearch, title); startActivity(Intent.createChooser(intent, chooserTitle)); } } private void showError(CharSequence message) { Context context = getActivity(); Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG); toast.show(); } private void selectItem(PlaylistItem item) { mMediaServer.status().command.playback.play(item.getId()); } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); PlaylistItem item = (PlaylistItem) l.getItemAtPosition(position); selectItem(item); } public void selectCurrentTrack() { final int count = mAdapter.getCount(); for (int position = 0; position < count; position++) { PlaylistItem item = mAdapter.getItem(position); if (item instanceof Track) { Track track = (Track) item; if (track.isCurrent()) { // Scroll to current track ListView listView = getListView(); listView.setSelection(position); break; } } } } @Override public void setEmptyText(CharSequence text) { mEmptyView.setText(text); } /** {@inheritDoc} */ public Loader<Remote<Playlist>> onCreateLoader(int id, Bundle args) { setEmptyText(getText(R.string.loading)); String search = ""; return new PlaylistLoader(mContext, mMediaServer, search); } /** {@inheritDoc} */ public void onLoadFinished(Loader<Remote<Playlist>> loader, Remote<Playlist> remote) { boolean wasEmpty = mAdapter.isEmpty(); boolean hasError = (remote.error != null); mAdapter.setItems(remote.data); if (hasError) { setEmptyText(getText(R.string.connection_error)); showError(String.valueOf(remote.error)); } else { setEmptyText(getText(R.string.emptyplaylist)); } if (wasEmpty) { selectCurrentTrack(); } } /** {@inheritDoc} */ public void onLoaderReset(Loader<Remote<Playlist>> loader) { mAdapter.setItems(null); } void onStatusChanged(Status status) { String title = status.getTrack().getTitle(); if (!TextUtils.equals(title, mCurrent)) { // Reload the playlist and scroll to the new current track mCurrent = title; reload(); } } public void reload() { if (mMediaServer != null) { getLoaderManager().restartLoader(LOADER_PLAYLIST, null, this); } } private class StatusReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Status status = (Status) intent.getSerializableExtra(Intents.EXTRA_STATUS); onStatusChanged(status); } } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.fragment; import org.peterbaldwin.client.android.vlcremote.R; import org.peterbaldwin.vlcremote.net.MediaServer; import android.content.Context; import android.os.Bundle; import android.os.Vibrator; import android.support.v4.app.Fragment; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; public class NavigationFragment extends Fragment implements View.OnTouchListener, GestureDetector.OnGestureListener { private MediaServer mMediaServer; private GestureDetector mGestureDetector; @Override public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.navigation_fragment, root, false); Context context = view.getContext(); GestureDetector.OnGestureListener listener = this; mGestureDetector = new GestureDetector(context, listener); view.findViewById(R.id.overlay).setOnTouchListener(this); return view; } public void setMediaServer(MediaServer mediaServer) { mMediaServer = mediaServer; } /** {@inheritDoc} */ public boolean onTouch(View v, MotionEvent event) { return mGestureDetector.onTouchEvent(event); } /** {@inheritDoc} */ public boolean onSingleTapUp(MotionEvent e) { mMediaServer.status().command.key("nav-activate"); vibrate(); return true; } /** {@inheritDoc} */ public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (Math.abs(velocityX) > Math.abs(velocityY)) { if (velocityX > 0) { mMediaServer.status().command.key("nav-right"); vibrate(); return true; } else if (velocityX < 0) { mMediaServer.status().command.key("nav-left"); vibrate(); return true; } } else if (Math.abs(velocityY) > Math.abs(velocityX)) { if (velocityY > 0) { mMediaServer.status().command.key("nav-down"); vibrate(); return true; } else if (velocityY < 0) { mMediaServer.status().command.key("nav-up"); vibrate(); return true; } } return false; } @SuppressWarnings("unchecked") private <T> T getSystemService(String name) { Context context = getActivity(); return (T) context.getSystemService(Context.VIBRATOR_SERVICE); } private void vibrate() { Vibrator v = getSystemService(Context.VIBRATOR_SERVICE); if (v != null) { v.vibrate(100); } } /** {@inheritDoc} */ public boolean onDown(MotionEvent e) { return false; } /** {@inheritDoc} */ public void onShowPress(MotionEvent e) { } /** {@inheritDoc} */ public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } /** {@inheritDoc} */ public void onLongPress(MotionEvent e) { } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.fragment; import org.peterbaldwin.client.android.vlcremote.R; import org.peterbaldwin.vlcremote.intent.Intents; import org.peterbaldwin.vlcremote.model.Status; import org.peterbaldwin.vlcremote.net.MediaServer; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; public final class ButtonsFragment extends Fragment implements View.OnClickListener { private static final String DIALOG_HOTKEYS = "hotkeys"; private MediaServer mMediaServer; private BroadcastReceiver mStatusReceiver; private ImageButton mButtonShuffle; private ImageButton mButtonRepeat; private boolean mRandom; private boolean mRepeat; private boolean mLoop; private View mHotkeysButton; public void setMediaServer(MediaServer mediaServer) { mMediaServer = mediaServer; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { return inflater.inflate(R.layout.frame_layout, parent, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); View view = getView(); mButtonShuffle = (ImageButton) view.findViewById(R.id.playlist_button_shuffle); mButtonRepeat = (ImageButton) view.findViewById(R.id.playlist_button_repeat); mHotkeysButton = view.findViewById(R.id.button_hotkeys); mButtonShuffle.setOnClickListener(this); mButtonRepeat.setOnClickListener(this); mHotkeysButton.setOnClickListener(this); } @Override public void onResume() { super.onResume(); mStatusReceiver = new StatusReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(Intents.ACTION_STATUS); getActivity().registerReceiver(mStatusReceiver, filter); } @Override public void onPause() { getActivity().unregisterReceiver(mStatusReceiver); mStatusReceiver = null; super.onPause(); } /** {@inheritDoc} */ public void onClick(View v) { switch (v.getId()) { case R.id.button_hotkeys: DialogFragment dialog = new HotkeyDialog(); dialog.show(getFragmentManager(), DIALOG_HOTKEYS); break; case R.id.playlist_button_shuffle: mMediaServer.status().command.playback.random(); mRandom = !mRandom; updateButtons(); break; case R.id.playlist_button_repeat: // Order: Normal -> Repeat -> Loop if (mRepeat) { // Switch to loop if (mLoop) { // Turn-off repeat mMediaServer.status().command.playback.repeat(); mRepeat = false; } else { // Manual transition: // This needs to be a two step process // because the commands will conflict // if they are issued too close together. // The transition is optimized when // switching from normal mode to repeat // to avoid the two step process when possible. // The UI is not updated until the // server responds to hide the // intermediate state. // Turn-on loop then turn-off repeat shortly after. mMediaServer.status().command.playback.loop().repeat(); } } else if (mLoop) { // Switch to normal // Turn-off loop mMediaServer.status().command.playback.loop(); mLoop = false; } else { // Turn-on repeat and turn-on loop to make the transition // from repeat to loop one step instead of two steps. // Loop has no effect when repeat is on. mMediaServer.status().command.playback.repeat().loop(); mRepeat = true; mLoop = true; } updateButtons(); break; } } private int getShuffleResId() { if (mRandom) { return R.drawable.ic_mp_shuffle_on_btn; } else { return R.drawable.ic_mp_shuffle_off_btn; } } private int getRepeatResId() { if (mRepeat) { return R.drawable.ic_mp_repeat_once_btn; } else if (mLoop) { return R.drawable.ic_mp_repeat_all_btn; } else { return R.drawable.ic_mp_repeat_off_btn; } } private void updateButtons() { mButtonShuffle.setImageResource(getShuffleResId()); mButtonRepeat.setImageResource(getRepeatResId()); } void onStatusChanged(Status status) { mRandom = status.isRandom(); mLoop = status.isLoop(); mRepeat = status.isRepeat(); updateButtons(); } private class StatusReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Status status = (Status) intent.getSerializableExtra(Intents.EXTRA_STATUS); onStatusChanged(status); } } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.fragment; import org.peterbaldwin.client.android.vlcremote.R; import org.peterbaldwin.vlcremote.intent.Intents; import org.peterbaldwin.vlcremote.model.Status; import org.peterbaldwin.vlcremote.net.MediaServer; import org.peterbaldwin.vlcremote.net.MediaServer.StatusRequest; import org.peterbaldwin.vlcremote.net.MediaServer.StatusRequest.CommandInterface; import org.peterbaldwin.vlcremote.net.MediaServer.StatusRequest.CommandInterface.PlaybackInterface; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; /** * Controls playback and displays progress. */ public class PlaybackFragment extends Fragment implements View.OnClickListener, OnSeekBarChangeListener { private BroadcastReceiver mStatusReceiver; private ImageButton mButtonPlaylistPause; private ImageButton mButtonPlaylistStop; private ImageButton mButtonPlaylistSkipForward; private ImageButton mButtonPlaylistSkipBackward; private ImageButton mButtonPlaylistSeekForward; private ImageButton mButtonPlaylistSeekBackward; private SeekBar mSeekPosition; private TextView mTextTime; private TextView mTextLength; private MediaServer mMediaServer; public void setMediaServer(MediaServer server) { mMediaServer = server; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.audio_player_common, container, false); mButtonPlaylistPause = setupImageButton(v, R.id.button_pause); mButtonPlaylistStop = setupImageButton(v, R.id.button_stop); mButtonPlaylistSkipForward = setupImageButton(v, R.id.button_skip_forward); mButtonPlaylistSkipBackward = setupImageButton(v, R.id.button_skip_backward); mButtonPlaylistSeekForward = setupImageButton(v, R.id.button_seek_forward); mButtonPlaylistSeekBackward = setupImageButton(v, R.id.button_seek_backward); mSeekPosition = (SeekBar) v.findViewById(R.id.seek_progress); mSeekPosition.setMax(100); mSeekPosition.setOnSeekBarChangeListener(this); mTextTime = (TextView) v.findViewById(R.id.text_time); mTextLength = (TextView) v.findViewById(R.id.text_length); return v; } private ImageButton setupImageButton(View v, int viewId) { ImageButton button = (ImageButton) v.findViewById(viewId); if (button != null) { button.setOnClickListener(this); } return button; } private StatusRequest status() { return mMediaServer.status(); } private CommandInterface command() { return status().command; } private PlaybackInterface playlist() { return command().playback; } /** {@inheritDoc} */ public void onClick(View v) { if (v == mButtonPlaylistPause) { playlist().pause(); } else if (v == mButtonPlaylistStop) { playlist().stop(); } else if (v == mButtonPlaylistSkipBackward) { playlist().previous(); } else if (v == mButtonPlaylistSkipForward) { playlist().next(); } else if (v == mButtonPlaylistSeekBackward) { command().seek(Uri.encode("-10")); } else if (v == mButtonPlaylistSeekForward) { command().seek(Uri.encode("+10")); } } /** {@inheritDoc} */ public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (seekBar == mSeekPosition) { if (fromUser) { seekPosition(); } } } /** {@inheritDoc} */ public void onStartTrackingTouch(SeekBar seekBar) { } /** {@inheritDoc} */ public void onStopTrackingTouch(SeekBar seekBar) { if (seekBar == mSeekPosition) { seekPosition(); } } private void seekPosition() { int position = mSeekPosition.getProgress(); command().seek(String.valueOf(position)); } @Override public void onResume() { super.onResume(); mStatusReceiver = new StatusReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(Intents.ACTION_STATUS); getActivity().registerReceiver(mStatusReceiver, filter); } @Override public void onPause() { getActivity().unregisterReceiver(mStatusReceiver); mStatusReceiver = null; super.onPause(); } void onStatusChanged(Status status) { int resId = status.isPlaying() ? R.drawable.ic_media_playback_pause : R.drawable.ic_media_playback_start; mButtonPlaylistPause.setImageResource(resId); int time = status.getTime(); int length = status.getLength(); mSeekPosition.setMax(length); mSeekPosition.setProgress(time); // Call setKeyProgressIncrement after calling setMax because the // implementation of setMax will automatically adjust the increment. mSeekPosition.setKeyProgressIncrement(3); String formattedTime = formatTime(time); mTextTime.setText(formattedTime); String formattedLength = formatTime(length); mTextLength.setText(formattedLength); } private static void doubleDigit(StringBuilder builder, long value) { builder.insert(0, value); if (value < 10) { builder.insert(0, '0'); } } /** * Formats a time. * * @param time the time (in seconds) * @return the formatted time. */ private static String formatTime(int time) { long seconds = time % 60; time /= 60; long minutes = time % 60; time /= 60; long hours = time; StringBuilder builder = new StringBuilder(8); doubleDigit(builder, seconds); builder.insert(0, ':'); if (hours == 0) { builder.insert(0, minutes); } else { doubleDigit(builder, minutes); builder.insert(0, ':'); builder.insert(0, hours); } return builder.toString(); } private class StatusReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intents.ACTION_STATUS.equals(action)) { Status status = (Status) intent.getSerializableExtra(Intents.EXTRA_STATUS); onStatusChanged(status); } } } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.fragment; import org.peterbaldwin.vlcremote.net.MediaServer; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.text.format.DateUtils; /** * Polls the server for status updates. */ public class StatusFragment extends Fragment implements Handler.Callback { private static final int TIMER = 1; private static final long INTERVAL = DateUtils.SECOND_IN_MILLIS; private Handler mHandler; private MediaServer mMediaServer; public void setMediaServer(MediaServer server) { mMediaServer = server; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = new Handler(this); } @Override public void onResume() { super.onResume(); startTimer(); } @Override public void onPause() { stopTimer(); super.onPause(); } private void startTimer() { mHandler.sendEmptyMessage(TIMER); } private void stopTimer() { mHandler.removeMessages(TIMER); } /** {@inheritDoc} */ public boolean handleMessage(Message msg) { switch (msg.what) { case TIMER: onTimerEvent(); return true; default: return false; } } private void onTimerEvent() { if (mMediaServer != null) { mMediaServer.status().programmatic().get(); } // Schedule the next timer event mHandler.sendEmptyMessageDelayed(TIMER, INTERVAL); } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.fragment; import org.peterbaldwin.client.android.vlcremote.R; import org.peterbaldwin.vlcremote.intent.Intents; import org.peterbaldwin.vlcremote.loader.ImageLoader; import org.peterbaldwin.vlcremote.model.Status; import org.peterbaldwin.vlcremote.model.Track; import org.peterbaldwin.vlcremote.net.MediaServer; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; public class ArtFragment extends Fragment implements LoaderCallbacks<Drawable> { private static final int LOADER_IMAGE = 1; private BroadcastReceiver mStatusReceiver; private MediaServer mMediaServer; private ImageView mImageView; private String mArtUrl; @Override public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.art_fragment, root, false); mImageView = (ImageView) view.findViewById(android.R.id.icon); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (mMediaServer != null) { getLoaderManager().initLoader(LOADER_IMAGE, Bundle.EMPTY, this); } } @Override public void onResume() { super.onResume(); mStatusReceiver = new StatusReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(Intents.ACTION_STATUS); getActivity().registerReceiver(mStatusReceiver, filter); } @Override public void onPause() { getActivity().unregisterReceiver(mStatusReceiver); mStatusReceiver = null; super.onPause(); } /** {@inheritDoc} */ public Loader<Drawable> onCreateLoader(int id, Bundle args) { Context context = getActivity(); Uri uri = mArtUrl != null ? Uri.parse(mArtUrl) : null; if (uri != null) { uri = resizeImage(uri); } return new ImageLoader(context, mMediaServer, uri); } /** {@inheritDoc} */ public void onLoadFinished(Loader<Drawable> loader, Drawable data) { mImageView.setImageDrawable(data); } /** {@inheritDoc} */ public void onLoaderReset(Loader<Drawable> loader) { mImageView.setImageResource(R.drawable.albumart_mp_unknown); } public void setMediaServer(MediaServer mediaServer) { mMediaServer = mediaServer; if (mMediaServer != null) { getLoaderManager().restartLoader(LOADER_IMAGE, Bundle.EMPTY, this); } } private void onStatusChanged(Status status) { Track track = status.getTrack(); String artUrl = track.getArtUrl(); if (mArtUrl == null || !mArtUrl.equals(artUrl)) { mArtUrl = artUrl; getLoaderManager().restartLoader(LOADER_IMAGE, null, this); } } private static Uri resizeImage(Uri uri) { if (isJamendoImage(uri)) { return resizeJamendoImage(uri); } else { return uri; } } private static boolean isJamendoImage(Uri uri) { return "imgjam.com".equals(uri.getAuthority()) && uri.getPathSegments().size() != 0 && uri.getLastPathSegment().matches("1\\.\\d+\\.jpg"); } private static Uri resizeJamendoImage(Uri uri) { String path = uri.getPath(); path = path.replace("/" + uri.getLastPathSegment(), "/1.400.jpg"); return uri.buildUpon().path(path).build(); } private class StatusReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (this != mStatusReceiver) { // TODO: Determine why this receiver is not unregistered return; } String action = intent.getAction(); if (Intents.ACTION_STATUS.equals(action)) { Status status = (Status) intent.getSerializableExtra(Intents.EXTRA_STATUS); onStatusChanged(status); } } } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.fragment; import org.peterbaldwin.client.android.vlcremote.R; import org.peterbaldwin.vlcremote.loader.DirectoryLoader; import org.peterbaldwin.vlcremote.model.Directory; import org.peterbaldwin.vlcremote.model.File; import org.peterbaldwin.vlcremote.model.Preferences; import org.peterbaldwin.vlcremote.model.Remote; import org.peterbaldwin.vlcremote.net.MediaServer; import org.peterbaldwin.vlcremote.widget.DirectoryAdapter; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class BrowseFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Remote<Directory>> { private interface Data { int DIRECTORY = 1; } private interface State { String DIRECTORY = "vlc:directory"; } private DirectoryAdapter mAdapter; private MediaServer mMediaServer; private String mDirectory = "~"; private Preferences mPreferences; private TextView mTitle; private TextView mEmpty; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); Context context = getActivity(); mPreferences = Preferences.get(context); if (savedInstanceState == null) { mDirectory = mPreferences.getBrowseDirectory(); } else { mDirectory = savedInstanceState.getString(State.DIRECTORY); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.browse, root, false); mTitle = (TextView) view.findViewById(android.R.id.title); mEmpty = (TextView) view.findViewById(android.R.id.empty); return view; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(State.DIRECTORY, mDirectory); } public void setMediaServer(MediaServer mediaServer) { mMediaServer = mediaServer; } @Override public void setEmptyText(CharSequence text) { mEmpty.setText(text); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Context context = getActivity(); mAdapter = new DirectoryAdapter(context); setListAdapter(mAdapter); registerForContextMenu(getListView()); if (mMediaServer != null) { getLoaderManager().initLoader(Data.DIRECTORY, Bundle.EMPTY, this); } } @Override public void onListItemClick(ListView l, View v, int position, long id) { File file = mAdapter.getItem(position); if (file.isDirectory()) { openDirectory(file); } else { mMediaServer.status().command.input.play(file.getMrl(), file.getOptions()); } } private void openDirectory(File file) { openDirectory(file.getPath()); } public void openDirectory(String path) { mDirectory = path; mAdapter.clear(); getLoaderManager().restartLoader(Data.DIRECTORY, null, this); } private boolean isDirectory(ContextMenuInfo menuInfo) { if (menuInfo instanceof AdapterContextMenuInfo) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; if (info.position < mAdapter.getCount()) { File file = mAdapter.getItem(info.position); return file.isDirectory(); } } return false; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.browse_options, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_refresh: getLoaderManager().restartLoader(Data.DIRECTORY, Bundle.EMPTY, this); return true; case R.id.menu_parent: openParentDirectory(); return true; case R.id.menu_home: mDirectory = mPreferences.getHomeDirectory(); getLoaderManager().restartLoader(Data.DIRECTORY, Bundle.EMPTY, this); return true; case R.id.menu_set_home: mPreferences.setHomeDirectory(mDirectory); showSetHomeToast(); return true; default: return super.onOptionsItemSelected(item); } } private void openParentDirectory() { for (int position = 0, n = mAdapter.getCount(); position < n; position++) { File file = mAdapter.getItem(position); if (file.isDirectory() && "..".equals(file.getName())) { openDirectory(file); return; } } // Open the list of drives if there is no parent directory entry openDirectory(""); } private void showSetHomeToast() { Context context = getActivity(); CharSequence message = getString(R.string.sethome, getTitle()); Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getActivity().getMenuInflater(); inflater.inflate(R.menu.browse_context, menu); menu.findItem(R.id.browse_context_open).setVisible(isDirectory(menuInfo)); menu.findItem(R.id.browse_context_stream).setVisible(!isDirectory(menuInfo)); } @Override public boolean onContextItemSelected(MenuItem item) { ContextMenuInfo menuInfo = item.getMenuInfo(); if (menuInfo instanceof AdapterContextMenuInfo) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; if (info.position < mAdapter.getCount()) { File file = mAdapter.getItem(info.position); switch (item.getItemId()) { case R.id.browse_context_open: openDirectory(file); return true; case R.id.browse_context_play: mMediaServer.status().command.input.play(file.getMrl(), file.getOptions()); return true; case R.id.browse_context_stream: mMediaServer.status().command.input.play(file.getMrl(), file.getStreamingOptions()); Intent intent = file.getIntentForStreaming(mMediaServer.getAuthority()); startActivity(intent); return true; case R.id.browse_context_enqueue: mMediaServer.status().command.input.enqueue(file.getMrl()); return true; } } } return super.onContextItemSelected(item); } /** {@inheritDoc} */ public Loader<Remote<Directory>> onCreateLoader(int id, Bundle args) { Context context = getActivity(); mPreferences.setBrowseDirectory(mDirectory); setEmptyText(getText(R.string.loading)); return new DirectoryLoader(context, mMediaServer, mDirectory); } /** {@inheritDoc} */ public void onLoadFinished(Loader<Remote<Directory>> loader, Remote<Directory> result) { mAdapter.setDirectory(result.data); setEmptyText(getText(R.string.connection_error)); setTitle(result.data != null ? result.data.getPath() : null); if (isEmptyDirectory(result.data)) { handleEmptyDirectory(); } } private void setTitle(CharSequence title) { mTitle.setText(title); } public CharSequence getTitle() { return mTitle.getText(); } private boolean isEmptyDirectory(Directory directory) { if (directory != null) { return directory.isEmpty(); } else { // The directory could not be retrieved return false; } } private void handleEmptyDirectory() { showEmptyDirectoryError(); openDirectory("~"); } private void showEmptyDirectoryError() { Context context = getActivity(); Toast toast = Toast.makeText(context, R.string.browse_empty, Toast.LENGTH_LONG); toast.show(); } /** {@inheritDoc} */ public void onLoaderReset(Loader<Remote<Directory>> loader) { mAdapter.setDirectory(null); } // TODO: Automatically reload directory when connection is restored }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.fragment; import org.peterbaldwin.client.android.vlcremote.R; import org.peterbaldwin.vlcremote.net.MediaServer; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; public class ServicesDiscoveryFragment extends ListFragment { private MediaServer mMediaServer; private String[] mServiceValues; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mServiceValues = getResources().getStringArray(R.array.service_values); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedInstanceState) { return inflater.inflate(R.layout.services_discovery_fragment, root, false); } @Override public void onListItemClick(ListView l, View v, int position, long id) { String value = mServiceValues[position]; mMediaServer.status().command.playback.sd(value); } public void setMediaServer(MediaServer server) { mMediaServer = server; } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.fragment; public interface HotkeyListener { void onHotkey(String key); }
Java
package org.peterbaldwin.vlcremote.fragment; import org.peterbaldwin.client.android.vlcremote.R; import org.peterbaldwin.vlcremote.intent.Intents; import org.peterbaldwin.vlcremote.model.Status; import org.peterbaldwin.vlcremote.net.MediaServer; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.SeekBar; public class VolumeFragment extends Fragment implements SeekBar.OnSeekBarChangeListener { private static final int MAX_VOLUME = 1024; private ImageView mIcon; private SeekBar mSeekBar; private MediaServer mMediaServer; private BroadcastReceiver mStatusReceiver; public void setMediaServer(MediaServer mediaServer) { mMediaServer = mediaServer; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.volume_fragment, root, false); mIcon = (ImageView) view.findViewById(android.R.id.icon); mSeekBar = (SeekBar) view.findViewById(android.R.id.progress); mSeekBar.setOnSeekBarChangeListener(this); return view; } /** {@inheritDoc} */ public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { setVolume(progress); } } /** {@inheritDoc} */ public void onStartTrackingTouch(SeekBar seekBar) { } /** {@inheritDoc} */ public void onStopTrackingTouch(SeekBar seekBar) { setVolume(seekBar.getProgress()); } private void setVolume(int value) { mMediaServer.status().command.volume(value); } void onVolumeChanged(int value) { mIcon.setImageResource(getVolumeImage(value)); mSeekBar.setProgress(value); } private static int getVolumeImage(int volume) { if (volume == 0) { return R.drawable.ic_media_volume_muted; } else if (volume < (MAX_VOLUME / 3)) { return R.drawable.ic_media_volume_low; } else if (volume < (2 * MAX_VOLUME / 3)) { return R.drawable.ic_media_volume_medium; } else { return R.drawable.ic_media_volume_high; } } @Override public void onResume() { super.onResume(); mStatusReceiver = new StatusReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(Intents.ACTION_STATUS); getActivity().registerReceiver(mStatusReceiver, filter); } @Override public void onPause() { getActivity().unregisterReceiver(mStatusReceiver); mStatusReceiver = null; super.onPause(); } private class StatusReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intents.ACTION_STATUS.equals(action)) { Status status = (Status) intent.getSerializableExtra(Intents.EXTRA_STATUS); onVolumeChanged(status.getVolume()); } } } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.fragment; import org.peterbaldwin.client.android.vlcremote.R; import org.peterbaldwin.vlcremote.intent.Intents; import org.peterbaldwin.vlcremote.model.Status; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class InfoFragment extends Fragment { private BroadcastReceiver mStatusReceiver; private TextView mArtist; private TextView mAlbum; private TextView mTrack; @Override public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.info_fragment, root, false); mArtist = (TextView) view.findViewById(R.id.artist); mAlbum = (TextView) view.findViewById(R.id.album); mTrack = (TextView) view.findViewById(R.id.track); return view; } @Override public void onResume() { super.onResume(); mStatusReceiver = new StatusReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(Intents.ACTION_STATUS); getActivity().registerReceiver(mStatusReceiver, filter); } @Override public void onPause() { getActivity().unregisterReceiver(mStatusReceiver); mStatusReceiver = null; super.onPause(); } void onStatusChanged(Status status) { setText(mArtist, status.getTrack().getArtist()); setText(mAlbum, status.getTrack().getAlbum()); setText(mTrack, status.getTrack().getTitle()); } private static void setText(TextView textView, String value) { textView.setText(value); } private class StatusReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intents.ACTION_STATUS.equals(action)) { // TODO: Filter by authority Status status = (Status) intent.getSerializableExtra(Intents.EXTRA_STATUS); onStatusChanged(status); } } } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.model; /** * Light-weight wrapper for data that is loaded from a remote server. * <p> * Holds the remote data, or an error if there was a problem receiving the data. */ public final class Remote<T> { public final T data; public final Throwable error; private Remote(T data, Throwable error) { this.data = data; this.error = error; } public static <T> Remote<T> data(T data) { return new Remote<T>(data, null); } public static <T> Remote<T> error(Throwable t) { return new Remote<T>(null, t); } }
Java
/*- * Copyright (C) 2009 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.model; import android.text.TextUtils; import java.io.Serializable; public final class Track implements PlaylistItem, Serializable { private static final long serialVersionUID = 1L; private int mId; private boolean mCurrent; private String mUri; private String mName; private long mDuration; private String mTitle; private String mArtist; private String mGenre; private String mCopyright; private String mAlbum; private String mTrack; private String mDescription; private String mRating; private String mDate; private String mUrl; private String mLanguage; private String mNowPlaying; private String mPublisher; private String mEncodedBy; private String mArtUrl; private String mTrackId; public int getId() { return mId; } public void setId(int id) { mId = id; } /** {@inheritDoc} */ public boolean isCurrent() { return mCurrent; } /** {@inheritDoc} */ public CharSequence getText1() { return isNotEmpty(mTitle) ? mTitle : isNotEmpty(mName) ? mName : ""; } /** {@inheritDoc} */ public CharSequence getText2() { return isNotEmpty(mArtist) ? mArtist : ""; } public void setCurrent(boolean current) { mCurrent = current; } public String getUri() { return mUri; } public void setUri(String uri) { mUri = uri; } public String getName() { return mName; } public void setName(String name) { mName = name; } public long getDuration() { return mDuration; } public void setDuration(long duration) { mDuration = duration; } public String getTitle() { return mTitle; } public void setTitle(String title) { this.mTitle = title; } public String getArtist() { return mArtist; } public void setArtist(String artist) { this.mArtist = artist; } public String getGenre() { return mGenre; } public void setGenre(String genre) { this.mGenre = genre; } public String getCopyright() { return mCopyright; } public void setCopyright(String copyright) { this.mCopyright = copyright; } public String getAlbum() { return mAlbum; } public void setAlbum(String album) { this.mAlbum = album; } public String getTrack() { return mTrack; } public void setTrack(String track) { this.mTrack = track; } public String getDescription() { return mDescription; } public void setDescription(String description) { this.mDescription = description; } public String getRating() { return mRating; } public void setRating(String rating) { this.mRating = rating; } public String getDate() { return mDate; } public void setDate(String date) { this.mDate = date; } public String getUrl() { return mUrl; } public void setUrl(String url) { this.mUrl = url; } public String getLanguage() { return mLanguage; } public void setLanguage(String language) { this.mLanguage = language; } public String getNowPlaying() { return mNowPlaying; } public void setNowPlaying(String nowPlaying) { this.mNowPlaying = nowPlaying; } public String getPublisher() { return mPublisher; } public void setPublisher(String publisher) { this.mPublisher = publisher; } public String getEncodedBy() { return mEncodedBy; } public void setEncodedBy(String encodedBy) { this.mEncodedBy = encodedBy; } public String getArtUrl() { return mArtUrl; } public void setArtUrl(String art_url) { this.mArtUrl = art_url; } public String getTrackId() { return mTrackId; } public void setTrackId(String trackId) { this.mTrackId = trackId; } @Override public String toString() { // XSPF playlists set the title, but use a URL for the name. // M3U playlists don't have a title, but set a good name. return mTitle != null ? mTitle : mName; } private static boolean isNotEmpty(CharSequence text) { return !TextUtils.isEmpty(text); } }
Java
/*- * Copyright (C) 2009 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.model; import java.util.ArrayList; @SuppressWarnings("serial") public final class Directory extends ArrayList<File> { public Directory() { } public Directory(int capacity) { super(capacity); } public String getPath() { // Compute the path from the .. entry for (File file : this) { String name = file.getName(); String path = file.getPath(); if (name != null && path != null && name.equals("..") && path.endsWith("..")) { int length = path.length(); length -= "..".length(); return path.substring(0, length); } } return null; } }
Java
/*- * Copyright (C) 2009 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.model; import java.io.Serializable; public final class Status implements Serializable { private static final long serialVersionUID = 1L; private int mVolume; private int mLength; private int mTime; private String mState; private double mPosition; private boolean mFullscreen; private boolean mRandom; private boolean mLoop; private boolean mRepeat; private final Track mTrack = new Track(); public int getVolume() { return mVolume; } /** * Returns the length of the media in seconds. */ public int getLength() { return mLength; } public int getTime() { return mTime; } public boolean isPlaying() { return "playing".equals(mState); } public boolean isPaused() { return "paused".equals(mState); } public boolean isStopped() { return "stop".equals(mState); } public String getState() { return mState; } /** * Returns the playback position as a percentage. */ public double getPosition() { return mPosition; } public boolean isFullscreen() { return mFullscreen; } public boolean isRandom() { return mRandom; } public boolean isLoop() { return mLoop; } public boolean isRepeat() { return mRepeat; } public void setVolume(int volume) { mVolume = volume; } public void setLength(int length) { mLength = length; } public void setTime(int time) { mTime = time; } public void setState(String state) { mState = state; } public void setPosition(double position) { mPosition = position; } public void setFullscreen(boolean fullscreen) { mFullscreen = fullscreen; } public void setRandom(boolean random) { mRandom = random; } public void setLoop(boolean loop) { mLoop = loop; } public void setRepeat(boolean repeat) { mRepeat = repeat; } public Track getTrack() { return mTrack; } }
Java
/*- * Copyright (C) 2009 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.model; import android.content.Intent; import android.net.Uri; import android.webkit.MimeTypeMap; import java.util.ArrayList; import java.util.Collections; import java.util.List; public final class File { private static final MimeTypeMap sMimeTypeMap = MimeTypeMap.getSingleton(); private static String parseExtension(String path) { int index = path.lastIndexOf('.'); if (index != -1) { return path.substring(index + 1); } else { return null; } } private String mType; private Long mSize; private String mDate; private String mPath; private String mName; private String mExtension; public File(String type, Long size, String date, String path, String name, String extension) { mType = type; mSize = size; mDate = date; mPath = path; mName = name; mExtension = extension != null ? extension : path != null ? parseExtension(path) : null; } public String getType() { return mType; } public void setType(String type) { mType = type; } public boolean isDirectory() { // Type is "directory" in VLC 1.0 and "dir" in VLC 1.1 return "directory".equals(mType) || "dir".equals(mType); } public boolean isImage() { String mimeType = getMimeType(); return mimeType != null && mimeType.startsWith("image/"); } public Long getSize() { return mSize; } public void setSize(Long size) { mSize = size; } public String getDate() { return mDate; } public void setDate(String date) { mDate = date; } public String getPath() { return mPath; } public String getMrl() { if (isImage()) { return "fake://"; } else { java.io.File file = new java.io.File(mPath); Uri uri = Uri.fromFile(file); return uri.toString(); } } public List<String> getOptions() { if (isImage()) { return Collections.singletonList(":fake-file=" + getPath()); } else { return Collections.emptyList(); } } public List<String> getStreamingOptions() { List<String> options = new ArrayList<String>(getOptions()); String mimeType = getMimeType(); if (mimeType != null && mimeType.startsWith("audio/")) { options.add(":sout=#transcode{acodec=vorb,ab=128}:standard{access=http,mux=ogg,dst=0.0.0.0:8000}"); } else { options.add(":sout=#transcode{vcodec=mp4v,vb=384,acodec=mp4a,ab=64,channels=2,fps=25,venc=x264{profile=baseline,keyint=50,bframes=0,no-cabac,ref=1,vbv-maxrate=4096,vbv-bufsize=1024,aq-mode=0,no-mbtree,partitions=none,no-weightb,weightp=0,me=dia,subme=0,no-mixed-refs,no-8x8dct,trellis=0,level1.3},vfilter=canvas{width=320,height=180,aspect=320:180,padd},senc,soverlay}:rtp{sdp=rtsp://0.0.0.0:5554/stream.sdp,caching=4000}}"); } return options; } public Intent getIntentForStreaming(String authority) { Intent intent = new Intent(Intent.ACTION_VIEW); String mimeType = getMimeType(); if (mimeType != null && mimeType.startsWith("audio/")) { Uri.Builder builder = new Uri.Builder(); builder.scheme("rtsp"); builder.encodedAuthority(swapPortNumber(authority, 5554)); builder.path("stream.sdp"); Uri data = builder.build(); intent.setData(data); } else { Uri.Builder builder = new Uri.Builder(); builder.scheme("http"); builder.encodedAuthority(swapPortNumber(authority, 8000)); Uri data = builder.build(); intent.setDataAndType(data, "application/ogg"); } return intent; } public void setPath(String path) { mPath = path; if (mExtension == null && path != null) { mExtension = parseExtension(path); } } public String getName() { return mName; } public void setName(String name) { mName = name; } public String getExtension() { return mExtension; } public void setExtension(String extension) { mExtension = extension; } public String getMimeType() { if (mExtension != null) { // See http://code.google.com/p/android/issues/detail?id=8806 String extension = mExtension.toLowerCase(); return sMimeTypeMap.getMimeTypeFromExtension(extension); } else { return null; } } @Override public String toString() { return mName; } private static String removePortNumber(String authority) { int index = authority.lastIndexOf(':'); if (index != -1) { // Remove port number authority = authority.substring(0, index); } return authority; } private static String swapPortNumber(String authority, int port) { return removePortNumber(authority) + ":" + port; } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.model; import org.json.JSONArray; import org.json.JSONException; import android.content.Context; import android.content.SharedPreferences; import android.text.format.DateUtils; import java.util.ArrayList; import java.util.List; /** * Convenience class for reading and writing application preferences. */ public final class Preferences { private static final String PREFERENCES = "preferences"; private static final String PREFERENCE_SERVER = "server"; private static final String PREFERENCE_REMEMBERED_SERVERS = "remembered_servers"; private static final String PREFERENCE_BROWSE_DIRECTORY = "browse_directory"; private static final String PREFERENCE_HOME_DIRECTORY = "home_directory"; private static final String PREFERENCE_RESUME_ON_IDLE = "resume_on_idle"; private SharedPreferences mPreferences; public Preferences(SharedPreferences preferences) { mPreferences = preferences; } public static Preferences get(Context context) { return new Preferences(context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE)); } public boolean setResumeOnIdle() { SharedPreferences.Editor editor = mPreferences.edit(); editor.putLong(PREFERENCE_RESUME_ON_IDLE, System.currentTimeMillis()); return editor.commit(); } /** * Returns {@code true} if {@link #setResumeOnIdle()} was called in the last * hour. */ public boolean isResumeOnIdleSet() { long start = mPreferences.getLong(PREFERENCE_RESUME_ON_IDLE, 0L); long end = System.currentTimeMillis(); return start < end && (end - start) < DateUtils.HOUR_IN_MILLIS; } public boolean clearResumeOnIdle() { SharedPreferences.Editor editor = mPreferences.edit(); editor.remove(PREFERENCE_RESUME_ON_IDLE); return editor.commit(); } public String getAuthority() { return mPreferences.getString(PREFERENCE_SERVER, null); } public String getHomeDirectory() { return mPreferences.getString(PREFERENCE_HOME_DIRECTORY, "~"); } public String getBrowseDirectory() { return mPreferences.getString(PREFERENCE_BROWSE_DIRECTORY, "~"); } public boolean setAuthority(String authority) { return mPreferences.edit().putString(PREFERENCE_SERVER, authority).commit(); } public boolean setHomeDirectory(String dir) { return mPreferences.edit().putString(PREFERENCE_HOME_DIRECTORY, dir).commit(); } public boolean setBrowseDirectory(String dir) { return mPreferences.edit().putString(PREFERENCE_BROWSE_DIRECTORY, dir).commit(); } public ArrayList<String> getRememberedServers() { return fromJSONArray(mPreferences.getString(PREFERENCE_REMEMBERED_SERVERS, "[]")); } public boolean setRemeberedServers(List<String> rememberedServers) { SharedPreferences.Editor editor = mPreferences.edit(); editor.putString(PREFERENCE_REMEMBERED_SERVERS, toJSONArray(rememberedServers)); return editor.commit(); } private static String toJSONArray(List<String> list) { JSONArray array = new JSONArray(list); return array.toString(); } private static ArrayList<String> fromJSONArray(String json) { try { JSONArray array = new JSONArray(json); int n = array.length(); ArrayList<String> list = new ArrayList<String>(n); for (int i = 0; i < n; i++) { String element = array.getString(i); list.add(element); } return list; } catch (JSONException e) { return new ArrayList<String>(0); } } }
Java
/*- * Copyright (C) 2009 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.model; import java.util.ArrayList; public final class Playlist extends ArrayList<PlaylistItem> implements PlaylistItem { private static final long serialVersionUID = 1L; private final int mId; private final String mName; public Playlist(int id, String name) { mId = id; mName = name; } public int getId() { return mId; } public String getName() { return mName; } /** {@inheritDoc} */ public boolean isCurrent() { return false; } /** {@inheritDoc} */ public CharSequence getText1() { return mName; } /** {@inheritDoc} */ public CharSequence getText2() { return ""; } }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.vlcremote.model; /** * Abstraction for any item that can appear in a playlist. */ public interface PlaylistItem { int getId(); String getName(); boolean isCurrent(); CharSequence getText1(); CharSequence getText2(); }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.client.android.vlcremote; /** * Alias for backwards-compatibility. */ public class PlaybackActivity extends org.peterbaldwin.vlcremote.app.PlaybackActivity { }
Java
/*- * Copyright (C) 2011 Peter Baldwin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.peterbaldwin.client.android.vlcremote; /** * Alias for backwards-compatibility. */ public class MediaAppWidgetProvider extends org.peterbaldwin.vlcremote.appwidget.MediaAppWidgetProvider { }
Java
public class Profesor extends Persona implements Evaluar { private String titulo_acam; public Profesor(){} public Profesor(long cedula, String nombre, String apellido,String t) { super(cedula, nombre, apellido); this.titulo_acam = t; } public String getTitulo_acam() { return titulo_acam; } public void setTitulo_acam(String titulo_acam) { this.titulo_acam = titulo_acam; } public void EvaluarEstudiante(Estudiante e) { float t = 0; float []n = e.getNotas(); for(int i = 0;i < 3;i++) t += n[i]; e.setNota_final(t/3); e.setEstado((e.getNota_final() >= 10 ? true : false)); } }
Java
import java.awt.*; import javax.swing.*; import com.cloudgarden.layout.AnchorLayout; import info.clearthought.layout.TableLayout; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.WindowConstants; import javax.swing.border.BevelBorder; import javax.swing.border.LineBorder; import javax.swing.SwingUtilities; import java.awt.*; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. * @param <JPanelConFondo> */ public class Acceso_pantalla extends javax.swing.JFrame { private JPanel jPanel1; private JButton jButton1; private JPasswordField Txtpass; private JTextArea jTextArea2; private JTextArea jTextArea1; private JTextField txtlog; private Acceso acc = new Acceso(); ActionListener Permitir = new ActionListener() { public void actionPerformed(ActionEvent e) { if((txtlog.getText().compareTo(acc.getLog()) == 0 ) && (txtlog.getText().compareTo(acc.getLog())) == 0) Cerrar(); else JOptionPane.showMessageDialog(null,"Acceso Denegado", "Error", JOptionPane.ERROR_MESSAGE); } }; public void Cerrar() { FrameSeccion fs = new FrameSeccion(); fs.setVisible(true); fs.setLocationRelativeTo(null); this.dispose(); } public Acceso_pantalla() { super(); initGUI(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); this.setTitle("Acceso al Sistema"); { jPanel1 = new JPanel(); getContentPane().add(jPanel1); jPanel1.setBounds(32, 20, 230, 152); jPanel1.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); jPanel1.setOpaque(false); jPanel1.setLayout(null); jPanel1.addFocusListener(new FocusAdapter() { }); { txtlog = new JTextField(); jPanel1.add(txtlog); txtlog.setBounds(43, 30, 138, 21); txtlog.addFocusListener(new FocusAdapter() { }); } { jTextArea1 = new JTextArea(); jPanel1.add(jTextArea1); jTextArea1.setText("Login"); jTextArea1.setBounds(81, 12, 60, 19); jTextArea1.setOpaque(false); jTextArea1.setFont(new java.awt.Font("Courier 10 Pitch",1,16)); jTextArea1.setEditable(false); } { jTextArea2 = new JTextArea(); jPanel1.add(jTextArea2); jTextArea2.setText("Password"); jTextArea2.setOpaque(false); jTextArea2.setBounds(68, 58, 90, 19); jTextArea2.setFont(new java.awt.Font("Courier 10 Pitch",1,16)); jTextArea2.setEditable(false); } { jButton1 = new JButton(); jPanel1.add(jButton1); jButton1.setText("Aceptar"); jButton1.setBounds(63, 107, 102, 25); jButton1.addActionListener(Permitir); } { Txtpass = new JPasswordField(); jPanel1.add(Txtpass); Txtpass.setBounds(43, 75, 138, 21); Txtpass.addFocusListener(new FocusAdapter() { }); } } pack(); this.setSize(306, 227); } catch (Exception e) { e.printStackTrace(); } } }
Java
import java.io.*; import java.util.*; import javax.swing.JOptionPane; public class Control { private BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); boolean prof_registrado = false; Seccion sec; public Control() { super(); this.sec = new Seccion(); } //*************************************** PROCESAR SECCION ******************************************** public void ProcesarSeccion() { int opt = 0; boolean seg; System.out.print("Ingrese el numero de la seccion : "); try { String num_sec = in.readLine(); this.sec.setNum_secc(num_sec); }catch(IOException e){} do { do { System.out.println("\nRegistro Academico\n"); System.out.print("(1)Incluir Profesor." + "\n(2)Inscribir Estudiantes." + "\n(3)Mostar Profesor." + "\n(4)Aplicar Evaluacion." + "\n(5)Retirar Estudiante." + "\n(6)Buscar Estudiante." + "\n(7)Promedio de notas." + "\n(8)Listado de Estudiantes." + "\n(9)Listado de Estudiantes Aprobados." + "\n(10)Listado de Estudiantes Aplazados." + "\n(0)Salir." +"\nOpcion :"); seg = false; try { opt = Integer.parseInt(in.readLine()); if(opt < 0 || opt > 10) { System.out.println("Opcion invalida!"); seg = true; } } catch(Exception e) { System.out.println("Opcion invalida!"); seg = true; } }while(seg); limpiar(); switch(opt) { case 1: IncluirProfesor(); break; case 2: InscribirEstudiante(); break; case 3: Mostar_Profesor(); break; case 4: AplicarEvaluacion(); break; case 5: RetirarEstudiante(); break; case 6: BuscarEstudiante(); break; case 7: MostrarPromedio(); break; case 8: ListarEstudiante(); break; case 9: ListarEstudiantesAprob(); break; case 10: ListarEstudiantesAplazados(); break; } }while(opt != 0); } public void limpiar() { for (int i=0; i<15;i++) System.out.println(); } public void MostrarPromedio() { if(this.sec.NumeroEstudiante() == 0) System.out.println("No existen estudiantes registrados!"); else System.out.println("Promedio de la seccion : " + this.sec.Promedio()); } public void AplicarEvaluacion() { if(!prof_registrado) System.out.println("Debe registrar un Profesor!"); else if(this.sec.NumeroEstudiante() == 0) System.out.println("No existen estudiantes registrados!"); else { this.sec.AplicarEvaluaciones(); this.sec.EvaluarEstuduantes(); System.out.println("La evaluacion fue realizada con exito!"); } } public void BuscarEstudiante() { if(this.sec.NumeroEstudiante() == 0) System.out.println("No existen estudiantes registrados!"); else { System.out.println("Ingrese la cedula : "); try { int i = this.sec.Buscar((long)Integer.parseInt(in.readLine())); if(i == -1) JOptionPane.showMessageDialog(null,"El estudiante no existe!", "Advertencia", JOptionPane.WARNING_MESSAGE); else { System.out.println("Cedula : " + this.sec.getEstudiante(i).getCedula()); System.out.println("Nombre : " + this.sec.getEstudiante(i).getNombre()); System.out.println("Apellido : " + this.sec.getEstudiante(i).getApellido()); } } catch(Exception e) { System.out.println("Se produjo un ERROR!."); } } } public void RetirarEstudiante() { if(this.sec.NumeroEstudiante() == 0) System.out.println("No existen estudiantes registrados!"); else { System.out.println("Ingrese la cedula : "); try { int i = this.sec.Buscar((long)Integer.parseInt(in.readLine())); if(i == -1) System.out.println("El estudiante no existe!"); else { this.sec.RetirarEstudiante(i); System.out.println("Estudiante eliminado correctamente!"); } } catch(Exception e) { System.out.println("Se produjo un ERROR!."); } } } public void ListarEstudiantesAprob() { boolean imp = true; if(this.sec.NumeroEstudiante() == 0) { System.out.println("No existen estudiantes registrados!"); Imprimir_en_TXT("Estudiantes Aprobados.txt","No existen estudiantes Aprobados!",true); } else { System.out.println("Estudiantes Aprobados :"); Imprimir_en_TXT("Estudiantes Aprobados.txt","Estudiantes Aprobados :",true); Vector<Estudiante> Est = sec.getEstudiantes(); for(int i = 0;i < Est.size();i++) if(Est.elementAt(i).getEstado()) { System.out.println(Est.elementAt(i).getCedula() + " " + Est.elementAt(i).getApellido() + " " + Est.elementAt(i).getNombre() + " " + Est.elementAt(i).getNota_final()); Imprimir_en_TXT("Estudiantes Aprobados.txt",Est.elementAt(i).getCedula() + " " + Est.elementAt(i).getApellido() + " " + Est.elementAt(i).getNombre() + " " + Est.elementAt(i).getNota_final(),false); imp = false; } if(imp)System.out.println("No existen estudiantes Aprobados!"); } } public void ListarEstudiantesAplazados() { boolean imp = true; if(this.sec.NumeroEstudiante() == 0) { System.out.println("No existen estudiantes registrados!"); Imprimir_en_TXT("Estudiantes Aplazados.txt","No existen estudiantes registrados!",true); } else { System.out.println("Estudiantes Aplazados :"); Imprimir_en_TXT("Estudiantes Aplazados.txt","Estudiantes Aplazados :",true); Vector<Estudiante> Est = sec.getEstudiantes(); for(int i = 0;i < Est.size();i++) if(!Est.elementAt(i).getEstado()) { System.out.println(Est.elementAt(i).getCedula() + " " + Est.elementAt(i).getApellido() + " " + Est.elementAt(i).getNombre() + " " + Est.elementAt(i).getNota_final()); Imprimir_en_TXT("Estudiantes Aplazados.txt",Est.elementAt(i).getCedula() + " " + Est.elementAt(i).getApellido() + " " + Est.elementAt(i).getNombre() + " " + Est.elementAt(i).getNota_final(),false); imp = false; } if(imp)System.out.println("No existen estudiantes Aplazados!"); } } public void ListarEstudiante() { if(this.sec.NumeroEstudiante() == 0) System.out.println("No existen estudiantes registrados!"); else { String str = ""; int x; boolean seg; do { seg = false; System.out.println("Estudiantes ordenados por :" + "\n(1)Cedula" + "\n(2)Notas" + "\nOpcion :"); try { x = Integer.parseInt(in.readLine()); if(x <= 0) { System.out.println("Debe ingresar un numero valido!"); seg = true; } else if(x == 1) { sec.OrdenarEstudianteCed(); str = "Cedula:"; } else { sec.OrdenarEstudianteNota(); str = "Notas:"; } } catch(Exception e) { System.out.println("Debe ingresar un numero valido!"); seg = true; } }while(seg); System.out.println("Estudiantes Inscritos ordenados por " + str + " :"); Imprimir_en_TXT("Estudiantes ordenados por " + str + ".txt","Estudiantes Inscritos ordenados por " + str + " :",true); Vector<Estudiante> Est = sec.getEstudiantes(); for(int i = 0;i < Est.size();i++) { System.out.println(Est.elementAt(i).getCedula() + " " + Est.elementAt(i).getApellido() + " " + Est.elementAt(i).getNombre() + " " + Est.elementAt(i).getNota_final()); Imprimir_en_TXT("Estudiantes ordenados por " + str + ".txt",Est.elementAt(i).getCedula() + " " + Est.elementAt(i).getApellido() + " " + Est.elementAt(i).getNombre() + " " + Est.elementAt(i).getNota_final(),false); } } } public void InscribirEstudiante() { int n = 0; String c = "",nomb = "",a = ""; boolean seg; do { System.out.print("Ingrese el numero de estudiantes a inscribir :"); seg = false; try { n = Integer.parseInt(in.readLine()); if(n <= 0) { System.out.println("Debe ingresar un numero valido!"); seg = true; } } catch(Exception e) { System.out.println("Debe ingresar un numero valido!"); seg = true; } }while(seg); while(n-- > 0) { System.out.println("Ingrese los datos del Estudiante:"); try { System.out.print("Cedula : ");c = in.readLine(); if(this.sec.Buscar((long)Integer.parseInt(c)) == -1) { System.out.print("Nombre : ");nomb = in.readLine(); System.out.print("Apellido : ");a = in.readLine(); Estudiante e = new Estudiante((long)Integer.parseInt(c),nomb,a); this.sec.InscribirEstudiantes(e); } else { System.out.println("Ya existe un estudiante con cedula " + c); n++; } } catch(Exception e) { System.out.println("Se produjo un ERROR en la lectura de los datos."); n++; } } } public void IncluirProfesor() { if(prof_registrado) { System.out.println("El profesor ya fue registrado!"); } else { String c,n,a,t; System.out.println("Ingrese los datos del profesor:"); try { System.out.print("Cedula : ");c = in.readLine(); System.out.print("Nombre : ");n = in.readLine(); System.out.print("Apellido : ");a = in.readLine(); System.out.print("Titulo Academico : ");t = in.readLine(); this.sec.setProf((long)Integer.parseInt(c),n,a,t); prof_registrado = true; } catch(Exception e) { System.out.println("Se produjo un ERROR en la lectura de los datos."); } } } public void Mostar_Profesor() { if(!prof_registrado) System.out.println("Debe registrar un Profesor!"); else System.out.println("Prof. " + this.sec.getProf().getApellido() + ' ' + this.sec.getProf().getNombre() + ", " + this.sec.getProf().getTitulo_acam()); } public void Imprimir_en_TXT(String archivo,String texto,boolean nuevo) { try { FileWriter fw = new FileWriter(archivo,!nuevo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw); out.println(texto); out.close(); }catch(Exception e) { System.out.println("No se pudo imprimir en el archivo + \"" + archivo + "\""); } } }
Java
import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.WindowConstants; import javax.swing.border.BevelBorder; import javax.swing.border.LineBorder; import javax.swing.border.SoftBevelBorder; import javax.swing.SwingUtilities; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class FrameProfesor extends javax.swing.JFrame { private JTextField TxtNombre; private JTextField TxtCedula; private JLabel jLabel2; private JLabel jLabel3; private JLabel jLabel4; private JLabel jLabel5; private JButton BTBorrar; private JPanel jPanel1; private JButton BTCancelar; private JButton BTIncluir; private JLabel jLabel1; private JTextField TxtTituloAcad; private JTextField TxtApellido; private Seccion sec; public FrameProfesor() { super(); initGUI(); } public FrameProfesor(Seccion sec) { super(); this.sec = sec; initGUI(); } ActionListener AccIncluir = new ActionListener() { public void actionPerformed(ActionEvent e) { IncluirProfersor(); } }; public void MostrarProfesor() { if(this.sec.getProfReg()) { Profesor p = this.sec.getProf(); this.TxtApellido.setText(p.getApellido()); this.TxtNombre.setText(p.getNombre()); this.TxtTituloAcad.setText(p.getTitulo_acam()); this.TxtCedula.setText(Long.toString(p.getCedula())); this.BTIncluir.setEnabled(false); this.BTBorrar.setEnabled(false); this.BTCancelar.setEnabled(true); } } public void IncluirProfersor() { try { if(this.TxtApellido.getText().equals("") || this.TxtNombre.getText().equals("") || this.TxtCedula.getText().equals("") || this.TxtTituloAcad.getText().equals("")) JOptionPane.showMessageDialog(null,"Debe llenar todos los datos para poder inscribir al profesor", "Faltan Datos", JOptionPane.ERROR_MESSAGE); else { sec.setProf((long)Integer.parseInt(TxtCedula.getText()), TxtNombre.getText(),TxtApellido.getText(),TxtTituloAcad.getText()); sec.setProfReg(true); JOptionPane.showMessageDialog(null,"El profesor fué incluido con éxito", "Operación Realizada", JOptionPane.INFORMATION_MESSAGE); MostrarProfesor(); } } catch(Exception e) { JOptionPane.showMessageDialog(null,"Ingrese datos validos", "Error", JOptionPane.ERROR_MESSAGE); Borrar(); } } ActionListener Borrar = new ActionListener() { public void actionPerformed(ActionEvent e) { BTBorrar.setMnemonic(KeyEvent.VK_B); Borrar(); } }; public void Borrar() { TxtCedula.setText(""); TxtNombre.setText(""); TxtApellido.setText(""); TxtTituloAcad.setText(""); } ActionListener Cancelar = new ActionListener() { public void actionPerformed(ActionEvent e) { Cerrar(); } }; public void Cerrar() { this.dispose(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); getContentPane().setBackground(Color.white); this.setName("Profesor"); this.setTitle("Profesor"); this.setFont(new java.awt.Font("Courier 10 Pitch",0,28)); { jLabel5 = new JLabel(); getContentPane().add(jLabel5); jLabel5.setText("Datos del Profesor"); jLabel5.setBounds(103, 8, 241, 35); jLabel5.setFont(new java.awt.Font("Bitstream Charter",1,28)); } { BTIncluir = new JButton(); getContentPane().add(BTIncluir); BTIncluir.setText("Incluir"); BTIncluir.setBounds(62, 255, 85, 28); BTIncluir.addActionListener(AccIncluir); } { BTCancelar = new JButton(); getContentPane().add(BTCancelar); BTCancelar.setText("Salir"); BTCancelar.setBounds(298, 255, 100, 28); BTCancelar.addActionListener(Cancelar); } { jPanel1 = new JPanel(); getContentPane().add(jPanel1); jPanel1.setBounds(34, 46, 389, 192); jPanel1.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); jPanel1.setName("Datos del Profesor"); jPanel1.setOpaque(false); jPanel1.setLayout(null); { jLabel1 = new JLabel(); jPanel1.add(jLabel1); jLabel1.setText("Cedula"); jLabel1.setBounds(56, 30, 66, 15); jLabel1.setFont(new java.awt.Font("Dialog",0,14)); } { TxtCedula = new JTextField(); jPanel1.add(TxtCedula); TxtCedula.setBounds(155, 24, 132, 22); TxtCedula.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); } { jLabel2 = new JLabel(); jPanel1.add(jLabel2); jLabel2.setText("Nombre"); jLabel2.setBounds(53, 68, 66, 15); jLabel2.setFont(new java.awt.Font("Dialog",0,14)); } { TxtNombre = new JTextField(); jPanel1.add(TxtNombre); TxtNombre.setBounds(155, 61, 132, 22); TxtNombre.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); } { jLabel3 = new JLabel(); jPanel1.add(jLabel3); jLabel3.setText("Apellido"); jLabel3.setBounds(53, 106, 66, 15); jLabel3.setFont(new java.awt.Font("Dialog",0,14)); } { TxtApellido = new JTextField(); jPanel1.add(TxtApellido); TxtApellido.setBounds(155, 99, 132, 22); TxtApellido.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); } { jLabel4 = new JLabel(); jPanel1.add(jLabel4); jLabel4.setText("Titulo Academico"); jLabel4.setBounds(19, 134, 130, 35); jLabel4.setFont(new java.awt.Font("Dialog",0,14)); } { TxtTituloAcad = new JTextField(); jPanel1.add(TxtTituloAcad); TxtTituloAcad.setBounds(155, 139, 132, 22); TxtTituloAcad.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); } } { BTBorrar = new JButton(); getContentPane().add(BTBorrar); BTBorrar.setText("Borrar"); BTBorrar.setBounds(185, 255, 84, 28); BTBorrar.addActionListener(Borrar); } pack(); this.setSize(465, 338); MostrarProfesor(); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } }
Java
import java.awt.*; import javax.swing.*; import java.awt.Dimension; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.PrintWriter; import java.util.Vector; import javax.swing.JApplet; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.SwingUtilities; public class JTableDemo extends javax.swing.JApplet { private Vector<Estudiante> Est; private String titulo = ""; public JTableDemo() { super(); initGUI(); } public JTableDemo(Vector<Estudiante> Est,String t) { super(); this.titulo = t; this.Est = Est; initGUI(); } private Object Valor(Estudiante e,int i) { switch(i) { case 0:return e.getCedula(); case 1:return e.getNombre(); case 2:return e.getApellido(); case 3:return e.getNota_final(); } return 0; } public void Imprimir_en_TXT(String archivo,String texto,boolean nuevo) { try { FileWriter fw = new FileWriter(archivo,!nuevo); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw); out.print(texto); out.close(); }catch(Exception e) { System.out.println("No se pudo imprimir en el archivo + \"" + archivo + "\""); } } private void initGUI() { try { setSize(new Dimension(600, 300)); Container c = getContentPane(); c.setLayout(new BorderLayout()); final String[] colHeads = {"Cedula","Nombre","Apellido","Nota Final"}; //Inicializar Tabla Object[][] Datos = new Object[Est.size()][4]; Estudiante e; Imprimir_en_TXT(titulo + ".txt",titulo + '\n',true); titulo += ".txt"; Imprimir_en_TXT(titulo,"Cedula Nombre Apellido Nota Final\n\n",false); for(int j,i = 0;i < Est.size();i++) { e = Est.elementAt(i); for(j = 0;j < 4;j++) { Datos[i][j] = Valor(e,j); Imprimir_en_TXT(titulo,Datos[i][j].toString() + " ",false); } Imprimir_en_TXT(titulo,"\n",false); } JTable table = new JTable(Datos, colHeads); // añadir a la tabla el panel con scroll int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(table, v, h); // añadir el panel con scroll al content pane c.add(jsp, BorderLayout.CENTER); } catch (Exception e) { e.printStackTrace(); } } }
Java
import java.awt.Graphics; import java.awt.Image; import javax.swing.ImageIcon; import javax.swing.JPanel; public class Panel extends JPanel { private int anchoImagen, altoImagen; private Image image; public Panel(String rutaImagen, int ancho, int alto) { super(); image = new ImageIcon(getClass().getResource(rutaImagen)).getImage(); this.anchoImagen = ancho; this.altoImagen = alto; this.setLayout(null); } @Override public void paintComponent(Graphics g) { g.drawImage(image, 0, 0, this.anchoImagen, this.altoImagen, null); setOpaque(false); super.paintComponent(g); } }
Java
import java.awt.Color; import java.awt.Dimension; import javax.swing.JComponent; import javax.swing.JFrame; /*Desarrolladores: * Arrieche, Andrés C.I V- 19.423.804 * Fernández, Jhoswar C.I V- 19.779.296 * Ramírez, Jeniree C.I V- 18.619.418 Sección 3. */ public class Principal { public static void main(String[] args) { Acceso_pantalla acc = new Acceso_pantalla(); acc.setVisible(true); acc.setLocationRelativeTo(null); } }
Java
public abstract class Persona { private long cedula; String nombre; String apellido; public Persona() { super(); } public Persona(long cedula, String nombre, String apellido) { super(); this.cedula = cedula; this.nombre = nombre; this.apellido = apellido; } public long getCedula() { return cedula; } public void setCedula(long cedula) { this.cedula = cedula; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } }
Java
public interface Evaluado { public abstract void presentarEvaluacion(); }
Java
import java.io.BufferedReader; import java.io.InputStreamReader; public class Acceso { private String log,pass; public Acceso() { super(); this.log = "usuario"; this.pass = "123456"; } public Acceso(String log, String pass) { super(); this.log = log; this.pass = pass; } public String getLog() { return log; } public void setLog(String log) { this.log = log; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } }
Java
public interface Evaluar { public abstract void EvaluarEstudiante(Estudiante e); }
Java
import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.*; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.util.Vector; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class FramePrincipal extends javax.swing.JFrame { private JMenuBar jMenuBar1; private JMenu jMenu1; private JMenu jMenu3; private JMenu jMenu4; private JMenu jMenu6; private JMenuItem Estudiante; private JMenuItem RProfesor; private JMenuItem AplicarEvaluaciones; private JRadioButtonMenuItem jRadioButtonOrdenarNot; private JMenuItem LGeneral; private JMenuItem LAprobados; private JMenuItem LAplazados; private JMenuItem Salir; private JMenuItem jMenuItem2; private JPopupMenu jPopupMenu1; private JRadioButtonMenuItem jRadioButtonOrdenarCed; private JMenu jMenu2; private JDesktopPane jDesktopPane1; private Image image; private Seccion sec; private int opc_ordenar = 0; ActionListener opc_ced = new ActionListener() { public void actionPerformed(ActionEvent e) { opc_ordenar = 0; } }; ActionListener opc_nota = new ActionListener() { public void actionPerformed(ActionEvent e) { opc_ordenar = 1; } }; ActionListener rep_general = new ActionListener() { public void actionPerformed(ActionEvent e) { String t = "Listado General ordenado por " + Ordenar(); Reporte(sec.getEstudiantes(),t); } }; ActionListener rep_aprob = new ActionListener() { public void actionPerformed(ActionEvent e) { String t = "Listado de Aprobados ordenado por " + Ordenar(); Reporte(sec.getEstudiantesAprob(),t); } }; ActionListener rep_aplaz = new ActionListener() { public void actionPerformed(ActionEvent e) { String t = "Listado de Aplazados ordenado por " + Ordenar(); Reporte(sec.getEstudiantesAplaz(),t); } }; public String Ordenar() { if(opc_ordenar == 0) { this.sec.OrdenarEstudianteCed(); return "Cedula"; } else { this.sec.OrdenarEstudianteNota(); return "Nota Final"; } } public void Reporte(Vector<Estudiante> Est,String t) { if(this.sec.NumeroEstudiante() == 0) JOptionPane.showMessageDialog(null,"No Existen estudiantes registrados", "Advertencia", JOptionPane.INFORMATION_MESSAGE); else if(Est.size() != 0) { JFrame frame = new JFrame(); JTableDemo inst = new JTableDemo(Est,t); frame.getContentPane().add(inst); ((JComponent)frame.getContentPane()).setPreferredSize(inst.getSize()); frame.pack(); frame.setVisible(true); frame.setTitle(t); frame.setLocationRelativeTo(null); inst.setSize(new Dimension(600, 300)); } else JOptionPane.showMessageDialog(null,"No Existen estudiantes que cumplan la condicion", "Advertencia", JOptionPane.INFORMATION_MESSAGE); } ActionListener Ventprof = new ActionListener() { public void actionPerformed(ActionEvent e) { FrameProfesor ventProf = new FrameProfesor(sec); ventProf.setVisible(true); ventProf.setLocationRelativeTo(null); } }; ActionListener VentEst = new ActionListener() { public void actionPerformed(ActionEvent e) { FrameEstudiante ventEstud = new FrameEstudiante(sec); ventEstud.setVisible(true); ventEstud.setLocationRelativeTo(null); } }; ActionListener Evaluar = new ActionListener() { public void actionPerformed(ActionEvent e) { AplicarEvaluacion(); } }; public void AplicarEvaluacion() { if(this.sec.NumeroEstudiante() == 0) JOptionPane.showMessageDialog(null,"No Existen estudiantes registrados", "Advertencia", JOptionPane.INFORMATION_MESSAGE); else if(!this.sec.getProfReg()) JOptionPane.showMessageDialog(null,"No Existe profesor registrado", "Advertencia", JOptionPane.INFORMATION_MESSAGE); else { this.sec.AplicarEvaluaciones(); this.sec.EvaluarEstuduantes(); JOptionPane.showMessageDialog(null,"La evaluacion fue realizada con exito", "Operación Realizada", JOptionPane.INFORMATION_MESSAGE); } } public FramePrincipal() { super(); initGUI(); Panel pan = new Panel("/Imagenes/imagen2.jpg", this.getWidth(), this.getHeight()); this.add(pan, BorderLayout.CENTER); pan.setPreferredSize(new java.awt.Dimension(486, 273)); } public FramePrincipal(Seccion sec) { super(); this.sec = sec; initGUI(); this.setTitle("Registro Academico (Seccion " + this.sec.getNum_secc() + ")"); Panel pan = new Panel("/Imagenes/imagen2.jpg", this.getWidth(), this.getHeight()); this.add(pan, BorderLayout.CENTER); pan.setPreferredSize(new java.awt.Dimension(486, 273)); } private void initGUI() { try { { this.setFont(new java.awt.Font("DejaVu Sans Mono",0,10)); getContentPane().setForeground(new java.awt.Color(255,255,255)); this.setJMenuBar(jMenuBar1); } { this.setJMenuBar(jMenuBar1); } { jDesktopPane1 = new JDesktopPane(); getContentPane().add(jDesktopPane1, BorderLayout.CENTER); jDesktopPane1.setPreferredSize(new java.awt.Dimension(390, 159)); { jPopupMenu1 = new JPopupMenu(); setComponentPopupMenu(jDesktopPane1, jPopupMenu1); } { jMenuItem2 = new JMenuItem(); jDesktopPane1.add(jMenuItem2, JLayeredPane.DEFAULT_LAYER); jMenuItem2.setText("jMenuItem2"); } } this.setSize(598, 433); { jMenuBar1 = new JMenuBar(); setJMenuBar(jMenuBar1); { jMenu1 = new JMenu(); jMenuBar1.add(jMenu1); jMenu1.setText("Registrar"); { Estudiante = new JMenuItem(); jMenu1.add(Estudiante); Estudiante.setText("Estudiante"); Estudiante.addActionListener(VentEst); } { RProfesor = new JMenuItem(); jMenu1.add(RProfesor); RProfesor.setText("Profesor"); RProfesor.addActionListener(Ventprof); } } { jMenu4 = new JMenu(); jMenuBar1.add(jMenu4); jMenu4.setText("Evaluar"); { AplicarEvaluaciones = new JMenuItem(); jMenu4.add(AplicarEvaluaciones); AplicarEvaluaciones.addActionListener(Evaluar); AplicarEvaluaciones.setText("Aplicar Evaluaciones"); } } { jMenu3 = new JMenu(); jMenu3.setText("Reportes"); jMenuBar1.add(jMenu3); { jMenu4 = new JMenu(); jMenu4.setText("Estudiantes"); jMenu3.add(jMenu4); { LGeneral = new JMenuItem(); jMenu4.add(LGeneral); LGeneral.setText("General"); LGeneral.addActionListener(rep_general); } { LAprobados = new JMenuItem(); jMenu4.add(LAprobados); LAprobados.setText("Aprobados"); LAprobados.addActionListener(rep_aprob); } { LAplazados = new JMenuItem(); jMenu4.add(LAplazados); LAplazados.setText("Aplazados"); LAplazados.addActionListener(rep_aplaz); } { jMenu2 = new JMenu(); jMenu4.add(jMenu2); jMenu2.setText("Ordenar Por"); { jRadioButtonOrdenarCed = new JRadioButtonMenuItem(); jMenu2.add(jRadioButtonOrdenarCed); jRadioButtonOrdenarCed.setText("Cedula"); } { jRadioButtonOrdenarNot = new JRadioButtonMenuItem(); jMenu2.add(jRadioButtonOrdenarNot); jRadioButtonOrdenarNot.setText("Nota Final"); } } } } { jMenu6 = new JMenu(); jMenuBar1.add(jMenu6); jMenu6.setText("Salir"); jRadioButtonOrdenarCed.addActionListener(opc_ced); jRadioButtonOrdenarNot.addActionListener(opc_nota); { JMenuItem Salir = new JMenuItem("Salir"); jMenu6.add(Salir); Salir.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent evento ) { System.exit( 0 ); } } ); } } } } catch (Exception e) { e.printStackTrace(); } } /** * Auto-generated method for setting the popup menu for a component */ private void setComponentPopupMenu(final java.awt.Component parent, final javax.swing.JPopupMenu menu) { parent.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent e) { if(e.isPopupTrigger()) menu.show(parent, e.getX(), e.getY()); } public void mouseReleased(java.awt.event.MouseEvent e) { if(e.isPopupTrigger()) menu.show(parent, e.getX(), e.getY()); } }); } }
Java
public class Estudiante extends Persona implements Evaluado { private float notas[] = new float[3]; float nota_final; boolean estado; public Estudiante(){} public Estudiante(long cedula, String nombre, String apellido) { super(cedula, nombre, apellido); } public float[] getNotas() { return notas; } public void setNotas(float[] notas) { this.notas = notas; } public float getNota_final() { return nota_final; } public void setNota_final(float nota_final) { this.nota_final = nota_final; } public boolean getEstado() { return estado; } public void setEstado(boolean estado) { this.estado = estado; } public void presentarEvaluacion() { for(int i=0; i<=2; i++) notas[i] = (float)Math.floor(Math.random()*20); } }
Java
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.WindowConstants; import javax.swing.border.LineBorder; import javax.swing.SwingUtilities; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class FrameSeccion extends javax.swing.JFrame { private JPanel jPanel1; private JButton BTRegistrar; private JTextField TXTnumero; private JLabel jLabel1; public FrameSeccion() { super(); initGUI(); } ActionListener Registrar = new ActionListener() { public void actionPerformed(ActionEvent e) { Cerrar(); } }; private void Cerrar() { Seccion sec = new Seccion(this.TXTnumero.getText()); FramePrincipal Principal = new FramePrincipal(sec); Principal.setVisible(true); Principal.setLocationRelativeTo(null); this.dispose(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); this.setTitle("Registrar Seccion"); { jPanel1 = new JPanel(); getContentPane().add(jPanel1); jPanel1.setBounds(41, 20, 264, 112); jPanel1.setLayout(null); jPanel1.setBorder(new LineBorder(new java.awt.Color(0,0,0), 1, false)); { jLabel1 = new JLabel(); jPanel1.add(jLabel1); jLabel1.setText("Ingrese el número de la Seccion"); jLabel1.setBounds(21, 13, 254, 15); } { TXTnumero = new JTextField(); jPanel1.add(TXTnumero); TXTnumero.setBounds(48, 42, 168, 22); } { BTRegistrar = new JButton(); jPanel1.add(BTRegistrar); BTRegistrar.setText("Registrar"); BTRegistrar.setBounds(75, 73, 104, 27); BTRegistrar.setFont(new java.awt.Font("Bitstream Charter",1,12)); BTRegistrar.addActionListener(Registrar); } } pack(); this.setSize(353, 188); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } }
Java
import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JWindow; import javax.swing.WindowConstants; import javax.swing.border.BevelBorder; import javax.swing.border.LineBorder; import javax.swing.SwingUtilities; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class FrameEstudiante extends javax.swing.JFrame { private JPanel jPanel1; private JLabel jLabel1; private JButton BTBuscar; private JWindow jWindow1; private JTextField TxtApellido; private JLabel jLabel8; private JLabel jLabel7; private JTextField TxtNombre; private JTextField TxtCedula; private JLabel jLabel6; private JButton BTCancelar; private JButton BTEliminar; private JButton BTIncluir; private JButton BTBorrar; private Seccion sec; public FrameEstudiante(Seccion sec) { super(); this.sec = sec; initGUI(); } public FrameEstudiante() { super(); initGUI(); } ActionListener AccBuscar = new ActionListener() { public void actionPerformed(ActionEvent e) { Buscar(); } }; public void Buscar() { if(this.TxtCedula.getText().equals("")) JOptionPane.showMessageDialog(null,"Debe ingresar una cedula", "Error", JOptionPane.ERROR_MESSAGE); else { try { int x = this.sec.Buscar((long)Integer.parseInt(TxtCedula.getText())); if(x == -1) { this.BTIncluir.setEnabled(true); this.BTEliminar.setEnabled(false); this.BTBuscar.setEnabled(false); this.BTBorrar.setEnabled(true); this.TxtCedula.setEditable(false); this.TxtApellido.setEditable(true); this.TxtNombre.setEditable(true); this.TxtNombre.setFocusable(true); } else { Estudiante e = this.sec.getEstudiante(x); TxtCedula.setText(Long.toString(this.sec.getEstudiante(x).getCedula())); TxtNombre.setText(e.getNombre()); TxtApellido.setText(e.getApellido()); this.BTIncluir.setEnabled(false); this.BTBuscar.setEnabled(false); this.BTBorrar.setEnabled(true); this.BTEliminar.setEnabled(true); this.TxtCedula.setEditable(false); this.TxtApellido.setEditable(true); this.TxtNombre.setEditable(true); } }catch(Exception e) { JOptionPane.showMessageDialog(null,"Ingrese datos validos", "Error", JOptionPane.ERROR_MESSAGE); Borrar(); } } } ActionListener Incluir = new ActionListener() { public void actionPerformed(ActionEvent e) { IncluirEst(); } }; public void IncluirEst() { try { if(this.TxtApellido.getText().equals("") || this.TxtNombre.getText().equals("")) JOptionPane.showMessageDialog(null,"Debe llenar todos los datos para poder inscribir un estudiante", "Faltan Datos", JOptionPane.ERROR_MESSAGE); else { Estudiante e = new Estudiante((long)Integer.parseInt(TxtCedula.getText()), TxtNombre.getText(),TxtApellido.getText()); this.sec.InscribirEstudiantes(e); JOptionPane.showMessageDialog(null,"El Estudiante fué incluido con éxito", "Operación Realizada", JOptionPane.INFORMATION_MESSAGE); Borrar(); } }catch(Exception e) { JOptionPane.showMessageDialog(null,"Ingrese datos validos", "Error", JOptionPane.ERROR_MESSAGE); Borrar(); } } ActionListener Borrar = new ActionListener() { public void actionPerformed(ActionEvent e) { BTBorrar.setMnemonic(KeyEvent.VK_B); Borrar(); } }; public void Borrar() { TxtCedula.setText(""); TxtNombre.setText(""); TxtApellido.setText(""); this.BTIncluir.setEnabled(false); this.BTBuscar.setEnabled(true); this.BTBorrar.setEnabled(true); this.BTEliminar.setEnabled(false); this.TxtCedula.setEditable(true); this.TxtApellido.setEditable(false); this.TxtNombre.setEditable(false); } ActionListener Eliminar = new ActionListener() { public void actionPerformed(ActionEvent e) { Elimina(); } }; public void Elimina() { this.sec.RetirarEstudiante(this.sec.Buscar((long)Integer.parseInt(this.TxtCedula.getText()))); JOptionPane.showMessageDialog(null,"El Estudiante fué Eliminado con éxito", "Operación Realizada", JOptionPane.INFORMATION_MESSAGE); Borrar(); } ActionListener Cancelar = new ActionListener() { public void actionPerformed(ActionEvent e) { Cerrar(); } }; public void Cerrar() { this.dispose(); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); getContentPane().setBackground(Color.white); this.setTitle("Estudiante"); { BTIncluir = new JButton(); getContentPane().add(BTIncluir); BTIncluir.setText("Incluir"); BTIncluir.setBounds(24, 212, 79, 29); BTIncluir.addActionListener(Incluir); } { BTCancelar = new JButton(); getContentPane().add(BTCancelar); BTCancelar.setText("Salir"); BTCancelar.setBounds(344, 212, 79, 29); BTCancelar.addActionListener(Cancelar); } { BTBorrar = new JButton(); getContentPane().add(BTBorrar); BTBorrar.setText("Borrar"); BTBorrar.setBounds(230, 212, 80, 29); BTBorrar.addActionListener(Borrar); } { jPanel1 = new JPanel(); getContentPane().add(jPanel1); jPanel1.setBounds(34, 50, 372, 139); jPanel1.setBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED)); jPanel1.setLayout(null); jPanel1.setOpaque(false); { jLabel8 = new JLabel(); jPanel1.add(jLabel8); jLabel8.setText("Cedula"); jLabel8.setBounds(25, 28, 64, 15); jLabel8.setFont(new java.awt.Font("DejaVu Sans",0,14)); } { jLabel6 = new JLabel(); jPanel1.add(jLabel6); jLabel6.setText("Apellido"); jLabel6.setBounds(23, 100, 79, 15); jLabel6.setFont(new java.awt.Font("DejaVu Sans",0,14)); } { jLabel7 = new JLabel(); jPanel1.add(jLabel7); jLabel7.setText("Nombre"); jLabel7.setBounds(23, 62, 79, 15); jLabel7.setFont(new java.awt.Font("DejaVu Sans",0,14)); } { TxtCedula = new JTextField(); jPanel1.add(TxtCedula); TxtCedula.setBounds(105, 22, 137, 22); } { TxtNombre = new JTextField(); jPanel1.add(TxtNombre); TxtNombre.setBounds(105, 57, 137, 22); } { TxtApellido = new JTextField(); jPanel1.add(TxtApellido); TxtApellido.setBounds(105, 95, 137, 22); } { BTBuscar = new JButton(); jPanel1.add(BTBuscar); BTBuscar.setText("Buscar"); BTBuscar.setBounds(266, 22, 83, 22); BTBuscar.addActionListener(AccBuscar); } } { jLabel1 = new JLabel(); getContentPane().add(jLabel1); jLabel1.setText("Datos del Estudiante"); jLabel1.setBounds(69, 12, 310, 32); jLabel1.setFont(new java.awt.Font("Bitstream Charter",1,26)); } { BTEliminar = new JButton(); getContentPane().add(BTEliminar); BTEliminar.setText("Eliminar"); BTEliminar.setBounds(125, 212, 80, 29); BTEliminar.addActionListener(Eliminar); } pack(); this.setSize(448, 306); Borrar(); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } }
Java
import java.util.*; public class Seccion { private Profesor prof; String num_secc; boolean prof_reg = false; Vector<Estudiante> Estudiantes = new Vector<Estudiante>(0); public Seccion() { super(); prof = new Profesor(); } public Seccion(String s) { super(); num_secc = s; prof = new Profesor(); } public boolean getProfReg() { return prof_reg; } public void setProfReg(boolean c) { prof_reg = c; } public String getNum_secc() { return num_secc; } public void setNum_secc(String num_secc) { this.num_secc = num_secc; } public Profesor getProf() { return prof; } public void setProf(long c,String n,String a,String t) { this.prof = new Profesor(c,n,a,t); } public Estudiante getEstudiante(int i) { return Estudiantes.elementAt(i); } public Vector<Estudiante> getEstudiantes() { return Estudiantes; } public Vector<Estudiante> getEstudiantesAprob() { Vector<Estudiante> Est = new Vector<Estudiante>(0); for(int i = 0;i < NumeroEstudiante();i++) if(Estudiantes.elementAt(i).getEstado()) Est.add(Estudiantes.elementAt(i)); return Est; } public Vector<Estudiante> getEstudiantesAplaz() { Vector<Estudiante> Est = new Vector<Estudiante>(0); for(int i = 0;i < NumeroEstudiante();i++) if(!Estudiantes.elementAt(i).getEstado()) Est.add(Estudiantes.elementAt(i)); return Est; } public void InscribirEstudiantes(Estudiante e) { Estudiantes.add(e); } public int Buscar(long ced) { for(int i = 0;i < NumeroEstudiante();i++) if(Estudiantes.elementAt(i).getCedula() == ced) return i; return -1; } public void RetirarEstudiante(int x) { Estudiantes.removeElementAt(x); } public int NumeroEstudiante(){ return Estudiantes.size(); } public void AplicarEvaluaciones() { for(int i = 0;i < NumeroEstudiante();i++) Estudiantes.elementAt(i).presentarEvaluacion(); } public void EvaluarEstuduantes() { for(int i = 0;i < NumeroEstudiante();i++) this.prof.EvaluarEstudiante(Estudiantes.elementAt(i)); } public float Promedio() { float t = 0; for(int i = 0;i < NumeroEstudiante();i++) t += Estudiantes.elementAt(i).getNota_final(); return t / NumeroEstudiante(); } public void OrdenarEstudianteNota() { int x = 1; Estudiante est = new Estudiante(); boolean ordenar; do { ordenar = false; for(int i = 0;i < NumeroEstudiante()-x;i++) if(Estudiantes.elementAt(i).getNota_final() < Estudiantes.elementAt(i+1).getNota_final()) { est = Estudiantes.elementAt(i); Estudiantes.setElementAt(Estudiantes.elementAt(i+1),i); Estudiantes.setElementAt(est,i+1); ordenar = true; } x++; }while(ordenar); } public void OrdenarEstudianteCed() { int x = 1; Estudiante est = new Estudiante(); boolean ordenar; do { ordenar = false; for(int i = 0;i < NumeroEstudiante()-x;i++) if(Estudiantes.elementAt(i).getCedula() > Estudiantes.elementAt(i+1).getCedula()) { est = Estudiantes.elementAt(i); Estudiantes.setElementAt(Estudiantes.elementAt(i+1),i); Estudiantes.setElementAt(est,i+1); ordenar = true; } x++; }while(ordenar); } }
Java
package com.risk.client; import com.google.gwt.user.client.rpc.AsyncCallback; /** * The async counterpart of <code>GreetingService</code>. */ public interface GreetingServiceAsync { void greetServer(String input, AsyncCallback<String> callback) throws IllegalArgumentException; }
Java
package com.risk.client; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; /** * The client side stub for the RPC service. */ @RemoteServiceRelativePath("greet") public interface GreetingService extends RemoteService { String greetServer(String name) throws IllegalArgumentException; }
Java
package com.risk.client; import com.risk.shared.FieldVerifier; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; /** * Entry point classes define <code>onModuleLoad()</code>. */ public class Risk_online implements EntryPoint { /** * The message displayed to the user when the server cannot be reached or * returns an error. */ private static final String SERVER_ERROR = "An error occurred while " + "attempting to contact the server. Please check your network " + "connection and try again."; /** * Create a remote service proxy to talk to the server-side Greeting service. */ private final GreetingServiceAsync greetingService = GWT .create(GreetingService.class); /** * This is the entry point method. */ public void onModuleLoad() { final Button sendButton = new Button("Send"); final TextBox nameField = new TextBox(); nameField.setText("GWT User"); final Label errorLabel = new Label(); // We can add style names to widgets sendButton.addStyleName("sendButton"); // Add the nameField and sendButton to the RootPanel // Use RootPanel.get() to get the entire body element RootPanel.get("nameFieldContainer").add(nameField); RootPanel.get("sendButtonContainer").add(sendButton); RootPanel.get("errorLabelContainer").add(errorLabel); // Focus the cursor on the name field when the app loads nameField.setFocus(true); nameField.selectAll(); // Create the popup dialog box final DialogBox dialogBox = new DialogBox(); dialogBox.setText("Remote Procedure Call"); dialogBox.setAnimationEnabled(true); final Button closeButton = new Button("Close"); // We can set the id of a widget by accessing its Element closeButton.getElement().setId("closeButton"); final Label textToServerLabel = new Label(); final HTML serverResponseLabel = new HTML(); VerticalPanel dialogVPanel = new VerticalPanel(); dialogVPanel.addStyleName("dialogVPanel"); dialogVPanel.add(new HTML("<b>Sending name to the server:</b>")); dialogVPanel.add(textToServerLabel); dialogVPanel.add(new HTML("<br><b>Server replies:</b>")); dialogVPanel.add(serverResponseLabel); dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT); dialogVPanel.add(closeButton); dialogBox.setWidget(dialogVPanel); // Add a handler to close the DialogBox closeButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { dialogBox.hide(); sendButton.setEnabled(true); sendButton.setFocus(true); } }); // Create a handler for the sendButton and nameField class MyHandler implements ClickHandler, KeyUpHandler { /** * Fired when the user clicks on the sendButton. */ public void onClick(ClickEvent event) { sendNameToServer(); } /** * Fired when the user types in the nameField. */ public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { sendNameToServer(); } } /** * Send the name from the nameField to the server and wait for a response. */ private void sendNameToServer() { // First, we validate the input. errorLabel.setText(""); String textToServer = nameField.getText(); if (!FieldVerifier.isValidName(textToServer)) { errorLabel.setText("Please enter at least four characters"); return; } // Then, we send the input to the server. sendButton.setEnabled(false); textToServerLabel.setText(textToServer); serverResponseLabel.setText(""); greetingService.greetServer(textToServer, new AsyncCallback<String>() { public void onFailure(Throwable caught) { // Show the RPC error message to the user dialogBox .setText("Remote Procedure Call - Failure"); serverResponseLabel .addStyleName("serverResponseLabelError"); serverResponseLabel .setHTML(SERVER_ERROR); dialogBox.center(); closeButton.setFocus(true); } public void onSuccess(String result) { dialogBox .setText("Remote Procedure Call"); serverResponseLabel .removeStyleName("serverResponseLabelError"); serverResponseLabel .setHTML(result); dialogBox.center(); closeButton.setFocus(true); } }); } } // Add a handler to send the name to the server MyHandler handler = new MyHandler(); sendButton.addClickHandler(handler); nameField.addKeyUpHandler(handler); } }
Java
package com.risk.shared; /** * <p> * FieldVerifier validates that the name the user enters is valid. * </p> * <p> * This class is in the <code>shared</code> packing because we use it in both * the client code and on the server. On the client, we verify that the name is * valid before sending an RPC request so the user doesn't have to wait for a * network round trip to get feedback. On the server, we verify that the name is * correct to ensure that the input is correct regardless of where the RPC * originates. * </p> * <p> * When creating a class that is used on both the client and the server, be sure * that all code is translatable and does not use native JavaScript. Code that * is note translatable (such as code that interacts with a database or the file * system) cannot be compiled into client side JavaScript. Code that uses native * JavaScript (such as Widgets) cannot be run on the server. * </p> */ public class FieldVerifier { /** * Verifies that the specified name is valid for our service. * * In this example, we only require that the name is at least four * characters. In your application, you can use more complex checks to ensure * that usernames, passwords, email addresses, URLs, and other fields have the * proper syntax. * * @param name the name to validate * @return true if valid, false if invalid */ public static boolean isValidName(String name) { if (name == null) { return false; } return name.length() > 3; } }
Java
package com.risk.server; import com.risk.client.GreetingService; import com.risk.shared.FieldVerifier; import com.google.gwt.user.server.rpc.RemoteServiceServlet; /** * The server side implementation of the RPC service. */ @SuppressWarnings("serial") public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService { public String greetServer(String input) throws IllegalArgumentException { // Verify that the input is valid. if (!FieldVerifier.isValidName(input)) { // If the input is not valid, throw an IllegalArgumentException back to // the client. throw new IllegalArgumentException( "Name must be at least 4 characters long"); } String serverInfo = getServletContext().getServerInfo(); String userAgent = getThreadLocalRequest().getHeader("User-Agent"); // Escape data from the client to avoid cross-site script vulnerabilities. input = escapeHtml(input); userAgent = escapeHtml(userAgent); return "Hello, " + input + "!<br><br>I am running " + serverInfo + ".<br><br>It looks like you are using:<br>" + userAgent; } /** * Escape an html string. Escaping data received from the client helps to * prevent cross-site script vulnerabilities. * * @param html the html string to escape * @return the escaped string */ private String escapeHtml(String html) { if (html == null) { return null; } return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;") .replaceAll(">", "&gt;"); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GiaoTiepThread; /** * * @author TanAnh */ class Demo { public static void main(String args[]) { Queue q = new Queue(); new Publisher(q); new Consumer(q); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GiaoTiepThread; /** * * @author TanAnh */ class Queue { int exchangeValue; boolean busy = false; synchronized int get() { if (!busy) { try { wait(); } catch (InterruptedException e) { System.out.println( "Get: InterruptedException"); } } System.out.println("Get: " + exchangeValue); busy=false; notify(); return exchangeValue; } synchronized void put(int exchangeValue) { if (busy) { try { wait(); } catch (InterruptedException e) { System.out.println( "Put: InterruptedException"); } } this.exchangeValue = exchangeValue; busy = true; System.out.println("Put: " + exchangeValue); notify(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GiaoTiepThread; /** * * @author TanAnh */ class Publisher implements Runnable { Queue q; Publisher(Queue q) { this.q = q; new Thread(this, "Publisher").start(); } public void run() { for (int i = 0; i < 5; i++) { q.put(i); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GiaoTiepThread; /** * * @author TanAnh */ class Consumer implements Runnable { Queue q; Consumer(Queue q) { this.q = q; new Thread(this, "Consumer").start(); } public void run() { for (int i = 0; i < 5; i++) { q.get(); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author TanAnh */ public class Demo { public static void main(String args[]) throws InterruptedException{ Parentheses p3=new Parentheses(); MyThread name1=new MyThread(p3, "Bob"); MyThread name2=new MyThread(p3, "Mary"); MyThread name3=new MyThread(p3, "Anh"); MyThread name4=new MyThread(p3, "Luong"); name1.t.join(); name2.t.join(); name3.t.join(); name4.t.join(); System.out.println("Interupted"); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author TanAnh */ public class MyThread implements Runnable { String s1; Parentheses p1; Thread t; public MyThread(Parentheses p2, String s2){ p1=p2; s1=s2; t=new Thread(this); t.start(); } @Override public void run() { synchronized(p1){ p1.display(s1); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import org.xml.sax.SAXException; /** * * @author PC */ public class _MainFrm extends javax.swing.JFrame { /** * Creates new form _MainFrm */ public _MainFrm() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jScrollPane2 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable1); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane2.setViewportView(jTextArea1); jButton1.setText("Execute"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("jButton2"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(20, 20, 20) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 369, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26)) .addGroup(layout.createSequentialGroup() .addGap(34, 34, 34) .addComponent(jButton1) .addGap(32, 32, 32) .addComponent(jButton2) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(28, 28, 28) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2)) .addContainerGap(59, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try { // TODO add your handling code here: String query = jTextArea1.getText(); String_Utilities.QUERY res = String_Utilities.getQuery(query); switch (res) { case INSERT: String_Utilities.insert_method(query); break; case UPDATE: String_Utilities.update_method(query); break; case CREATE: Table table=new Table(); new XuLyChuoi().TaoBang(query, table); new Create().CreateTable(table); } } catch (ParserConfigurationException ex) { Logger.getLogger(_MainFrm.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(_MainFrm.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(_MainFrm.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerConfigurationException ex) { Logger.getLogger(_MainFrm.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerException ex) { Logger.getLogger(_MainFrm.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* * Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* * If Nimbus (introduced in Java SE 6) is not available, stay with the * default look and feel. For details see * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(_MainFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(_MainFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(_MainFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(_MainFrm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new _MainFrm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * * @author TanAnh */ public class String_Utilities { private static String getPara(String query) { int from = query.indexOf('('); int to = query.indexOf(')'); return query.substring(from + 1, to).trim(); } private static String getParavalues(String query) { query = query.toLowerCase(); int from = query.indexOf("values") + "values".length(); int to = query.length() - 1; return query.substring(from + 1, to).trim(); } private static List<Col> getListCol(String Para, String ParaValues) { List<Col> res = new LinkedList<Col>(); String[] lisPara = Para.split(","); String[] lisParaValues = ParaValues.split(","); for (int i = 0; i < lisPara.length; i++) { Col c = new Col(); if (lisParaValues[i].contains("'")) { c.Type = "string"; } else { c.Type = "int"; } c.Ten = lisPara[i]; c.Value = lisParaValues[i]; res.add(c); } return res; } private static String getTableName_update(String query) { int from = "update".length() + 1; int to = query.indexOf("set"); String res = query.substring(from, to); return res.trim(); } private static String getPara_update(String query) { int from = query.indexOf("set") + "set".length(); int to = query.indexOf("where"); String res = query.substring(from, to); return res.trim(); } private static String get_Where(String query) { int from = query.indexOf("where") + "where".length(); int to = query.length(); String res = query.substring(from, to); return res.trim(); } private static void do_update(String Para, String s_Where, String TableName) { String[] where = s_Where.split("="); String[] paras = Para.split(","); try { File directory = new File(""); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(directory.getAbsolutePath() + "\\src\\XML\\Database.xml")); javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath(); String expresstion = "//Table[@Ten='" + TableName + "']"; Node node_tab = (Node) xpath.evaluate(expresstion, doc, XPathConstants.NODE); expresstion = "//Record[Col=" + where[1] + "]"; Node node_rec = get_record_update(where, doc); Node node_col; for (String string : paras) { String[] s_val = string.split("="); // expresstion = "//Col[@Ten='" + s_val[0].trim() + "']"; //// String ss="HoTen"; //// expresstion = "//Col[@Ten='" + ss + "']"; //// // node_col = (Node) xpath.evaluate(expresstion, node_rec, XPathConstants.NODE); // // // System.err.println(node_col.getNodeValue()); // node_col.setTextContent(s_val[1]); // NodeList list_col = node_rec.getChildNodes(); int n = list_col.getLength(); for (int i = 0; i < n; i++) { String tam = null; if (list_col.item(i).getNodeName() == "Col") { tam = list_col.item(i).getAttributes().getNamedItem("Ten").getTextContent(); } if (tam.contains(s_val[0].trim())) { list_col.item(i).setTextContent(s_val[1]); } } } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(directory.getAbsolutePath() + "\\src\\XML\\Database.xml")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); } catch (TransformerException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (XPathExpressionException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } } private static Node get_record_update(String[] where, Document doc) { Node res = null; String tagname = where[0].trim(); NodeList nodelist = doc.getElementsByTagName("Col"); for (int i = 0; i < nodelist.getLength(); i++) { String tam = nodelist.item(i).getTextContent().trim(); if (tam.contains(where[1])) { res = nodelist.item(i); break; } } return res.getParentNode(); } public enum QUERY { SELECT, INSERT, UPDATE, DELETE, CREATE } public static QUERY getQuery(String s) { QUERY res = null; int kq = 0; String sub = s.substring(0, "delete".length()).toUpperCase(); if (sub.compareToIgnoreCase(QUERY.DELETE.toString()) == 0) { res = QUERY.DELETE; } if (sub.compareToIgnoreCase(QUERY.UPDATE.toString()) == 0) { res = QUERY.UPDATE; } if (sub.compareToIgnoreCase(QUERY.INSERT.toString()) == 0) { res = QUERY.INSERT; } if (sub.compareToIgnoreCase(QUERY.SELECT.toString()) == 0) { res = QUERY.SELECT; } if (sub.compareToIgnoreCase(QUERY.CREATE.toString()) == 0) { res = QUERY.CREATE; } return res; } public static void main(String args[]) throws TransformerConfigurationException, TransformerException { String query = "update HOCSINH set HoTen='Tuan Kiet', DTB=8.9 where MaHS=6"; QUERY res = getQuery(query); switch (res) { case INSERT: insert_method(query); break; case UPDATE: update_method(query); break; } } public static void update_method(String query) { String tableName = getTableName_update(query); String Para = getPara_update(query); String s_Where = get_Where(query); do_update(Para, s_Where, tableName); } public static void insert_method(String query) throws TransformerConfigurationException, TransformerException { String tableName = getTableName(query); String Para = getPara(query); String ParaValues = getParavalues(query); List<Col> list_col = getListCol(Para, ParaValues); Record rc=new Record(); rc.add_rec_to_table(list_col, tableName); System.err.println(getQuery(query)); } private static String getTableName(String query) { int from = query.indexOf("into") + "into".length(); int to = query.indexOf('('); return query.substring(from, to).trim(); } }
Java
package XML; import java.util.ArrayList; import java.util.List; public class Table { public String TenBang; public List<Record> ListRecord=new ArrayList<Record>(); public String TenKhoaChinh; public String KieuKhoaChinh; public Table(String TenBang,List<Record> ListRecord,String TenKhoaChinh, String KieuKhoaChinh) { this.TenBang=TenBang; this.ListRecord=ListRecord; this.TenKhoaChinh=TenKhoaChinh; this.KieuKhoaChinh=KieuKhoaChinh; } public Table() { } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; /** * * @author PC */ public class Condition { public String TenBang; public String[] Bien; public String[] GiaTri; public String[] DauSoSanh; public String[] DauNoi; public Condition() { } public Condition(String TenBang,String[] Bien,String[] GiaTri,String[] DauSoSanh,String[] DauNoi) { this.TenBang=TenBang; this.Bien=Bien; this.GiaTri=GiaTri; this.DauSoSanh=DauSoSanh; this.DauNoi=DauNoi; } }
Java
package XML; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import org.xml.sax.SAXException; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author PC */ public class Form extends javax.swing.JFrame { /** * Creates new form Form */ public Form() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jTextArea2 = new javax.swing.JTextArea(); jScrollPane3 = new javax.swing.JScrollPane(); jTextArea3 = new javax.swing.JTextArea(); jScrollPane4 = new javax.swing.JScrollPane(); jTextArea4 = new javax.swing.JTextArea(); jButton2 = new javax.swing.JButton(); jScrollPane5 = new javax.swing.JScrollPane(); jTextArea5 = new javax.swing.JTextArea(); jScrollPane6 = new javax.swing.JScrollPane(); jTextArea6 = new javax.swing.JTextArea(); jButton3 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); jButton1.setText("OK"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jTextArea2.setColumns(20); jTextArea2.setRows(5); jScrollPane2.setViewportView(jTextArea2); jTextArea3.setColumns(20); jTextArea3.setRows(5); jScrollPane3.setViewportView(jTextArea3); jTextArea4.setColumns(20); jTextArea4.setRows(5); jScrollPane4.setViewportView(jTextArea4); jButton2.setText("OK"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jTextArea5.setColumns(20); jTextArea5.setRows(5); jScrollPane5.setViewportView(jTextArea5); jTextArea6.setColumns(20); jTextArea6.setRows(5); jScrollPane6.setViewportView(jTextArea6); jButton3.setText("OK"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton1) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE) .addComponent(jScrollPane2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton2) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE) .addComponent(jScrollPane4)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE) .addComponent(jScrollPane6) .addGroup(layout.createSequentialGroup() .addComponent(jButton3) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE) .addComponent(jScrollPane3) .addComponent(jScrollPane5)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2) .addComponent(jButton3)) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE) .addComponent(jScrollPane4) .addComponent(jScrollPane6)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: String th=""; Table dl=new Table(); XuLyChuoi xl=new XuLyChuoi(); xl.TaoBang(jTextArea1.getText(), dl); for(int i=0;i<dl.ListRecord.get(0).ListCol.size();i++) { th+=dl.ListRecord.get(0).ListCol.get(i).Ten+"\t"+dl.ListRecord.get(0).ListCol.get(i).Type+"\n"; } th+=dl.TenKhoaChinh; jTextArea2.setText(dl.TenBang+"\n\n"+th); Create cr=new Create(); try { cr.CreateTable(dl); } catch (ParserConfigurationException ex) { Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerConfigurationException ex) { Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex); } catch (TransformerException ex) { Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: Condition ct=new Condition(); XuLyChuoi xl=new XuLyChuoi(); xl.XoaDong(jTextArea3.getText(),ct); String th=ct.TenBang+"\n"; for(int i=0;i<ct.Bien.length;i++) { th+=ct.Bien[i]+"\t"+ct.DauSoSanh[i]+"\t"+ct.GiaTri[i]+"\n"; } for(int i=0;i<ct.DauNoi.length;i++) { th+=ct.DauNoi[i]+"\n"; } jTextArea4.setText(th); Delete dl=new Delete(); dl.DeleteRecord(ct); }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // TODO add your handling code here: Attributes tt=new Attributes(); Condition ct=new Condition(); Condition dk=new Condition(); XuLyChuoi xl=new XuLyChuoi(); xl.ChonDong(jTextArea5.getText(),tt); ct=tt.DieuKien1; dk=tt.DieuKien2; String th=new String(); if(ct!=null) { th = ct.TenBang + "\n"; for (int i = 0; i < ct.Bien.length; i++) { th += ct.Bien[i] + "\t" + ct.DauSoSanh[i] + "\t" + ct.GiaTri[i] + "\n"; } for (int i = 0; i < ct.DauNoi.length; i++) { th += ct.DauNoi[i] + "\n"; } } if(dk!=null) { th = dk.TenBang + "\n"; for (int i = 0; i < dk.Bien.length; i++) { th += dk.Bien[i] + "\t" + dk.DauSoSanh[i] + "\t" + dk.GiaTri[i] + "\n"; } for (int i = 0; i < dk.DauNoi.length; i++) { th += dk.DauNoi[i] + "\n"; } } jTextArea6.setText(th); Select sl=new Select(); sl.SelectRecord(tt,null); }//GEN-LAST:event_jButton3ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* * Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* * If Nimbus (introduced in Java SE 6) is not available, stay with the * default look and feel. For details see * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* * Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Form().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JScrollPane jScrollPane6; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextArea jTextArea2; private javax.swing.JTextArea jTextArea3; private javax.swing.JTextArea jTextArea4; private javax.swing.JTextArea jTextArea5; private javax.swing.JTextArea jTextArea6; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; import java.io.Serializable; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; /** * * @author PC */ class Col implements Serializable{ public String Ten; public String Type; public String Value; public Col() { } void append_to_record(Node rec, Document doc) { Element col = doc.createElement("Col"); col.setAttribute("Ten", this.Ten); col.setAttribute("Type", this.Type); col.setTextContent(this.Value); rec.appendChild(col); System.out.println("added a record"); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * * @author PC */ public class Record implements Serializable{ public List<Col> ListCol=new ArrayList<Col>(); public Record() { } public static void add_rec_to_table(List<Col> list_col, String TableName) throws TransformerConfigurationException, TransformerException { try { File directory = new File(""); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(directory.getAbsolutePath() + "\\src\\XML\\Database.xml")); javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath(); String expresstion = "//Table[@Ten='" + TableName + "']"; Node node_tab = (Node) xpath.evaluate(expresstion, doc, XPathConstants.NODE); Element e_rec = doc.createElement("Record"); node_tab.appendChild(e_rec); for (Col col : list_col) { col.append_to_record(e_rec, doc); } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(directory.getAbsolutePath() + "\\src\\XML\\Database.xml")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); } catch (XPathExpressionException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; /** * * @author PC */ public class Attributes { public String Bang1; public String Bang2; public String[] ThuocTinh1; public String[] ThuocTinh2; public Condition DieuKien1; public Condition DieuKien2; public String BienNoi1; public String BienNoi2; public boolean SoSanh; public Attributes() { } public Attributes(String Bang1, String Bang2, String[] ThuocTinh1, String[] ThuocTinh2, Condition DieuKien1, Condition DieuKien2, String BienNoi1, String BienNoi2, boolean SoSanh) { this.Bang1=Bang1; this.Bang2=Bang2; this.ThuocTinh1=ThuocTinh1; this.ThuocTinh2=ThuocTinh2; this.DieuKien1=DieuKien1; this.DieuKien2=DieuKien2; this.BienNoi1=BienNoi1; this.BienNoi2=BienNoi2; this.SoSanh=SoSanh; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * * @author PC */ public class Create { public void CreateTable(Table dl) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException { File directory = new File(""); String filepath = directory.getAbsolutePath() + "\\src\\XML\\Database.xml"; DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(filepath); Element database=doc.getDocumentElement(); Element table=doc.createElement("Table"); table.setAttribute("Ten", dl.TenBang); //table.setAttribute("pk", dl.TenKhoaChinh); Element record =doc.createElement("Record"); Element[] col=new Element[dl.ListRecord.get(0).ListCol.size()]; for (int i = 0; i < dl.ListRecord.get(0).ListCol.size(); i++) { col[i]=doc.createElement("Col"); col[i].setAttribute("Ten", dl.ListRecord.get(0).ListCol.get(i).Ten); col[i].setAttribute("Type", dl.ListRecord.get(0).ListCol.get(i).Type); /* if(dl.ListRecord.get(0).ListCol.get(i).Ten.compareTo(dl.TenKhoaChinh)==0) col[i].setAttribute("PK", "true"); else col[i].setAttribute("PK", "false"); */ record.appendChild(col[i]); } table.appendChild(record); database.appendChild(table); TransformerFactory tff = TransformerFactory.newInstance(); Transformer transformer = tff.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource xmlSource = new DOMSource(doc); StreamResult outputTarget = new StreamResult(filepath); transformer.transform(xmlSource, outputTarget); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; /** * * @author PC */ import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Delete { public void DeleteRecord(Condition ct) { try { File directory = new File(""); String filepath = directory.getAbsolutePath() + "\\src\\XML\\Database.xml"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(filepath); XPathFactory xfactory = XPathFactory.newInstance(); javax.xml.xpath.XPath xpath = xfactory.newXPath(); String reg="//Table[@Ten='"+ct.TenBang+"']/Record[Col["; for (int i = 0; i < ct.Bien.length - 1; i++) { reg += "@Ten='" + ct.Bien[i] + "' and ." + ct.DauSoSanh[i] + "'" + ct.GiaTri[i] + "' " + ct.DauNoi[i] + " "; } reg += "@Ten='" + ct.Bien[ct.Bien.length - 1] + "' and ." + ct.DauSoSanh[ct.Bien.length - 1] + "'" + ct.GiaTri[ct.Bien.length - 1] + "']]"; System.out.println(reg); XPathExpression expr = xpath.compile(reg); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { Node item=nodes.item(i); item.getParentNode().removeChild(item); } TransformerFactory tff = TransformerFactory.newInstance(); Transformer transformer = tff.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource xmlSource = new DOMSource(doc); StreamResult outputTarget = new StreamResult(filepath); transformer.transform(xmlSource, outputTarget); } catch (Exception ex) { } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; /** * * @author PC */ import java.io.File; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Select { public void SelectRecord(Attributes tt, Table tb) { try { File directory = new File(""); String filepath = directory.getAbsolutePath() + "\\src\\XML\\Database.xml"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(filepath); XPathFactory xfactory = XPathFactory.newInstance(); javax.xml.xpath.XPath xpath = xfactory.newXPath(); String reg1 = new String(); String reg2 = new String(); if (tt.DieuKien1 != null) { reg1 = "//Table[@Ten='" + tt.DieuKien1.TenBang + "']/Record[Col["; for (int i = 0; i < tt.DieuKien1.Bien.length - 1; i++) { reg1 += "@Ten='" + tt.DieuKien1.Bien[i] + "' and ." + tt.DieuKien1.DauSoSanh[i] + "'" + tt.DieuKien1.GiaTri[i] + "' " + tt.DieuKien1.DauNoi[i] + " "; } reg1 += "@Ten='" + tt.DieuKien1.Bien[tt.DieuKien1.Bien.length - 1] + "' and ." + tt.DieuKien1.DauSoSanh[tt.DieuKien1.Bien.length - 1] + "'" + tt.DieuKien1.GiaTri[tt.DieuKien1.Bien.length - 1] + "']]"; } if (tt.DieuKien2 != null) { reg2 = "//Table[@Ten='" + tt.DieuKien2.TenBang + "']/Record[Col["; for (int i = 0; i < tt.DieuKien2.Bien.length - 1; i++) { reg2 += "@Ten='" + tt.DieuKien2.Bien[i] + "' and ." + tt.DieuKien2.DauSoSanh[i] + "'" + tt.DieuKien2.GiaTri[i] + "' " + tt.DieuKien2.DauNoi[i] + " "; } reg2 += "@Ten='" + tt.DieuKien2.Bien[tt.DieuKien2.Bien.length - 1] + "' and ." + tt.DieuKien2.DauSoSanh[tt.DieuKien2.Bien.length - 1] + "'" + tt.DieuKien2.GiaTri[tt.DieuKien2.Bien.length - 1] + "']]"; } System.out.println(reg1); System.out.println(reg2); String rx = new String(); String rx1 = new String(); String rx2 = new String(); if (tt.Bang2 == null && tt.DieuKien2 == null) { if (tt.DieuKien1 == null)//Khong where { rx = "//Table[@Ten='" + tt.Bang1 + "']/Record"; XPathExpression expr = xpath.compile(rx); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { NodeList nl = nodes.item(i).getChildNodes(); for (int j = 0; j < nl.getLength(); j++)//chon ra Col { Node it = nl.item(j); if (it.getNodeType() == Node.ELEMENT_NODE) { for (int k = 0; k < tt.ThuocTinh1.length; k++) { if (it.getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh1[k]) == 0) { System.out.println(nl.item(j).getTextContent()); } } } } } } else//Co where khong long khong ket { rx = "//Table[@Ten='" + tt.DieuKien1.TenBang + "']/Record[Col["; for (int i = 0; i < tt.DieuKien1.Bien.length - 1; i++) { rx += "@Ten='" + tt.DieuKien1.Bien[i] + "' and ." + tt.DieuKien1.DauSoSanh[i] + "'" + tt.DieuKien1.GiaTri[i] + "' " + tt.DieuKien1.DauNoi[i] + " "; } rx += "@Ten='" + tt.DieuKien1.Bien[tt.DieuKien1.Bien.length - 1] + "' and ." + tt.DieuKien1.DauSoSanh[tt.DieuKien1.Bien.length - 1] + "'" + tt.DieuKien1.GiaTri[tt.DieuKien1.Bien.length - 1] + "']]"; XPathExpression expr = xpath.compile(rx); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { NodeList nl = nodes.item(i).getChildNodes(); for (int j = 0; j < nl.getLength(); j++)//chon ra Col { Node it = nl.item(j); if (it.getNodeType() == Node.ELEMENT_NODE) { for (int k = 0; k < tt.ThuocTinh1.length; k++) { if (it.getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh1[k]) == 0) { System.out.println(nl.item(j).getTextContent()); } } } } } } } else//tt.Bang2!=null || tt.DieuKien2!=null { if (tt.DieuKien1 == null) { if (tt.DieuKien2 == null)//Ket khong long { rx1 = "//Table[@Ten='" + tt.Bang1 + "']/Record/Col[@Ten='" + tt.BienNoi1 + "']"; rx2 = "//Table[@Ten='" + tt.Bang2 + "']/Record/Col[@Ten='" + tt.BienNoi2 + "']"; XPathExpression expr1 = xpath.compile(rx1); Object result1 = expr1.evaluate(doc, XPathConstants.NODESET); NodeList nodes1 = (NodeList) result1; XPathExpression expr2 = xpath.compile(rx2); Object result2 = expr2.evaluate(doc, XPathConstants.NODESET); NodeList nodes2 = (NodeList) result2; for (int i = 0; i < nodes1.getLength(); i++) { Node i1 = nodes1.item(i); for (int j = 0; j < nodes2.getLength(); j++) { Node i2 = nodes2.item(j); if (i1.getTextContent().compareTo(i2.getTextContent()) == 0) { NodeList pr1 = i1.getParentNode().getChildNodes(); for (int l = 0; l < pr1.getLength(); l++) { if(pr1.item(l).getNodeType()==Node.ELEMENT_NODE) { for (int m = 0; m < tt.ThuocTinh1.length; m++) { if(pr1.item(l).getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh1[m])==0) System.out.println(pr1.item(l).getTextContent()); } } } NodeList pr2 = i2.getParentNode().getChildNodes(); for (int l = 0; l < pr2.getLength(); l++) { if(pr2.item(l).getNodeType()==Node.ELEMENT_NODE) { for (int m = 0; m < tt.ThuocTinh2.length; m++) { if(pr2.item(l).getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh2[m])==0) System.out.println(pr2.item(l).getTextContent()); } } } } } } } else { if (tt.Bang2 != null)//Long khong ket { //Chon Col rx1="//Table[@Ten='" + tt.Bang1 + "']/Record/Col[@Ten='"+tt.BienNoi1+"']"; XPathExpression expr1 = xpath.compile(rx1); Object result1 = expr1.evaluate(doc, XPathConstants.NODESET); NodeList nodes1 = (NodeList) result1; //Chon Record rx2 = "//Table[@Ten='" + tt.DieuKien2.TenBang + "']/Record[Col["; for (int i = 0; i < tt.DieuKien2.Bien.length - 1; i++) { rx2 += "@Ten='" + tt.DieuKien2.Bien[i] + "' and ." + tt.DieuKien2.DauSoSanh[i] + "'" + tt.DieuKien2.GiaTri[i] + "' " + tt.DieuKien2.DauNoi[i] + " "; } rx2 += "@Ten='" + tt.DieuKien2.Bien[tt.DieuKien2.Bien.length - 1] + "' and ." + tt.DieuKien2.DauSoSanh[tt.DieuKien2.Bien.length - 1] + "'" + tt.DieuKien2.GiaTri[tt.DieuKien2.Bien.length - 1] + "']]"; XPathExpression expr2 = xpath.compile(rx2); Object result2 = expr2.evaluate(doc, XPathConstants.NODESET); NodeList nodes2 = (NodeList) result2; for (int i = 0; i < nodes2.getLength(); i++) { NodeList nl2 = nodes2.item(i).getChildNodes(); for (int j = 0; j < nl2.getLength(); j++)//chon ra Col { Node it2 = nl2.item(j); if (it2.getNodeType() == Node.ELEMENT_NODE) { if (it2.getAttributes().item(0).getNodeValue().compareTo(tt.BienNoi2) == 0) { if(tt.SoSanh==true)//in { for (int k = 0; k < nodes1.getLength(); k++) { if(nodes1.item(k).getTextContent().equals(it2.getTextContent())) { NodeList pr1 = nodes1.item(k).getParentNode().getChildNodes(); for (int l = 0; l < pr1.getLength(); l++) { if(pr1.item(l).getNodeType()==Node.ELEMENT_NODE) { for (int m = 0; m < tt.ThuocTinh1.length; m++) { if(pr1.item(l).getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh1[m])==0) System.out.println(pr1.item(l).getTextContent()); } } } } } } else//not in { for (int k = 0; k < nodes1.getLength(); k++) { if(!nodes1.item(k).getTextContent().equals(it2.getTextContent())) { NodeList pr1 = nodes1.item(k).getParentNode().getChildNodes(); for (int l = 0; l < pr1.getLength(); l++) { if(pr1.item(l).getNodeType()==Node.ELEMENT_NODE) { for (int m = 0; m < tt.ThuocTinh1.length; m++) { if(pr1.item(l).getAttributes().item(0).getNodeValue().compareTo(tt.ThuocTinh1[m])==0) System.out.println(pr1.item(l).getTextContent()); } } } } } } } } } } } } } } } catch (Exception ex) { } } }
Java
package XML; /* * To change this template, choose Tools | Templates and open the template in * the editor. */ /** * * @author PC */ import java.lang.*; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; public class XuLyChuoi { public String XoaMoiKhoangTrang(String chuoi) { return chuoi.replaceAll("\\s", ""); } public void TaoBang(String chuoi, Table dl) { String[] h = chuoi.split("\\("); String c1 = XoaMoiKhoangTrang(h[0]); String ct = c1.substring(0, 11); ct = ct.toLowerCase(); if (ct.contains("createtable")) { dl.TenBang = c1.substring(11, c1.length()); } String c2 = XoaMoiKhoangTrang(h[1]); Record rc=new Record(); if (c2.contains("primarykey")) { c2 = c2.substring(0, c2.length() - 1); String[] tt = c2.split(","); for (int i = 0; i < tt.length - 1; i++) { if (tt[i].contains("int")) { Col temp=new Col(); temp.Type = "int"; temp.Ten = tt[i].substring(0, tt[i].length() - 3); temp.Value=new String(); rc.ListCol.add(temp); } if (tt[i].contains("varchar")) { Col temp=new Col(); temp.Type = "string"; temp.Ten = tt[i].substring(0, tt[i].length() - 7); temp.Value=new String(); rc.ListCol.add(temp); } } h[2] = XoaMoiKhoangTrang(h[2]); dl.TenKhoaChinh = h[2].substring(0, h[2].length() - 2); } else { c2 = c2.substring(0, c2.length() - 1); String[] tt = c2.split(","); for (int i = 0; i < tt.length; i++) { if (tt[i].contains("int")) { Col temp=new Col(); temp.Type = "int"; temp.Ten = tt[i].substring(0, tt[i].length() - 3); temp.Value=new String(); rc.ListCol.add(temp); } if (tt[i].contains("varchar")) { Col temp=new Col(); temp.Type = "string"; temp.Ten = tt[i].substring(0, tt[i].length() - 7); temp.Value=new String(); rc.ListCol.add(temp); } } dl.TenKhoaChinh = null; } dl.ListRecord.add(rc); } public void XoaDong(String chuoi, Condition ct) { String regex = null; if (chuoi.contains("where")) { regex = "where"; } if (chuoi.contains("WHERE")) { regex = "WHERE"; } String[] h = chuoi.split(regex); h[0] = XoaMoiKhoangTrang(h[0]); ct.TenBang = h[0].substring(10); char[] s = h[1].toCharArray(); List<String> d = new ArrayList<String>(); List<String> n = new ArrayList<String>(); for (int i = 0; i < s.length; i++) { if (s[i] == '<' || s[i] == '=' || s[i] == '>') { d.add(Character.toString(s[i])); } } for (int i = 0; i < s.length - 4; i++) { if ((s[i] == ' ' && s[i + 1] == 'a' && s[i + 2] == 'n' && s[i + 3] == 'd' && s[i + 4] == ' ') || (s[i] == ' ' && s[i + 1] == 'A' && s[i + 2] == 'N' && s[i + 3] == 'D' && s[i + 4] == ' ')) { n.add("and"); } if ((s[i] == ' ' && s[i + 1] == 'o' && s[i + 2] == 'r' && s[i + 3] == ' ') || (s[i] == ' ' && s[i + 1] == 'O' && s[i + 2] == 'R' && s[i + 3] == ' ')) { n.add("or"); } } String tokens[] = null; String splitPattern = "<|>|=|AND|OR|and|or"; Pattern p = Pattern.compile(splitPattern); tokens = p.split(h[1].trim()); ct.Bien = new String[tokens.length / 2]; ct.GiaTri = new String[tokens.length / 2]; ct.DauNoi = new String[(tokens.length / 2) - 1]; for (int i = 0; i < tokens.length / 2; i++) { ct.Bien[i] = tokens[2 * i].trim(); if (tokens[2 * i + 1].trim().contains("'")) { ct.GiaTri[i] = tokens[2 * i + 1].trim().replaceAll("'", " ").trim(); } else { ct.GiaTri[i] = tokens[2 * i + 1].trim(); } } ct.DauNoi = n.toArray(new String[0]); ct.DauSoSanh = d.toArray(new String[0]); } public void ChonDong(String chuoi, Attributes tt) { chuoi = chuoi.trim(); chuoi = chuoi.replaceAll("\n", " "); chuoi = chuoi.replaceAll("\t", " "); System.out.println(chuoi); String tokens[] = null; String splitPattern = "select |SELECT | FROM | from "; if (!(chuoi.contains(" WHERE ") || chuoi.contains(" where "))) { Pattern p = Pattern.compile(splitPattern); tokens = p.split(chuoi); tokens[1] = XoaMoiKhoangTrang(tokens[1]); String c[] = tokens[1].split(","); tt.Bang1 = tokens[2].trim(); tt.Bang2 = null; tt.ThuocTinh1 = new String[c.length]; for (int i = 0; i < c.length; i++) { tt.ThuocTinh1[i] = c[i]; } } else { splitPattern += "| WHERE | where "; Pattern p = Pattern.compile(splitPattern); tokens = p.split(chuoi); if (tokens[2].contains(",")) //co 2 bang { tokens[2] = XoaMoiKhoangTrang(tokens[2]); tt.Bang1 = tokens[2].substring(0, tokens[2].indexOf(",")).trim(); tt.Bang2 = tokens[2].substring(tokens[2].indexOf(",") + 1, tokens[2].length()).trim(); String[] at = tokens[1].split(","); List<String> tt1 = new ArrayList<String>(); List<String> tt2 = new ArrayList<String>(); for (int i = 0; i < at.length; i++) { if (at[i].contains(tt.Bang1)) { tt1.add(at[i].substring(tt.Bang1.length() + 1)); } if (at[i].contains(tt.Bang2)) { tt2.add(at[i].substring(tt.Bang2.length() + 1)); } } tt.ThuocTinh1 = tt1.toArray(new String[0]); tt.ThuocTinh2 = tt2.toArray(new String[0]); System.out.println(tt.Bang1); for (int i = 0; i < tt.ThuocTinh1.length; i++) { System.out.println(tt.ThuocTinh1[i]); } System.out.println("\n" + tt.Bang2); for (int i = 0; i < tt.ThuocTinh2.length; i++) { System.out.println(tt.ThuocTinh2[i]); } String[] bn = tokens[3].split("="); for (int i = 0; i < bn.length; i++) { if (bn[i].contains(tt.Bang1)) { tt.BienNoi1 = bn[i].substring(tt.Bang1.length() + 1); } if (bn[i].contains(tt.Bang2)) { tt.BienNoi2 = bn[i].substring(tt.Bang2.length() + 1); } } tt.SoSanh = true; System.out.println(tt.BienNoi1); System.out.println(tt.BienNoi2); } else //Khong co 2 bang { tokens[1] = XoaMoiKhoangTrang(tokens[1]); String c[] = tokens[1].split(","); tt.Bang1 = tokens[2].trim(); tt.ThuocTinh1 = new String[c.length]; for (int i = 0; i < c.length; i++) { tt.ThuocTinh1[i] = c[i]; } if (tokens.length == 4) //Khong long nhau { tt.Bang2 = null; for (int i = 0; i < tokens.length; i++) { System.out.println(tokens[i]); } tt.DieuKien1=new Condition(); tt.DieuKien1.TenBang=tt.Bang1; char[] s = tokens[3].toCharArray(); List<String> d = new ArrayList<String>(); List<String> n = new ArrayList<String>(); for (int i = 0; i < s.length; i++) { if (s[i] == '<' || s[i] == '=' || s[i] == '>') { d.add(Character.toString(s[i])); } } for (int i = 0; i < s.length - 4; i++) { if ((s[i] == ' ' && s[i + 1] == 'a' && s[i + 2] == 'n' && s[i + 3] == 'd' && s[i + 4] == ' ') || (s[i] == ' ' && s[i + 1] == 'A' && s[i + 2] == 'N' && s[i + 3] == 'D' && s[i + 4] == ' ')) { n.add("and"); } if ((s[i] == ' ' && s[i + 1] == 'o' && s[i + 2] == 'r' && s[i + 3] == ' ') || (s[i] == ' ' && s[i + 1] == 'O' && s[i + 2] == 'R' && s[i + 3] == ' ')) { n.add("or"); } } String tks[] = null; String sp = "<|>|=|AND|OR|and|or"; Pattern pt = Pattern.compile(sp); tks = pt.split(tokens[3].trim()); tt.DieuKien1.Bien = new String[tks.length / 2]; tt.DieuKien1.GiaTri = new String[tks.length / 2]; tt.DieuKien1.DauNoi = new String[(tks.length / 2) - 1]; for (int i = 0; i < tks.length / 2; i++) { tt.DieuKien1.Bien[i] = tks[2 * i].trim(); if (tks[2 * i + 1].trim().contains("'")) { tt.DieuKien1.GiaTri[i]=tks[2 * i + 1].trim().replaceAll("'", " ").trim(); } else { tt.DieuKien1.GiaTri[i] = tks[2 * i + 1].trim(); } } tt.DieuKien1.DauNoi = n.toArray(new String[0]); tt.DieuKien1.DauSoSanh = d.toArray(new String[0]); } else //Long Nhau { tt.Bang2 = tokens[5].trim(); tt.BienNoi2 = tokens[4].trim(); System.out.println(tt.Bang2); System.out.println(tt.BienNoi2); for (int i = 0; i < tokens.length; i++) { System.out.println(tokens[i]); } tokens[6]=tokens[6].trim().substring(0,tokens[6].length()-1); tt.DieuKien2=new Condition(); tt.DieuKien2.TenBang=tt.Bang2; char[] s = tokens[6].toCharArray(); List<String> d = new ArrayList<String>(); List<String> n = new ArrayList<String>(); for (int i = 0; i < s.length; i++) { if (s[i] == '<' || s[i] == '=' || s[i] == '>') { d.add(Character.toString(s[i])); } } for (int i = 0; i < s.length - 4; i++) { if ((s[i] == ' ' && s[i + 1] == 'a' && s[i + 2] == 'n' && s[i + 3] == 'd' && s[i + 4] == ' ') || (s[i] == ' ' && s[i + 1] == 'A' && s[i + 2] == 'N' && s[i + 3] == 'D' && s[i + 4] == ' ')) { n.add("and"); } if ((s[i] == ' ' && s[i + 1] == 'o' && s[i + 2] == 'r' && s[i + 3] == ' ') || (s[i] == ' ' && s[i + 1] == 'O' && s[i + 2] == 'R' && s[i + 3] == ' ')) { n.add("or"); } } String tks[] = null; String sp = "<|>|=|AND|OR|and|or"; Pattern pt = Pattern.compile(sp); tks = pt.split(tokens[6].trim()); tt.DieuKien2.Bien = new String[tks.length / 2]; tt.DieuKien2.GiaTri = new String[tks.length / 2]; tt.DieuKien2.DauNoi = new String[(tks.length / 2) - 1]; for (int i = 0; i < tks.length / 2; i++) { tt.DieuKien2.Bien[i] = tks[2 * i].trim(); if (tks[2 * i + 1].trim().contains("'")) { tt.DieuKien2.GiaTri[i] = tks[2 * i + 1].trim().replaceAll("'", " ").trim(); } else { tt.DieuKien2.GiaTri[i] = tks[2 * i + 1].trim(); } } tt.DieuKien2.DauNoi = n.toArray(new String[0]); tt.DieuKien2.DauSoSanh = d.toArray(new String[0]); tokens[3]=tokens[3].trim(); tt.BienNoi1=tokens[3].substring(0,tokens[3].indexOf(" ")); if(tokens[3].contains(" not ") || tokens[3].contains(" NOT ")) tt.SoSanh=false; else tt.SoSanh=true; } } } } }
Java
import java.util.logging.Level; import java.util.logging.Logger; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author TanAnh */ public class Parentheses { void display(String s) { try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(Parentheses.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(s); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GiaoTiepThread; /** * * @author TanAnh */ class Demo { public static void main(String args[]) { Queue q = new Queue(); new Publisher(q); new Consumer(q); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GiaoTiepThread; /** * * @author TanAnh */ class Queue { int exchangeValue; boolean busy = false; synchronized int get() { if (!busy) { try { wait(); } catch (InterruptedException e) { System.out.println( "Get: InterruptedException"); } } System.out.println("Get: " + exchangeValue); busy=false; notify(); return exchangeValue; } synchronized void put(int exchangeValue) { if (busy) { try { wait(); } catch (InterruptedException e) { System.out.println( "Put: InterruptedException"); } } this.exchangeValue = exchangeValue; busy = true; System.out.println("Put: " + exchangeValue); notify(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GiaoTiepThread; /** * * @author TanAnh */ class Publisher implements Runnable { Queue q; Publisher(Queue q) { this.q = q; new Thread(this, "Publisher").start(); } public void run() { for (int i = 0; i < 5; i++) { q.put(i); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GiaoTiepThread; /** * * @author TanAnh */ class Consumer implements Runnable { Queue q; Consumer(Queue q) { this.q = q; new Thread(this, "Consumer").start(); } public void run() { for (int i = 0; i < 5; i++) { q.get(); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author TanAnh */ public class Demo { public static void main(String args[]) throws InterruptedException{ Parentheses p3=new Parentheses(); MyThread name1=new MyThread(p3, "Bob"); MyThread name2=new MyThread(p3, "Mary"); MyThread name3=new MyThread(p3, "Anh"); MyThread name4=new MyThread(p3, "Luong"); name1.t.join(); name2.t.join(); name3.t.join(); name4.t.join(); System.out.println("Interupted"); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author TanAnh */ public class MyThread implements Runnable { String s1; Parentheses p1; Thread t; public MyThread(Parentheses p2, String s2){ p1=p2; s1=s2; t=new Thread(this); t.start(); } @Override public void run() { synchronized(p1){ p1.display(s1); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * * @author TanAnh */ public class String_Utilities { private static String getPara(String query) { int from = query.indexOf('('); int to = query.indexOf(')'); return query.substring(from + 1, to).trim(); } private static String getParavalues(String query) { query = query.toLowerCase(); int from = query.indexOf("values") + "values".length(); int to = query.length() - 1; return query.substring(from + 1, to).trim(); } private static List<Col> getListCol(String Para, String ParaValues) { List<Col> res = new LinkedList<Col>(); String[] lisPara = Para.split(","); String[] lisParaValues = ParaValues.split(","); for (int i = 0; i < lisPara.length; i++) { Col c = new Col(); if (lisParaValues[i].contains("'")) { c.Type = "String"; } else { c.Type = "int"; } c.Ten = lisPara[i]; c.Value = lisParaValues[i]; res.add(c); } return res; } private static void add_rec_to_table(List<Col> list_col, String TableName) throws TransformerConfigurationException, TransformerException { try { String filePath = "c:\\Database.xml"; Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(filePath)); javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath(); String expresstion = "//Table[@Ten='" + TableName + "']"; Node node_tab = (Node) xpath.evaluate(expresstion, doc, XPathConstants.NODE); Element e_rec = doc.createElement("Record"); node_tab.appendChild(e_rec); for (Col col : list_col) { col.append_to_record(e_rec, doc); } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(filePath)); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); } catch (XPathExpressionException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } } private static String getTableName_update(String query) { int from = "update".length() + 1; int to = query.indexOf("set"); String res = query.substring(from, to); return res.trim(); } private static String getPara_update(String query) { int from = query.indexOf("set") + "set".length(); int to = query.indexOf("where"); String res = query.substring(from, to); return res.trim(); } private static String get_Where(String query) { int from = query.indexOf("where") + "where".length(); int to = query.length(); String res = query.substring(from, to); return res.trim(); } private static void do_update(String Para, String s_Where, String TableName) { String[] where = s_Where.split("="); String[] paras = Para.split(","); try { String filePath = "c:\\Database.xml"; Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(filePath)); javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath(); String expresstion = "//Table[@Ten='" + TableName + "']"; Node node_tab = (Node) xpath.evaluate(expresstion, doc, XPathConstants.NODE); expresstion = "//Record[Col=" + where[1] + "]"; Node node_rec = get_record_update(where, doc); Node node_col; for (String string : paras) { String[] s_val = string.split("="); // expresstion = "//Col[@Ten='" + s_val[0].trim() + "']"; //// String ss="HoTen"; //// expresstion = "//Col[@Ten='" + ss + "']"; //// // node_col = (Node) xpath.evaluate(expresstion, node_rec, XPathConstants.NODE); // // // System.err.println(node_col.getNodeValue()); // node_col.setTextContent(s_val[1]); // NodeList list_col = node_rec.getChildNodes(); int n = list_col.getLength(); for (int i = 0; i < n; i++) { String tam = null; if (list_col.item(i).getNodeName() == "Col") { tam = list_col.item(i).getAttributes().getNamedItem("Ten").getTextContent(); } if (tam.contains(s_val[0].trim())) { list_col.item(i).setTextContent(s_val[1]); } } } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(filePath)); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); } catch (TransformerException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (XPathExpressionException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } } private static Node get_record_update(String[] where, Document doc) { Node res = null; String tagname = where[0].trim(); NodeList nodelist = doc.getElementsByTagName("Col"); for (int i = 0; i < nodelist.getLength(); i++) { String tam = nodelist.item(i).getTextContent().trim(); if (tam.contains(where[1])) { res = nodelist.item(i); break; } } return res.getParentNode(); } static class Col { public String Ten; public String Type; public String Value; public Col() { } void append_to_record(Node rec, Document doc) { Element col = doc.createElement("Col"); col.setAttribute("Ten", this.Ten); col.setAttribute("Type", this.Type); col.setTextContent(this.Value); rec.appendChild(col); System.out.println("added a record"); } } public enum QUERY { SELECT, INSERT, UPDATE, DELETE, CREATE } public static QUERY getQuery(String s) { QUERY res = null; int kq = 0; String sub = s.substring(0, "delete".length()).toUpperCase(); if (sub.compareToIgnoreCase(QUERY.DELETE.toString()) == 0) { res = QUERY.DELETE; } if (sub.compareToIgnoreCase(QUERY.UPDATE.toString()) == 0) { res = QUERY.UPDATE; } if (sub.compareToIgnoreCase(QUERY.INSERT.toString()) == 0) { res = QUERY.INSERT; } if (sub.compareToIgnoreCase(QUERY.SELECT.toString()) == 0) { res = QUERY.SELECT; } if (sub.compareToIgnoreCase(QUERY.CREATE.toString()) == 0) { res = QUERY.CREATE; } return res; } public static void main(String args[]) throws TransformerConfigurationException, TransformerException { String query = "update QLHS set HoTen='Tuan Kiet', DTB=8.9 where MaHS=6"; QUERY res = getQuery(query); switch (res) { case INSERT: insert_method(query); break; case UPDATE: update_method(query); break; } } private static void update_method(String query) { String tableName = getTableName_update(query); String Para = getPara_update(query); String s_Where = get_Where(query); do_update(Para, s_Where, tableName); } static void insert_method(String query) throws TransformerConfigurationException, TransformerException { String tableName = getTableName(query); String Para = getPara(query); String ParaValues = getParavalues(query); List<Col> list_col = getListCol(Para, ParaValues); add_rec_to_table(list_col, tableName); System.err.println(getQuery(query)); } private static String getTableName(String query) { int from = query.indexOf("into") + "into".length(); int to = query.indexOf('('); return query.substring(from, to).trim(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; /** * * @author TanAnh */ import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.io.File; public class NewClass { public static void main(String argv[]) { try { File fXmlFile = new File("c:\\test.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("staff"); System.out.println("-----------------------"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("First Name : " + getTagValue("firstname", eElement)); System.out.println("Last Name : " + getTagValue("lastname", eElement)); System.out.println("Nick Name : " + getTagValue("nickname", eElement)); System.out.println("Salary : " + getTagValue("salary", eElement)); } } } catch (Exception e) { System.err.println(e.getMessage()); } } private static String getTagValue(String sTag, Element eElement) { NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes(); Node nValue = (Node) nlList.item(0); return nValue.getNodeValue(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.*; import javax.xml.xpath.*; import org.w3c.dom.*; import org.xml.sax.SAXException; /** * * @author TanAnh */ public class XPath { public static void main(String args[]) { String a; try { String filePath = "C:\\test.xml"; DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new File(filePath)); javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "/company/staff"; Node widgetNode = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE); NodeList listnod = widgetNode.getChildNodes(); for (int i = 0; i < listnod.getLength(); i++) { a = listnod.item(i).getTextContent(); System.out.print("-" + a); } System.out.println(); System.out.println("----------------"); expression = "nickname"; Node newnode = (Node) xpath.evaluate(expression, widgetNode, XPathConstants.NODE); System.err.println(newnode.getTextContent()); } catch (XPathExpressionException ex) { } catch (SAXException ex) { } catch (IOException ex) { } catch (ParserConfigurationException ex) { } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; import java.io.File; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.*; /** * * @author TanAnh */ public class WriteXMLFile { public static void main(String argv[]) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements // Document doc = docBuilder.newDocument(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("company"); doc.appendChild(rootElement); // staff elements Element staff = doc.createElement("Staff"); rootElement.appendChild(staff); // set attribute to staff element Attr attr = doc.createAttribute("id"); attr.setValue("1"); staff.setAttributeNode(attr); // shorten way // staff.setAttribute("id", "1"); // firstname elements Element firstname = doc.createElement("firstname"); firstname.appendChild(doc.createTextNode("yong")); staff.appendChild(firstname); // lastname elements Element lastname = doc.createElement("lastname"); lastname.appendChild(doc.createTextNode("mook kim")); staff.appendChild(lastname); // nickname elements Element nickname = doc.createElement("nickname"); nickname.appendChild(doc.createTextNode("mkyong")); staff.appendChild(nickname); // salary elements Element salary = doc.createElement("salary"); salary.appendChild(doc.createTextNode("100000")); staff.appendChild(salary); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("C:\\test.xml")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.io.File; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.*; import org.w3c.dom.NamedNodeMap; public class ModifyXMLFile { public static void main(String argv[]) { try { String filePath = "C:\\test.xml"; DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new File(filePath)); // Get the root element Node company = doc.getFirstChild(); // Get the staff element , it may not working if tag has spaces, or // whatever weird characters in front...it's better to use // getElementsByTagName() to get it directly. // Node staff = company.getFirstChild(); // Get the staff element by tag name directly Node staff = doc.getElementsByTagName("staff").item(0); // update staff attribute NamedNodeMap attr = staff.getAttributes(); Node nodeAttr = attr.getNamedItem("id"); nodeAttr.setTextContent("2"); // append a new node to staff Element age = doc.createElement("age"); age.appendChild(doc.createTextNode("28")); staff.appendChild(age); // loop the staff child node NodeList list = staff.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); // get the salary element, and update the value if ("salary".equals(node.getNodeName())) { node.setTextContent("2000000"); } //remove firstname if ("firstname".equals(node.getNodeName())) { staff.removeChild(node); } } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(filePath)); transformer.transform(source, result); System.out.println("Done"); } catch (Exception pce) { System.err.println("ERR"+pce.getMessage()); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author TanAnh */ import java.net.*; import java.io.*; public class SimpleClient { public static void main(String args[]) { try { Socket s = new Socket("localhost", 2002); OutputStream os = s.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(os); HocSinh to = new HocSinh(1, "Nguyen Tan Anh"); oos.writeObject(to); oos.close(); os.close(); s.close(); } catch (Exception e) { System.out.println(e); } } }
Java
import java.util.logging.Level; import java.util.logging.Logger; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author TanAnh */ public class Parentheses { void display(String s) { try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(Parentheses.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(s); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package TestSocket; import java.io.*; import java.net.*; /** * * @author TanAnh */ public class SimpleServer { public static void main(String args[]) { int port = 2002; try { ServerSocket ss = new ServerSocket(port); Socket s = ss.accept(); InputStream is = s.getInputStream(); ObjectInputStream ois = new ObjectInputStream(is); HocSinh to = (HocSinh) ois.readObject(); if (to != null) { System.out.println(to.id); System.out.println(to.value); } is.close(); s.close(); ss.close(); } catch (Exception e) { System.out.println(e); } } }
Java
package TestSocket; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.Serializable; /** * * @author TanAnh */ class HocSinh implements Serializable { int value; String id; public HocSinh(int v, String s) { this.value = v; this.id = s; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GiaoTiepThread; /** * * @author TanAnh */ class Demo { public static void main(String args[]) { Queue q = new Queue(); new Publisher(q); new Consumer(q); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GiaoTiepThread; /** * * @author TanAnh */ class Queue { int exchangeValue; boolean busy = false; synchronized int get() { if (!busy) { try { wait(); } catch (InterruptedException e) { System.out.println( "Get: InterruptedException"); } } System.out.println("Get: " + exchangeValue); busy=false; notify(); return exchangeValue; } synchronized void put(int exchangeValue) { if (busy) { try { wait(); } catch (InterruptedException e) { System.out.println( "Put: InterruptedException"); } } this.exchangeValue = exchangeValue; busy = true; System.out.println("Put: " + exchangeValue); notify(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GiaoTiepThread; /** * * @author TanAnh */ class Publisher implements Runnable { Queue q; Publisher(Queue q) { this.q = q; new Thread(this, "Publisher").start(); } public void run() { for (int i = 0; i < 5; i++) { q.put(i); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package GiaoTiepThread; /** * * @author TanAnh */ class Consumer implements Runnable { Queue q; Consumer(Queue q) { this.q = q; new Thread(this, "Consumer").start(); } public void run() { for (int i = 0; i < 5; i++) { q.get(); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author TanAnh */ public class Demo { public static void main(String args[]) throws InterruptedException{ Parentheses p3=new Parentheses(); MyThread name1=new MyThread(p3, "Bob"); MyThread name2=new MyThread(p3, "Mary"); MyThread name3=new MyThread(p3, "Anh"); MyThread name4=new MyThread(p3, "Luong"); name1.t.join(); name2.t.join(); name3.t.join(); name4.t.join(); System.out.println("Interupted"); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author TanAnh */ public class MyThread implements Runnable { String s1; Parentheses p1; Thread t; public MyThread(Parentheses p2, String s2){ p1=p2; s1=s2; t=new Thread(this); t.start(); } @Override public void run() { synchronized(p1){ p1.display(s1); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * * @author TanAnh */ public class String_Utilities { private static String getPara(String query) { int from = query.indexOf('('); int to = query.indexOf(')'); return query.substring(from + 1, to).trim(); } private static String getParavalues(String query) { query = query.toLowerCase(); int from = query.indexOf("values") + "values".length(); int to = query.length() - 1; return query.substring(from + 1, to).trim(); } private static List<Col> getListCol(String Para, String ParaValues) { List<Col> res = new LinkedList<Col>(); String[] lisPara = Para.split(","); String[] lisParaValues = ParaValues.split(","); for (int i = 0; i < lisPara.length; i++) { Col c = new Col(); if (lisParaValues[i].contains("'")) { c.Type = "String"; } else { c.Type = "int"; } c.Ten = lisPara[i]; c.Value = lisParaValues[i]; res.add(c); } return res; } private static void add_rec_to_table(List<Col> list_col, String TableName) throws TransformerConfigurationException, TransformerException { try { File directory = new File(""); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(directory.getAbsolutePath() + "\\src\\XML\\Database.xml")); javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath(); String expresstion = "//Table[@Ten='" + TableName + "']"; Node node_tab = (Node) xpath.evaluate(expresstion, doc, XPathConstants.NODE); Element e_rec = doc.createElement("Record"); node_tab.appendChild(e_rec); for (Col col : list_col) { col.append_to_record(e_rec, doc); } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(directory.getAbsolutePath() + "\\src\\XML\\Database.xml")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); } catch (XPathExpressionException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } } private static String getTableName_update(String query) { int from = "update".length() + 1; int to = query.indexOf("set"); String res = query.substring(from, to); return res.trim(); } private static String getPara_update(String query) { int from = query.indexOf("set") + "set".length(); int to = query.indexOf("where"); String res = query.substring(from, to); return res.trim(); } private static String get_Where(String query) { int from = query.indexOf("where") + "where".length(); int to = query.length(); String res = query.substring(from, to); return res.trim(); } private static void do_update(String Para, String s_Where, String TableName) { String[] where = s_Where.split("="); String[] paras = Para.split(","); try { File directory = new File(""); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(directory.getAbsolutePath() + "\\src\\XML\\Database.xml")); javax.xml.xpath.XPath xpath = XPathFactory.newInstance().newXPath(); String expresstion = "//Table[@Ten='" + TableName + "']"; Node node_tab = (Node) xpath.evaluate(expresstion, doc, XPathConstants.NODE); expresstion = "//Record[Col=" + where[1] + "]"; Node node_rec = get_record_update(where, doc); Node node_col; for (String string : paras) { String[] s_val = string.split("="); // expresstion = "//Col[@Ten='" + s_val[0].trim() + "']"; //// String ss="HoTen"; //// expresstion = "//Col[@Ten='" + ss + "']"; //// // node_col = (Node) xpath.evaluate(expresstion, node_rec, XPathConstants.NODE); // // // System.err.println(node_col.getNodeValue()); // node_col.setTextContent(s_val[1]); // NodeList list_col = node_rec.getChildNodes(); int n = list_col.getLength(); for (int i = 0; i < n; i++) { String tam = null; if (list_col.item(i).getNodeName() == "Col") { tam = list_col.item(i).getAttributes().getNamedItem("Ten").getTextContent(); } if (tam.contains(s_val[0].trim())) { list_col.item(i).setTextContent(s_val[1]); } } } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(directory.getAbsolutePath() + "\\src\\XML\\Database.xml")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); } catch (TransformerException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (XPathExpressionException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(String_Utilities.class.getName()).log(Level.SEVERE, null, ex); } } private static Node get_record_update(String[] where, Document doc) { Node res = null; String tagname = where[0].trim(); NodeList nodelist = doc.getElementsByTagName("Col"); for (int i = 0; i < nodelist.getLength(); i++) { String tam = nodelist.item(i).getTextContent().trim(); if (tam.contains(where[1])) { res = nodelist.item(i); break; } } return res.getParentNode(); } static class Col { public String Ten; public String Type; public String Value; public Col() { } void append_to_record(Node rec, Document doc) { Element col = doc.createElement("Col"); col.setAttribute("Ten", this.Ten); col.setAttribute("Type", this.Type); col.setTextContent(this.Value); rec.appendChild(col); System.out.println("added a record"); } } public enum QUERY { SELECT, INSERT, UPDATE, DELETE, CREATE } public static QUERY getQuery(String s) { QUERY res = null; int kq = 0; String sub = s.substring(0, "delete".length()).toUpperCase(); if (sub.compareToIgnoreCase(QUERY.DELETE.toString()) == 0) { res = QUERY.DELETE; } if (sub.compareToIgnoreCase(QUERY.UPDATE.toString()) == 0) { res = QUERY.UPDATE; } if (sub.compareToIgnoreCase(QUERY.INSERT.toString()) == 0) { res = QUERY.INSERT; } if (sub.compareToIgnoreCase(QUERY.SELECT.toString()) == 0) { res = QUERY.SELECT; } if (sub.compareToIgnoreCase(QUERY.CREATE.toString()) == 0) { res = QUERY.CREATE; } return res; } public static void main(String args[]) throws TransformerConfigurationException, TransformerException { String query = "update HOCSINH set HoTen='Tuan Kiet', DTB=8.9 where MaHS=6"; QUERY res = getQuery(query); switch (res) { case INSERT: insert_method(query); break; case UPDATE: update_method(query); break; } } private static void update_method(String query) { String tableName = getTableName_update(query); String Para = getPara_update(query); String s_Where = get_Where(query); do_update(Para, s_Where, tableName); } static void insert_method(String query) throws TransformerConfigurationException, TransformerException { String tableName = getTableName(query); String Para = getPara(query); String ParaValues = getParavalues(query); List<Col> list_col = getListCol(Para, ParaValues); add_rec_to_table(list_col, tableName); System.err.println(getQuery(query)); } private static String getTableName(String query) { int from = query.indexOf("into") + "into".length(); int to = query.indexOf('('); return query.substring(from, to).trim(); } }
Java
package XML; public class Table { public String TenBang; public String[] Kieu; public String[] TenBien; public String TenKhoaChinh; public String KieuKhoaChinh; public String[] GiaTri; public Table(String TenBang, String[] Kieu, String[] TenBien, String TenKhoaChinh, String KieuKhoaChinh, String[] GiaTri) { this.TenBang=TenBang; this.Kieu=Kieu; this.TenBien=TenBien; this.TenKhoaChinh=TenKhoaChinh; this.KieuKhoaChinh=KieuKhoaChinh; this.GiaTri=GiaTri; } public Table() { } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; import java.util.List; /** * * @author PC */ public class Records{ public List<Record> records; public Records() { } public Records(List<Record> records) { this.records=records; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package XML; /** * * @author PC */ public class Condition { public String TenBang; public String[] Bien; public String[] GiaTri; public String[] DauSoSanh; public String[] DauNoi; public Condition() { } public Condition(String TenBang,String[] Bien,String[] GiaTri,String[] DauSoSanh,String[] DauNoi) { this.TenBang=TenBang; this.Bien=Bien; this.GiaTri=GiaTri; this.DauSoSanh=DauSoSanh; this.DauNoi=DauNoi; } }
Java