package net.sourceforge.phpeclipse.wiki.actions.mediawiki.post; //Parts of this sources are copied and modified from the jEdit Wikipedia plugin: //http://www.djini.de/software/wikipedia/index.html // //The modified sources are available under the "Common Public License" //with permission from the original author: Daniel Wunsch import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import net.sourceforge.phpeclipse.wiki.actions.mediawiki.config.IWikipedia; import net.sourceforge.phpeclipse.wiki.actions.mediawiki.connect.Content; import net.sourceforge.phpeclipse.wiki.actions.mediawiki.connect.MediaWikiConnector; import net.sourceforge.phpeclipse.wiki.editor.WikiEditor; import net.sourceforge.phpeclipse.wiki.editor.WikiEditorPlugin; import net.sourceforge.phpeclipse.wiki.internal.Configuration; import net.sourceforge.phpeclipse.wiki.internal.ConfigurationManager; import net.sourceforge.phpeclipse.wiki.internal.IConfiguration; import net.sourceforge.phpeclipse.wiki.preferences.Util; import net.sourceforge.phpeclipse.wiki.velocity.EditorText; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.action.IAction; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.window.Window; import org.eclipse.ui.IEditorActionDelegate; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.dialogs.ListSelectionDialog; import org.eclipse.ui.internal.dialogs.ListContentProvider; import org.eclipse.ui.texteditor.AbstractTextEditor; public class StoreWikipediaAction implements IEditorActionDelegate { /** * Constant for an empty char array */ public static final char[] NO_CHAR = new char[0]; private static final int DEFAULT_READING_SIZE = 8192; private AbstractTextEditor fEditor; private EditorText text; private IWorkbenchWindow window; public void dispose() { } public String generateUrl(Configuration config, String template, String wikiname) { /* first, we init the runtime engine. Defaults are fine. */ try { Velocity.init(); /* lets make a Context and put data into it */ VelocityContext context = new VelocityContext(); context.put("config", config); text.clear(); text.setWikiname(wikiname); context.put("text", text); /* lets make our own string to render */ StringWriter w = new StringWriter(); w = new StringWriter(); Velocity.evaluate(context, w, "mystring", template); return w.toString(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return template; } protected Configuration getConfigurationPrefix(String prefix) { List allConfigsList = ConfigurationManager.getInstance().getConfigurations(); ArrayList configsList = new ArrayList(); for (int i = 0; i < allConfigsList.size(); i++) { IConfiguration temp = (IConfiguration) allConfigsList.get(i); if (temp.getType().startsWith(prefix)) { configsList.add(temp); } } if (configsList.size() == 1) { return (Configuration) configsList.get(0); } Collections.sort(configsList); Configuration configuration = null; ListSelectionDialog listSelectionDialog = new ListSelectionDialog(WikiEditorPlugin.getDefault().getWorkbench() .getActiveWorkbenchWindow().getShell(), configsList, new ListContentProvider(), new LabelProvider(), "Select the refresh URL."); listSelectionDialog.setTitle("Multiple active configuration found"); if (listSelectionDialog.open() == Window.OK) { Object[] locations = listSelectionDialog.getResult(); if (locations != null) { for (int i = 0; i < locations.length; i++) { configuration = (Configuration) locations[i]; break; } } } return configuration; } protected Configuration getConfiguration() { return getConfigurationPrefix(WikiEditorPlugin.PREFIX_STORE); } public IDocument getDocument() { IDocument doc = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput()); return doc; } private String getWikiFile(IFile file) { return Util.getFileWikiName(file); } public void init(IWorkbenchWindow window) { this.window = window; } // void postWikiFile(IFile currentFile) { // String wikiName = getWikiFile(currentFile); // try { // if (fEditor != null) { // selectWiki(currentFile.getContents(), wikiName); // } // } catch (Exception e) { // } // // } public void run(IAction action) { if (fEditor == null) { IEditorPart targetEditor = window.getActivePage().getActiveEditor(); if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) { fEditor = (AbstractTextEditor) targetEditor; } } if (fEditor != null) { Configuration configuration = getConfiguration(); if (configuration != null && !configuration.equals("")) { try { String wikiLocale = configuration.getType().substring(WikiEditorPlugin.PREFIX_STORE.length()); IWikipedia wikipediaProperties = WikiEditorPlugin.getWikiInstance(wikiLocale); String user = configuration.getUser(); String password = configuration.getPassword(); if (user == null || password == null || user.equals("") || password.equals("")) { String[] result = new String[2]; boolean cache = configuration.promptForPassword(configuration.getUser(), "Set User/Password", true, result); if (result[0] == null || result[1] == null) { return; } if (result[0].equals("") || result[1].equals("")) { return; } user = result[0]; password = result[1]; } // IDocument doc = getDocument(); // ITextSelection selection = (ITextSelection) fEditor.getSelectionProvider().getSelection(); // int pos = selection.getOffset(); if (fEditor.getEditorInput() instanceof IFileEditorInput) { IFileEditorInput ei = (IFileEditorInput) fEditor.getEditorInput(); IFile currentFile = ei.getFile(); IFile[] files = { currentFile }; PostJob job = new PostJob(configuration, wikipediaProperties, user, password, files); job.setRule(null); job.setUser(true); job.schedule(); String wikiName = getWikiFile(currentFile); if (fEditor != null) { selectWiki(configuration, currentFile.getContents(), wikipediaProperties, user, password, wikiName); } } } catch (CoreException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void selectionChanged(IAction action, ISelection selection) { if (selection.isEmpty()) { return; } if (selection instanceof TextSelection) { action.setEnabled(true); return; } if (window.getActivePage() != null && window.getActivePage().getActivePart() != null) { action.setEnabled(window.getActivePage().getActivePart().getClass().equals(WikiEditor.class)); } } private void selectWiki(Configuration configuration, InputStream is, IWikipedia wikipediaProperties, String user, String password, String wikiName) { try { // IDocument doc = fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput()); String url = generateUrl(configuration, configuration.getURL(), wikiName); MediaWikiConnector connector = new MediaWikiConnector(); String actionUrl = configuration.getURL(); if (actionUrl == null || actionUrl.equals("")) { // fall back to default settings actionUrl = wikipediaProperties.getActionUrl(); } Date d = new Date(); Content content = new Content(String.valueOf(d.getTime()), getInputStreamAsString(is, wikipediaProperties.getCharSet())); boolean success = connector.login(wikipediaProperties, actionUrl, user, password, false); if (success) { connector.store(wikipediaProperties, actionUrl, wikiName, content, "", false, false); connector.logout(wikipediaProperties, actionUrl); } } catch (Exception e) { e.printStackTrace(); WikiEditorPlugin.getDefault() .reportError("Exception occured: ", e.getMessage() + "\nSee stacktrace in /.metadata/.log file."); } } public void setActiveEditor(IAction action, IEditorPart targetEditor) { if (targetEditor != null && (targetEditor instanceof AbstractTextEditor)) { fEditor = (AbstractTextEditor) targetEditor; text = new EditorText(targetEditor); } } /** * Returns the given input stream's contents as a character array. If a length is specified (ie. if length != -1), only length * chars are returned. Otherwise all chars in the stream are returned. Note this doesn't close the stream. * * @throws IOException * if a problem occured reading the stream. */ public static String getInputStreamAsString(InputStream stream, String encoding) throws IOException { char[] array = getInputStreamAsCharArray(stream, -1, encoding); if (array != null) { return new String(array); } return null; } /** * Returns the given input stream's contents as a character array. If a length is specified (ie. if length != -1), only length * chars are returned. Otherwise all chars in the stream are returned. Note this doesn't close the stream. * * @throws IOException * if a problem occured reading the stream. */ public static char[] getInputStreamAsCharArray(InputStream stream, int length, String encoding) throws IOException { InputStreamReader reader = null; reader = encoding == null ? new InputStreamReader(stream) : new InputStreamReader(stream, encoding); char[] contents; if (length == -1) { contents = NO_CHAR; int contentsLength = 0; int amountRead = -1; do { int amountRequested = Math.max(stream.available(), DEFAULT_READING_SIZE); // read at least 8K // resize contents if needed if (contentsLength + amountRequested > contents.length) { System.arraycopy(contents, 0, contents = new char[contentsLength + amountRequested], 0, contentsLength); } // read as many chars as possible amountRead = reader.read(contents, contentsLength, amountRequested); if (amountRead > 0) { // remember length of contents contentsLength += amountRead; } } while (amountRead != -1); // resize contents if necessary if (contentsLength < contents.length) { System.arraycopy(contents, 0, contents = new char[contentsLength], 0, contentsLength); } } else { contents = new char[length]; int len = 0; int readSize = 0; while ((readSize != -1) && (len != length)) { // See PR 1FMS89U // We record first the read size. In this case len is the actual read size. len += readSize; readSize = reader.read(contents, len, length - len); } // See PR 1FMS89U // Now we need to resize in case the default encoding used more than one byte for each // character if (len != length) System.arraycopy(contents, 0, (contents = new char[len]), 0, len); } return contents; } }